]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/bxe/bxe.c
Update libucl to git version 8d3b186
[FreeBSD/FreeBSD.git] / sys / dev / bxe / bxe.c
1 /*-
2  * Copyright (c) 2007-2014 QLogic Corporation. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS'
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #define BXE_DRIVER_VERSION "1.78.78"
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 #if 0
128     {
129         BRCM_VENDORID,
130         CHIP_NUM_57712_VF,
131         PCI_ANY_ID, PCI_ANY_ID,
132         "QLogic NetXtreme II BCM57712 VF 10GbE"
133     },
134 #endif
135     {
136         BRCM_VENDORID,
137         CHIP_NUM_57800,
138         PCI_ANY_ID, PCI_ANY_ID,
139         "QLogic NetXtreme II BCM57800 10GbE"
140     },
141     {
142         BRCM_VENDORID,
143         CHIP_NUM_57800_MF,
144         PCI_ANY_ID, PCI_ANY_ID,
145         "QLogic NetXtreme II BCM57800 MF 10GbE"
146     },
147 #if 0
148     {
149         BRCM_VENDORID,
150         CHIP_NUM_57800_VF,
151         PCI_ANY_ID, PCI_ANY_ID,
152         "QLogic NetXtreme II BCM57800 VF 10GbE"
153     },
154 #endif
155     {
156         BRCM_VENDORID,
157         CHIP_NUM_57810,
158         PCI_ANY_ID, PCI_ANY_ID,
159         "QLogic NetXtreme II BCM57810 10GbE"
160     },
161     {
162         BRCM_VENDORID,
163         CHIP_NUM_57810_MF,
164         PCI_ANY_ID, PCI_ANY_ID,
165         "QLogic NetXtreme II BCM57810 MF 10GbE"
166     },
167 #if 0
168     {
169         BRCM_VENDORID,
170         CHIP_NUM_57810_VF,
171         PCI_ANY_ID, PCI_ANY_ID,
172         "QLogic NetXtreme II BCM57810 VF 10GbE"
173     },
174 #endif
175     {
176         BRCM_VENDORID,
177         CHIP_NUM_57811,
178         PCI_ANY_ID, PCI_ANY_ID,
179         "QLogic NetXtreme II BCM57811 10GbE"
180     },
181     {
182         BRCM_VENDORID,
183         CHIP_NUM_57811_MF,
184         PCI_ANY_ID, PCI_ANY_ID,
185         "QLogic NetXtreme II BCM57811 MF 10GbE"
186     },
187 #if 0
188     {
189         BRCM_VENDORID,
190         CHIP_NUM_57811_VF,
191         PCI_ANY_ID, PCI_ANY_ID,
192         "QLogic NetXtreme II BCM57811 VF 10GbE"
193     },
194 #endif
195     {
196         BRCM_VENDORID,
197         CHIP_NUM_57840_4_10,
198         PCI_ANY_ID, PCI_ANY_ID,
199         "QLogic NetXtreme II BCM57840 4x10GbE"
200     },
201 #if 0
202     {
203         BRCM_VENDORID,
204         CHIP_NUM_57840_2_20,
205         PCI_ANY_ID, PCI_ANY_ID,
206         "QLogic NetXtreme II BCM57840 2x20GbE"
207     },
208 #endif
209     {
210         BRCM_VENDORID,
211         CHIP_NUM_57840_MF,
212         PCI_ANY_ID, PCI_ANY_ID,
213         "QLogic NetXtreme II BCM57840 MF 10GbE"
214     },
215 #if 0
216     {
217         BRCM_VENDORID,
218         CHIP_NUM_57840_VF,
219         PCI_ANY_ID, PCI_ANY_ID,
220         "QLogic NetXtreme II BCM57840 VF 10GbE"
221     },
222 #endif
223     {
224         0, 0, 0, 0, NULL
225     }
226 };
227
228 MALLOC_DECLARE(M_BXE_ILT);
229 MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
230
231 /*
232  * FreeBSD device entry points.
233  */
234 static int bxe_probe(device_t);
235 static int bxe_attach(device_t);
236 static int bxe_detach(device_t);
237 static int bxe_shutdown(device_t);
238
239 /*
240  * FreeBSD KLD module/device interface event handler method.
241  */
242 static device_method_t bxe_methods[] = {
243     /* Device interface (device_if.h) */
244     DEVMETHOD(device_probe,     bxe_probe),
245     DEVMETHOD(device_attach,    bxe_attach),
246     DEVMETHOD(device_detach,    bxe_detach),
247     DEVMETHOD(device_shutdown,  bxe_shutdown),
248 #if 0
249     DEVMETHOD(device_suspend,   bxe_suspend),
250     DEVMETHOD(device_resume,    bxe_resume),
251 #endif
252     /* Bus interface (bus_if.h) */
253     DEVMETHOD(bus_print_child,  bus_generic_print_child),
254     DEVMETHOD(bus_driver_added, bus_generic_driver_added),
255     KOBJMETHOD_END
256 };
257
258 /*
259  * FreeBSD KLD Module data declaration
260  */
261 static driver_t bxe_driver = {
262     "bxe",                   /* module name */
263     bxe_methods,             /* event handler */
264     sizeof(struct bxe_softc) /* extra data */
265 };
266
267 /*
268  * FreeBSD dev class is needed to manage dev instances and
269  * to associate with a bus type
270  */
271 static devclass_t bxe_devclass;
272
273 MODULE_DEPEND(bxe, pci, 1, 1, 1);
274 MODULE_DEPEND(bxe, ether, 1, 1, 1);
275 DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
276
277 /* resources needed for unloading a previously loaded device */
278
279 #define BXE_PREV_WAIT_NEEDED 1
280 struct mtx bxe_prev_mtx;
281 MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
282 struct bxe_prev_list_node {
283     LIST_ENTRY(bxe_prev_list_node) node;
284     uint8_t bus;
285     uint8_t slot;
286     uint8_t path;
287     uint8_t aer; /* XXX automatic error recovery */
288     uint8_t undi;
289 };
290 static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
291
292 static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
293
294 /* Tunable device values... */
295
296 SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
297
298 /* Debug */
299 unsigned long bxe_debug = 0;
300 SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, CTLFLAG_RDTUN,
301              &bxe_debug, 0, "Debug logging mode");
302
303 /* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
304 static int bxe_interrupt_mode = INTR_MODE_MSIX;
305 SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
306            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
307
308 /* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
309 static int bxe_queue_count = 4;
310 SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
311            &bxe_queue_count, 0, "Multi-Queue queue count");
312
313 /* max number of buffers per queue (default RX_BD_USABLE) */
314 static int bxe_max_rx_bufs = 0;
315 SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
316            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
317
318 /* Host interrupt coalescing RX tick timer (usecs) */
319 static int bxe_hc_rx_ticks = 25;
320 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
321            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
322
323 /* Host interrupt coalescing TX tick timer (usecs) */
324 static int bxe_hc_tx_ticks = 50;
325 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
326            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
327
328 /* Maximum number of Rx packets to process at a time */
329 static int bxe_rx_budget = 0xffffffff;
330 SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
331            &bxe_rx_budget, 0, "Rx processing budget");
332
333 /* Maximum LRO aggregation size */
334 static int bxe_max_aggregation_size = 0;
335 SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
336            &bxe_max_aggregation_size, 0, "max aggregation size");
337
338 /* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
339 static int bxe_mrrs = -1;
340 SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
341            &bxe_mrrs, 0, "PCIe maximum read request size");
342
343 /* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
344 static int bxe_autogreeen = 0;
345 SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
346            &bxe_autogreeen, 0, "AutoGrEEEn support");
347
348 /* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
349 static int bxe_udp_rss = 0;
350 SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
351            &bxe_udp_rss, 0, "UDP RSS support");
352
353
354 #define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
355
356 #define STATS_OFFSET32(stat_name)                   \
357     (offsetof(struct bxe_eth_stats, stat_name) / 4)
358
359 #define Q_STATS_OFFSET32(stat_name)                   \
360     (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
361
362 static const struct {
363     uint32_t offset;
364     uint32_t size;
365     uint32_t flags;
366 #define STATS_FLAGS_PORT  1
367 #define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
368 #define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
369     char string[STAT_NAME_LEN];
370 } bxe_eth_stats_arr[] = {
371     { STATS_OFFSET32(total_bytes_received_hi),
372                 8, STATS_FLAGS_BOTH, "rx_bytes" },
373     { STATS_OFFSET32(error_bytes_received_hi),
374                 8, STATS_FLAGS_BOTH, "rx_error_bytes" },
375     { STATS_OFFSET32(total_unicast_packets_received_hi),
376                 8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
377     { STATS_OFFSET32(total_multicast_packets_received_hi),
378                 8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
379     { STATS_OFFSET32(total_broadcast_packets_received_hi),
380                 8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
381     { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
382                 8, STATS_FLAGS_PORT, "rx_crc_errors" },
383     { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
384                 8, STATS_FLAGS_PORT, "rx_align_errors" },
385     { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
386                 8, STATS_FLAGS_PORT, "rx_undersize_packets" },
387     { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
388                 8, STATS_FLAGS_PORT, "rx_oversize_packets" },
389     { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
390                 8, STATS_FLAGS_PORT, "rx_fragments" },
391     { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
392                 8, STATS_FLAGS_PORT, "rx_jabbers" },
393     { STATS_OFFSET32(no_buff_discard_hi),
394                 8, STATS_FLAGS_BOTH, "rx_discards" },
395     { STATS_OFFSET32(mac_filter_discard),
396                 4, STATS_FLAGS_PORT, "rx_filtered_packets" },
397     { STATS_OFFSET32(mf_tag_discard),
398                 4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
399     { STATS_OFFSET32(pfc_frames_received_hi),
400                 8, STATS_FLAGS_PORT, "pfc_frames_received" },
401     { STATS_OFFSET32(pfc_frames_sent_hi),
402                 8, STATS_FLAGS_PORT, "pfc_frames_sent" },
403     { STATS_OFFSET32(brb_drop_hi),
404                 8, STATS_FLAGS_PORT, "rx_brb_discard" },
405     { STATS_OFFSET32(brb_truncate_hi),
406                 8, STATS_FLAGS_PORT, "rx_brb_truncate" },
407     { STATS_OFFSET32(pause_frames_received_hi),
408                 8, STATS_FLAGS_PORT, "rx_pause_frames" },
409     { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
410                 8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
411     { STATS_OFFSET32(nig_timer_max),
412                 4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
413     { STATS_OFFSET32(total_bytes_transmitted_hi),
414                 8, STATS_FLAGS_BOTH, "tx_bytes" },
415     { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
416                 8, STATS_FLAGS_PORT, "tx_error_bytes" },
417     { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
418                 8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
419     { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
420                 8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
421     { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
422                 8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
423     { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
424                 8, STATS_FLAGS_PORT, "tx_mac_errors" },
425     { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
426                 8, STATS_FLAGS_PORT, "tx_carrier_errors" },
427     { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
428                 8, STATS_FLAGS_PORT, "tx_single_collisions" },
429     { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
430                 8, STATS_FLAGS_PORT, "tx_multi_collisions" },
431     { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
432                 8, STATS_FLAGS_PORT, "tx_deferred" },
433     { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
434                 8, STATS_FLAGS_PORT, "tx_excess_collisions" },
435     { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
436                 8, STATS_FLAGS_PORT, "tx_late_collisions" },
437     { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
438                 8, STATS_FLAGS_PORT, "tx_total_collisions" },
439     { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
440                 8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
441     { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
442                 8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
443     { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
444                 8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
445     { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
446                 8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
447     { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
448                 8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
449     { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
450                 8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
451     { STATS_OFFSET32(etherstatspktsover1522octets_hi),
452                 8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
453     { STATS_OFFSET32(pause_frames_sent_hi),
454                 8, STATS_FLAGS_PORT, "tx_pause_frames" },
455     { STATS_OFFSET32(total_tpa_aggregations_hi),
456                 8, STATS_FLAGS_FUNC, "tpa_aggregations" },
457     { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
458                 8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
459     { STATS_OFFSET32(total_tpa_bytes_hi),
460                 8, STATS_FLAGS_FUNC, "tpa_bytes"},
461 #if 0
462     { STATS_OFFSET32(recoverable_error),
463                 4, STATS_FLAGS_FUNC, "recoverable_errors" },
464     { STATS_OFFSET32(unrecoverable_error),
465                 4, STATS_FLAGS_FUNC, "unrecoverable_errors" },
466 #endif
467     { STATS_OFFSET32(eee_tx_lpi),
468                 4, STATS_FLAGS_PORT, "eee_tx_lpi"},
469     { STATS_OFFSET32(rx_calls),
470                 4, STATS_FLAGS_FUNC, "rx_calls"},
471     { STATS_OFFSET32(rx_pkts),
472                 4, STATS_FLAGS_FUNC, "rx_pkts"},
473     { STATS_OFFSET32(rx_tpa_pkts),
474                 4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
475     { STATS_OFFSET32(rx_soft_errors),
476                 4, STATS_FLAGS_FUNC, "rx_soft_errors"},
477     { STATS_OFFSET32(rx_hw_csum_errors),
478                 4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
479     { STATS_OFFSET32(rx_ofld_frames_csum_ip),
480                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
481     { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
482                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
483     { STATS_OFFSET32(rx_budget_reached),
484                 4, STATS_FLAGS_FUNC, "rx_budget_reached"},
485     { STATS_OFFSET32(tx_pkts),
486                 4, STATS_FLAGS_FUNC, "tx_pkts"},
487     { STATS_OFFSET32(tx_soft_errors),
488                 4, STATS_FLAGS_FUNC, "tx_soft_errors"},
489     { STATS_OFFSET32(tx_ofld_frames_csum_ip),
490                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
491     { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
492                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
493     { STATS_OFFSET32(tx_ofld_frames_csum_udp),
494                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
495     { STATS_OFFSET32(tx_ofld_frames_lso),
496                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
497     { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
498                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
499     { STATS_OFFSET32(tx_encap_failures),
500                 4, STATS_FLAGS_FUNC, "tx_encap_failures"},
501     { STATS_OFFSET32(tx_hw_queue_full),
502                 4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
503     { STATS_OFFSET32(tx_hw_max_queue_depth),
504                 4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
505     { STATS_OFFSET32(tx_dma_mapping_failure),
506                 4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
507     { STATS_OFFSET32(tx_max_drbr_queue_depth),
508                 4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
509     { STATS_OFFSET32(tx_window_violation_std),
510                 4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
511     { STATS_OFFSET32(tx_window_violation_tso),
512                 4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
513 #if 0
514     { STATS_OFFSET32(tx_unsupported_tso_request_ipv6),
515                 4, STATS_FLAGS_FUNC, "tx_unsupported_tso_request_ipv6"},
516     { STATS_OFFSET32(tx_unsupported_tso_request_not_tcp),
517                 4, STATS_FLAGS_FUNC, "tx_unsupported_tso_request_not_tcp"},
518 #endif
519     { STATS_OFFSET32(tx_chain_lost_mbuf),
520                 4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
521     { STATS_OFFSET32(tx_frames_deferred),
522                 4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
523     { STATS_OFFSET32(tx_queue_xoff),
524                 4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
525     { STATS_OFFSET32(mbuf_defrag_attempts),
526                 4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
527     { STATS_OFFSET32(mbuf_defrag_failures),
528                 4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
529     { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
530                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
531     { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
532                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
533     { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
534                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
535     { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
536                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
537     { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
538                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
539     { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
540                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
541     { STATS_OFFSET32(mbuf_alloc_tx),
542                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
543     { STATS_OFFSET32(mbuf_alloc_rx),
544                 4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
545     { STATS_OFFSET32(mbuf_alloc_sge),
546                 4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
547     { STATS_OFFSET32(mbuf_alloc_tpa),
548                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"}
549 };
550
551 static const struct {
552     uint32_t offset;
553     uint32_t size;
554     char string[STAT_NAME_LEN];
555 } bxe_eth_q_stats_arr[] = {
556     { Q_STATS_OFFSET32(total_bytes_received_hi),
557                 8, "rx_bytes" },
558     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
559                 8, "rx_ucast_packets" },
560     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
561                 8, "rx_mcast_packets" },
562     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
563                 8, "rx_bcast_packets" },
564     { Q_STATS_OFFSET32(no_buff_discard_hi),
565                 8, "rx_discards" },
566     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
567                 8, "tx_bytes" },
568     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
569                 8, "tx_ucast_packets" },
570     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
571                 8, "tx_mcast_packets" },
572     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
573                 8, "tx_bcast_packets" },
574     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
575                 8, "tpa_aggregations" },
576     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
577                 8, "tpa_aggregated_frames"},
578     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
579                 8, "tpa_bytes"},
580     { Q_STATS_OFFSET32(rx_calls),
581                 4, "rx_calls"},
582     { Q_STATS_OFFSET32(rx_pkts),
583                 4, "rx_pkts"},
584     { Q_STATS_OFFSET32(rx_tpa_pkts),
585                 4, "rx_tpa_pkts"},
586     { Q_STATS_OFFSET32(rx_soft_errors),
587                 4, "rx_soft_errors"},
588     { Q_STATS_OFFSET32(rx_hw_csum_errors),
589                 4, "rx_hw_csum_errors"},
590     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
591                 4, "rx_ofld_frames_csum_ip"},
592     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
593                 4, "rx_ofld_frames_csum_tcp_udp"},
594     { Q_STATS_OFFSET32(rx_budget_reached),
595                 4, "rx_budget_reached"},
596     { Q_STATS_OFFSET32(tx_pkts),
597                 4, "tx_pkts"},
598     { Q_STATS_OFFSET32(tx_soft_errors),
599                 4, "tx_soft_errors"},
600     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
601                 4, "tx_ofld_frames_csum_ip"},
602     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
603                 4, "tx_ofld_frames_csum_tcp"},
604     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
605                 4, "tx_ofld_frames_csum_udp"},
606     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
607                 4, "tx_ofld_frames_lso"},
608     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
609                 4, "tx_ofld_frames_lso_hdr_splits"},
610     { Q_STATS_OFFSET32(tx_encap_failures),
611                 4, "tx_encap_failures"},
612     { Q_STATS_OFFSET32(tx_hw_queue_full),
613                 4, "tx_hw_queue_full"},
614     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
615                 4, "tx_hw_max_queue_depth"},
616     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
617                 4, "tx_dma_mapping_failure"},
618     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
619                 4, "tx_max_drbr_queue_depth"},
620     { Q_STATS_OFFSET32(tx_window_violation_std),
621                 4, "tx_window_violation_std"},
622     { Q_STATS_OFFSET32(tx_window_violation_tso),
623                 4, "tx_window_violation_tso"},
624 #if 0
625     { Q_STATS_OFFSET32(tx_unsupported_tso_request_ipv6),
626                 4, "tx_unsupported_tso_request_ipv6"},
627     { Q_STATS_OFFSET32(tx_unsupported_tso_request_not_tcp),
628                 4, "tx_unsupported_tso_request_not_tcp"},
629 #endif
630     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
631                 4, "tx_chain_lost_mbuf"},
632     { Q_STATS_OFFSET32(tx_frames_deferred),
633                 4, "tx_frames_deferred"},
634     { Q_STATS_OFFSET32(tx_queue_xoff),
635                 4, "tx_queue_xoff"},
636     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
637                 4, "mbuf_defrag_attempts"},
638     { Q_STATS_OFFSET32(mbuf_defrag_failures),
639                 4, "mbuf_defrag_failures"},
640     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
641                 4, "mbuf_rx_bd_alloc_failed"},
642     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
643                 4, "mbuf_rx_bd_mapping_failed"},
644     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
645                 4, "mbuf_rx_tpa_alloc_failed"},
646     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
647                 4, "mbuf_rx_tpa_mapping_failed"},
648     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
649                 4, "mbuf_rx_sge_alloc_failed"},
650     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
651                 4, "mbuf_rx_sge_mapping_failed"},
652     { Q_STATS_OFFSET32(mbuf_alloc_tx),
653                 4, "mbuf_alloc_tx"},
654     { Q_STATS_OFFSET32(mbuf_alloc_rx),
655                 4, "mbuf_alloc_rx"},
656     { Q_STATS_OFFSET32(mbuf_alloc_sge),
657                 4, "mbuf_alloc_sge"},
658     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
659                 4, "mbuf_alloc_tpa"}
660 };
661
662 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
663 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
664
665
666 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
667                                  uint8_t          read_cfg,
668                                  uint8_t          cmng_type);
669 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
670 static void    storm_memset_cmng(struct bxe_softc *sc,
671                                  struct cmng_init *cmng,
672                                  uint8_t          port);
673 static void    bxe_set_reset_global(struct bxe_softc *sc);
674 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
675 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
676                                  int              engine);
677 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
678 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
679                                    uint8_t          *global,
680                                    uint8_t          print);
681 static void    bxe_int_disable(struct bxe_softc *sc);
682 static int     bxe_release_leader_lock(struct bxe_softc *sc);
683 static void    bxe_pf_disable(struct bxe_softc *sc);
684 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
685 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
686                                       struct bxe_fastpath *fp,
687                                       uint16_t            rx_bd_prod,
688                                       uint16_t            rx_cq_prod,
689                                       uint16_t            rx_sge_prod);
690 static void    bxe_link_report_locked(struct bxe_softc *sc);
691 static void    bxe_link_report(struct bxe_softc *sc);
692 static void    bxe_link_status_update(struct bxe_softc *sc);
693 static void    bxe_periodic_callout_func(void *xsc);
694 static void    bxe_periodic_start(struct bxe_softc *sc);
695 static void    bxe_periodic_stop(struct bxe_softc *sc);
696 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
697                                     uint16_t prev_index,
698                                     uint16_t index);
699 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
700                                      int                 queue);
701 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
702                                      uint16_t            index);
703 static uint8_t bxe_txeof(struct bxe_softc *sc,
704                          struct bxe_fastpath *fp);
705 static void    bxe_task_fp(struct bxe_fastpath *fp);
706 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
707                                      struct mbuf      *m,
708                                      uint8_t          contents);
709 static int     bxe_alloc_mem(struct bxe_softc *sc);
710 static void    bxe_free_mem(struct bxe_softc *sc);
711 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
712 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
713 static int     bxe_interrupt_attach(struct bxe_softc *sc);
714 static void    bxe_interrupt_detach(struct bxe_softc *sc);
715 static void    bxe_set_rx_mode(struct bxe_softc *sc);
716 static int     bxe_init_locked(struct bxe_softc *sc);
717 static int     bxe_stop_locked(struct bxe_softc *sc);
718 static __noinline int bxe_nic_load(struct bxe_softc *sc,
719                                    int              load_mode);
720 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
721                                      uint32_t         unload_mode,
722                                      uint8_t          keep_link);
723
724 static void bxe_handle_sp_tq(void *context, int pending);
725 static void bxe_handle_rx_mode_tq(void *context, int pending);
726 static void bxe_handle_fp_tq(void *context, int pending);
727
728
729 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
730 uint32_t
731 calc_crc32(uint8_t  *crc32_packet,
732            uint32_t crc32_length,
733            uint32_t crc32_seed,
734            uint8_t  complement)
735 {
736    uint32_t byte         = 0;
737    uint32_t bit          = 0;
738    uint8_t  msb          = 0;
739    uint32_t temp         = 0;
740    uint32_t shft         = 0;
741    uint8_t  current_byte = 0;
742    uint32_t crc32_result = crc32_seed;
743    const uint32_t CRC32_POLY = 0x1edc6f41;
744
745    if ((crc32_packet == NULL) ||
746        (crc32_length == 0) ||
747        ((crc32_length % 8) != 0))
748     {
749         return (crc32_result);
750     }
751
752     for (byte = 0; byte < crc32_length; byte = byte + 1)
753     {
754         current_byte = crc32_packet[byte];
755         for (bit = 0; bit < 8; bit = bit + 1)
756         {
757             /* msb = crc32_result[31]; */
758             msb = (uint8_t)(crc32_result >> 31);
759
760             crc32_result = crc32_result << 1;
761
762             /* it (msb != current_byte[bit]) */
763             if (msb != (0x1 & (current_byte >> bit)))
764             {
765                 crc32_result = crc32_result ^ CRC32_POLY;
766                 /* crc32_result[0] = 1 */
767                 crc32_result |= 1;
768             }
769         }
770     }
771
772     /* Last step is to:
773      * 1. "mirror" every bit
774      * 2. swap the 4 bytes
775      * 3. complement each bit
776      */
777
778     /* Mirror */
779     temp = crc32_result;
780     shft = sizeof(crc32_result) * 8 - 1;
781
782     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
783     {
784         temp <<= 1;
785         temp |= crc32_result & 1;
786         shft-- ;
787     }
788
789     /* temp[31-bit] = crc32_result[bit] */
790     temp <<= shft;
791
792     /* Swap */
793     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
794     {
795         uint32_t t0, t1, t2, t3;
796         t0 = (0x000000ff & (temp >> 24));
797         t1 = (0x0000ff00 & (temp >> 8));
798         t2 = (0x00ff0000 & (temp << 8));
799         t3 = (0xff000000 & (temp << 24));
800         crc32_result = t0 | t1 | t2 | t3;
801     }
802
803     /* Complement */
804     if (complement)
805     {
806         crc32_result = ~crc32_result;
807     }
808
809     return (crc32_result);
810 }
811
812 int
813 bxe_test_bit(int                    nr,
814              volatile unsigned long *addr)
815 {
816     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
817 }
818
819 void
820 bxe_set_bit(unsigned int           nr,
821             volatile unsigned long *addr)
822 {
823     atomic_set_acq_long(addr, (1 << nr));
824 }
825
826 void
827 bxe_clear_bit(int                    nr,
828               volatile unsigned long *addr)
829 {
830     atomic_clear_acq_long(addr, (1 << nr));
831 }
832
833 int
834 bxe_test_and_set_bit(int                    nr,
835                        volatile unsigned long *addr)
836 {
837     unsigned long x;
838     nr = (1 << nr);
839     do {
840         x = *addr;
841     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
842     // if (x & nr) bit_was_set; else bit_was_not_set;
843     return (x & nr);
844 }
845
846 int
847 bxe_test_and_clear_bit(int                    nr,
848                        volatile unsigned long *addr)
849 {
850     unsigned long x;
851     nr = (1 << nr);
852     do {
853         x = *addr;
854     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
855     // if (x & nr) bit_was_set; else bit_was_not_set;
856     return (x & nr);
857 }
858
859 int
860 bxe_cmpxchg(volatile int *addr,
861             int          old,
862             int          new)
863 {
864     int x;
865     do {
866         x = *addr;
867     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
868     return (x);
869 }
870
871 /*
872  * Get DMA memory from the OS.
873  *
874  * Validates that the OS has provided DMA buffers in response to a
875  * bus_dmamap_load call and saves the physical address of those buffers.
876  * When the callback is used the OS will return 0 for the mapping function
877  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
878  * failures back to the caller.
879  *
880  * Returns:
881  *   Nothing.
882  */
883 static void
884 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
885 {
886     struct bxe_dma *dma = arg;
887
888     if (error) {
889         dma->paddr = 0;
890         dma->nseg  = 0;
891         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
892     } else {
893         dma->paddr = segs->ds_addr;
894         dma->nseg  = nseg;
895 #if 0
896         BLOGD(dma->sc, DBG_LOAD,
897               "DMA alloc '%s': vaddr=%p paddr=%p nseg=%d size=%lu\n",
898               dma->msg, dma->vaddr, (void *)dma->paddr,
899               dma->nseg, dma->size);
900 #endif
901     }
902 }
903
904 /*
905  * Allocate a block of memory and map it for DMA. No partial completions
906  * allowed and release any resources acquired if we can't acquire all
907  * resources.
908  *
909  * Returns:
910  *   0 = Success, !0 = Failure
911  */
912 int
913 bxe_dma_alloc(struct bxe_softc *sc,
914               bus_size_t       size,
915               struct bxe_dma   *dma,
916               const char       *msg)
917 {
918     int rc;
919
920     if (dma->size > 0) {
921         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
922               (unsigned long)dma->size);
923         return (1);
924     }
925
926     memset(dma, 0, sizeof(*dma)); /* sanity */
927     dma->sc   = sc;
928     dma->size = size;
929     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
930
931     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
932                             BCM_PAGE_SIZE,      /* alignment */
933                             0,                  /* boundary limit */
934                             BUS_SPACE_MAXADDR,  /* restricted low */
935                             BUS_SPACE_MAXADDR,  /* restricted hi */
936                             NULL,               /* addr filter() */
937                             NULL,               /* addr filter() arg */
938                             size,               /* max map size */
939                             1,                  /* num discontinuous */
940                             size,               /* max seg size */
941                             BUS_DMA_ALLOCNOW,   /* flags */
942                             NULL,               /* lock() */
943                             NULL,               /* lock() arg */
944                             &dma->tag);         /* returned dma tag */
945     if (rc != 0) {
946         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
947         memset(dma, 0, sizeof(*dma));
948         return (1);
949     }
950
951     rc = bus_dmamem_alloc(dma->tag,
952                           (void **)&dma->vaddr,
953                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
954                           &dma->map);
955     if (rc != 0) {
956         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
957         bus_dma_tag_destroy(dma->tag);
958         memset(dma, 0, sizeof(*dma));
959         return (1);
960     }
961
962     rc = bus_dmamap_load(dma->tag,
963                          dma->map,
964                          dma->vaddr,
965                          size,
966                          bxe_dma_map_addr, /* BLOGD in here */
967                          dma,
968                          BUS_DMA_NOWAIT);
969     if (rc != 0) {
970         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
971         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
972         bus_dma_tag_destroy(dma->tag);
973         memset(dma, 0, sizeof(*dma));
974         return (1);
975     }
976
977     return (0);
978 }
979
980 void
981 bxe_dma_free(struct bxe_softc *sc,
982              struct bxe_dma   *dma)
983 {
984     if (dma->size > 0) {
985 #if 0
986         BLOGD(sc, DBG_LOAD,
987               "DMA free '%s': vaddr=%p paddr=%p nseg=%d size=%lu\n",
988               dma->msg, dma->vaddr, (void *)dma->paddr,
989               dma->nseg, dma->size);
990 #endif
991
992         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
993
994         bus_dmamap_sync(dma->tag, dma->map,
995                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
996         bus_dmamap_unload(dma->tag, dma->map);
997         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
998         bus_dma_tag_destroy(dma->tag);
999     }
1000
1001     memset(dma, 0, sizeof(*dma));
1002 }
1003
1004 /*
1005  * These indirect read and write routines are only during init.
1006  * The locking is handled by the MCP.
1007  */
1008
1009 void
1010 bxe_reg_wr_ind(struct bxe_softc *sc,
1011                uint32_t         addr,
1012                uint32_t         val)
1013 {
1014     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1015     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
1016     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1017 }
1018
1019 uint32_t
1020 bxe_reg_rd_ind(struct bxe_softc *sc,
1021                uint32_t         addr)
1022 {
1023     uint32_t val;
1024
1025     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1026     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
1027     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1028
1029     return (val);
1030 }
1031
1032 #if 0
1033 void bxe_dp_dmae(struct bxe_softc *sc, struct dmae_command *dmae, int msglvl)
1034 {
1035     uint32_t src_type = dmae->opcode & DMAE_COMMAND_SRC;
1036
1037     switch (dmae->opcode & DMAE_COMMAND_DST) {
1038     case DMAE_CMD_DST_PCI:
1039         if (src_type == DMAE_CMD_SRC_PCI)
1040             DP(msglvl, "DMAE: opcode 0x%08x\n"
1041                "src [%x:%08x], len [%d*4], dst [%x:%08x]\n"
1042                "comp_addr [%x:%08x], comp_val 0x%08x\n",
1043                dmae->opcode, dmae->src_addr_hi, dmae->src_addr_lo,
1044                dmae->len, dmae->dst_addr_hi, dmae->dst_addr_lo,
1045                dmae->comp_addr_hi, dmae->comp_addr_lo,
1046                dmae->comp_val);
1047         else
1048             DP(msglvl, "DMAE: opcode 0x%08x\n"
1049                "src [%08x], len [%d*4], dst [%x:%08x]\n"
1050                "comp_addr [%x:%08x], comp_val 0x%08x\n",
1051                dmae->opcode, dmae->src_addr_lo >> 2,
1052                dmae->len, dmae->dst_addr_hi, dmae->dst_addr_lo,
1053                dmae->comp_addr_hi, dmae->comp_addr_lo,
1054                dmae->comp_val);
1055         break;
1056     case DMAE_CMD_DST_GRC:
1057         if (src_type == DMAE_CMD_SRC_PCI)
1058             DP(msglvl, "DMAE: opcode 0x%08x\n"
1059                "src [%x:%08x], len [%d*4], dst_addr [%08x]\n"
1060                "comp_addr [%x:%08x], comp_val 0x%08x\n",
1061                dmae->opcode, dmae->src_addr_hi, dmae->src_addr_lo,
1062                dmae->len, dmae->dst_addr_lo >> 2,
1063                dmae->comp_addr_hi, dmae->comp_addr_lo,
1064                dmae->comp_val);
1065         else
1066             DP(msglvl, "DMAE: opcode 0x%08x\n"
1067                "src [%08x], len [%d*4], dst [%08x]\n"
1068                "comp_addr [%x:%08x], comp_val 0x%08x\n",
1069                dmae->opcode, dmae->src_addr_lo >> 2,
1070                dmae->len, dmae->dst_addr_lo >> 2,
1071                dmae->comp_addr_hi, dmae->comp_addr_lo,
1072                dmae->comp_val);
1073         break;
1074     default:
1075         if (src_type == DMAE_CMD_SRC_PCI)
1076             DP(msglvl, "DMAE: opcode 0x%08x\n"
1077                "src_addr [%x:%08x]  len [%d * 4]  dst_addr [none]\n"
1078                "comp_addr [%x:%08x]  comp_val 0x%08x\n",
1079                dmae->opcode, dmae->src_addr_hi, dmae->src_addr_lo,
1080                dmae->len, dmae->comp_addr_hi, dmae->comp_addr_lo,
1081                dmae->comp_val);
1082         else
1083             DP(msglvl, "DMAE: opcode 0x%08x\n"
1084                "src_addr [%08x]  len [%d * 4]  dst_addr [none]\n"
1085                "comp_addr [%x:%08x]  comp_val 0x%08x\n",
1086                dmae->opcode, dmae->src_addr_lo >> 2,
1087                dmae->len, dmae->comp_addr_hi, dmae->comp_addr_lo,
1088                dmae->comp_val);
1089         break;
1090     }
1091
1092 }
1093 #endif
1094
1095 static int
1096 bxe_acquire_hw_lock(struct bxe_softc *sc,
1097                     uint32_t         resource)
1098 {
1099     uint32_t lock_status;
1100     uint32_t resource_bit = (1 << resource);
1101     int func = SC_FUNC(sc);
1102     uint32_t hw_lock_control_reg;
1103     int cnt;
1104
1105     /* validate the resource is within range */
1106     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1107         BLOGE(sc, "resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE\n", resource);
1108         return (-1);
1109     }
1110
1111     if (func <= 5) {
1112         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1113     } else {
1114         hw_lock_control_reg =
1115                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1116     }
1117
1118     /* validate the resource is not already taken */
1119     lock_status = REG_RD(sc, hw_lock_control_reg);
1120     if (lock_status & resource_bit) {
1121         BLOGE(sc, "resource in use (status 0x%x bit 0x%x)\n",
1122               lock_status, resource_bit);
1123         return (-1);
1124     }
1125
1126     /* try every 5ms for 5 seconds */
1127     for (cnt = 0; cnt < 1000; cnt++) {
1128         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1129         lock_status = REG_RD(sc, hw_lock_control_reg);
1130         if (lock_status & resource_bit) {
1131             return (0);
1132         }
1133         DELAY(5000);
1134     }
1135
1136     BLOGE(sc, "Resource lock timeout!\n");
1137     return (-1);
1138 }
1139
1140 static int
1141 bxe_release_hw_lock(struct bxe_softc *sc,
1142                     uint32_t         resource)
1143 {
1144     uint32_t lock_status;
1145     uint32_t resource_bit = (1 << resource);
1146     int func = SC_FUNC(sc);
1147     uint32_t hw_lock_control_reg;
1148
1149     /* validate the resource is within range */
1150     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1151         BLOGE(sc, "resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE\n", resource);
1152         return (-1);
1153     }
1154
1155     if (func <= 5) {
1156         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1157     } else {
1158         hw_lock_control_reg =
1159                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1160     }
1161
1162     /* validate the resource is currently taken */
1163     lock_status = REG_RD(sc, hw_lock_control_reg);
1164     if (!(lock_status & resource_bit)) {
1165         BLOGE(sc, "resource not in use (status 0x%x bit 0x%x)\n",
1166               lock_status, resource_bit);
1167         return (-1);
1168     }
1169
1170     REG_WR(sc, hw_lock_control_reg, resource_bit);
1171     return (0);
1172 }
1173
1174 /*
1175  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1176  * had we done things the other way around, if two pfs from the same port
1177  * would attempt to access nvram at the same time, we could run into a
1178  * scenario such as:
1179  * pf A takes the port lock.
1180  * pf B succeeds in taking the same lock since they are from the same port.
1181  * pf A takes the per pf misc lock. Performs eeprom access.
1182  * pf A finishes. Unlocks the per pf misc lock.
1183  * Pf B takes the lock and proceeds to perform it's own access.
1184  * pf A unlocks the per port lock, while pf B is still working (!).
1185  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1186  * access corrupted by pf B).*
1187  */
1188 static int
1189 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1190 {
1191     int port = SC_PORT(sc);
1192     int count, i;
1193     uint32_t val = 0;
1194
1195     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1196     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1197
1198     /* adjust timeout for emulation/FPGA */
1199     count = NVRAM_TIMEOUT_COUNT;
1200     if (CHIP_REV_IS_SLOW(sc)) {
1201         count *= 100;
1202     }
1203
1204     /* request access to nvram interface */
1205     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1206            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1207
1208     for (i = 0; i < count*10; i++) {
1209         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1210         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1211             break;
1212         }
1213
1214         DELAY(5);
1215     }
1216
1217     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1218         BLOGE(sc, "Cannot get access to nvram interface\n");
1219         return (-1);
1220     }
1221
1222     return (0);
1223 }
1224
1225 static int
1226 bxe_release_nvram_lock(struct bxe_softc *sc)
1227 {
1228     int port = SC_PORT(sc);
1229     int count, i;
1230     uint32_t val = 0;
1231
1232     /* adjust timeout for emulation/FPGA */
1233     count = NVRAM_TIMEOUT_COUNT;
1234     if (CHIP_REV_IS_SLOW(sc)) {
1235         count *= 100;
1236     }
1237
1238     /* relinquish nvram interface */
1239     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1240            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1241
1242     for (i = 0; i < count*10; i++) {
1243         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1244         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1245             break;
1246         }
1247
1248         DELAY(5);
1249     }
1250
1251     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1252         BLOGE(sc, "Cannot free access to nvram interface\n");
1253         return (-1);
1254     }
1255
1256     /* release HW lock: protect against other PFs in PF Direct Assignment */
1257     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1258
1259     return (0);
1260 }
1261
1262 static void
1263 bxe_enable_nvram_access(struct bxe_softc *sc)
1264 {
1265     uint32_t val;
1266
1267     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1268
1269     /* enable both bits, even on read */
1270     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1271            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1272 }
1273
1274 static void
1275 bxe_disable_nvram_access(struct bxe_softc *sc)
1276 {
1277     uint32_t val;
1278
1279     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1280
1281     /* disable both bits, even after read */
1282     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1283            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1284                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1285 }
1286
1287 static int
1288 bxe_nvram_read_dword(struct bxe_softc *sc,
1289                      uint32_t         offset,
1290                      uint32_t         *ret_val,
1291                      uint32_t         cmd_flags)
1292 {
1293     int count, i, rc;
1294     uint32_t val;
1295
1296     /* build the command word */
1297     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1298
1299     /* need to clear DONE bit separately */
1300     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1301
1302     /* address of the NVRAM to read from */
1303     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1304            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1305
1306     /* issue a read command */
1307     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1308
1309     /* adjust timeout for emulation/FPGA */
1310     count = NVRAM_TIMEOUT_COUNT;
1311     if (CHIP_REV_IS_SLOW(sc)) {
1312         count *= 100;
1313     }
1314
1315     /* wait for completion */
1316     *ret_val = 0;
1317     rc = -1;
1318     for (i = 0; i < count; i++) {
1319         DELAY(5);
1320         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1321
1322         if (val & MCPR_NVM_COMMAND_DONE) {
1323             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1324             /* we read nvram data in cpu order
1325              * but ethtool sees it as an array of bytes
1326              * converting to big-endian will do the work
1327              */
1328             *ret_val = htobe32(val);
1329             rc = 0;
1330             break;
1331         }
1332     }
1333
1334     if (rc == -1) {
1335         BLOGE(sc, "nvram read timeout expired\n");
1336     }
1337
1338     return (rc);
1339 }
1340
1341 static int
1342 bxe_nvram_read(struct bxe_softc *sc,
1343                uint32_t         offset,
1344                uint8_t          *ret_buf,
1345                int              buf_size)
1346 {
1347     uint32_t cmd_flags;
1348     uint32_t val;
1349     int rc;
1350
1351     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1352         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1353               offset, buf_size);
1354         return (-1);
1355     }
1356
1357     if ((offset + buf_size) > sc->devinfo.flash_size) {
1358         BLOGE(sc, "Invalid parameter, "
1359                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1360               offset, buf_size, sc->devinfo.flash_size);
1361         return (-1);
1362     }
1363
1364     /* request access to nvram interface */
1365     rc = bxe_acquire_nvram_lock(sc);
1366     if (rc) {
1367         return (rc);
1368     }
1369
1370     /* enable access to nvram interface */
1371     bxe_enable_nvram_access(sc);
1372
1373     /* read the first word(s) */
1374     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1375     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1376         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1377         memcpy(ret_buf, &val, 4);
1378
1379         /* advance to the next dword */
1380         offset += sizeof(uint32_t);
1381         ret_buf += sizeof(uint32_t);
1382         buf_size -= sizeof(uint32_t);
1383         cmd_flags = 0;
1384     }
1385
1386     if (rc == 0) {
1387         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1388         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1389         memcpy(ret_buf, &val, 4);
1390     }
1391
1392     /* disable access to nvram interface */
1393     bxe_disable_nvram_access(sc);
1394     bxe_release_nvram_lock(sc);
1395
1396     return (rc);
1397 }
1398
1399 static int
1400 bxe_nvram_write_dword(struct bxe_softc *sc,
1401                       uint32_t         offset,
1402                       uint32_t         val,
1403                       uint32_t         cmd_flags)
1404 {
1405     int count, i, rc;
1406
1407     /* build the command word */
1408     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1409
1410     /* need to clear DONE bit separately */
1411     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1412
1413     /* write the data */
1414     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1415
1416     /* address of the NVRAM to write to */
1417     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1418            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1419
1420     /* issue the write command */
1421     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1422
1423     /* adjust timeout for emulation/FPGA */
1424     count = NVRAM_TIMEOUT_COUNT;
1425     if (CHIP_REV_IS_SLOW(sc)) {
1426         count *= 100;
1427     }
1428
1429     /* wait for completion */
1430     rc = -1;
1431     for (i = 0; i < count; i++) {
1432         DELAY(5);
1433         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1434         if (val & MCPR_NVM_COMMAND_DONE) {
1435             rc = 0;
1436             break;
1437         }
1438     }
1439
1440     if (rc == -1) {
1441         BLOGE(sc, "nvram write timeout expired\n");
1442     }
1443
1444     return (rc);
1445 }
1446
1447 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1448
1449 static int
1450 bxe_nvram_write1(struct bxe_softc *sc,
1451                  uint32_t         offset,
1452                  uint8_t          *data_buf,
1453                  int              buf_size)
1454 {
1455     uint32_t cmd_flags;
1456     uint32_t align_offset;
1457     uint32_t val;
1458     int rc;
1459
1460     if ((offset + buf_size) > sc->devinfo.flash_size) {
1461         BLOGE(sc, "Invalid parameter, "
1462                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1463               offset, buf_size, sc->devinfo.flash_size);
1464         return (-1);
1465     }
1466
1467     /* request access to nvram interface */
1468     rc = bxe_acquire_nvram_lock(sc);
1469     if (rc) {
1470         return (rc);
1471     }
1472
1473     /* enable access to nvram interface */
1474     bxe_enable_nvram_access(sc);
1475
1476     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1477     align_offset = (offset & ~0x03);
1478     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1479
1480     if (rc == 0) {
1481         val &= ~(0xff << BYTE_OFFSET(offset));
1482         val |= (*data_buf << BYTE_OFFSET(offset));
1483
1484         /* nvram data is returned as an array of bytes
1485          * convert it back to cpu order
1486          */
1487         val = be32toh(val);
1488
1489         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1490     }
1491
1492     /* disable access to nvram interface */
1493     bxe_disable_nvram_access(sc);
1494     bxe_release_nvram_lock(sc);
1495
1496     return (rc);
1497 }
1498
1499 static int
1500 bxe_nvram_write(struct bxe_softc *sc,
1501                 uint32_t         offset,
1502                 uint8_t          *data_buf,
1503                 int              buf_size)
1504 {
1505     uint32_t cmd_flags;
1506     uint32_t val;
1507     uint32_t written_so_far;
1508     int rc;
1509
1510     if (buf_size == 1) {
1511         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1512     }
1513
1514     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1515         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1516               offset, buf_size);
1517         return (-1);
1518     }
1519
1520     if (buf_size == 0) {
1521         return (0); /* nothing to do */
1522     }
1523
1524     if ((offset + buf_size) > sc->devinfo.flash_size) {
1525         BLOGE(sc, "Invalid parameter, "
1526                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1527               offset, buf_size, sc->devinfo.flash_size);
1528         return (-1);
1529     }
1530
1531     /* request access to nvram interface */
1532     rc = bxe_acquire_nvram_lock(sc);
1533     if (rc) {
1534         return (rc);
1535     }
1536
1537     /* enable access to nvram interface */
1538     bxe_enable_nvram_access(sc);
1539
1540     written_so_far = 0;
1541     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1542     while ((written_so_far < buf_size) && (rc == 0)) {
1543         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1544             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1545         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1546             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1547         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1548             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1549         }
1550
1551         memcpy(&val, data_buf, 4);
1552
1553         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1554
1555         /* advance to the next dword */
1556         offset += sizeof(uint32_t);
1557         data_buf += sizeof(uint32_t);
1558         written_so_far += sizeof(uint32_t);
1559         cmd_flags = 0;
1560     }
1561
1562     /* disable access to nvram interface */
1563     bxe_disable_nvram_access(sc);
1564     bxe_release_nvram_lock(sc);
1565
1566     return (rc);
1567 }
1568
1569 /* copy command into DMAE command memory and set DMAE command Go */
1570 void
1571 bxe_post_dmae(struct bxe_softc    *sc,
1572               struct dmae_command *dmae,
1573               int                 idx)
1574 {
1575     uint32_t cmd_offset;
1576     int i;
1577
1578     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_command) * idx));
1579     for (i = 0; i < ((sizeof(struct dmae_command) / 4)); i++) {
1580         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1581     }
1582
1583     REG_WR(sc, dmae_reg_go_c[idx], 1);
1584 }
1585
1586 uint32_t
1587 bxe_dmae_opcode_add_comp(uint32_t opcode,
1588                          uint8_t  comp_type)
1589 {
1590     return (opcode | ((comp_type << DMAE_COMMAND_C_DST_SHIFT) |
1591                       DMAE_COMMAND_C_TYPE_ENABLE));
1592 }
1593
1594 uint32_t
1595 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1596 {
1597     return (opcode & ~DMAE_COMMAND_SRC_RESET);
1598 }
1599
1600 uint32_t
1601 bxe_dmae_opcode(struct bxe_softc *sc,
1602                 uint8_t          src_type,
1603                 uint8_t          dst_type,
1604                 uint8_t          with_comp,
1605                 uint8_t          comp_type)
1606 {
1607     uint32_t opcode = 0;
1608
1609     opcode |= ((src_type << DMAE_COMMAND_SRC_SHIFT) |
1610                (dst_type << DMAE_COMMAND_DST_SHIFT));
1611
1612     opcode |= (DMAE_COMMAND_SRC_RESET | DMAE_COMMAND_DST_RESET);
1613
1614     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1615
1616     opcode |= ((SC_VN(sc) << DMAE_COMMAND_E1HVN_SHIFT) |
1617                (SC_VN(sc) << DMAE_COMMAND_DST_VN_SHIFT));
1618
1619     opcode |= (DMAE_COM_SET_ERR << DMAE_COMMAND_ERR_POLICY_SHIFT);
1620
1621 #ifdef __BIG_ENDIAN
1622     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1623 #else
1624     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1625 #endif
1626
1627     if (with_comp) {
1628         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1629     }
1630
1631     return (opcode);
1632 }
1633
1634 static void
1635 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1636                         struct dmae_command *dmae,
1637                         uint8_t             src_type,
1638                         uint8_t             dst_type)
1639 {
1640     memset(dmae, 0, sizeof(struct dmae_command));
1641
1642     /* set the opcode */
1643     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1644                                    TRUE, DMAE_COMP_PCI);
1645
1646     /* fill in the completion parameters */
1647     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1648     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1649     dmae->comp_val     = DMAE_COMP_VAL;
1650 }
1651
1652 /* issue a DMAE command over the init channel and wait for completion */
1653 static int
1654 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1655                          struct dmae_command *dmae)
1656 {
1657     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1658     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1659
1660     BXE_DMAE_LOCK(sc);
1661
1662     /* reset completion */
1663     *wb_comp = 0;
1664
1665     /* post the command on the channel used for initializations */
1666     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1667
1668     /* wait for completion */
1669     DELAY(5);
1670
1671     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1672         if (!timeout ||
1673             (sc->recovery_state != BXE_RECOVERY_DONE &&
1674              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1675             BLOGE(sc, "DMAE timeout!\n");
1676             BXE_DMAE_UNLOCK(sc);
1677             return (DMAE_TIMEOUT);
1678         }
1679
1680         timeout--;
1681         DELAY(50);
1682     }
1683
1684     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1685         BLOGE(sc, "DMAE PCI error!\n");
1686         BXE_DMAE_UNLOCK(sc);
1687         return (DMAE_PCI_ERROR);
1688     }
1689
1690     BXE_DMAE_UNLOCK(sc);
1691     return (0);
1692 }
1693
1694 void
1695 bxe_read_dmae(struct bxe_softc *sc,
1696               uint32_t         src_addr,
1697               uint32_t         len32)
1698 {
1699     struct dmae_command dmae;
1700     uint32_t *data;
1701     int i, rc;
1702
1703     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1704
1705     if (!sc->dmae_ready) {
1706         data = BXE_SP(sc, wb_data[0]);
1707
1708         for (i = 0; i < len32; i++) {
1709             data[i] = (CHIP_IS_E1(sc)) ?
1710                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1711                           REG_RD(sc, (src_addr + (i * 4)));
1712         }
1713
1714         return;
1715     }
1716
1717     /* set opcode and fixed command fields */
1718     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1719
1720     /* fill in addresses and len */
1721     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1722     dmae.src_addr_hi = 0;
1723     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1724     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1725     dmae.len         = len32;
1726
1727     /* issue the command and wait for completion */
1728     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1729         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1730     };
1731 }
1732
1733 void
1734 bxe_write_dmae(struct bxe_softc *sc,
1735                bus_addr_t       dma_addr,
1736                uint32_t         dst_addr,
1737                uint32_t         len32)
1738 {
1739     struct dmae_command dmae;
1740     int rc;
1741
1742     if (!sc->dmae_ready) {
1743         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1744
1745         if (CHIP_IS_E1(sc)) {
1746             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1747         } else {
1748             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1749         }
1750
1751         return;
1752     }
1753
1754     /* set opcode and fixed command fields */
1755     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1756
1757     /* fill in addresses and len */
1758     dmae.src_addr_lo = U64_LO(dma_addr);
1759     dmae.src_addr_hi = U64_HI(dma_addr);
1760     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1761     dmae.dst_addr_hi = 0;
1762     dmae.len         = len32;
1763
1764     /* issue the command and wait for completion */
1765     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1766         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1767     }
1768 }
1769
1770 void
1771 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1772                         bus_addr_t       phys_addr,
1773                         uint32_t         addr,
1774                         uint32_t         len)
1775 {
1776     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1777     int offset = 0;
1778
1779     while (len > dmae_wr_max) {
1780         bxe_write_dmae(sc,
1781                        (phys_addr + offset), /* src DMA address */
1782                        (addr + offset),      /* dst GRC address */
1783                        dmae_wr_max);
1784         offset += (dmae_wr_max * 4);
1785         len -= dmae_wr_max;
1786     }
1787
1788     bxe_write_dmae(sc,
1789                    (phys_addr + offset), /* src DMA address */
1790                    (addr + offset),      /* dst GRC address */
1791                    len);
1792 }
1793
1794 void
1795 bxe_set_ctx_validation(struct bxe_softc   *sc,
1796                        struct eth_context *cxt,
1797                        uint32_t           cid)
1798 {
1799     /* ustorm cxt validation */
1800     cxt->ustorm_ag_context.cdu_usage =
1801         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1802             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1803     /* xcontext validation */
1804     cxt->xstorm_ag_context.cdu_reserved =
1805         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1806             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1807 }
1808
1809 static void
1810 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1811                             uint8_t          port,
1812                             uint8_t          fw_sb_id,
1813                             uint8_t          sb_index,
1814                             uint8_t          ticks)
1815 {
1816     uint32_t addr =
1817         (BAR_CSTRORM_INTMEM +
1818          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1819
1820     REG_WR8(sc, addr, ticks);
1821
1822     BLOGD(sc, DBG_LOAD,
1823           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1824           port, fw_sb_id, sb_index, ticks);
1825 }
1826
1827 static void
1828 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1829                             uint8_t          port,
1830                             uint16_t         fw_sb_id,
1831                             uint8_t          sb_index,
1832                             uint8_t          disable)
1833 {
1834     uint32_t enable_flag =
1835         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1836     uint32_t addr =
1837         (BAR_CSTRORM_INTMEM +
1838          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1839     uint8_t flags;
1840
1841     /* clear and set */
1842     flags = REG_RD8(sc, addr);
1843     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1844     flags |= enable_flag;
1845     REG_WR8(sc, addr, flags);
1846
1847     BLOGD(sc, DBG_LOAD,
1848           "port %d fw_sb_id %d sb_index %d disable %d\n",
1849           port, fw_sb_id, sb_index, disable);
1850 }
1851
1852 void
1853 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1854                              uint8_t          fw_sb_id,
1855                              uint8_t          sb_index,
1856                              uint8_t          disable,
1857                              uint16_t         usec)
1858 {
1859     int port = SC_PORT(sc);
1860     uint8_t ticks = (usec / 4); /* XXX ??? */
1861
1862     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1863
1864     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1865     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1866 }
1867
1868 void
1869 elink_cb_udelay(struct bxe_softc *sc,
1870                 uint32_t         usecs)
1871 {
1872     DELAY(usecs);
1873 }
1874
1875 uint32_t
1876 elink_cb_reg_read(struct bxe_softc *sc,
1877                   uint32_t         reg_addr)
1878 {
1879     return (REG_RD(sc, reg_addr));
1880 }
1881
1882 void
1883 elink_cb_reg_write(struct bxe_softc *sc,
1884                    uint32_t         reg_addr,
1885                    uint32_t         val)
1886 {
1887     REG_WR(sc, reg_addr, val);
1888 }
1889
1890 void
1891 elink_cb_reg_wb_write(struct bxe_softc *sc,
1892                       uint32_t         offset,
1893                       uint32_t         *wb_write,
1894                       uint16_t         len)
1895 {
1896     REG_WR_DMAE(sc, offset, wb_write, len);
1897 }
1898
1899 void
1900 elink_cb_reg_wb_read(struct bxe_softc *sc,
1901                      uint32_t         offset,
1902                      uint32_t         *wb_write,
1903                      uint16_t         len)
1904 {
1905     REG_RD_DMAE(sc, offset, wb_write, len);
1906 }
1907
1908 uint8_t
1909 elink_cb_path_id(struct bxe_softc *sc)
1910 {
1911     return (SC_PATH(sc));
1912 }
1913
1914 void
1915 elink_cb_event_log(struct bxe_softc     *sc,
1916                    const elink_log_id_t elink_log_id,
1917                    ...)
1918 {
1919     /* XXX */
1920 #if 0
1921     //va_list ap;
1922     va_start(ap, elink_log_id);
1923     _XXX_(sc, lm_log_id, ap);
1924     va_end(ap);
1925 #endif
1926     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1927 }
1928
1929 static int
1930 bxe_set_spio(struct bxe_softc *sc,
1931              int              spio,
1932              uint32_t         mode)
1933 {
1934     uint32_t spio_reg;
1935
1936     /* Only 2 SPIOs are configurable */
1937     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1938         BLOGE(sc, "Invalid SPIO 0x%x\n", spio);
1939         return (-1);
1940     }
1941
1942     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1943
1944     /* read SPIO and mask except the float bits */
1945     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1946
1947     switch (mode) {
1948     case MISC_SPIO_OUTPUT_LOW:
1949         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1950         /* clear FLOAT and set CLR */
1951         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1952         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1953         break;
1954
1955     case MISC_SPIO_OUTPUT_HIGH:
1956         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1957         /* clear FLOAT and set SET */
1958         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1959         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1960         break;
1961
1962     case MISC_SPIO_INPUT_HI_Z:
1963         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1964         /* set FLOAT */
1965         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1966         break;
1967
1968     default:
1969         break;
1970     }
1971
1972     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1973     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1974
1975     return (0);
1976 }
1977
1978 static int
1979 bxe_gpio_read(struct bxe_softc *sc,
1980               int              gpio_num,
1981               uint8_t          port)
1982 {
1983     /* The GPIO should be swapped if swap register is set and active */
1984     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1985                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1986     int gpio_shift = (gpio_num +
1987                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1988     uint32_t gpio_mask = (1 << gpio_shift);
1989     uint32_t gpio_reg;
1990
1991     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1992         BLOGE(sc, "Invalid GPIO %d\n", gpio_num);
1993         return (-1);
1994     }
1995
1996     /* read GPIO value */
1997     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1998
1999     /* get the requested pin value */
2000     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
2001 }
2002
2003 static int
2004 bxe_gpio_write(struct bxe_softc *sc,
2005                int              gpio_num,
2006                uint32_t         mode,
2007                uint8_t          port)
2008 {
2009     /* The GPIO should be swapped if swap register is set and active */
2010     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2011                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2012     int gpio_shift = (gpio_num +
2013                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2014     uint32_t gpio_mask = (1 << gpio_shift);
2015     uint32_t gpio_reg;
2016
2017     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2018         BLOGE(sc, "Invalid GPIO %d\n", gpio_num);
2019         return (-1);
2020     }
2021
2022     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2023
2024     /* read GPIO and mask except the float bits */
2025     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
2026
2027     switch (mode) {
2028     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2029         BLOGD(sc, DBG_PHY,
2030               "Set GPIO %d (shift %d) -> output low\n",
2031               gpio_num, gpio_shift);
2032         /* clear FLOAT and set CLR */
2033         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
2034         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
2035         break;
2036
2037     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2038         BLOGD(sc, DBG_PHY,
2039               "Set GPIO %d (shift %d) -> output high\n",
2040               gpio_num, gpio_shift);
2041         /* clear FLOAT and set SET */
2042         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
2043         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
2044         break;
2045
2046     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2047         BLOGD(sc, DBG_PHY,
2048               "Set GPIO %d (shift %d) -> input\n",
2049               gpio_num, gpio_shift);
2050         /* set FLOAT */
2051         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
2052         break;
2053
2054     default:
2055         break;
2056     }
2057
2058     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2059     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2060
2061     return (0);
2062 }
2063
2064 static int
2065 bxe_gpio_mult_write(struct bxe_softc *sc,
2066                     uint8_t          pins,
2067                     uint32_t         mode)
2068 {
2069     uint32_t gpio_reg;
2070
2071     /* any port swapping should be handled by caller */
2072
2073     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2074
2075     /* read GPIO and mask except the float bits */
2076     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
2077     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2078     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
2079     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
2080
2081     switch (mode) {
2082     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2083         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
2084         /* set CLR */
2085         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
2086         break;
2087
2088     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2089         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
2090         /* set SET */
2091         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2092         break;
2093
2094     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2095         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2096         /* set FLOAT */
2097         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2098         break;
2099
2100     default:
2101         BLOGE(sc, "Invalid GPIO mode assignment %d\n", mode);
2102         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2103         return (-1);
2104     }
2105
2106     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2107     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2108
2109     return (0);
2110 }
2111
2112 static int
2113 bxe_gpio_int_write(struct bxe_softc *sc,
2114                    int              gpio_num,
2115                    uint32_t         mode,
2116                    uint8_t          port)
2117 {
2118     /* The GPIO should be swapped if swap register is set and active */
2119     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2120                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2121     int gpio_shift = (gpio_num +
2122                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2123     uint32_t gpio_mask = (1 << gpio_shift);
2124     uint32_t gpio_reg;
2125
2126     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2127         BLOGE(sc, "Invalid GPIO %d\n", gpio_num);
2128         return (-1);
2129     }
2130
2131     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2132
2133     /* read GPIO int */
2134     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2135
2136     switch (mode) {
2137     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2138         BLOGD(sc, DBG_PHY,
2139               "Clear GPIO INT %d (shift %d) -> output low\n",
2140               gpio_num, gpio_shift);
2141         /* clear SET and set CLR */
2142         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2143         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2144         break;
2145
2146     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2147         BLOGD(sc, DBG_PHY,
2148               "Set GPIO INT %d (shift %d) -> output high\n",
2149               gpio_num, gpio_shift);
2150         /* clear CLR and set SET */
2151         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2152         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2153         break;
2154
2155     default:
2156         break;
2157     }
2158
2159     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2160     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2161
2162     return (0);
2163 }
2164
2165 uint32_t
2166 elink_cb_gpio_read(struct bxe_softc *sc,
2167                    uint16_t         gpio_num,
2168                    uint8_t          port)
2169 {
2170     return (bxe_gpio_read(sc, gpio_num, port));
2171 }
2172
2173 uint8_t
2174 elink_cb_gpio_write(struct bxe_softc *sc,
2175                     uint16_t         gpio_num,
2176                     uint8_t          mode, /* 0=low 1=high */
2177                     uint8_t          port)
2178 {
2179     return (bxe_gpio_write(sc, gpio_num, mode, port));
2180 }
2181
2182 uint8_t
2183 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2184                          uint8_t          pins,
2185                          uint8_t          mode) /* 0=low 1=high */
2186 {
2187     return (bxe_gpio_mult_write(sc, pins, mode));
2188 }
2189
2190 uint8_t
2191 elink_cb_gpio_int_write(struct bxe_softc *sc,
2192                         uint16_t         gpio_num,
2193                         uint8_t          mode, /* 0=low 1=high */
2194                         uint8_t          port)
2195 {
2196     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2197 }
2198
2199 void
2200 elink_cb_notify_link_changed(struct bxe_softc *sc)
2201 {
2202     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2203                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2204 }
2205
2206 /* send the MCP a request, block until there is a reply */
2207 uint32_t
2208 elink_cb_fw_command(struct bxe_softc *sc,
2209                     uint32_t         command,
2210                     uint32_t         param)
2211 {
2212     int mb_idx = SC_FW_MB_IDX(sc);
2213     uint32_t seq;
2214     uint32_t rc = 0;
2215     uint32_t cnt = 1;
2216     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2217
2218     BXE_FWMB_LOCK(sc);
2219
2220     seq = ++sc->fw_seq;
2221     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2222     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2223
2224     BLOGD(sc, DBG_PHY,
2225           "wrote command 0x%08x to FW MB param 0x%08x\n",
2226           (command | seq), param);
2227
2228     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2229     do {
2230         DELAY(delay * 1000);
2231         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2232     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2233
2234     BLOGD(sc, DBG_PHY,
2235           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2236           cnt*delay, rc, seq);
2237
2238     /* is this a reply to our command? */
2239     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2240         rc &= FW_MSG_CODE_MASK;
2241     } else {
2242         /* Ruh-roh! */
2243         BLOGE(sc, "FW failed to respond!\n");
2244         // XXX bxe_fw_dump(sc);
2245         rc = 0;
2246     }
2247
2248     BXE_FWMB_UNLOCK(sc);
2249     return (rc);
2250 }
2251
2252 static uint32_t
2253 bxe_fw_command(struct bxe_softc *sc,
2254                uint32_t         command,
2255                uint32_t         param)
2256 {
2257     return (elink_cb_fw_command(sc, command, param));
2258 }
2259
2260 static void
2261 __storm_memset_dma_mapping(struct bxe_softc *sc,
2262                            uint32_t         addr,
2263                            bus_addr_t       mapping)
2264 {
2265     REG_WR(sc, addr, U64_LO(mapping));
2266     REG_WR(sc, (addr + 4), U64_HI(mapping));
2267 }
2268
2269 static void
2270 storm_memset_spq_addr(struct bxe_softc *sc,
2271                       bus_addr_t       mapping,
2272                       uint16_t         abs_fid)
2273 {
2274     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2275                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2276     __storm_memset_dma_mapping(sc, addr, mapping);
2277 }
2278
2279 static void
2280 storm_memset_vf_to_pf(struct bxe_softc *sc,
2281                       uint16_t         abs_fid,
2282                       uint16_t         pf_id)
2283 {
2284     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2285     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2286     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2287     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2288 }
2289
2290 static void
2291 storm_memset_func_en(struct bxe_softc *sc,
2292                      uint16_t         abs_fid,
2293                      uint8_t          enable)
2294 {
2295     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2296     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2297     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2298     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2299 }
2300
2301 static void
2302 storm_memset_eq_data(struct bxe_softc       *sc,
2303                      struct event_ring_data *eq_data,
2304                      uint16_t               pfid)
2305 {
2306     uint32_t addr;
2307     size_t size;
2308
2309     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2310     size = sizeof(struct event_ring_data);
2311     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2312 }
2313
2314 static void
2315 storm_memset_eq_prod(struct bxe_softc *sc,
2316                      uint16_t         eq_prod,
2317                      uint16_t         pfid)
2318 {
2319     uint32_t addr = (BAR_CSTRORM_INTMEM +
2320                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2321     REG_WR16(sc, addr, eq_prod);
2322 }
2323
2324 /*
2325  * Post a slowpath command.
2326  *
2327  * A slowpath command is used to propogate a configuration change through
2328  * the controller in a controlled manner, allowing each STORM processor and
2329  * other H/W blocks to phase in the change.  The commands sent on the
2330  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2331  * completion of the ramrod will occur in different ways.  Here's a
2332  * breakdown of ramrods and how they complete:
2333  *
2334  * RAMROD_CMD_ID_ETH_PORT_SETUP
2335  *   Used to setup the leading connection on a port.  Completes on the
2336  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2337  *
2338  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2339  *   Used to setup an additional connection on a port.  Completes on the
2340  *   RCQ of the multi-queue/RSS connection being initialized.
2341  *
2342  * RAMROD_CMD_ID_ETH_STAT_QUERY
2343  *   Used to force the storm processors to update the statistics database
2344  *   in host memory.  This ramrod is send on the leading connection CID and
2345  *   completes as an index increment of the CSTORM on the default status
2346  *   block.
2347  *
2348  * RAMROD_CMD_ID_ETH_UPDATE
2349  *   Used to update the state of the leading connection, usually to udpate
2350  *   the RSS indirection table.  Completes on the RCQ of the leading
2351  *   connection. (Not currently used under FreeBSD until OS support becomes
2352  *   available.)
2353  *
2354  * RAMROD_CMD_ID_ETH_HALT
2355  *   Used when tearing down a connection prior to driver unload.  Completes
2356  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2357  *   use this on the leading connection.
2358  *
2359  * RAMROD_CMD_ID_ETH_SET_MAC
2360  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2361  *   the RCQ of the leading connection.
2362  *
2363  * RAMROD_CMD_ID_ETH_CFC_DEL
2364  *   Used when tearing down a conneciton prior to driver unload.  Completes
2365  *   on the RCQ of the leading connection (since the current connection
2366  *   has been completely removed from controller memory).
2367  *
2368  * RAMROD_CMD_ID_ETH_PORT_DEL
2369  *   Used to tear down the leading connection prior to driver unload,
2370  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2371  *   default status block.
2372  *
2373  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2374  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2375  *   RSS connection that is being offloaded.  (Not currently used under
2376  *   FreeBSD.)
2377  *
2378  * There can only be one command pending per function.
2379  *
2380  * Returns:
2381  *   0 = Success, !0 = Failure.
2382  */
2383
2384 /* must be called under the spq lock */
2385 static inline
2386 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2387 {
2388     struct eth_spe *next_spe = sc->spq_prod_bd;
2389
2390     if (sc->spq_prod_bd == sc->spq_last_bd) {
2391         /* wrap back to the first eth_spq */
2392         sc->spq_prod_bd = sc->spq;
2393         sc->spq_prod_idx = 0;
2394     } else {
2395         sc->spq_prod_bd++;
2396         sc->spq_prod_idx++;
2397     }
2398
2399     return (next_spe);
2400 }
2401
2402 /* must be called under the spq lock */
2403 static inline
2404 void bxe_sp_prod_update(struct bxe_softc *sc)
2405 {
2406     int func = SC_FUNC(sc);
2407
2408     /*
2409      * Make sure that BD data is updated before writing the producer.
2410      * BD data is written to the memory, the producer is read from the
2411      * memory, thus we need a full memory barrier to ensure the ordering.
2412      */
2413     mb();
2414
2415     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2416              sc->spq_prod_idx);
2417
2418     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2419                       BUS_SPACE_BARRIER_WRITE);
2420 }
2421
2422 /**
2423  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2424  *
2425  * @cmd:      command to check
2426  * @cmd_type: command type
2427  */
2428 static inline
2429 int bxe_is_contextless_ramrod(int cmd,
2430                               int cmd_type)
2431 {
2432     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2433         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2434         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2435         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2436         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2437         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2438         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2439         return (TRUE);
2440     } else {
2441         return (FALSE);
2442     }
2443 }
2444
2445 /**
2446  * bxe_sp_post - place a single command on an SP ring
2447  *
2448  * @sc:         driver handle
2449  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2450  * @cid:        SW CID the command is related to
2451  * @data_hi:    command private data address (high 32 bits)
2452  * @data_lo:    command private data address (low 32 bits)
2453  * @cmd_type:   command type (e.g. NONE, ETH)
2454  *
2455  * SP data is handled as if it's always an address pair, thus data fields are
2456  * not swapped to little endian in upper functions. Instead this function swaps
2457  * data as if it's two uint32 fields.
2458  */
2459 int
2460 bxe_sp_post(struct bxe_softc *sc,
2461             int              command,
2462             int              cid,
2463             uint32_t         data_hi,
2464             uint32_t         data_lo,
2465             int              cmd_type)
2466 {
2467     struct eth_spe *spe;
2468     uint16_t type;
2469     int common;
2470
2471     common = bxe_is_contextless_ramrod(command, cmd_type);
2472
2473     BXE_SP_LOCK(sc);
2474
2475     if (common) {
2476         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2477             BLOGE(sc, "EQ ring is full!\n");
2478             BXE_SP_UNLOCK(sc);
2479             return (-1);
2480         }
2481     } else {
2482         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2483             BLOGE(sc, "SPQ ring is full!\n");
2484             BXE_SP_UNLOCK(sc);
2485             return (-1);
2486         }
2487     }
2488
2489     spe = bxe_sp_get_next(sc);
2490
2491     /* CID needs port number to be encoded int it */
2492     spe->hdr.conn_and_cmd_data =
2493         htole32((command << SPE_HDR_CMD_ID_SHIFT) | HW_CID(sc, cid));
2494
2495     type = (cmd_type << SPE_HDR_CONN_TYPE_SHIFT) & SPE_HDR_CONN_TYPE;
2496
2497     /* TBD: Check if it works for VFs */
2498     type |= ((SC_FUNC(sc) << SPE_HDR_FUNCTION_ID_SHIFT) &
2499              SPE_HDR_FUNCTION_ID);
2500
2501     spe->hdr.type = htole16(type);
2502
2503     spe->data.update_data_addr.hi = htole32(data_hi);
2504     spe->data.update_data_addr.lo = htole32(data_lo);
2505
2506     /*
2507      * It's ok if the actual decrement is issued towards the memory
2508      * somewhere between the lock and unlock. Thus no more explict
2509      * memory barrier is needed.
2510      */
2511     if (common) {
2512         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2513     } else {
2514         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2515     }
2516
2517     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2518     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2519           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2520     BLOGD(sc, DBG_SP,
2521           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2522           sc->spq_prod_idx,
2523           (uint32_t)U64_HI(sc->spq_dma.paddr),
2524           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2525           command,
2526           common,
2527           HW_CID(sc, cid),
2528           data_hi,
2529           data_lo,
2530           type,
2531           atomic_load_acq_long(&sc->cq_spq_left),
2532           atomic_load_acq_long(&sc->eq_spq_left));
2533
2534     bxe_sp_prod_update(sc);
2535
2536     BXE_SP_UNLOCK(sc);
2537     return (0);
2538 }
2539
2540 /**
2541  * bxe_debug_print_ind_table - prints the indirection table configuration.
2542  *
2543  * @sc: driver hanlde
2544  * @p:  pointer to rss configuration
2545  */
2546 #if 0
2547 static void
2548 bxe_debug_print_ind_table(struct bxe_softc               *sc,
2549                           struct ecore_config_rss_params *p)
2550 {
2551     int i;
2552
2553     BLOGD(sc, DBG_LOAD, "Setting indirection table to:\n");
2554     BLOGD(sc, DBG_LOAD, "    0x0000: ");
2555     for (i = 0; i < T_ETH_INDIRECTION_TABLE_SIZE; i++) {
2556         BLOGD(sc, DBG_LOAD, "0x%02x ", p->ind_table[i]);
2557
2558         /* Print 4 bytes in a line */
2559         if ((i + 1 < T_ETH_INDIRECTION_TABLE_SIZE) &&
2560             (((i + 1) & 0x3) == 0)) {
2561             BLOGD(sc, DBG_LOAD, "\n");
2562             BLOGD(sc, DBG_LOAD, "0x%04x: ", i + 1);
2563         }
2564     }
2565
2566     BLOGD(sc, DBG_LOAD, "\n");
2567 }
2568 #endif
2569
2570 /*
2571  * FreeBSD Device probe function.
2572  *
2573  * Compares the device found to the driver's list of supported devices and
2574  * reports back to the bsd loader whether this is the right driver for the device.
2575  * This is the driver entry function called from the "kldload" command.
2576  *
2577  * Returns:
2578  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2579  */
2580 static int
2581 bxe_probe(device_t dev)
2582 {
2583     struct bxe_softc *sc;
2584     struct bxe_device_type *t;
2585     char *descbuf;
2586     uint16_t did, sdid, svid, vid;
2587
2588     /* Find our device structure */
2589     sc = device_get_softc(dev);
2590     sc->dev = dev;
2591     t = bxe_devs;
2592
2593     /* Get the data for the device to be probed. */
2594     vid  = pci_get_vendor(dev);
2595     did  = pci_get_device(dev);
2596     svid = pci_get_subvendor(dev);
2597     sdid = pci_get_subdevice(dev);
2598
2599     BLOGD(sc, DBG_LOAD,
2600           "%s(); VID = 0x%04X, DID = 0x%04X, SVID = 0x%04X, "
2601           "SDID = 0x%04X\n", __FUNCTION__, vid, did, svid, sdid);
2602
2603     /* Look through the list of known devices for a match. */
2604     while (t->bxe_name != NULL) {
2605         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2606             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2607             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2608             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2609             if (descbuf == NULL)
2610                 return (ENOMEM);
2611
2612             /* Print out the device identity. */
2613             snprintf(descbuf, BXE_DEVDESC_MAX,
2614                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2615                      (((pci_read_config(dev, PCIR_REVID, 4) &
2616                         0xf0) >> 4) + 'A'),
2617                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2618                      BXE_DRIVER_VERSION);
2619
2620             device_set_desc_copy(dev, descbuf);
2621             free(descbuf, M_TEMP);
2622             return (BUS_PROBE_DEFAULT);
2623         }
2624         t++;
2625     }
2626
2627     return (ENXIO);
2628 }
2629
2630 static void
2631 bxe_init_mutexes(struct bxe_softc *sc)
2632 {
2633 #ifdef BXE_CORE_LOCK_SX
2634     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2635              "bxe%d_core_lock", sc->unit);
2636     sx_init(&sc->core_sx, sc->core_sx_name);
2637 #else
2638     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2639              "bxe%d_core_lock", sc->unit);
2640     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2641 #endif
2642
2643     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2644              "bxe%d_sp_lock", sc->unit);
2645     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2646
2647     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2648              "bxe%d_dmae_lock", sc->unit);
2649     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2650
2651     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2652              "bxe%d_phy_lock", sc->unit);
2653     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2654
2655     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2656              "bxe%d_fwmb_lock", sc->unit);
2657     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2658
2659     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2660              "bxe%d_print_lock", sc->unit);
2661     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2662
2663     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2664              "bxe%d_stats_lock", sc->unit);
2665     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2666
2667     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2668              "bxe%d_mcast_lock", sc->unit);
2669     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2670 }
2671
2672 static void
2673 bxe_release_mutexes(struct bxe_softc *sc)
2674 {
2675 #ifdef BXE_CORE_LOCK_SX
2676     sx_destroy(&sc->core_sx);
2677 #else
2678     if (mtx_initialized(&sc->core_mtx)) {
2679         mtx_destroy(&sc->core_mtx);
2680     }
2681 #endif
2682
2683     if (mtx_initialized(&sc->sp_mtx)) {
2684         mtx_destroy(&sc->sp_mtx);
2685     }
2686
2687     if (mtx_initialized(&sc->dmae_mtx)) {
2688         mtx_destroy(&sc->dmae_mtx);
2689     }
2690
2691     if (mtx_initialized(&sc->port.phy_mtx)) {
2692         mtx_destroy(&sc->port.phy_mtx);
2693     }
2694
2695     if (mtx_initialized(&sc->fwmb_mtx)) {
2696         mtx_destroy(&sc->fwmb_mtx);
2697     }
2698
2699     if (mtx_initialized(&sc->print_mtx)) {
2700         mtx_destroy(&sc->print_mtx);
2701     }
2702
2703     if (mtx_initialized(&sc->stats_mtx)) {
2704         mtx_destroy(&sc->stats_mtx);
2705     }
2706
2707     if (mtx_initialized(&sc->mcast_mtx)) {
2708         mtx_destroy(&sc->mcast_mtx);
2709     }
2710 }
2711
2712 static void
2713 bxe_tx_disable(struct bxe_softc* sc)
2714 {
2715     if_t ifp = sc->ifp;
2716
2717     /* tell the stack the driver is stopped and TX queue is full */
2718     if (ifp !=  NULL) {
2719         if_setdrvflags(ifp, 0);
2720     }
2721 }
2722
2723 static void
2724 bxe_drv_pulse(struct bxe_softc *sc)
2725 {
2726     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2727              sc->fw_drv_pulse_wr_seq);
2728 }
2729
2730 static inline uint16_t
2731 bxe_tx_avail(struct bxe_softc *sc,
2732              struct bxe_fastpath *fp)
2733 {
2734     int16_t  used;
2735     uint16_t prod;
2736     uint16_t cons;
2737
2738     prod = fp->tx_bd_prod;
2739     cons = fp->tx_bd_cons;
2740
2741     used = SUB_S16(prod, cons);
2742
2743 #if 0
2744     KASSERT((used < 0), ("used tx bds < 0"));
2745     KASSERT((used > sc->tx_ring_size), ("used tx bds > tx_ring_size"));
2746     KASSERT(((sc->tx_ring_size - used) > MAX_TX_AVAIL),
2747             ("invalid number of tx bds used"));
2748 #endif
2749
2750     return (int16_t)(sc->tx_ring_size) - used;
2751 }
2752
2753 static inline int
2754 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2755 {
2756     uint16_t hw_cons;
2757
2758     mb(); /* status block fields can change */
2759     hw_cons = le16toh(*fp->tx_cons_sb);
2760     return (hw_cons != fp->tx_pkt_cons);
2761 }
2762
2763 static inline uint8_t
2764 bxe_has_tx_work(struct bxe_fastpath *fp)
2765 {
2766     /* expand this for multi-cos if ever supported */
2767     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2768 }
2769
2770 static inline int
2771 bxe_has_rx_work(struct bxe_fastpath *fp)
2772 {
2773     uint16_t rx_cq_cons_sb;
2774
2775     mb(); /* status block fields can change */
2776     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2777     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2778         rx_cq_cons_sb++;
2779     return (fp->rx_cq_cons != rx_cq_cons_sb);
2780 }
2781
2782 static void
2783 bxe_sp_event(struct bxe_softc    *sc,
2784              struct bxe_fastpath *fp,
2785              union eth_rx_cqe    *rr_cqe)
2786 {
2787     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2788     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2789     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2790     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2791
2792     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2793           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2794
2795 #if 0
2796     /*
2797      * If cid is within VF range, replace the slowpath object with the
2798      * one corresponding to this VF
2799      */
2800     if ((cid >= BXE_FIRST_VF_CID) && (cid < BXE_FIRST_VF_CID + BXE_VF_CIDS)) {
2801         bxe_iov_set_queue_sp_obj(sc, cid, &q_obj);
2802     }
2803 #endif
2804
2805     switch (command) {
2806     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2807         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2808         drv_cmd = ECORE_Q_CMD_UPDATE;
2809         break;
2810
2811     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2812         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2813         drv_cmd = ECORE_Q_CMD_SETUP;
2814         break;
2815
2816     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2817         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2818         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2819         break;
2820
2821     case (RAMROD_CMD_ID_ETH_HALT):
2822         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2823         drv_cmd = ECORE_Q_CMD_HALT;
2824         break;
2825
2826     case (RAMROD_CMD_ID_ETH_TERMINATE):
2827         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2828         drv_cmd = ECORE_Q_CMD_TERMINATE;
2829         break;
2830
2831     case (RAMROD_CMD_ID_ETH_EMPTY):
2832         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2833         drv_cmd = ECORE_Q_CMD_EMPTY;
2834         break;
2835
2836     default:
2837         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2838               command, fp->index);
2839         return;
2840     }
2841
2842     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2843         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2844         /*
2845          * q_obj->complete_cmd() failure means that this was
2846          * an unexpected completion.
2847          *
2848          * In this case we don't want to increase the sc->spq_left
2849          * because apparently we haven't sent this command the first
2850          * place.
2851          */
2852         // bxe_panic(sc, ("Unexpected SP completion\n"));
2853         return;
2854     }
2855
2856 #if 0
2857     /* SRIOV: reschedule any 'in_progress' operations */
2858     bxe_iov_sp_event(sc, cid, TRUE);
2859 #endif
2860
2861     atomic_add_acq_long(&sc->cq_spq_left, 1);
2862
2863     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2864           atomic_load_acq_long(&sc->cq_spq_left));
2865
2866 #if 0
2867     if ((drv_cmd == ECORE_Q_CMD_UPDATE) && (IS_FCOE_FP(fp)) &&
2868         (!!bxe_test_bit(ECORE_AFEX_FCOE_Q_UPDATE_PENDING, &sc->sp_state))) {
2869         /*
2870          * If Queue update ramrod is completed for last Queue in AFEX VIF set
2871          * flow, then ACK MCP at the end. Mark pending ACK to MCP bit to
2872          * prevent case that both bits are cleared. At the end of load/unload
2873          * driver checks that sp_state is cleared and this order prevents
2874          * races.
2875          */
2876         bxe_set_bit(ECORE_AFEX_PENDING_VIFSET_MCP_ACK, &sc->sp_state);
2877         wmb();
2878         bxe_clear_bit(ECORE_AFEX_FCOE_Q_UPDATE_PENDING, &sc->sp_state);
2879
2880         /* schedule the sp task as MCP ack is required */
2881         bxe_schedule_sp_task(sc);
2882     }
2883 #endif
2884 }
2885
2886 /*
2887  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2888  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2889  * the current aggregation queue as in-progress.
2890  */
2891 static void
2892 bxe_tpa_start(struct bxe_softc            *sc,
2893               struct bxe_fastpath         *fp,
2894               uint16_t                    queue,
2895               uint16_t                    cons,
2896               uint16_t                    prod,
2897               struct eth_fast_path_rx_cqe *cqe)
2898 {
2899     struct bxe_sw_rx_bd tmp_bd;
2900     struct bxe_sw_rx_bd *rx_buf;
2901     struct eth_rx_bd *rx_bd;
2902     int max_agg_queues;
2903     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2904     uint16_t index;
2905
2906     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2907                        "cons=%d prod=%d\n",
2908           fp->index, queue, cons, prod);
2909
2910     max_agg_queues = MAX_AGG_QS(sc);
2911
2912     KASSERT((queue < max_agg_queues),
2913             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2914              fp->index, queue, max_agg_queues));
2915
2916     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2917             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2918              fp->index, queue));
2919
2920     /* copy the existing mbuf and mapping from the TPA pool */
2921     tmp_bd = tpa_info->bd;
2922
2923     if (tmp_bd.m == NULL) {
2924         BLOGE(sc, "fp[%02d].tpa[%02d] mbuf not allocated!\n",
2925               fp->index, queue);
2926         /* XXX Error handling? */
2927         return;
2928     }
2929
2930     /* change the TPA queue to the start state */
2931     tpa_info->state            = BXE_TPA_STATE_START;
2932     tpa_info->placement_offset = cqe->placement_offset;
2933     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2934     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2935     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2936
2937     fp->rx_tpa_queue_used |= (1 << queue);
2938
2939     /*
2940      * If all the buffer descriptors are filled with mbufs then fill in
2941      * the current consumer index with a new BD. Else if a maximum Rx
2942      * buffer limit is imposed then fill in the next producer index.
2943      */
2944     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2945                 prod : cons;
2946
2947     /* move the received mbuf and mapping to TPA pool */
2948     tpa_info->bd = fp->rx_mbuf_chain[cons];
2949
2950     /* release any existing RX BD mbuf mappings */
2951     if (cons != index) {
2952         rx_buf = &fp->rx_mbuf_chain[cons];
2953
2954         if (rx_buf->m_map != NULL) {
2955             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2956                             BUS_DMASYNC_POSTREAD);
2957             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2958         }
2959
2960         /*
2961          * We get here when the maximum number of rx buffers is less than
2962          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2963          * it out here without concern of a memory leak.
2964          */
2965         fp->rx_mbuf_chain[cons].m = NULL;
2966     }
2967
2968     /* update the Rx SW BD with the mbuf info from the TPA pool */
2969     fp->rx_mbuf_chain[index] = tmp_bd;
2970
2971     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2972     rx_bd = &fp->rx_chain[index];
2973     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2974     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2975 }
2976
2977 /*
2978  * When a TPA aggregation is completed, loop through the individual mbufs
2979  * of the aggregation, combining them into a single mbuf which will be sent
2980  * up the stack. Refill all freed SGEs with mbufs as we go along.
2981  */
2982 static int
2983 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2984                    struct bxe_fastpath       *fp,
2985                    struct bxe_sw_tpa_info    *tpa_info,
2986                    uint16_t                  queue,
2987                    uint16_t                  pages,
2988                    struct mbuf               *m,
2989                                struct eth_end_agg_rx_cqe *cqe,
2990                    uint16_t                  cqe_idx)
2991 {
2992     struct mbuf *m_frag;
2993     uint32_t frag_len, frag_size, i;
2994     uint16_t sge_idx;
2995     int rc = 0;
2996     int j;
2997
2998     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2999
3000     BLOGD(sc, DBG_LRO,
3001           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
3002           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
3003
3004     /* make sure the aggregated frame is not too big to handle */
3005     if (pages > 8 * PAGES_PER_SGE) {
3006         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
3007                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
3008               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
3009               tpa_info->len_on_bd, frag_size);
3010         bxe_panic(sc, ("sge page count error\n"));
3011         return (EINVAL);
3012     }
3013
3014     /*
3015      * Scan through the scatter gather list pulling individual mbufs into a
3016      * single mbuf for the host stack.
3017      */
3018     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
3019         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
3020
3021         /*
3022          * Firmware gives the indices of the SGE as if the ring is an array
3023          * (meaning that the "next" element will consume 2 indices).
3024          */
3025         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
3026
3027         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
3028                            "sge_idx=%d frag_size=%d frag_len=%d\n",
3029               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
3030
3031         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3032
3033         /* allocate a new mbuf for the SGE */
3034         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3035         if (rc) {
3036             /* Leave all remaining SGEs in the ring! */
3037             return (rc);
3038         }
3039
3040         /* update the fragment length */
3041         m_frag->m_len = frag_len;
3042
3043         /* concatenate the fragment to the head mbuf */
3044         m_cat(m, m_frag);
3045         fp->eth_q_stats.mbuf_alloc_sge--;
3046
3047         /* update the TPA mbuf size and remaining fragment size */
3048         m->m_pkthdr.len += frag_len;
3049         frag_size -= frag_len;
3050     }
3051
3052     BLOGD(sc, DBG_LRO,
3053           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
3054           fp->index, queue, frag_size);
3055
3056     return (rc);
3057 }
3058
3059 static inline void
3060 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
3061 {
3062     int i, j;
3063
3064     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
3065         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
3066
3067         for (j = 0; j < 2; j++) {
3068             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
3069             idx--;
3070         }
3071     }
3072 }
3073
3074 static inline void
3075 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
3076 {
3077     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
3078     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
3079
3080     /*
3081      * Clear the two last indices in the page to 1. These are the indices that
3082      * correspond to the "next" element, hence will never be indicated and
3083      * should be removed from the calculations.
3084      */
3085     bxe_clear_sge_mask_next_elems(fp);
3086 }
3087
3088 static inline void
3089 bxe_update_last_max_sge(struct bxe_fastpath *fp,
3090                         uint16_t            idx)
3091 {
3092     uint16_t last_max = fp->last_max_sge;
3093
3094     if (SUB_S16(idx, last_max) > 0) {
3095         fp->last_max_sge = idx;
3096     }
3097 }
3098
3099 static inline void
3100 bxe_update_sge_prod(struct bxe_softc          *sc,
3101                     struct bxe_fastpath       *fp,
3102                     uint16_t                  sge_len,
3103                     struct eth_end_agg_rx_cqe *cqe)
3104 {
3105     uint16_t last_max, last_elem, first_elem;
3106     uint16_t delta = 0;
3107     uint16_t i;
3108
3109     if (!sge_len) {
3110         return;
3111     }
3112
3113     /* first mark all used pages */
3114     for (i = 0; i < sge_len; i++) {
3115         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
3116                             RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[i])));
3117     }
3118
3119     BLOGD(sc, DBG_LRO,
3120           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
3121           fp->index, sge_len - 1,
3122           le16toh(cqe->sgl_or_raw_data.sgl[sge_len - 1]));
3123
3124     /* assume that the last SGE index is the biggest */
3125     bxe_update_last_max_sge(fp,
3126                             le16toh(cqe->sgl_or_raw_data.sgl[sge_len - 1]));
3127
3128     last_max = RX_SGE(fp->last_max_sge);
3129     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
3130     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
3131
3132     /* if ring is not full */
3133     if (last_elem + 1 != first_elem) {
3134         last_elem++;
3135     }
3136
3137     /* now update the prod */
3138     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
3139         if (__predict_true(fp->sge_mask[i])) {
3140             break;
3141         }
3142
3143         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3144         delta += BIT_VEC64_ELEM_SZ;
3145     }
3146
3147     if (delta > 0) {
3148         fp->rx_sge_prod += delta;
3149         /* clear page-end entries */
3150         bxe_clear_sge_mask_next_elems(fp);
3151     }
3152
3153     BLOGD(sc, DBG_LRO,
3154           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3155           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3156 }
3157
3158 /*
3159  * The aggregation on the current TPA queue has completed. Pull the individual
3160  * mbuf fragments together into a single mbuf, perform all necessary checksum
3161  * calculations, and send the resuting mbuf to the stack.
3162  */
3163 static void
3164 bxe_tpa_stop(struct bxe_softc          *sc,
3165              struct bxe_fastpath       *fp,
3166              struct bxe_sw_tpa_info    *tpa_info,
3167              uint16_t                  queue,
3168              uint16_t                  pages,
3169                          struct eth_end_agg_rx_cqe *cqe,
3170              uint16_t                  cqe_idx)
3171 {
3172     if_t ifp = sc->ifp;
3173     struct mbuf *m;
3174     int rc = 0;
3175
3176     BLOGD(sc, DBG_LRO,
3177           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3178           fp->index, queue, tpa_info->placement_offset,
3179           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3180
3181     m = tpa_info->bd.m;
3182
3183     /* allocate a replacement before modifying existing mbuf */
3184     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3185     if (rc) {
3186         /* drop the frame and log an error */
3187         fp->eth_q_stats.rx_soft_errors++;
3188         goto bxe_tpa_stop_exit;
3189     }
3190
3191     /* we have a replacement, fixup the current mbuf */
3192     m_adj(m, tpa_info->placement_offset);
3193     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3194
3195     /* mark the checksums valid (taken care of by the firmware) */
3196     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3197     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3198     m->m_pkthdr.csum_data = 0xffff;
3199     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3200                                CSUM_IP_VALID   |
3201                                CSUM_DATA_VALID |
3202                                CSUM_PSEUDO_HDR);
3203
3204     /* aggregate all of the SGEs into a single mbuf */
3205     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3206     if (rc) {
3207         /* drop the packet and log an error */
3208         fp->eth_q_stats.rx_soft_errors++;
3209         m_freem(m);
3210     } else {
3211         if (tpa_info->parsing_flags & PARSING_FLAGS_VLAN) {
3212             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3213             m->m_flags |= M_VLANTAG;
3214         }
3215
3216         /* assign packet to this interface interface */
3217         if_setrcvif(m, ifp);
3218
3219 #if __FreeBSD_version >= 800000
3220         /* specify what RSS queue was used for this flow */
3221         m->m_pkthdr.flowid = fp->index;
3222         M_HASHTYPE_SET(m, M_HASHTYPE_OPAQUE);
3223 #endif
3224
3225         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3226         fp->eth_q_stats.rx_tpa_pkts++;
3227
3228         /* pass the frame to the stack */
3229         if_input(ifp, m);
3230     }
3231
3232     /* we passed an mbuf up the stack or dropped the frame */
3233     fp->eth_q_stats.mbuf_alloc_tpa--;
3234
3235 bxe_tpa_stop_exit:
3236
3237     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3238     fp->rx_tpa_queue_used &= ~(1 << queue);
3239 }
3240
3241 static uint8_t
3242 bxe_rxeof(struct bxe_softc    *sc,
3243           struct bxe_fastpath *fp)
3244 {
3245     if_t ifp = sc->ifp;
3246     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3247     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3248     int rx_pkts = 0;
3249     int rc;
3250
3251     BXE_FP_RX_LOCK(fp);
3252
3253     /* CQ "next element" is of the size of the regular element */
3254     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3255     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3256         hw_cq_cons++;
3257     }
3258
3259     bd_cons = fp->rx_bd_cons;
3260     bd_prod = fp->rx_bd_prod;
3261     bd_prod_fw = bd_prod;
3262     sw_cq_cons = fp->rx_cq_cons;
3263     sw_cq_prod = fp->rx_cq_prod;
3264
3265     /*
3266      * Memory barrier necessary as speculative reads of the rx
3267      * buffer can be ahead of the index in the status block
3268      */
3269     rmb();
3270
3271     BLOGD(sc, DBG_RX,
3272           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3273           fp->index, hw_cq_cons, sw_cq_cons);
3274
3275     while (sw_cq_cons != hw_cq_cons) {
3276         struct bxe_sw_rx_bd *rx_buf = NULL;
3277         union eth_rx_cqe *cqe;
3278         struct eth_fast_path_rx_cqe *cqe_fp;
3279         uint8_t cqe_fp_flags;
3280         enum eth_rx_cqe_type cqe_fp_type;
3281         uint16_t len, pad;
3282         struct mbuf *m = NULL;
3283
3284         comp_ring_cons = RCQ(sw_cq_cons);
3285         bd_prod = RX_BD(bd_prod);
3286         bd_cons = RX_BD(bd_cons);
3287
3288         cqe          = &fp->rcq_chain[comp_ring_cons];
3289         cqe_fp       = &cqe->fast_path_cqe;
3290         cqe_fp_flags = cqe_fp->type_error_flags;
3291         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3292
3293         BLOGD(sc, DBG_RX,
3294               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3295               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3296               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u\n",
3297               fp->index,
3298               hw_cq_cons,
3299               sw_cq_cons,
3300               bd_prod,
3301               bd_cons,
3302               CQE_TYPE(cqe_fp_flags),
3303               cqe_fp_flags,
3304               cqe_fp->status_flags,
3305               le32toh(cqe_fp->rss_hash_result),
3306               le16toh(cqe_fp->vlan_tag),
3307               le16toh(cqe_fp->pkt_len_or_gro_seg_len));
3308
3309         /* is this a slowpath msg? */
3310         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3311             bxe_sp_event(sc, fp, cqe);
3312             goto next_cqe;
3313         }
3314
3315         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3316
3317         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3318             struct bxe_sw_tpa_info *tpa_info;
3319             uint16_t frag_size, pages;
3320             uint8_t queue;
3321
3322 #if 0
3323             /* sanity check */
3324             if (!fp->tpa_enable &&
3325                 (CQE_TYPE_START(cqe_fp_type) || CQE_TYPE_STOP(cqe_fp_type))) {
3326                 BLOGE(sc, "START/STOP packet while !tpa_enable type (0x%x)\n",
3327                       CQE_TYPE(cqe_fp_type));
3328             }
3329 #endif
3330
3331             if (CQE_TYPE_START(cqe_fp_type)) {
3332                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3333                               bd_cons, bd_prod, cqe_fp);
3334                 m = NULL; /* packet not ready yet */
3335                 goto next_rx;
3336             }
3337
3338             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3339                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3340
3341             queue = cqe->end_agg_cqe.queue_index;
3342             tpa_info = &fp->rx_tpa_info[queue];
3343
3344             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3345                   fp->index, queue);
3346
3347             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3348                          tpa_info->len_on_bd);
3349             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3350
3351             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3352                          &cqe->end_agg_cqe, comp_ring_cons);
3353
3354             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe);
3355
3356             goto next_cqe;
3357         }
3358
3359         /* non TPA */
3360
3361         /* is this an error packet? */
3362         if (__predict_false(cqe_fp_flags &
3363                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3364             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3365             fp->eth_q_stats.rx_soft_errors++;
3366             goto next_rx;
3367         }
3368
3369         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3370         pad = cqe_fp->placement_offset;
3371
3372         m = rx_buf->m;
3373
3374         if (__predict_false(m == NULL)) {
3375             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3376                   bd_cons, fp->index);
3377             goto next_rx;
3378         }
3379
3380         /* XXX double copy if packet length under a threshold */
3381
3382         /*
3383          * If all the buffer descriptors are filled with mbufs then fill in
3384          * the current consumer index with a new BD. Else if a maximum Rx
3385          * buffer limit is imposed then fill in the next producer index.
3386          */
3387         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3388                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3389                                       bd_prod : bd_cons);
3390         if (rc != 0) {
3391             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3392                   fp->index, rc);
3393             fp->eth_q_stats.rx_soft_errors++;
3394
3395             if (sc->max_rx_bufs != RX_BD_USABLE) {
3396                 /* copy this consumer index to the producer index */
3397                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3398                        sizeof(struct bxe_sw_rx_bd));
3399                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3400             }
3401
3402             goto next_rx;
3403         }
3404
3405         /* current mbuf was detached from the bd */
3406         fp->eth_q_stats.mbuf_alloc_rx--;
3407
3408         /* we allocated a replacement mbuf, fixup the current one */
3409         m_adj(m, pad);
3410         m->m_pkthdr.len = m->m_len = len;
3411
3412         /* assign packet to this interface interface */
3413         if_setrcvif(m, ifp);
3414
3415         /* assume no hardware checksum has complated */
3416         m->m_pkthdr.csum_flags = 0;
3417
3418         /* validate checksum if offload enabled */
3419         if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
3420             /* check for a valid IP frame */
3421             if (!(cqe->fast_path_cqe.status_flags &
3422                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3423                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3424                 if (__predict_false(cqe_fp_flags &
3425                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3426                     fp->eth_q_stats.rx_hw_csum_errors++;
3427                 } else {
3428                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3429                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3430                 }
3431             }
3432
3433             /* check for a valid TCP/UDP frame */
3434             if (!(cqe->fast_path_cqe.status_flags &
3435                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3436                 if (__predict_false(cqe_fp_flags &
3437                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3438                     fp->eth_q_stats.rx_hw_csum_errors++;
3439                 } else {
3440                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3441                     m->m_pkthdr.csum_data = 0xFFFF;
3442                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3443                                                CSUM_PSEUDO_HDR);
3444                 }
3445             }
3446         }
3447
3448         /* if there is a VLAN tag then flag that info */
3449         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_VLAN) {
3450             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3451             m->m_flags |= M_VLANTAG;
3452         }
3453
3454 #if __FreeBSD_version >= 800000
3455         /* specify what RSS queue was used for this flow */
3456         m->m_pkthdr.flowid = fp->index;
3457         M_HASHTYPE_SET(m, M_HASHTYPE_OPAQUE);
3458 #endif
3459
3460 next_rx:
3461
3462         bd_cons    = RX_BD_NEXT(bd_cons);
3463         bd_prod    = RX_BD_NEXT(bd_prod);
3464         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3465
3466         /* pass the frame to the stack */
3467         if (__predict_true(m != NULL)) {
3468             if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3469             rx_pkts++;
3470             if_input(ifp, m);
3471         }
3472
3473 next_cqe:
3474
3475         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3476         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3477
3478         /* limit spinning on the queue */
3479         if (rx_pkts == sc->rx_budget) {
3480             fp->eth_q_stats.rx_budget_reached++;
3481             break;
3482         }
3483     } /* while work to do */
3484
3485     fp->rx_bd_cons = bd_cons;
3486     fp->rx_bd_prod = bd_prod_fw;
3487     fp->rx_cq_cons = sw_cq_cons;
3488     fp->rx_cq_prod = sw_cq_prod;
3489
3490     /* Update producers */
3491     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3492
3493     fp->eth_q_stats.rx_pkts += rx_pkts;
3494     fp->eth_q_stats.rx_calls++;
3495
3496     BXE_FP_RX_UNLOCK(fp);
3497
3498     return (sw_cq_cons != hw_cq_cons);
3499 }
3500
3501 static uint16_t
3502 bxe_free_tx_pkt(struct bxe_softc    *sc,
3503                 struct bxe_fastpath *fp,
3504                 uint16_t            idx)
3505 {
3506     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3507     struct eth_tx_start_bd *tx_start_bd;
3508     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3509     uint16_t new_cons;
3510     int nbd;
3511
3512     /* unmap the mbuf from non-paged memory */
3513     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3514
3515     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3516     nbd = le16toh(tx_start_bd->nbd) - 1;
3517
3518 #if 0
3519     if ((nbd - 1) > (MAX_MBUF_FRAGS + 2)) {
3520         bxe_panic(sc, ("BAD nbd!\n"));
3521     }
3522 #endif
3523
3524     new_cons = (tx_buf->first_bd + nbd);
3525
3526 #if 0
3527     struct eth_tx_bd *tx_data_bd;
3528
3529     /*
3530      * The following code doesn't do anything but is left here
3531      * for clarity on what the new value of new_cons skipped.
3532      */
3533
3534     /* get the next bd */
3535     bd_idx = TX_BD(TX_BD_NEXT(bd_idx));
3536
3537     /* skip the parse bd */
3538     --nbd;
3539     bd_idx = TX_BD(TX_BD_NEXT(bd_idx));
3540
3541     /* skip the TSO split header bd since they have no mapping */
3542     if (tx_buf->flags & BXE_TSO_SPLIT_BD) {
3543         --nbd;
3544         bd_idx = TX_BD(TX_BD_NEXT(bd_idx));
3545     }
3546
3547     /* now free frags */
3548     while (nbd > 0) {
3549         tx_data_bd = &fp->tx_chain[bd_idx].reg_bd;
3550         if (--nbd) {
3551             bd_idx = TX_BD(TX_BD_NEXT(bd_idx));
3552         }
3553     }
3554 #endif
3555
3556     /* free the mbuf */
3557     if (__predict_true(tx_buf->m != NULL)) {
3558         m_freem(tx_buf->m);
3559         fp->eth_q_stats.mbuf_alloc_tx--;
3560     } else {
3561         fp->eth_q_stats.tx_chain_lost_mbuf++;
3562     }
3563
3564     tx_buf->m = NULL;
3565     tx_buf->first_bd = 0;
3566
3567     return (new_cons);
3568 }
3569
3570 /* transmit timeout watchdog */
3571 static int
3572 bxe_watchdog(struct bxe_softc    *sc,
3573              struct bxe_fastpath *fp)
3574 {
3575     BXE_FP_TX_LOCK(fp);
3576
3577     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3578         BXE_FP_TX_UNLOCK(fp);
3579         return (0);
3580     }
3581
3582     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3583
3584     BXE_FP_TX_UNLOCK(fp);
3585
3586     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3587     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3588
3589     return (-1);
3590 }
3591
3592 /* processes transmit completions */
3593 static uint8_t
3594 bxe_txeof(struct bxe_softc    *sc,
3595           struct bxe_fastpath *fp)
3596 {
3597     if_t ifp = sc->ifp;
3598     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3599     uint16_t tx_bd_avail;
3600
3601     BXE_FP_TX_LOCK_ASSERT(fp);
3602
3603     bd_cons = fp->tx_bd_cons;
3604     hw_cons = le16toh(*fp->tx_cons_sb);
3605     sw_cons = fp->tx_pkt_cons;
3606
3607     while (sw_cons != hw_cons) {
3608         pkt_cons = TX_BD(sw_cons);
3609
3610         BLOGD(sc, DBG_TX,
3611               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3612               fp->index, hw_cons, sw_cons, pkt_cons);
3613
3614         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3615
3616         sw_cons++;
3617     }
3618
3619     fp->tx_pkt_cons = sw_cons;
3620     fp->tx_bd_cons  = bd_cons;
3621
3622     BLOGD(sc, DBG_TX,
3623           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3624           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3625
3626     mb();
3627
3628     tx_bd_avail = bxe_tx_avail(sc, fp);
3629
3630     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3631         if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
3632     } else {
3633         if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
3634     }
3635
3636     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3637         /* reset the watchdog timer if there are pending transmits */
3638         fp->watchdog_timer = BXE_TX_TIMEOUT;
3639         return (TRUE);
3640     } else {
3641         /* clear watchdog when there are no pending transmits */
3642         fp->watchdog_timer = 0;
3643         return (FALSE);
3644     }
3645 }
3646
3647 static void
3648 bxe_drain_tx_queues(struct bxe_softc *sc)
3649 {
3650     struct bxe_fastpath *fp;
3651     int i, count;
3652
3653     /* wait until all TX fastpath tasks have completed */
3654     for (i = 0; i < sc->num_queues; i++) {
3655         fp = &sc->fp[i];
3656
3657         count = 1000;
3658
3659         while (bxe_has_tx_work(fp)) {
3660
3661             BXE_FP_TX_LOCK(fp);
3662             bxe_txeof(sc, fp);
3663             BXE_FP_TX_UNLOCK(fp);
3664
3665             if (count == 0) {
3666                 BLOGE(sc, "Timeout waiting for fp[%d] "
3667                           "transmits to complete!\n", i);
3668                 bxe_panic(sc, ("tx drain failure\n"));
3669                 return;
3670             }
3671
3672             count--;
3673             DELAY(1000);
3674             rmb();
3675         }
3676     }
3677
3678     return;
3679 }
3680
3681 static int
3682 bxe_del_all_macs(struct bxe_softc          *sc,
3683                  struct ecore_vlan_mac_obj *mac_obj,
3684                  int                       mac_type,
3685                  uint8_t                   wait_for_comp)
3686 {
3687     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3688     int rc;
3689
3690     /* wait for completion of requested */
3691     if (wait_for_comp) {
3692         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3693     }
3694
3695     /* Set the mac type of addresses we want to clear */
3696     bxe_set_bit(mac_type, &vlan_mac_flags);
3697
3698     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3699     if (rc < 0) {
3700         BLOGE(sc, "Failed to delete MACs (%d)\n", rc);
3701     }
3702
3703     return (rc);
3704 }
3705
3706 static int
3707 bxe_fill_accept_flags(struct bxe_softc *sc,
3708                       uint32_t         rx_mode,
3709                       unsigned long    *rx_accept_flags,
3710                       unsigned long    *tx_accept_flags)
3711 {
3712     /* Clear the flags first */
3713     *rx_accept_flags = 0;
3714     *tx_accept_flags = 0;
3715
3716     switch (rx_mode) {
3717     case BXE_RX_MODE_NONE:
3718         /*
3719          * 'drop all' supersedes any accept flags that may have been
3720          * passed to the function.
3721          */
3722         break;
3723
3724     case BXE_RX_MODE_NORMAL:
3725         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3726         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3727         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3728
3729         /* internal switching mode */
3730         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3731         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3732         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3733
3734         break;
3735
3736     case BXE_RX_MODE_ALLMULTI:
3737         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3738         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3739         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3740
3741         /* internal switching mode */
3742         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3743         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3744         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3745
3746         break;
3747
3748     case BXE_RX_MODE_PROMISC:
3749         /*
3750          * According to deffinition of SI mode, iface in promisc mode
3751          * should receive matched and unmatched (in resolution of port)
3752          * unicast packets.
3753          */
3754         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3755         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3756         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3757         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3758
3759         /* internal switching mode */
3760         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3761         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3762
3763         if (IS_MF_SI(sc)) {
3764             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3765         } else {
3766             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3767         }
3768
3769         break;
3770
3771     default:
3772         BLOGE(sc, "Unknown rx_mode (%d)\n", rx_mode);
3773         return (-1);
3774     }
3775
3776     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3777     if (rx_mode != BXE_RX_MODE_NONE) {
3778         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3779         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3780     }
3781
3782     return (0);
3783 }
3784
3785 static int
3786 bxe_set_q_rx_mode(struct bxe_softc *sc,
3787                   uint8_t          cl_id,
3788                   unsigned long    rx_mode_flags,
3789                   unsigned long    rx_accept_flags,
3790                   unsigned long    tx_accept_flags,
3791                   unsigned long    ramrod_flags)
3792 {
3793     struct ecore_rx_mode_ramrod_params ramrod_param;
3794     int rc;
3795
3796     memset(&ramrod_param, 0, sizeof(ramrod_param));
3797
3798     /* Prepare ramrod parameters */
3799     ramrod_param.cid = 0;
3800     ramrod_param.cl_id = cl_id;
3801     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3802     ramrod_param.func_id = SC_FUNC(sc);
3803
3804     ramrod_param.pstate = &sc->sp_state;
3805     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3806
3807     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3808     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3809
3810     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3811
3812     ramrod_param.ramrod_flags = ramrod_flags;
3813     ramrod_param.rx_mode_flags = rx_mode_flags;
3814
3815     ramrod_param.rx_accept_flags = rx_accept_flags;
3816     ramrod_param.tx_accept_flags = tx_accept_flags;
3817
3818     rc = ecore_config_rx_mode(sc, &ramrod_param);
3819     if (rc < 0) {
3820         BLOGE(sc, "Set rx_mode %d failed\n", sc->rx_mode);
3821         return (rc);
3822     }
3823
3824     return (0);
3825 }
3826
3827 static int
3828 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3829 {
3830     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3831     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3832     int rc;
3833
3834     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3835                                &tx_accept_flags);
3836     if (rc) {
3837         return (rc);
3838     }
3839
3840     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3841     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3842
3843     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3844     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3845                               rx_accept_flags, tx_accept_flags,
3846                               ramrod_flags));
3847 }
3848
3849 /* returns the "mcp load_code" according to global load_count array */
3850 static int
3851 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3852 {
3853     int path = SC_PATH(sc);
3854     int port = SC_PORT(sc);
3855
3856     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3857           path, load_count[path][0], load_count[path][1],
3858           load_count[path][2]);
3859     load_count[path][0]++;
3860     load_count[path][1 + port]++;
3861     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3862           path, load_count[path][0], load_count[path][1],
3863           load_count[path][2]);
3864     if (load_count[path][0] == 1) {
3865         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3866     } else if (load_count[path][1 + port] == 1) {
3867         return (FW_MSG_CODE_DRV_LOAD_PORT);
3868     } else {
3869         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3870     }
3871 }
3872
3873 /* returns the "mcp load_code" according to global load_count array */
3874 static int
3875 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3876 {
3877     int port = SC_PORT(sc);
3878     int path = SC_PATH(sc);
3879
3880     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3881           path, load_count[path][0], load_count[path][1],
3882           load_count[path][2]);
3883     load_count[path][0]--;
3884     load_count[path][1 + port]--;
3885     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3886           path, load_count[path][0], load_count[path][1],
3887           load_count[path][2]);
3888     if (load_count[path][0] == 0) {
3889         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3890     } else if (load_count[path][1 + port] == 0) {
3891         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3892     } else {
3893         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3894     }
3895 }
3896
3897 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3898 static uint32_t
3899 bxe_send_unload_req(struct bxe_softc *sc,
3900                     int              unload_mode)
3901 {
3902     uint32_t reset_code = 0;
3903 #if 0
3904     int port = SC_PORT(sc);
3905     int path = SC_PATH(sc);
3906 #endif
3907
3908     /* Select the UNLOAD request mode */
3909     if (unload_mode == UNLOAD_NORMAL) {
3910         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3911     }
3912 #if 0
3913     else if (sc->flags & BXE_NO_WOL_FLAG) {
3914         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP;
3915     } else if (sc->wol) {
3916         uint32_t emac_base = port ? GRCBASE_EMAC1 : GRCBASE_EMAC0;
3917         uint8_t *mac_addr = sc->dev->dev_addr;
3918         uint32_t val;
3919         uint16_t pmc;
3920
3921         /*
3922          * The mac address is written to entries 1-4 to
3923          * preserve entry 0 which is used by the PMF
3924          */
3925         uint8_t entry = (SC_VN(sc) + 1)*8;
3926
3927         val = (mac_addr[0] << 8) | mac_addr[1];
3928         EMAC_WR(sc, EMAC_REG_EMAC_MAC_MATCH + entry, val);
3929
3930         val = (mac_addr[2] << 24) | (mac_addr[3] << 16) |
3931               (mac_addr[4] << 8) | mac_addr[5];
3932         EMAC_WR(sc, EMAC_REG_EMAC_MAC_MATCH + entry + 4, val);
3933
3934         /* Enable the PME and clear the status */
3935         pmc = pci_read_config(sc->dev,
3936                               (sc->devinfo.pcie_pm_cap_reg +
3937                                PCIR_POWER_STATUS),
3938                               2);
3939         pmc |= PCIM_PSTAT_PMEENABLE | PCIM_PSTAT_PME;
3940         pci_write_config(sc->dev,
3941                          (sc->devinfo.pcie_pm_cap_reg +
3942                           PCIR_POWER_STATUS),
3943                          pmc, 4);
3944
3945         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_EN;
3946     }
3947 #endif
3948     else {
3949         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3950     }
3951
3952     /* Send the request to the MCP */
3953     if (!BXE_NOMCP(sc)) {
3954         reset_code = bxe_fw_command(sc, reset_code, 0);
3955     } else {
3956         reset_code = bxe_nic_unload_no_mcp(sc);
3957     }
3958
3959     return (reset_code);
3960 }
3961
3962 /* send UNLOAD_DONE command to the MCP */
3963 static void
3964 bxe_send_unload_done(struct bxe_softc *sc,
3965                      uint8_t          keep_link)
3966 {
3967     uint32_t reset_param =
3968         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3969
3970     /* Report UNLOAD_DONE to MCP */
3971     if (!BXE_NOMCP(sc)) {
3972         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3973     }
3974 }
3975
3976 static int
3977 bxe_func_wait_started(struct bxe_softc *sc)
3978 {
3979     int tout = 50;
3980
3981     if (!sc->port.pmf) {
3982         return (0);
3983     }
3984
3985     /*
3986      * (assumption: No Attention from MCP at this stage)
3987      * PMF probably in the middle of TX disable/enable transaction
3988      * 1. Sync IRS for default SB
3989      * 2. Sync SP queue - this guarantees us that attention handling started
3990      * 3. Wait, that TX disable/enable transaction completes
3991      *
3992      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3993      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3994      * received completion for the transaction the state is TX_STOPPED.
3995      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3996      * transaction.
3997      */
3998
3999     /* XXX make sure default SB ISR is done */
4000     /* need a way to synchronize an irq (intr_mtx?) */
4001
4002     /* XXX flush any work queues */
4003
4004     while (ecore_func_get_state(sc, &sc->func_obj) !=
4005            ECORE_F_STATE_STARTED && tout--) {
4006         DELAY(20000);
4007     }
4008
4009     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
4010         /*
4011          * Failed to complete the transaction in a "good way"
4012          * Force both transactions with CLR bit.
4013          */
4014         struct ecore_func_state_params func_params = { NULL };
4015
4016         BLOGE(sc, "Unexpected function state! "
4017                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
4018
4019         func_params.f_obj = &sc->func_obj;
4020         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
4021
4022         /* STARTED-->TX_STOPPED */
4023         func_params.cmd = ECORE_F_CMD_TX_STOP;
4024         ecore_func_state_change(sc, &func_params);
4025
4026         /* TX_STOPPED-->STARTED */
4027         func_params.cmd = ECORE_F_CMD_TX_START;
4028         return (ecore_func_state_change(sc, &func_params));
4029     }
4030
4031     return (0);
4032 }
4033
4034 static int
4035 bxe_stop_queue(struct bxe_softc *sc,
4036                int              index)
4037 {
4038     struct bxe_fastpath *fp = &sc->fp[index];
4039     struct ecore_queue_state_params q_params = { NULL };
4040     int rc;
4041
4042     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
4043
4044     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
4045     /* We want to wait for completion in this context */
4046     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
4047
4048     /* Stop the primary connection: */
4049
4050     /* ...halt the connection */
4051     q_params.cmd = ECORE_Q_CMD_HALT;
4052     rc = ecore_queue_state_change(sc, &q_params);
4053     if (rc) {
4054         return (rc);
4055     }
4056
4057     /* ...terminate the connection */
4058     q_params.cmd = ECORE_Q_CMD_TERMINATE;
4059     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
4060     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
4061     rc = ecore_queue_state_change(sc, &q_params);
4062     if (rc) {
4063         return (rc);
4064     }
4065
4066     /* ...delete cfc entry */
4067     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
4068     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
4069     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
4070     return (ecore_queue_state_change(sc, &q_params));
4071 }
4072
4073 /* wait for the outstanding SP commands */
4074 static inline uint8_t
4075 bxe_wait_sp_comp(struct bxe_softc *sc,
4076                  unsigned long    mask)
4077 {
4078     unsigned long tmp;
4079     int tout = 5000; /* wait for 5 secs tops */
4080
4081     while (tout--) {
4082         mb();
4083         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
4084             return (TRUE);
4085         }
4086
4087         DELAY(1000);
4088     }
4089
4090     mb();
4091
4092     tmp = atomic_load_acq_long(&sc->sp_state);
4093     if (tmp & mask) {
4094         BLOGE(sc, "Filtering completion timed out: "
4095                   "sp_state 0x%lx, mask 0x%lx\n",
4096               tmp, mask);
4097         return (FALSE);
4098     }
4099
4100     return (FALSE);
4101 }
4102
4103 static int
4104 bxe_func_stop(struct bxe_softc *sc)
4105 {
4106     struct ecore_func_state_params func_params = { NULL };
4107     int rc;
4108
4109     /* prepare parameters for function state transitions */
4110     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4111     func_params.f_obj = &sc->func_obj;
4112     func_params.cmd = ECORE_F_CMD_STOP;
4113
4114     /*
4115      * Try to stop the function the 'good way'. If it fails (in case
4116      * of a parity error during bxe_chip_cleanup()) and we are
4117      * not in a debug mode, perform a state transaction in order to
4118      * enable further HW_RESET transaction.
4119      */
4120     rc = ecore_func_state_change(sc, &func_params);
4121     if (rc) {
4122         BLOGE(sc, "FUNC_STOP ramrod failed. "
4123                   "Running a dry transaction\n");
4124         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
4125         return (ecore_func_state_change(sc, &func_params));
4126     }
4127
4128     return (0);
4129 }
4130
4131 static int
4132 bxe_reset_hw(struct bxe_softc *sc,
4133              uint32_t         load_code)
4134 {
4135     struct ecore_func_state_params func_params = { NULL };
4136
4137     /* Prepare parameters for function state transitions */
4138     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4139
4140     func_params.f_obj = &sc->func_obj;
4141     func_params.cmd = ECORE_F_CMD_HW_RESET;
4142
4143     func_params.params.hw_init.load_phase = load_code;
4144
4145     return (ecore_func_state_change(sc, &func_params));
4146 }
4147
4148 static void
4149 bxe_int_disable_sync(struct bxe_softc *sc,
4150                      int              disable_hw)
4151 {
4152     if (disable_hw) {
4153         /* prevent the HW from sending interrupts */
4154         bxe_int_disable(sc);
4155     }
4156
4157     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4158     /* make sure all ISRs are done */
4159
4160     /* XXX make sure sp_task is not running */
4161     /* cancel and flush work queues */
4162 }
4163
4164 static void
4165 bxe_chip_cleanup(struct bxe_softc *sc,
4166                  uint32_t         unload_mode,
4167                  uint8_t          keep_link)
4168 {
4169     int port = SC_PORT(sc);
4170     struct ecore_mcast_ramrod_params rparam = { NULL };
4171     uint32_t reset_code;
4172     int i, rc = 0;
4173
4174     bxe_drain_tx_queues(sc);
4175
4176     /* give HW time to discard old tx messages */
4177     DELAY(1000);
4178
4179     /* Clean all ETH MACs */
4180     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4181     if (rc < 0) {
4182         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4183     }
4184
4185     /* Clean up UC list  */
4186     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4187     if (rc < 0) {
4188         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4189     }
4190
4191     /* Disable LLH */
4192     if (!CHIP_IS_E1(sc)) {
4193         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4194     }
4195
4196     /* Set "drop all" to stop Rx */
4197
4198     /*
4199      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4200      * a race between the completion code and this code.
4201      */
4202     BXE_MCAST_LOCK(sc);
4203
4204     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4205         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4206     } else {
4207         bxe_set_storm_rx_mode(sc);
4208     }
4209
4210     /* Clean up multicast configuration */
4211     rparam.mcast_obj = &sc->mcast_obj;
4212     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4213     if (rc < 0) {
4214         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4215     }
4216
4217     BXE_MCAST_UNLOCK(sc);
4218
4219     // XXX bxe_iov_chip_cleanup(sc);
4220
4221     /*
4222      * Send the UNLOAD_REQUEST to the MCP. This will return if
4223      * this function should perform FUNCTION, PORT, or COMMON HW
4224      * reset.
4225      */
4226     reset_code = bxe_send_unload_req(sc, unload_mode);
4227
4228     /*
4229      * (assumption: No Attention from MCP at this stage)
4230      * PMF probably in the middle of TX disable/enable transaction
4231      */
4232     rc = bxe_func_wait_started(sc);
4233     if (rc) {
4234         BLOGE(sc, "bxe_func_wait_started failed\n");
4235     }
4236
4237     /*
4238      * Close multi and leading connections
4239      * Completions for ramrods are collected in a synchronous way
4240      */
4241     for (i = 0; i < sc->num_queues; i++) {
4242         if (bxe_stop_queue(sc, i)) {
4243             goto unload_error;
4244         }
4245     }
4246
4247     /*
4248      * If SP settings didn't get completed so far - something
4249      * very wrong has happen.
4250      */
4251     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4252         BLOGE(sc, "Common slow path ramrods got stuck!\n");
4253     }
4254
4255 unload_error:
4256
4257     rc = bxe_func_stop(sc);
4258     if (rc) {
4259         BLOGE(sc, "Function stop failed!\n");
4260     }
4261
4262     /* disable HW interrupts */
4263     bxe_int_disable_sync(sc, TRUE);
4264
4265     /* detach interrupts */
4266     bxe_interrupt_detach(sc);
4267
4268     /* Reset the chip */
4269     rc = bxe_reset_hw(sc, reset_code);
4270     if (rc) {
4271         BLOGE(sc, "Hardware reset failed\n");
4272     }
4273
4274     /* Report UNLOAD_DONE to MCP */
4275     bxe_send_unload_done(sc, keep_link);
4276 }
4277
4278 static void
4279 bxe_disable_close_the_gate(struct bxe_softc *sc)
4280 {
4281     uint32_t val;
4282     int port = SC_PORT(sc);
4283
4284     BLOGD(sc, DBG_LOAD,
4285           "Disabling 'close the gates'\n");
4286
4287     if (CHIP_IS_E1(sc)) {
4288         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4289                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4290         val = REG_RD(sc, addr);
4291         val &= ~(0x300);
4292         REG_WR(sc, addr, val);
4293     } else {
4294         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4295         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4296                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4297         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4298     }
4299 }
4300
4301 /*
4302  * Cleans the object that have internal lists without sending
4303  * ramrods. Should be run when interrutps are disabled.
4304  */
4305 static void
4306 bxe_squeeze_objects(struct bxe_softc *sc)
4307 {
4308     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4309     struct ecore_mcast_ramrod_params rparam = { NULL };
4310     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4311     int rc;
4312
4313     /* Cleanup MACs' object first... */
4314
4315     /* Wait for completion of requested */
4316     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4317     /* Perform a dry cleanup */
4318     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4319
4320     /* Clean ETH primary MAC */
4321     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4322     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4323                              &ramrod_flags);
4324     if (rc != 0) {
4325         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4326     }
4327
4328     /* Cleanup UC list */
4329     vlan_mac_flags = 0;
4330     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4331     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4332                              &ramrod_flags);
4333     if (rc != 0) {
4334         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4335     }
4336
4337     /* Now clean mcast object... */
4338
4339     rparam.mcast_obj = &sc->mcast_obj;
4340     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4341
4342     /* Add a DEL command... */
4343     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4344     if (rc < 0) {
4345         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4346     }
4347
4348     /* now wait until all pending commands are cleared */
4349
4350     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4351     while (rc != 0) {
4352         if (rc < 0) {
4353             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4354             return;
4355         }
4356
4357         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4358     }
4359 }
4360
4361 /* stop the controller */
4362 static __noinline int
4363 bxe_nic_unload(struct bxe_softc *sc,
4364                uint32_t         unload_mode,
4365                uint8_t          keep_link)
4366 {
4367     uint8_t global = FALSE;
4368     uint32_t val;
4369
4370     BXE_CORE_LOCK_ASSERT(sc);
4371
4372     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4373
4374     /* mark driver as unloaded in shmem2 */
4375     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4376         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4377         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4378                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4379     }
4380
4381     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4382         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4383         /*
4384          * We can get here if the driver has been unloaded
4385          * during parity error recovery and is either waiting for a
4386          * leader to complete or for other functions to unload and
4387          * then ifconfig down has been issued. In this case we want to
4388          * unload and let other functions to complete a recovery
4389          * process.
4390          */
4391         sc->recovery_state = BXE_RECOVERY_DONE;
4392         sc->is_leader = 0;
4393         bxe_release_leader_lock(sc);
4394         mb();
4395
4396         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4397         BLOGE(sc, "Can't unload in closed or error state\n");
4398         return (-1);
4399     }
4400
4401     /*
4402      * Nothing to do during unload if previous bxe_nic_load()
4403      * did not completed succesfully - all resourses are released.
4404      */
4405     if ((sc->state == BXE_STATE_CLOSED) ||
4406         (sc->state == BXE_STATE_ERROR)) {
4407         return (0);
4408     }
4409
4410     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4411     mb();
4412
4413     /* stop tx */
4414     bxe_tx_disable(sc);
4415
4416     sc->rx_mode = BXE_RX_MODE_NONE;
4417     /* XXX set rx mode ??? */
4418
4419     if (IS_PF(sc)) {
4420         /* set ALWAYS_ALIVE bit in shmem */
4421         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4422
4423         bxe_drv_pulse(sc);
4424
4425         bxe_stats_handle(sc, STATS_EVENT_STOP);
4426         bxe_save_statistics(sc);
4427     }
4428
4429     /* wait till consumers catch up with producers in all queues */
4430     bxe_drain_tx_queues(sc);
4431
4432     /* if VF indicate to PF this function is going down (PF will delete sp
4433      * elements and clear initializations
4434      */
4435     if (IS_VF(sc)) {
4436         ; /* bxe_vfpf_close_vf(sc); */
4437     } else if (unload_mode != UNLOAD_RECOVERY) {
4438         /* if this is a normal/close unload need to clean up chip */
4439         bxe_chip_cleanup(sc, unload_mode, keep_link);
4440     } else {
4441         /* Send the UNLOAD_REQUEST to the MCP */
4442         bxe_send_unload_req(sc, unload_mode);
4443
4444         /*
4445          * Prevent transactions to host from the functions on the
4446          * engine that doesn't reset global blocks in case of global
4447          * attention once gloabl blocks are reset and gates are opened
4448          * (the engine which leader will perform the recovery
4449          * last).
4450          */
4451         if (!CHIP_IS_E1x(sc)) {
4452             bxe_pf_disable(sc);
4453         }
4454
4455         /* disable HW interrupts */
4456         bxe_int_disable_sync(sc, TRUE);
4457
4458         /* detach interrupts */
4459         bxe_interrupt_detach(sc);
4460
4461         /* Report UNLOAD_DONE to MCP */
4462         bxe_send_unload_done(sc, FALSE);
4463     }
4464
4465     /*
4466      * At this stage no more interrupts will arrive so we may safely clean
4467      * the queue'able objects here in case they failed to get cleaned so far.
4468      */
4469     if (IS_PF(sc)) {
4470         bxe_squeeze_objects(sc);
4471     }
4472
4473     /* There should be no more pending SP commands at this stage */
4474     sc->sp_state = 0;
4475
4476     sc->port.pmf = 0;
4477
4478     bxe_free_fp_buffers(sc);
4479
4480     if (IS_PF(sc)) {
4481         bxe_free_mem(sc);
4482     }
4483
4484     bxe_free_fw_stats_mem(sc);
4485
4486     sc->state = BXE_STATE_CLOSED;
4487
4488     /*
4489      * Check if there are pending parity attentions. If there are - set
4490      * RECOVERY_IN_PROGRESS.
4491      */
4492     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4493         bxe_set_reset_in_progress(sc);
4494
4495         /* Set RESET_IS_GLOBAL if needed */
4496         if (global) {
4497             bxe_set_reset_global(sc);
4498         }
4499     }
4500
4501     /*
4502      * The last driver must disable a "close the gate" if there is no
4503      * parity attention or "process kill" pending.
4504      */
4505     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4506         bxe_reset_is_done(sc, SC_PATH(sc))) {
4507         bxe_disable_close_the_gate(sc);
4508     }
4509
4510     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4511
4512     return (0);
4513 }
4514
4515 /*
4516  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4517  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4518  */
4519 static int
4520 bxe_ifmedia_update(struct ifnet  *ifp)
4521 {
4522     struct bxe_softc *sc = (struct bxe_softc *)if_getsoftc(ifp);
4523     struct ifmedia *ifm;
4524
4525     ifm = &sc->ifmedia;
4526
4527     /* We only support Ethernet media type. */
4528     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4529         return (EINVAL);
4530     }
4531
4532     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4533     case IFM_AUTO:
4534          break;
4535     case IFM_10G_CX4:
4536     case IFM_10G_SR:
4537     case IFM_10G_T:
4538     case IFM_10G_TWINAX:
4539     default:
4540         /* We don't support changing the media type. */
4541         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4542               IFM_SUBTYPE(ifm->ifm_media));
4543         return (EINVAL);
4544     }
4545
4546     return (0);
4547 }
4548
4549 /*
4550  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4551  */
4552 static void
4553 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4554 {
4555     struct bxe_softc *sc = if_getsoftc(ifp);
4556
4557     /* Report link down if the driver isn't running. */
4558     if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0) {
4559         ifmr->ifm_active |= IFM_NONE;
4560         return;
4561     }
4562
4563     /* Setup the default interface info. */
4564     ifmr->ifm_status = IFM_AVALID;
4565     ifmr->ifm_active = IFM_ETHER;
4566
4567     if (sc->link_vars.link_up) {
4568         ifmr->ifm_status |= IFM_ACTIVE;
4569     } else {
4570         ifmr->ifm_active |= IFM_NONE;
4571         return;
4572     }
4573
4574     ifmr->ifm_active |= sc->media;
4575
4576     if (sc->link_vars.duplex == DUPLEX_FULL) {
4577         ifmr->ifm_active |= IFM_FDX;
4578     } else {
4579         ifmr->ifm_active |= IFM_HDX;
4580     }
4581 }
4582
4583 static int
4584 bxe_ioctl_nvram(struct bxe_softc *sc,
4585                 uint32_t         priv_op,
4586                 struct ifreq     *ifr)
4587 {
4588     struct bxe_nvram_data nvdata_base;
4589     struct bxe_nvram_data *nvdata;
4590     int len;
4591     int error = 0;
4592
4593     copyin(ifr->ifr_data, &nvdata_base, sizeof(nvdata_base));
4594
4595     len = (sizeof(struct bxe_nvram_data) +
4596            nvdata_base.len -
4597            sizeof(uint32_t));
4598
4599     if (len > sizeof(struct bxe_nvram_data)) {
4600         if ((nvdata = (struct bxe_nvram_data *)
4601                  malloc(len, M_DEVBUF,
4602                         (M_NOWAIT | M_ZERO))) == NULL) {
4603             BLOGE(sc, "BXE_IOC_RD_NVRAM malloc failed\n");
4604             return (1);
4605         }
4606         memcpy(nvdata, &nvdata_base, sizeof(struct bxe_nvram_data));
4607     } else {
4608         nvdata = &nvdata_base;
4609     }
4610
4611     if (priv_op == BXE_IOC_RD_NVRAM) {
4612         BLOGD(sc, DBG_IOCTL, "IOC_RD_NVRAM 0x%x %d\n",
4613               nvdata->offset, nvdata->len);
4614         error = bxe_nvram_read(sc,
4615                                nvdata->offset,
4616                                (uint8_t *)nvdata->value,
4617                                nvdata->len);
4618         copyout(nvdata, ifr->ifr_data, len);
4619     } else { /* BXE_IOC_WR_NVRAM */
4620         BLOGD(sc, DBG_IOCTL, "IOC_WR_NVRAM 0x%x %d\n",
4621               nvdata->offset, nvdata->len);
4622         copyin(ifr->ifr_data, nvdata, len);
4623         error = bxe_nvram_write(sc,
4624                                 nvdata->offset,
4625                                 (uint8_t *)nvdata->value,
4626                                 nvdata->len);
4627     }
4628
4629     if (len > sizeof(struct bxe_nvram_data)) {
4630         free(nvdata, M_DEVBUF);
4631     }
4632
4633     return (error);
4634 }
4635
4636 static int
4637 bxe_ioctl_stats_show(struct bxe_softc *sc,
4638                      uint32_t         priv_op,
4639                      struct ifreq     *ifr)
4640 {
4641     const size_t str_size   = (BXE_NUM_ETH_STATS * STAT_NAME_LEN);
4642     const size_t stats_size = (BXE_NUM_ETH_STATS * sizeof(uint64_t));
4643     caddr_t p_tmp;
4644     uint32_t *offset;
4645     int i;
4646
4647     switch (priv_op)
4648     {
4649     case BXE_IOC_STATS_SHOW_NUM:
4650         memset(ifr->ifr_data, 0, sizeof(union bxe_stats_show_data));
4651         ((union bxe_stats_show_data *)ifr->ifr_data)->desc.num =
4652             BXE_NUM_ETH_STATS;
4653         ((union bxe_stats_show_data *)ifr->ifr_data)->desc.len =
4654             STAT_NAME_LEN;
4655         return (0);
4656
4657     case BXE_IOC_STATS_SHOW_STR:
4658         memset(ifr->ifr_data, 0, str_size);
4659         p_tmp = ifr->ifr_data;
4660         for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4661             strcpy(p_tmp, bxe_eth_stats_arr[i].string);
4662             p_tmp += STAT_NAME_LEN;
4663         }
4664         return (0);
4665
4666     case BXE_IOC_STATS_SHOW_CNT:
4667         memset(ifr->ifr_data, 0, stats_size);
4668         p_tmp = ifr->ifr_data;
4669         for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4670             offset = ((uint32_t *)&sc->eth_stats +
4671                       bxe_eth_stats_arr[i].offset);
4672             switch (bxe_eth_stats_arr[i].size) {
4673             case 4:
4674                 *((uint64_t *)p_tmp) = (uint64_t)*offset;
4675                 break;
4676             case 8:
4677                 *((uint64_t *)p_tmp) = HILO_U64(*offset, *(offset + 1));
4678                 break;
4679             default:
4680                 *((uint64_t *)p_tmp) = 0;
4681             }
4682             p_tmp += sizeof(uint64_t);
4683         }
4684         return (0);
4685
4686     default:
4687         return (-1);
4688     }
4689 }
4690
4691 static void
4692 bxe_handle_chip_tq(void *context,
4693                    int  pending)
4694 {
4695     struct bxe_softc *sc = (struct bxe_softc *)context;
4696     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4697
4698     switch (work)
4699     {
4700     case CHIP_TQ_START:
4701         if ((if_getflags(sc->ifp) & IFF_UP) &&
4702             !(if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4703             /* start the interface */
4704             BLOGD(sc, DBG_LOAD, "Starting the interface...\n");
4705             BXE_CORE_LOCK(sc);
4706             bxe_init_locked(sc);
4707             BXE_CORE_UNLOCK(sc);
4708         }
4709         break;
4710
4711     case CHIP_TQ_STOP:
4712         if (!(if_getflags(sc->ifp) & IFF_UP) &&
4713             (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4714             /* bring down the interface */
4715             BLOGD(sc, DBG_LOAD, "Stopping the interface...\n");
4716             bxe_periodic_stop(sc);
4717             BXE_CORE_LOCK(sc);
4718             bxe_stop_locked(sc);
4719             BXE_CORE_UNLOCK(sc);
4720         }
4721         break;
4722
4723     case CHIP_TQ_REINIT:
4724         if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
4725             /* restart the interface */
4726             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4727             bxe_periodic_stop(sc);
4728             BXE_CORE_LOCK(sc);
4729             bxe_stop_locked(sc);
4730             bxe_init_locked(sc);
4731             BXE_CORE_UNLOCK(sc);
4732         }
4733         break;
4734
4735     default:
4736         break;
4737     }
4738 }
4739
4740 /*
4741  * Handles any IOCTL calls from the operating system.
4742  *
4743  * Returns:
4744  *   0 = Success, >0 Failure
4745  */
4746 static int
4747 bxe_ioctl(if_t ifp,
4748           u_long       command,
4749           caddr_t      data)
4750 {
4751     struct bxe_softc *sc = if_getsoftc(ifp);
4752     struct ifreq *ifr = (struct ifreq *)data;
4753     struct bxe_nvram_data *nvdata;
4754     uint32_t priv_op;
4755     int mask = 0;
4756     int reinit = 0;
4757     int error = 0;
4758
4759     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4760     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4761
4762     switch (command)
4763     {
4764     case SIOCSIFMTU:
4765         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4766               ifr->ifr_mtu);
4767
4768         if (sc->mtu == ifr->ifr_mtu) {
4769             /* nothing to change */
4770             break;
4771         }
4772
4773         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4774             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4775                   ifr->ifr_mtu, mtu_min, mtu_max);
4776             error = EINVAL;
4777             break;
4778         }
4779
4780         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4781                              (unsigned long)ifr->ifr_mtu);
4782         /* 
4783         atomic_store_rel_long((volatile unsigned long *)&if_getmtu(ifp),
4784                               (unsigned long)ifr->ifr_mtu);
4785         XXX - Not sure why it needs to be atomic
4786         */
4787         if_setmtu(ifp, ifr->ifr_mtu);
4788         reinit = 1;
4789         break;
4790
4791     case SIOCSIFFLAGS:
4792         /* toggle the interface state up or down */
4793         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4794
4795         /* check if the interface is up */
4796         if (if_getflags(ifp) & IFF_UP) {
4797             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4798                 /* set the receive mode flags */
4799                 bxe_set_rx_mode(sc);
4800             } else {
4801                 atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_START);
4802                 taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
4803             }
4804         } else {
4805             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4806                 atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_STOP);
4807                 taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
4808             }
4809         }
4810
4811         break;
4812
4813     case SIOCADDMULTI:
4814     case SIOCDELMULTI:
4815         /* add/delete multicast addresses */
4816         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4817
4818         /* check if the interface is up */
4819         if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4820             /* set the receive mode flags */
4821             bxe_set_rx_mode(sc);
4822         }
4823
4824         break;
4825
4826     case SIOCSIFCAP:
4827         /* find out which capabilities have changed */
4828         mask = (ifr->ifr_reqcap ^ if_getcapenable(ifp));
4829
4830         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4831               mask);
4832
4833         /* toggle the LRO capabilites enable flag */
4834         if (mask & IFCAP_LRO) {
4835             if_togglecapenable(ifp, IFCAP_LRO);
4836             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4837                   (if_getcapenable(ifp) & IFCAP_LRO) ? "ON" : "OFF");
4838             reinit = 1;
4839         }
4840
4841         /* toggle the TXCSUM checksum capabilites enable flag */
4842         if (mask & IFCAP_TXCSUM) {
4843             if_togglecapenable(ifp, IFCAP_TXCSUM);
4844             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4845                   (if_getcapenable(ifp) & IFCAP_TXCSUM) ? "ON" : "OFF");
4846             if (if_getcapenable(ifp) & IFCAP_TXCSUM) {
4847                 if_sethwassistbits(ifp, (CSUM_IP      | 
4848                                     CSUM_TCP      |
4849                                     CSUM_UDP      |
4850                                     CSUM_TSO      |
4851                                     CSUM_TCP_IPV6 |
4852                                     CSUM_UDP_IPV6), 0);
4853             } else {
4854                 if_clearhwassist(ifp); /* XXX */
4855             }
4856         }
4857
4858         /* toggle the RXCSUM checksum capabilities enable flag */
4859         if (mask & IFCAP_RXCSUM) {
4860             if_togglecapenable(ifp, IFCAP_RXCSUM);
4861             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4862                   (if_getcapenable(ifp) & IFCAP_RXCSUM) ? "ON" : "OFF");
4863             if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
4864                 if_sethwassistbits(ifp, (CSUM_IP      |
4865                                     CSUM_TCP      |
4866                                     CSUM_UDP      |
4867                                     CSUM_TSO      |
4868                                     CSUM_TCP_IPV6 |
4869                                     CSUM_UDP_IPV6), 0);
4870             } else {
4871                 if_clearhwassist(ifp); /* XXX */
4872             }
4873         }
4874
4875         /* toggle TSO4 capabilities enabled flag */
4876         if (mask & IFCAP_TSO4) {
4877             if_togglecapenable(ifp, IFCAP_TSO4);
4878             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4879                   (if_getcapenable(ifp) & IFCAP_TSO4) ? "ON" : "OFF");
4880         }
4881
4882         /* toggle TSO6 capabilities enabled flag */
4883         if (mask & IFCAP_TSO6) {
4884             if_togglecapenable(ifp, IFCAP_TSO6);
4885             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4886                   (if_getcapenable(ifp) & IFCAP_TSO6) ? "ON" : "OFF");
4887         }
4888
4889         /* toggle VLAN_HWTSO capabilities enabled flag */
4890         if (mask & IFCAP_VLAN_HWTSO) {
4891
4892             if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
4893             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4894                   (if_getcapenable(ifp) & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4895         }
4896
4897         /* toggle VLAN_HWCSUM capabilities enabled flag */
4898         if (mask & IFCAP_VLAN_HWCSUM) {
4899             /* XXX investigate this... */
4900             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4901             error = EINVAL;
4902         }
4903
4904         /* toggle VLAN_MTU capabilities enable flag */
4905         if (mask & IFCAP_VLAN_MTU) {
4906             /* XXX investigate this... */
4907             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4908             error = EINVAL;
4909         }
4910
4911         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4912         if (mask & IFCAP_VLAN_HWTAGGING) {
4913             /* XXX investigate this... */
4914             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4915             error = EINVAL;
4916         }
4917
4918         /* toggle VLAN_HWFILTER capabilities enabled flag */
4919         if (mask & IFCAP_VLAN_HWFILTER) {
4920             /* XXX investigate this... */
4921             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4922             error = EINVAL;
4923         }
4924
4925         /* XXX not yet...
4926          * IFCAP_WOL_MAGIC
4927          */
4928
4929         break;
4930
4931     case SIOCSIFMEDIA:
4932     case SIOCGIFMEDIA:
4933         /* set/get interface media */
4934         BLOGD(sc, DBG_IOCTL,
4935               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4936               (command & 0xff));
4937         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4938         break;
4939
4940     case SIOCGPRIVATE_0:
4941         copyin(ifr->ifr_data, &priv_op, sizeof(priv_op));
4942
4943         switch (priv_op)
4944         {
4945         case BXE_IOC_RD_NVRAM:
4946         case BXE_IOC_WR_NVRAM:
4947             nvdata = (struct bxe_nvram_data *)ifr->ifr_data;
4948             BLOGD(sc, DBG_IOCTL,
4949                   "Received Private NVRAM ioctl addr=0x%x size=%u\n",
4950                   nvdata->offset, nvdata->len);
4951             error = bxe_ioctl_nvram(sc, priv_op, ifr);
4952             break;
4953
4954         case BXE_IOC_STATS_SHOW_NUM:
4955         case BXE_IOC_STATS_SHOW_STR:
4956         case BXE_IOC_STATS_SHOW_CNT:
4957             BLOGD(sc, DBG_IOCTL, "Received Private Stats ioctl (%d)\n",
4958                   priv_op);
4959             error = bxe_ioctl_stats_show(sc, priv_op, ifr);
4960             break;
4961
4962         default:
4963             BLOGW(sc, "Received Private Unknown ioctl (%d)\n", priv_op);
4964             error = EINVAL;
4965             break;
4966         }
4967
4968         break;
4969
4970     default:
4971         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4972               (command & 0xff));
4973         error = ether_ioctl(ifp, command, data);
4974         break;
4975     }
4976
4977     if (reinit && (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4978         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4979               "Re-initializing hardware from IOCTL change\n");
4980         atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
4981         taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
4982     }
4983
4984     return (error);
4985 }
4986
4987 static __noinline void
4988 bxe_dump_mbuf(struct bxe_softc *sc,
4989               struct mbuf      *m,
4990               uint8_t          contents)
4991 {
4992     char * type;
4993     int i = 0;
4994
4995     if (!(sc->debug & DBG_MBUF)) {
4996         return;
4997     }
4998
4999     if (m == NULL) {
5000         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
5001         return;
5002     }
5003
5004     while (m) {
5005         BLOGD(sc, DBG_MBUF,
5006               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
5007               i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
5008
5009         if (m->m_flags & M_PKTHDR) {
5010              BLOGD(sc, DBG_MBUF,
5011                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
5012                    i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
5013                    (int)m->m_pkthdr.csum_flags, CSUM_BITS);
5014         }
5015
5016         if (m->m_flags & M_EXT) {
5017             switch (m->m_ext.ext_type) {
5018             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
5019             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
5020             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
5021             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
5022             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
5023             case EXT_PACKET:     type = "EXT_PACKET";     break;
5024             case EXT_MBUF:       type = "EXT_MBUF";       break;
5025             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
5026             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
5027             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
5028             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
5029             default:             type = "UNKNOWN";        break;
5030             }
5031
5032             BLOGD(sc, DBG_MBUF,
5033                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
5034                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
5035         }
5036
5037         if (contents) {
5038             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
5039         }
5040
5041         m = m->m_next;
5042         i++;
5043     }
5044 }
5045
5046 /*
5047  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
5048  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
5049  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
5050  * The headers comes in a seperate bd in FreeBSD so 13-3=10.
5051  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
5052  */
5053 static int
5054 bxe_chktso_window(struct bxe_softc  *sc,
5055                   int               nsegs,
5056                   bus_dma_segment_t *segs,
5057                   struct mbuf       *m)
5058 {
5059     uint32_t num_wnds, wnd_size, wnd_sum;
5060     int32_t frag_idx, wnd_idx;
5061     unsigned short lso_mss;
5062     int defrag;
5063
5064     defrag = 0;
5065     wnd_sum = 0;
5066     wnd_size = 10;
5067     num_wnds = nsegs - wnd_size;
5068     lso_mss = htole16(m->m_pkthdr.tso_segsz);
5069
5070     /*
5071      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
5072      * first window sum of data while skipping the first assuming it is the
5073      * header in FreeBSD.
5074      */
5075     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
5076         wnd_sum += htole16(segs[frag_idx].ds_len);
5077     }
5078
5079     /* check the first 10 bd window size */
5080     if (wnd_sum < lso_mss) {
5081         return (1);
5082     }
5083
5084     /* run through the windows */
5085     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
5086         /* subtract the first mbuf->m_len of the last wndw(-header) */
5087         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
5088         /* add the next mbuf len to the len of our new window */
5089         wnd_sum += htole16(segs[frag_idx].ds_len);
5090         if (wnd_sum < lso_mss) {
5091             return (1);
5092         }
5093     }
5094
5095     return (0);
5096 }
5097
5098 static uint8_t
5099 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
5100                     struct mbuf         *m,
5101                     uint32_t            *parsing_data)
5102 {
5103     struct ether_vlan_header *eh = NULL;
5104     struct ip *ip4 = NULL;
5105     struct ip6_hdr *ip6 = NULL;
5106     caddr_t ip = NULL;
5107     struct tcphdr *th = NULL;
5108     int e_hlen, ip_hlen, l4_off;
5109     uint16_t proto;
5110
5111     if (m->m_pkthdr.csum_flags == CSUM_IP) {
5112         /* no L4 checksum offload needed */
5113         return (0);
5114     }
5115
5116     /* get the Ethernet header */
5117     eh = mtod(m, struct ether_vlan_header *);
5118
5119     /* handle VLAN encapsulation if present */
5120     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
5121         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
5122         proto  = ntohs(eh->evl_proto);
5123     } else {
5124         e_hlen = ETHER_HDR_LEN;
5125         proto  = ntohs(eh->evl_encap_proto);
5126     }
5127
5128     switch (proto) {
5129     case ETHERTYPE_IP:
5130         /* get the IP header, if mbuf len < 20 then header in next mbuf */
5131         ip4 = (m->m_len < sizeof(struct ip)) ?
5132                   (struct ip *)m->m_next->m_data :
5133                   (struct ip *)(m->m_data + e_hlen);
5134         /* ip_hl is number of 32-bit words */
5135         ip_hlen = (ip4->ip_hl << 2);
5136         ip = (caddr_t)ip4;
5137         break;
5138     case ETHERTYPE_IPV6:
5139         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
5140         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
5141                   (struct ip6_hdr *)m->m_next->m_data :
5142                   (struct ip6_hdr *)(m->m_data + e_hlen);
5143         /* XXX cannot support offload with IPv6 extensions */
5144         ip_hlen = sizeof(struct ip6_hdr);
5145         ip = (caddr_t)ip6;
5146         break;
5147     default:
5148         /* We can't offload in this case... */
5149         /* XXX error stat ??? */
5150         return (0);
5151     }
5152
5153     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5154     l4_off = (e_hlen + ip_hlen);
5155
5156     *parsing_data |=
5157         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
5158          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
5159
5160     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5161                                   CSUM_TSO |
5162                                   CSUM_TCP_IPV6)) {
5163         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5164         th = (struct tcphdr *)(ip + ip_hlen);
5165         /* th_off is number of 32-bit words */
5166         *parsing_data |= ((th->th_off <<
5167                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
5168                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
5169         return (l4_off + (th->th_off << 2)); /* entire header length */
5170     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5171                                          CSUM_UDP_IPV6)) {
5172         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5173         return (l4_off + sizeof(struct udphdr)); /* entire header length */
5174     } else {
5175         /* XXX error stat ??? */
5176         return (0);
5177     }
5178 }
5179
5180 static uint8_t
5181 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
5182                  struct mbuf                *m,
5183                  struct eth_tx_parse_bd_e1x *pbd)
5184 {
5185     struct ether_vlan_header *eh = NULL;
5186     struct ip *ip4 = NULL;
5187     struct ip6_hdr *ip6 = NULL;
5188     caddr_t ip = NULL;
5189     struct tcphdr *th = NULL;
5190     struct udphdr *uh = NULL;
5191     int e_hlen, ip_hlen;
5192     uint16_t proto;
5193     uint8_t hlen;
5194     uint16_t tmp_csum;
5195     uint32_t *tmp_uh;
5196
5197     /* get the Ethernet header */
5198     eh = mtod(m, struct ether_vlan_header *);
5199
5200     /* handle VLAN encapsulation if present */
5201     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
5202         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
5203         proto  = ntohs(eh->evl_proto);
5204     } else {
5205         e_hlen = ETHER_HDR_LEN;
5206         proto  = ntohs(eh->evl_encap_proto);
5207     }
5208
5209     switch (proto) {
5210     case ETHERTYPE_IP:
5211         /* get the IP header, if mbuf len < 20 then header in next mbuf */
5212         ip4 = (m->m_len < sizeof(struct ip)) ?
5213                   (struct ip *)m->m_next->m_data :
5214                   (struct ip *)(m->m_data + e_hlen);
5215         /* ip_hl is number of 32-bit words */
5216         ip_hlen = (ip4->ip_hl << 1);
5217         ip = (caddr_t)ip4;
5218         break;
5219     case ETHERTYPE_IPV6:
5220         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
5221         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
5222                   (struct ip6_hdr *)m->m_next->m_data :
5223                   (struct ip6_hdr *)(m->m_data + e_hlen);
5224         /* XXX cannot support offload with IPv6 extensions */
5225         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
5226         ip = (caddr_t)ip6;
5227         break;
5228     default:
5229         /* We can't offload in this case... */
5230         /* XXX error stat ??? */
5231         return (0);
5232     }
5233
5234     hlen = (e_hlen >> 1);
5235
5236     /* note that rest of global_data is indirectly zeroed here */
5237     if (m->m_flags & M_VLANTAG) {
5238         pbd->global_data =
5239             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
5240     } else {
5241         pbd->global_data = htole16(hlen);
5242     }
5243
5244     pbd->ip_hlen_w = ip_hlen;
5245
5246     hlen += pbd->ip_hlen_w;
5247
5248     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5249
5250     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5251                                   CSUM_TSO |
5252                                   CSUM_TCP_IPV6)) {
5253         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5254         /* th_off is number of 32-bit words */
5255         hlen += (uint16_t)(th->th_off << 1);
5256     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5257                                          CSUM_UDP_IPV6)) {
5258         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5259         hlen += (sizeof(struct udphdr) / 2);
5260     } else {
5261         /* valid case as only CSUM_IP was set */
5262         return (0);
5263     }
5264
5265     pbd->total_hlen_w = htole16(hlen);
5266
5267     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5268                                   CSUM_TSO |
5269                                   CSUM_TCP_IPV6)) {
5270         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5271         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5272     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5273                                          CSUM_UDP_IPV6)) {
5274         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5275
5276         /*
5277          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5278          * checksums and does not know anything about the UDP header and where
5279          * the checksum field is located. It only knows about TCP. Therefore
5280          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5281          * offload. Since the checksum field offset for TCP is 16 bytes and
5282          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5283          * bytes less than the start of the UDP header. This allows the
5284          * hardware to write the checksum in the correct spot. But the
5285          * hardware will compute a checksum which includes the last 10 bytes
5286          * of the IP header. To correct this we tweak the stack computed
5287          * pseudo checksum by folding in the calculation of the inverse
5288          * checksum for those final 10 bytes of the IP header. This allows
5289          * the correct checksum to be computed by the hardware.
5290          */
5291
5292         /* set pointer 10 bytes before UDP header */
5293         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5294
5295         /* calculate a pseudo header checksum over the first 10 bytes */
5296         tmp_csum = in_pseudo(*tmp_uh,
5297                              *(tmp_uh + 1),
5298                              *(uint16_t *)(tmp_uh + 2));
5299
5300         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5301     }
5302
5303     return (hlen * 2); /* entire header length, number of bytes */
5304 }
5305
5306 static void
5307 bxe_set_pbd_lso_e2(struct mbuf *m,
5308                    uint32_t    *parsing_data)
5309 {
5310     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5311                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5312                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5313
5314     /* XXX test for IPv6 with extension header... */
5315 #if 0
5316     struct ip6_hdr *ip6;
5317     if (ip6 && ip6->ip6_nxt == 'some ipv6 extension header')
5318         *parsing_data |= ETH_TX_PARSE_BD_E2_IPV6_WITH_EXT_HDR;
5319 #endif
5320 }
5321
5322 static void
5323 bxe_set_pbd_lso(struct mbuf                *m,
5324                 struct eth_tx_parse_bd_e1x *pbd)
5325 {
5326     struct ether_vlan_header *eh = NULL;
5327     struct ip *ip = NULL;
5328     struct tcphdr *th = NULL;
5329     int e_hlen;
5330
5331     /* get the Ethernet header */
5332     eh = mtod(m, struct ether_vlan_header *);
5333
5334     /* handle VLAN encapsulation if present */
5335     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5336                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5337
5338     /* get the IP and TCP header, with LSO entire header in first mbuf */
5339     /* XXX assuming IPv4 */
5340     ip = (struct ip *)(m->m_data + e_hlen);
5341     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5342
5343     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5344     pbd->tcp_send_seq = ntohl(th->th_seq);
5345     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5346
5347 #if 1
5348         /* XXX IPv4 */
5349         pbd->ip_id = ntohs(ip->ip_id);
5350         pbd->tcp_pseudo_csum =
5351             ntohs(in_pseudo(ip->ip_src.s_addr,
5352                             ip->ip_dst.s_addr,
5353                             htons(IPPROTO_TCP)));
5354 #else
5355         /* XXX IPv6 */
5356         pbd->tcp_pseudo_csum =
5357             ntohs(in_pseudo(&ip6->ip6_src,
5358                             &ip6->ip6_dst,
5359                             htons(IPPROTO_TCP)));
5360 #endif
5361
5362     pbd->global_data |=
5363         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5364 }
5365
5366 /*
5367  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5368  * visible to the controller.
5369  *
5370  * If an mbuf is submitted to this routine and cannot be given to the
5371  * controller (e.g. it has too many fragments) then the function may free
5372  * the mbuf and return to the caller.
5373  *
5374  * Returns:
5375  *   0 = Success, !0 = Failure
5376  *   Note the side effect that an mbuf may be freed if it causes a problem.
5377  */
5378 static int
5379 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5380 {
5381     bus_dma_segment_t segs[32];
5382     struct mbuf *m0;
5383     struct bxe_sw_tx_bd *tx_buf;
5384     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5385     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5386     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5387     struct eth_tx_bd *tx_data_bd;
5388     struct eth_tx_bd *tx_total_pkt_size_bd;
5389     struct eth_tx_start_bd *tx_start_bd;
5390     uint16_t bd_prod, pkt_prod, total_pkt_size;
5391     uint8_t mac_type;
5392     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5393     struct bxe_softc *sc;
5394     uint16_t tx_bd_avail;
5395     struct ether_vlan_header *eh;
5396     uint32_t pbd_e2_parsing_data = 0;
5397     uint8_t hlen = 0;
5398     int tmp_bd;
5399     int i;
5400
5401     sc = fp->sc;
5402
5403     M_ASSERTPKTHDR(*m_head);
5404
5405     m0 = *m_head;
5406     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5407     tx_start_bd = NULL;
5408     tx_data_bd = NULL;
5409     tx_total_pkt_size_bd = NULL;
5410
5411     /* get the H/W pointer for packets and BDs */
5412     pkt_prod = fp->tx_pkt_prod;
5413     bd_prod = fp->tx_bd_prod;
5414
5415     mac_type = UNICAST_ADDRESS;
5416
5417     /* map the mbuf into the next open DMAable memory */
5418     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5419     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5420                                     tx_buf->m_map, m0,
5421                                     segs, &nsegs, BUS_DMA_NOWAIT);
5422
5423     /* mapping errors */
5424     if(__predict_false(error != 0)) {
5425         fp->eth_q_stats.tx_dma_mapping_failure++;
5426         if (error == ENOMEM) {
5427             /* resource issue, try again later */
5428             rc = ENOMEM;
5429         } else if (error == EFBIG) {
5430             /* possibly recoverable with defragmentation */
5431             fp->eth_q_stats.mbuf_defrag_attempts++;
5432             m0 = m_defrag(*m_head, M_NOWAIT);
5433             if (m0 == NULL) {
5434                 fp->eth_q_stats.mbuf_defrag_failures++;
5435                 rc = ENOBUFS;
5436             } else {
5437                 /* defrag successful, try mapping again */
5438                 *m_head = m0;
5439                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5440                                                 tx_buf->m_map, m0,
5441                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5442                 if (error) {
5443                     fp->eth_q_stats.tx_dma_mapping_failure++;
5444                     rc = error;
5445                 }
5446             }
5447         } else {
5448             /* unknown, unrecoverable mapping error */
5449             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5450             bxe_dump_mbuf(sc, m0, FALSE);
5451             rc = error;
5452         }
5453
5454         goto bxe_tx_encap_continue;
5455     }
5456
5457     tx_bd_avail = bxe_tx_avail(sc, fp);
5458
5459     /* make sure there is enough room in the send queue */
5460     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5461         /* Recoverable, try again later. */
5462         fp->eth_q_stats.tx_hw_queue_full++;
5463         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5464         rc = ENOMEM;
5465         goto bxe_tx_encap_continue;
5466     }
5467
5468     /* capture the current H/W TX chain high watermark */
5469     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5470                         (TX_BD_USABLE - tx_bd_avail))) {
5471         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5472     }
5473
5474     /* make sure it fits in the packet window */
5475     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5476         /*
5477          * The mbuf may be to big for the controller to handle. If the frame
5478          * is a TSO frame we'll need to do an additional check.
5479          */
5480         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5481             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5482                 goto bxe_tx_encap_continue; /* OK to send */
5483             } else {
5484                 fp->eth_q_stats.tx_window_violation_tso++;
5485             }
5486         } else {
5487             fp->eth_q_stats.tx_window_violation_std++;
5488         }
5489
5490         /* lets try to defragment this mbuf and remap it */
5491         fp->eth_q_stats.mbuf_defrag_attempts++;
5492         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5493
5494         m0 = m_defrag(*m_head, M_NOWAIT);
5495         if (m0 == NULL) {
5496             fp->eth_q_stats.mbuf_defrag_failures++;
5497             /* Ugh, just drop the frame... :( */
5498             rc = ENOBUFS;
5499         } else {
5500             /* defrag successful, try mapping again */
5501             *m_head = m0;
5502             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5503                                             tx_buf->m_map, m0,
5504                                             segs, &nsegs, BUS_DMA_NOWAIT);
5505             if (error) {
5506                 fp->eth_q_stats.tx_dma_mapping_failure++;
5507                 /* No sense in trying to defrag/copy chain, drop it. :( */
5508                 rc = error;
5509             }
5510             else {
5511                 /* if the chain is still too long then drop it */
5512                 if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5513                     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5514                     rc = ENODEV;
5515                 }
5516             }
5517         }
5518     }
5519
5520 bxe_tx_encap_continue:
5521
5522     /* Check for errors */
5523     if (rc) {
5524         if (rc == ENOMEM) {
5525             /* recoverable try again later  */
5526         } else {
5527             fp->eth_q_stats.tx_soft_errors++;
5528             fp->eth_q_stats.mbuf_alloc_tx--;
5529             m_freem(*m_head);
5530             *m_head = NULL;
5531         }
5532
5533         return (rc);
5534     }
5535
5536     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5537     if (m0->m_flags & M_BCAST) {
5538         mac_type = BROADCAST_ADDRESS;
5539     } else if (m0->m_flags & M_MCAST) {
5540         mac_type = MULTICAST_ADDRESS;
5541     }
5542
5543     /* store the mbuf into the mbuf ring */
5544     tx_buf->m        = m0;
5545     tx_buf->first_bd = fp->tx_bd_prod;
5546     tx_buf->flags    = 0;
5547
5548     /* prepare the first transmit (start) BD for the mbuf */
5549     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5550
5551     BLOGD(sc, DBG_TX,
5552           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5553           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5554
5555     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5556     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5557     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5558     total_pkt_size += tx_start_bd->nbytes;
5559     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5560
5561     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5562
5563     /* all frames have at least Start BD + Parsing BD */
5564     nbds = nsegs + 1;
5565     tx_start_bd->nbd = htole16(nbds);
5566
5567     if (m0->m_flags & M_VLANTAG) {
5568         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5569         tx_start_bd->bd_flags.as_bitfield |=
5570             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5571     } else {
5572         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5573         if (IS_VF(sc)) {
5574             /* map ethernet header to find type and header length */
5575             eh = mtod(m0, struct ether_vlan_header *);
5576             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5577         } else {
5578             /* used by FW for packet accounting */
5579             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5580 #if 0
5581             /*
5582              * If NPAR-SD is active then FW should do the tagging regardless
5583              * of value of priority. Otherwise, if priority indicates this is
5584              * a control packet we need to indicate to FW to avoid tagging.
5585              */
5586             if (!IS_MF_AFEX(sc) && (mbuf priority == PRIO_CONTROL)) {
5587                 SET_FLAG(tx_start_bd->general_data,
5588                          ETH_TX_START_BD_FORCE_VLAN_MODE, 1);
5589             }
5590 #endif
5591         }
5592     }
5593
5594     /*
5595      * add a parsing BD from the chain. The parsing BD is always added
5596      * though it is only used for TSO and chksum
5597      */
5598     bd_prod = TX_BD_NEXT(bd_prod);
5599
5600     if (m0->m_pkthdr.csum_flags) {
5601         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5602             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5603             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5604         }
5605
5606         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5607             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5608                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5609         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5610             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5611                                                   ETH_TX_BD_FLAGS_IS_UDP |
5612                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5613         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5614                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5615             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5616         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5617             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5618                                                   ETH_TX_BD_FLAGS_IS_UDP);
5619         }
5620     }
5621
5622     if (!CHIP_IS_E1x(sc)) {
5623         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5624         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5625
5626         if (m0->m_pkthdr.csum_flags) {
5627             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5628         }
5629
5630 #if 0
5631         /*
5632          * Add the MACs to the parsing BD if the module param was
5633          * explicitly set, if this is a vf, or in switch independent
5634          * mode.
5635          */
5636         if (sc->flags & BXE_TX_SWITCHING || IS_VF(sc) || IS_MF_SI(sc)) {
5637             eh = mtod(m0, struct ether_vlan_header *);
5638             bxe_set_fw_mac_addr(&pbd_e2->data.mac_addr.src_hi,
5639                                 &pbd_e2->data.mac_addr.src_mid,
5640                                 &pbd_e2->data.mac_addr.src_lo,
5641                                 eh->evl_shost);
5642             bxe_set_fw_mac_addr(&pbd_e2->data.mac_addr.dst_hi,
5643                                 &pbd_e2->data.mac_addr.dst_mid,
5644                                 &pbd_e2->data.mac_addr.dst_lo,
5645                                 eh->evl_dhost);
5646         }
5647 #endif
5648
5649         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5650                  mac_type);
5651     } else {
5652         uint16_t global_data = 0;
5653
5654         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5655         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5656
5657         if (m0->m_pkthdr.csum_flags) {
5658             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5659         }
5660
5661         SET_FLAG(global_data,
5662                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5663         pbd_e1x->global_data |= htole16(global_data);
5664     }
5665
5666     /* setup the parsing BD with TSO specific info */
5667     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5668         fp->eth_q_stats.tx_ofld_frames_lso++;
5669         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5670
5671         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5672             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5673
5674             /* split the first BD into header/data making the fw job easy */
5675             nbds++;
5676             tx_start_bd->nbd = htole16(nbds);
5677             tx_start_bd->nbytes = htole16(hlen);
5678
5679             bd_prod = TX_BD_NEXT(bd_prod);
5680
5681             /* new transmit BD after the tx_parse_bd */
5682             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5683             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5684             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5685             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5686             if (tx_total_pkt_size_bd == NULL) {
5687                 tx_total_pkt_size_bd = tx_data_bd;
5688             }
5689
5690             BLOGD(sc, DBG_TX,
5691                   "TSO split header size is %d (%x:%x) nbds %d\n",
5692                   le16toh(tx_start_bd->nbytes),
5693                   le32toh(tx_start_bd->addr_hi),
5694                   le32toh(tx_start_bd->addr_lo),
5695                   nbds);
5696         }
5697
5698         if (!CHIP_IS_E1x(sc)) {
5699             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5700         } else {
5701             bxe_set_pbd_lso(m0, pbd_e1x);
5702         }
5703     }
5704
5705     if (pbd_e2_parsing_data) {
5706         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5707     }
5708
5709     /* prepare remaining BDs, start tx bd contains first seg/frag */
5710     for (i = 1; i < nsegs ; i++) {
5711         bd_prod = TX_BD_NEXT(bd_prod);
5712         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5713         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5714         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5715         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5716         if (tx_total_pkt_size_bd == NULL) {
5717             tx_total_pkt_size_bd = tx_data_bd;
5718         }
5719         total_pkt_size += tx_data_bd->nbytes;
5720     }
5721
5722     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5723
5724     if (tx_total_pkt_size_bd != NULL) {
5725         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5726     }
5727
5728     if (__predict_false(sc->debug & DBG_TX)) {
5729         tmp_bd = tx_buf->first_bd;
5730         for (i = 0; i < nbds; i++)
5731         {
5732             if (i == 0) {
5733                 BLOGD(sc, DBG_TX,
5734                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5735                       "bd_flags=0x%x hdr_nbds=%d\n",
5736                       tx_start_bd,
5737                       tmp_bd,
5738                       le16toh(tx_start_bd->nbd),
5739                       le16toh(tx_start_bd->vlan_or_ethertype),
5740                       tx_start_bd->bd_flags.as_bitfield,
5741                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5742             } else if (i == 1) {
5743                 if (pbd_e1x) {
5744                     BLOGD(sc, DBG_TX,
5745                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5746                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5747                           "tcp_seq=%u total_hlen_w=%u\n",
5748                           pbd_e1x,
5749                           tmp_bd,
5750                           pbd_e1x->global_data,
5751                           pbd_e1x->ip_hlen_w,
5752                           pbd_e1x->ip_id,
5753                           pbd_e1x->lso_mss,
5754                           pbd_e1x->tcp_flags,
5755                           pbd_e1x->tcp_pseudo_csum,
5756                           pbd_e1x->tcp_send_seq,
5757                           le16toh(pbd_e1x->total_hlen_w));
5758                 } else { /* if (pbd_e2) */
5759                     BLOGD(sc, DBG_TX,
5760                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5761                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5762                           pbd_e2,
5763                           tmp_bd,
5764                           pbd_e2->data.mac_addr.dst_hi,
5765                           pbd_e2->data.mac_addr.dst_mid,
5766                           pbd_e2->data.mac_addr.dst_lo,
5767                           pbd_e2->data.mac_addr.src_hi,
5768                           pbd_e2->data.mac_addr.src_mid,
5769                           pbd_e2->data.mac_addr.src_lo,
5770                           pbd_e2->parsing_data);
5771                 }
5772             }
5773
5774             if (i != 1) { /* skip parse db as it doesn't hold data */
5775                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5776                 BLOGD(sc, DBG_TX,
5777                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5778                       tx_data_bd,
5779                       tmp_bd,
5780                       le16toh(tx_data_bd->nbytes),
5781                       le32toh(tx_data_bd->addr_hi),
5782                       le32toh(tx_data_bd->addr_lo));
5783             }
5784
5785             tmp_bd = TX_BD_NEXT(tmp_bd);
5786         }
5787     }
5788
5789     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5790
5791     /* update TX BD producer index value for next TX */
5792     bd_prod = TX_BD_NEXT(bd_prod);
5793
5794     /*
5795      * If the chain of tx_bd's describing this frame is adjacent to or spans
5796      * an eth_tx_next_bd element then we need to increment the nbds value.
5797      */
5798     if (TX_BD_IDX(bd_prod) < nbds) {
5799         nbds++;
5800     }
5801
5802     /* don't allow reordering of writes for nbd and packets */
5803     mb();
5804
5805     fp->tx_db.data.prod += nbds;
5806
5807     /* producer points to the next free tx_bd at this point */
5808     fp->tx_pkt_prod++;
5809     fp->tx_bd_prod = bd_prod;
5810
5811     DOORBELL(sc, fp->index, fp->tx_db.raw);
5812
5813     fp->eth_q_stats.tx_pkts++;
5814
5815     /* Prevent speculative reads from getting ahead of the status block. */
5816     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5817                       0, 0, BUS_SPACE_BARRIER_READ);
5818
5819     /* Prevent speculative reads from getting ahead of the doorbell. */
5820     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5821                       0, 0, BUS_SPACE_BARRIER_READ);
5822
5823     return (0);
5824 }
5825
5826 static void
5827 bxe_tx_start_locked(struct bxe_softc *sc,
5828                     if_t ifp,
5829                     struct bxe_fastpath *fp)
5830 {
5831     struct mbuf *m = NULL;
5832     int tx_count = 0;
5833     uint16_t tx_bd_avail;
5834
5835     BXE_FP_TX_LOCK_ASSERT(fp);
5836
5837     /* keep adding entries while there are frames to send */
5838     while (!if_sendq_empty(ifp)) {
5839
5840         /*
5841          * check for any frames to send
5842          * dequeue can still be NULL even if queue is not empty
5843          */
5844         m = if_dequeue(ifp);
5845         if (__predict_false(m == NULL)) {
5846             break;
5847         }
5848
5849         /* the mbuf now belongs to us */
5850         fp->eth_q_stats.mbuf_alloc_tx++;
5851
5852         /*
5853          * Put the frame into the transmit ring. If we don't have room,
5854          * place the mbuf back at the head of the TX queue, set the
5855          * OACTIVE flag, and wait for the NIC to drain the chain.
5856          */
5857         if (__predict_false(bxe_tx_encap(fp, &m))) {
5858             fp->eth_q_stats.tx_encap_failures++;
5859             if (m != NULL) {
5860                 /* mark the TX queue as full and return the frame */
5861                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5862                 if_sendq_prepend(ifp, m);
5863                 fp->eth_q_stats.mbuf_alloc_tx--;
5864                 fp->eth_q_stats.tx_queue_xoff++;
5865             }
5866
5867             /* stop looking for more work */
5868             break;
5869         }
5870
5871         /* the frame was enqueued successfully */
5872         tx_count++;
5873
5874         /* send a copy of the frame to any BPF listeners. */
5875         if_etherbpfmtap(ifp, m);
5876
5877         tx_bd_avail = bxe_tx_avail(sc, fp);
5878
5879         /* handle any completions if we're running low */
5880         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5881             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5882             bxe_txeof(sc, fp);
5883             if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5884                 break;
5885             }
5886         }
5887     }
5888
5889     /* all TX packets were dequeued and/or the tx ring is full */
5890     if (tx_count > 0) {
5891         /* reset the TX watchdog timeout timer */
5892         fp->watchdog_timer = BXE_TX_TIMEOUT;
5893     }
5894 }
5895
5896 /* Legacy (non-RSS) dispatch routine */
5897 static void
5898 bxe_tx_start(if_t ifp)
5899 {
5900     struct bxe_softc *sc;
5901     struct bxe_fastpath *fp;
5902
5903     sc = if_getsoftc(ifp);
5904
5905     if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5906         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5907         return;
5908     }
5909
5910     if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5911         BLOGW(sc, "Interface TX queue is full, ignoring transmit request\n");
5912         return;
5913     }
5914
5915     if (!sc->link_vars.link_up) {
5916         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5917         return;
5918     }
5919
5920     fp = &sc->fp[0];
5921
5922     BXE_FP_TX_LOCK(fp);
5923     bxe_tx_start_locked(sc, ifp, fp);
5924     BXE_FP_TX_UNLOCK(fp);
5925 }
5926
5927 #if __FreeBSD_version >= 800000
5928
5929 static int
5930 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5931                        if_t                ifp,
5932                        struct bxe_fastpath *fp,
5933                        struct mbuf         *m)
5934 {
5935     struct buf_ring *tx_br = fp->tx_br;
5936     struct mbuf *next;
5937     int depth, rc, tx_count;
5938     uint16_t tx_bd_avail;
5939
5940     rc = tx_count = 0;
5941
5942     if (!tx_br) {
5943         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5944         return (EINVAL);
5945     }
5946
5947     /* fetch the depth of the driver queue */
5948     depth = drbr_inuse_drv(ifp, tx_br);
5949     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5950         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5951     }
5952
5953     BXE_FP_TX_LOCK_ASSERT(fp);
5954
5955     if (m == NULL) {
5956         /* no new work, check for pending frames */
5957         next = drbr_dequeue_drv(ifp, tx_br);
5958     } else if (drbr_needs_enqueue_drv(ifp, tx_br)) {
5959         /* have both new and pending work, maintain packet order */
5960         rc = drbr_enqueue_drv(ifp, tx_br, m);
5961         if (rc != 0) {
5962             fp->eth_q_stats.tx_soft_errors++;
5963             goto bxe_tx_mq_start_locked_exit;
5964         }
5965         next = drbr_dequeue_drv(ifp, tx_br);
5966     } else {
5967         /* new work only and nothing pending */
5968         next = m;
5969     }
5970
5971     /* keep adding entries while there are frames to send */
5972     while (next != NULL) {
5973
5974         /* the mbuf now belongs to us */
5975         fp->eth_q_stats.mbuf_alloc_tx++;
5976
5977         /*
5978          * Put the frame into the transmit ring. If we don't have room,
5979          * place the mbuf back at the head of the TX queue, set the
5980          * OACTIVE flag, and wait for the NIC to drain the chain.
5981          */
5982         rc = bxe_tx_encap(fp, &next);
5983         if (__predict_false(rc != 0)) {
5984             fp->eth_q_stats.tx_encap_failures++;
5985             if (next != NULL) {
5986                 /* mark the TX queue as full and save the frame */
5987                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5988                 /* XXX this may reorder the frame */
5989                 rc = drbr_enqueue_drv(ifp, tx_br, next);
5990                 fp->eth_q_stats.mbuf_alloc_tx--;
5991                 fp->eth_q_stats.tx_frames_deferred++;
5992             }
5993
5994             /* stop looking for more work */
5995             break;
5996         }
5997
5998         /* the transmit frame was enqueued successfully */
5999         tx_count++;
6000
6001         /* send a copy of the frame to any BPF listeners */
6002         if_etherbpfmtap(ifp, next);
6003
6004         tx_bd_avail = bxe_tx_avail(sc, fp);
6005
6006         /* handle any completions if we're running low */
6007         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
6008             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
6009             bxe_txeof(sc, fp);
6010             if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
6011                 break;
6012             }
6013         }
6014
6015         next = drbr_dequeue_drv(ifp, tx_br);
6016     }
6017
6018     /* all TX packets were dequeued and/or the tx ring is full */
6019     if (tx_count > 0) {
6020         /* reset the TX watchdog timeout timer */
6021         fp->watchdog_timer = BXE_TX_TIMEOUT;
6022     }
6023
6024 bxe_tx_mq_start_locked_exit:
6025
6026     return (rc);
6027 }
6028
6029 /* Multiqueue (TSS) dispatch routine. */
6030 static int
6031 bxe_tx_mq_start(struct ifnet *ifp,
6032                 struct mbuf  *m)
6033 {
6034     struct bxe_softc *sc = if_getsoftc(ifp);
6035     struct bxe_fastpath *fp;
6036     int fp_index, rc;
6037
6038     fp_index = 0; /* default is the first queue */
6039
6040     /* check if flowid is set */
6041     if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
6042         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
6043
6044     fp = &sc->fp[fp_index];
6045
6046     if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6047         BLOGW(sc, "Interface not running, ignoring transmit request\n");
6048         return (ENETDOWN);
6049     }
6050
6051     if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
6052         BLOGW(sc, "Interface TX queue is full, ignoring transmit request\n");
6053         return (EBUSY);
6054     }
6055
6056     if (!sc->link_vars.link_up) {
6057         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
6058         return (ENETDOWN);
6059     }
6060
6061     /* XXX change to TRYLOCK here and if failed then schedule taskqueue */
6062
6063     BXE_FP_TX_LOCK(fp);
6064     rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
6065     BXE_FP_TX_UNLOCK(fp);
6066
6067     return (rc);
6068 }
6069
6070 static void
6071 bxe_mq_flush(struct ifnet *ifp)
6072 {
6073     struct bxe_softc *sc = if_getsoftc(ifp);
6074     struct bxe_fastpath *fp;
6075     struct mbuf *m;
6076     int i;
6077
6078     for (i = 0; i < sc->num_queues; i++) {
6079         fp = &sc->fp[i];
6080
6081         if (fp->state != BXE_FP_STATE_OPEN) {
6082             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
6083                   fp->index, fp->state);
6084             continue;
6085         }
6086
6087         if (fp->tx_br != NULL) {
6088             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
6089             BXE_FP_TX_LOCK(fp);
6090             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
6091                 m_freem(m);
6092             }
6093             BXE_FP_TX_UNLOCK(fp);
6094         }
6095     }
6096
6097     if_qflush(ifp);
6098 }
6099
6100 #endif /* FreeBSD_version >= 800000 */
6101
6102 static uint16_t
6103 bxe_cid_ilt_lines(struct bxe_softc *sc)
6104 {
6105     if (IS_SRIOV(sc)) {
6106         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
6107     }
6108     return (L2_ILT_LINES(sc));
6109 }
6110
6111 static void
6112 bxe_ilt_set_info(struct bxe_softc *sc)
6113 {
6114     struct ilt_client_info *ilt_client;
6115     struct ecore_ilt *ilt = sc->ilt;
6116     uint16_t line = 0;
6117
6118     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
6119     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
6120
6121     /* CDU */
6122     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
6123     ilt_client->client_num = ILT_CLIENT_CDU;
6124     ilt_client->page_size = CDU_ILT_PAGE_SZ;
6125     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
6126     ilt_client->start = line;
6127     line += bxe_cid_ilt_lines(sc);
6128
6129     if (CNIC_SUPPORT(sc)) {
6130         line += CNIC_ILT_LINES;
6131     }
6132
6133     ilt_client->end = (line - 1);
6134
6135     BLOGD(sc, DBG_LOAD,
6136           "ilt client[CDU]: start %d, end %d, "
6137           "psz 0x%x, flags 0x%x, hw psz %d\n",
6138           ilt_client->start, ilt_client->end,
6139           ilt_client->page_size,
6140           ilt_client->flags,
6141           ilog2(ilt_client->page_size >> 12));
6142
6143     /* QM */
6144     if (QM_INIT(sc->qm_cid_count)) {
6145         ilt_client = &ilt->clients[ILT_CLIENT_QM];
6146         ilt_client->client_num = ILT_CLIENT_QM;
6147         ilt_client->page_size = QM_ILT_PAGE_SZ;
6148         ilt_client->flags = 0;
6149         ilt_client->start = line;
6150
6151         /* 4 bytes for each cid */
6152         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
6153                              QM_ILT_PAGE_SZ);
6154
6155         ilt_client->end = (line - 1);
6156
6157         BLOGD(sc, DBG_LOAD,
6158               "ilt client[QM]: start %d, end %d, "
6159               "psz 0x%x, flags 0x%x, hw psz %d\n",
6160               ilt_client->start, ilt_client->end,
6161               ilt_client->page_size, ilt_client->flags,
6162               ilog2(ilt_client->page_size >> 12));
6163     }
6164
6165     if (CNIC_SUPPORT(sc)) {
6166         /* SRC */
6167         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
6168         ilt_client->client_num = ILT_CLIENT_SRC;
6169         ilt_client->page_size = SRC_ILT_PAGE_SZ;
6170         ilt_client->flags = 0;
6171         ilt_client->start = line;
6172         line += SRC_ILT_LINES;
6173         ilt_client->end = (line - 1);
6174
6175         BLOGD(sc, DBG_LOAD,
6176               "ilt client[SRC]: start %d, end %d, "
6177               "psz 0x%x, flags 0x%x, hw psz %d\n",
6178               ilt_client->start, ilt_client->end,
6179               ilt_client->page_size, ilt_client->flags,
6180               ilog2(ilt_client->page_size >> 12));
6181
6182         /* TM */
6183         ilt_client = &ilt->clients[ILT_CLIENT_TM];
6184         ilt_client->client_num = ILT_CLIENT_TM;
6185         ilt_client->page_size = TM_ILT_PAGE_SZ;
6186         ilt_client->flags = 0;
6187         ilt_client->start = line;
6188         line += TM_ILT_LINES;
6189         ilt_client->end = (line - 1);
6190
6191         BLOGD(sc, DBG_LOAD,
6192               "ilt client[TM]: start %d, end %d, "
6193               "psz 0x%x, flags 0x%x, hw psz %d\n",
6194               ilt_client->start, ilt_client->end,
6195               ilt_client->page_size, ilt_client->flags,
6196               ilog2(ilt_client->page_size >> 12));
6197     }
6198
6199     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
6200 }
6201
6202 static void
6203 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
6204 {
6205     int i;
6206
6207     BLOGD(sc, DBG_LOAD, "mtu = %d\n", sc->mtu);
6208
6209     for (i = 0; i < sc->num_queues; i++) {
6210         /* get the Rx buffer size for RX frames */
6211         sc->fp[i].rx_buf_size =
6212             (IP_HEADER_ALIGNMENT_PADDING +
6213              ETH_OVERHEAD +
6214              sc->mtu);
6215
6216         BLOGD(sc, DBG_LOAD, "rx_buf_size for fp[%02d] = %d\n",
6217               i, sc->fp[i].rx_buf_size);
6218
6219         /* get the mbuf allocation size for RX frames */
6220         if (sc->fp[i].rx_buf_size <= MCLBYTES) {
6221             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6222         } else if (sc->fp[i].rx_buf_size <= BCM_PAGE_SIZE) {
6223             sc->fp[i].mbuf_alloc_size = PAGE_SIZE;
6224         } else {
6225             sc->fp[i].mbuf_alloc_size = MJUM9BYTES;
6226         }
6227
6228         BLOGD(sc, DBG_LOAD, "mbuf_alloc_size for fp[%02d] = %d\n",
6229               i, sc->fp[i].mbuf_alloc_size);
6230     }
6231 }
6232
6233 static int
6234 bxe_alloc_ilt_mem(struct bxe_softc *sc)
6235 {
6236     int rc = 0;
6237
6238     if ((sc->ilt =
6239          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
6240                                     M_BXE_ILT,
6241                                     (M_NOWAIT | M_ZERO))) == NULL) {
6242         rc = 1;
6243     }
6244
6245     return (rc);
6246 }
6247
6248 static int
6249 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
6250 {
6251     int rc = 0;
6252
6253     if ((sc->ilt->lines =
6254          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6255                                     M_BXE_ILT,
6256                                     (M_NOWAIT | M_ZERO))) == NULL) {
6257         rc = 1;
6258     }
6259
6260     return (rc);
6261 }
6262
6263 static void
6264 bxe_free_ilt_mem(struct bxe_softc *sc)
6265 {
6266     if (sc->ilt != NULL) {
6267         free(sc->ilt, M_BXE_ILT);
6268         sc->ilt = NULL;
6269     }
6270 }
6271
6272 static void
6273 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6274 {
6275     if (sc->ilt->lines != NULL) {
6276         free(sc->ilt->lines, M_BXE_ILT);
6277         sc->ilt->lines = NULL;
6278     }
6279 }
6280
6281 static void
6282 bxe_free_mem(struct bxe_softc *sc)
6283 {
6284     int i;
6285
6286 #if 0
6287     if (!CONFIGURE_NIC_MODE(sc)) {
6288         /* free searcher T2 table */
6289         bxe_dma_free(sc, &sc->t2);
6290     }
6291 #endif
6292
6293     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6294         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6295         sc->context[i].vcxt = NULL;
6296         sc->context[i].size = 0;
6297     }
6298
6299     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6300
6301     bxe_free_ilt_lines_mem(sc);
6302
6303 #if 0
6304     bxe_iov_free_mem(sc);
6305 #endif
6306 }
6307
6308 static int
6309 bxe_alloc_mem(struct bxe_softc *sc)
6310 {
6311     int context_size;
6312     int allocated;
6313     int i;
6314
6315 #if 0
6316     if (!CONFIGURE_NIC_MODE(sc)) {
6317         /* allocate searcher T2 table */
6318         if (bxe_dma_alloc(sc, SRC_T2_SZ,
6319                           &sc->t2, "searcher t2 table") != 0) {
6320             return (-1);
6321         }
6322     }
6323 #endif
6324
6325     /*
6326      * Allocate memory for CDU context:
6327      * This memory is allocated separately and not in the generic ILT
6328      * functions because CDU differs in few aspects:
6329      * 1. There can be multiple entities allocating memory for context -
6330      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6331      * its own ILT lines.
6332      * 2. Since CDU page-size is not a single 4KB page (which is the case
6333      * for the other ILT clients), to be efficient we want to support
6334      * allocation of sub-page-size in the last entry.
6335      * 3. Context pointers are used by the driver to pass to FW / update
6336      * the context (for the other ILT clients the pointers are used just to
6337      * free the memory during unload).
6338      */
6339     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6340     for (i = 0, allocated = 0; allocated < context_size; i++) {
6341         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6342                                   (context_size - allocated));
6343
6344         if (bxe_dma_alloc(sc, sc->context[i].size,
6345                           &sc->context[i].vcxt_dma,
6346                           "cdu context") != 0) {
6347             bxe_free_mem(sc);
6348             return (-1);
6349         }
6350
6351         sc->context[i].vcxt =
6352             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6353
6354         allocated += sc->context[i].size;
6355     }
6356
6357     bxe_alloc_ilt_lines_mem(sc);
6358
6359     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6360           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6361     {
6362         for (i = 0; i < 4; i++) {
6363             BLOGD(sc, DBG_LOAD,
6364                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6365                   i,
6366                   sc->ilt->clients[i].page_size,
6367                   sc->ilt->clients[i].start,
6368                   sc->ilt->clients[i].end,
6369                   sc->ilt->clients[i].client_num,
6370                   sc->ilt->clients[i].flags);
6371         }
6372     }
6373     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6374         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6375         bxe_free_mem(sc);
6376         return (-1);
6377     }
6378
6379 #if 0
6380     if (bxe_iov_alloc_mem(sc)) {
6381         BLOGE(sc, "Failed to allocate memory for SRIOV\n");
6382         bxe_free_mem(sc);
6383         return (-1);
6384     }
6385 #endif
6386
6387     return (0);
6388 }
6389
6390 static void
6391 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6392 {
6393     struct bxe_softc *sc;
6394     int i;
6395
6396     sc = fp->sc;
6397
6398     if (fp->rx_mbuf_tag == NULL) {
6399         return;
6400     }
6401
6402     /* free all mbufs and unload all maps */
6403     for (i = 0; i < RX_BD_TOTAL; i++) {
6404         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6405             bus_dmamap_sync(fp->rx_mbuf_tag,
6406                             fp->rx_mbuf_chain[i].m_map,
6407                             BUS_DMASYNC_POSTREAD);
6408             bus_dmamap_unload(fp->rx_mbuf_tag,
6409                               fp->rx_mbuf_chain[i].m_map);
6410         }
6411
6412         if (fp->rx_mbuf_chain[i].m != NULL) {
6413             m_freem(fp->rx_mbuf_chain[i].m);
6414             fp->rx_mbuf_chain[i].m = NULL;
6415             fp->eth_q_stats.mbuf_alloc_rx--;
6416         }
6417     }
6418 }
6419
6420 static void
6421 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6422 {
6423     struct bxe_softc *sc;
6424     int i, max_agg_queues;
6425
6426     sc = fp->sc;
6427
6428     if (fp->rx_mbuf_tag == NULL) {
6429         return;
6430     }
6431
6432     max_agg_queues = MAX_AGG_QS(sc);
6433
6434     /* release all mbufs and unload all DMA maps in the TPA pool */
6435     for (i = 0; i < max_agg_queues; i++) {
6436         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6437             bus_dmamap_sync(fp->rx_mbuf_tag,
6438                             fp->rx_tpa_info[i].bd.m_map,
6439                             BUS_DMASYNC_POSTREAD);
6440             bus_dmamap_unload(fp->rx_mbuf_tag,
6441                               fp->rx_tpa_info[i].bd.m_map);
6442         }
6443
6444         if (fp->rx_tpa_info[i].bd.m != NULL) {
6445             m_freem(fp->rx_tpa_info[i].bd.m);
6446             fp->rx_tpa_info[i].bd.m = NULL;
6447             fp->eth_q_stats.mbuf_alloc_tpa--;
6448         }
6449     }
6450 }
6451
6452 static void
6453 bxe_free_sge_chain(struct bxe_fastpath *fp)
6454 {
6455     struct bxe_softc *sc;
6456     int i;
6457
6458     sc = fp->sc;
6459
6460     if (fp->rx_sge_mbuf_tag == NULL) {
6461         return;
6462     }
6463
6464     /* rree all mbufs and unload all maps */
6465     for (i = 0; i < RX_SGE_TOTAL; i++) {
6466         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6467             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6468                             fp->rx_sge_mbuf_chain[i].m_map,
6469                             BUS_DMASYNC_POSTREAD);
6470             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6471                               fp->rx_sge_mbuf_chain[i].m_map);
6472         }
6473
6474         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6475             m_freem(fp->rx_sge_mbuf_chain[i].m);
6476             fp->rx_sge_mbuf_chain[i].m = NULL;
6477             fp->eth_q_stats.mbuf_alloc_sge--;
6478         }
6479     }
6480 }
6481
6482 static void
6483 bxe_free_fp_buffers(struct bxe_softc *sc)
6484 {
6485     struct bxe_fastpath *fp;
6486     int i;
6487
6488     for (i = 0; i < sc->num_queues; i++) {
6489         fp = &sc->fp[i];
6490
6491 #if __FreeBSD_version >= 800000
6492         if (fp->tx_br != NULL) {
6493             struct mbuf *m;
6494             /* just in case bxe_mq_flush() wasn't called */
6495             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
6496                 m_freem(m);
6497             }
6498             buf_ring_free(fp->tx_br, M_DEVBUF);
6499             fp->tx_br = NULL;
6500         }
6501 #endif
6502
6503         /* free all RX buffers */
6504         bxe_free_rx_bd_chain(fp);
6505         bxe_free_tpa_pool(fp);
6506         bxe_free_sge_chain(fp);
6507
6508         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6509             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6510                   fp->eth_q_stats.mbuf_alloc_rx);
6511         }
6512
6513         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6514             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6515                   fp->eth_q_stats.mbuf_alloc_sge);
6516         }
6517
6518         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6519             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6520                   fp->eth_q_stats.mbuf_alloc_tpa);
6521         }
6522
6523         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6524             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6525                   fp->eth_q_stats.mbuf_alloc_tx);
6526         }
6527
6528         /* XXX verify all mbufs were reclaimed */
6529
6530         if (mtx_initialized(&fp->tx_mtx)) {
6531             mtx_destroy(&fp->tx_mtx);
6532         }
6533
6534         if (mtx_initialized(&fp->rx_mtx)) {
6535             mtx_destroy(&fp->rx_mtx);
6536         }
6537     }
6538 }
6539
6540 static int
6541 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6542                      uint16_t            prev_index,
6543                      uint16_t            index)
6544 {
6545     struct bxe_sw_rx_bd *rx_buf;
6546     struct eth_rx_bd *rx_bd;
6547     bus_dma_segment_t segs[1];
6548     bus_dmamap_t map;
6549     struct mbuf *m;
6550     int nsegs, rc;
6551
6552     rc = 0;
6553
6554     /* allocate the new RX BD mbuf */
6555     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6556     if (__predict_false(m == NULL)) {
6557         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6558         return (ENOBUFS);
6559     }
6560
6561     fp->eth_q_stats.mbuf_alloc_rx++;
6562
6563     /* initialize the mbuf buffer length */
6564     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6565
6566     /* map the mbuf into non-paged pool */
6567     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6568                                  fp->rx_mbuf_spare_map,
6569                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6570     if (__predict_false(rc != 0)) {
6571         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6572         m_freem(m);
6573         fp->eth_q_stats.mbuf_alloc_rx--;
6574         return (rc);
6575     }
6576
6577     /* all mbufs must map to a single segment */
6578     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6579
6580     /* release any existing RX BD mbuf mappings */
6581
6582     if (prev_index != index) {
6583         rx_buf = &fp->rx_mbuf_chain[prev_index];
6584
6585         if (rx_buf->m_map != NULL) {
6586             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6587                             BUS_DMASYNC_POSTREAD);
6588             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6589         }
6590
6591         /*
6592          * We only get here from bxe_rxeof() when the maximum number
6593          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6594          * holds the mbuf in the prev_index so it's OK to NULL it out
6595          * here without concern of a memory leak.
6596          */
6597         fp->rx_mbuf_chain[prev_index].m = NULL;
6598     }
6599
6600     rx_buf = &fp->rx_mbuf_chain[index];
6601
6602     if (rx_buf->m_map != NULL) {
6603         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6604                         BUS_DMASYNC_POSTREAD);
6605         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6606     }
6607
6608     /* save the mbuf and mapping info for a future packet */
6609     map = (prev_index != index) ?
6610               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6611     rx_buf->m_map = fp->rx_mbuf_spare_map;
6612     fp->rx_mbuf_spare_map = map;
6613     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6614                     BUS_DMASYNC_PREREAD);
6615     rx_buf->m = m;
6616
6617     rx_bd = &fp->rx_chain[index];
6618     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6619     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6620
6621     return (rc);
6622 }
6623
6624 static int
6625 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6626                       int                 queue)
6627 {
6628     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6629     bus_dma_segment_t segs[1];
6630     bus_dmamap_t map;
6631     struct mbuf *m;
6632     int nsegs;
6633     int rc = 0;
6634
6635     /* allocate the new TPA mbuf */
6636     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6637     if (__predict_false(m == NULL)) {
6638         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6639         return (ENOBUFS);
6640     }
6641
6642     fp->eth_q_stats.mbuf_alloc_tpa++;
6643
6644     /* initialize the mbuf buffer length */
6645     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6646
6647     /* map the mbuf into non-paged pool */
6648     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6649                                  fp->rx_tpa_info_mbuf_spare_map,
6650                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6651     if (__predict_false(rc != 0)) {
6652         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6653         m_free(m);
6654         fp->eth_q_stats.mbuf_alloc_tpa--;
6655         return (rc);
6656     }
6657
6658     /* all mbufs must map to a single segment */
6659     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6660
6661     /* release any existing TPA mbuf mapping */
6662     if (tpa_info->bd.m_map != NULL) {
6663         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6664                         BUS_DMASYNC_POSTREAD);
6665         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6666     }
6667
6668     /* save the mbuf and mapping info for the TPA mbuf */
6669     map = tpa_info->bd.m_map;
6670     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6671     fp->rx_tpa_info_mbuf_spare_map = map;
6672     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6673                     BUS_DMASYNC_PREREAD);
6674     tpa_info->bd.m = m;
6675     tpa_info->seg = segs[0];
6676
6677     return (rc);
6678 }
6679
6680 /*
6681  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6682  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6683  * chain.
6684  */
6685 static int
6686 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6687                       uint16_t            index)
6688 {
6689     struct bxe_sw_rx_bd *sge_buf;
6690     struct eth_rx_sge *sge;
6691     bus_dma_segment_t segs[1];
6692     bus_dmamap_t map;
6693     struct mbuf *m;
6694     int nsegs;
6695     int rc = 0;
6696
6697     /* allocate a new SGE mbuf */
6698     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6699     if (__predict_false(m == NULL)) {
6700         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6701         return (ENOMEM);
6702     }
6703
6704     fp->eth_q_stats.mbuf_alloc_sge++;
6705
6706     /* initialize the mbuf buffer length */
6707     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6708
6709     /* map the SGE mbuf into non-paged pool */
6710     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6711                                  fp->rx_sge_mbuf_spare_map,
6712                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6713     if (__predict_false(rc != 0)) {
6714         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6715         m_freem(m);
6716         fp->eth_q_stats.mbuf_alloc_sge--;
6717         return (rc);
6718     }
6719
6720     /* all mbufs must map to a single segment */
6721     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6722
6723     sge_buf = &fp->rx_sge_mbuf_chain[index];
6724
6725     /* release any existing SGE mbuf mapping */
6726     if (sge_buf->m_map != NULL) {
6727         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6728                         BUS_DMASYNC_POSTREAD);
6729         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6730     }
6731
6732     /* save the mbuf and mapping info for a future packet */
6733     map = sge_buf->m_map;
6734     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6735     fp->rx_sge_mbuf_spare_map = map;
6736     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6737                     BUS_DMASYNC_PREREAD);
6738     sge_buf->m = m;
6739
6740     sge = &fp->rx_sge_chain[index];
6741     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6742     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6743
6744     return (rc);
6745 }
6746
6747 static __noinline int
6748 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6749 {
6750     struct bxe_fastpath *fp;
6751     int i, j, rc = 0;
6752     int ring_prod, cqe_ring_prod;
6753     int max_agg_queues;
6754
6755     for (i = 0; i < sc->num_queues; i++) {
6756         fp = &sc->fp[i];
6757
6758 #if __FreeBSD_version >= 800000
6759         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
6760                                    M_NOWAIT, &fp->tx_mtx);
6761         if (fp->tx_br == NULL) {
6762             BLOGE(sc, "buf_ring alloc fail for fp[%02d]\n", i);
6763             goto bxe_alloc_fp_buffers_error;
6764         }
6765 #endif
6766
6767         ring_prod = cqe_ring_prod = 0;
6768         fp->rx_bd_cons = 0;
6769         fp->rx_cq_cons = 0;
6770
6771         /* allocate buffers for the RX BDs in RX BD chain */
6772         for (j = 0; j < sc->max_rx_bufs; j++) {
6773             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6774             if (rc != 0) {
6775                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6776                       i, rc);
6777                 goto bxe_alloc_fp_buffers_error;
6778             }
6779
6780             ring_prod     = RX_BD_NEXT(ring_prod);
6781             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6782         }
6783
6784         fp->rx_bd_prod = ring_prod;
6785         fp->rx_cq_prod = cqe_ring_prod;
6786         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6787
6788         if (if_getcapenable(sc->ifp) & IFCAP_LRO) {
6789             max_agg_queues = MAX_AGG_QS(sc);
6790
6791             fp->tpa_enable = TRUE;
6792
6793             /* fill the TPA pool */
6794             for (j = 0; j < max_agg_queues; j++) {
6795                 rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6796                 if (rc != 0) {
6797                     BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6798                           i, j);
6799                     fp->tpa_enable = FALSE;
6800                     goto bxe_alloc_fp_buffers_error;
6801                 }
6802
6803                 fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6804             }
6805
6806             if (fp->tpa_enable) {
6807                 /* fill the RX SGE chain */
6808                 ring_prod = 0;
6809                 for (j = 0; j < RX_SGE_USABLE; j++) {
6810                     rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6811                     if (rc != 0) {
6812                         BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6813                               i, ring_prod);
6814                         fp->tpa_enable = FALSE;
6815                         ring_prod = 0;
6816                         goto bxe_alloc_fp_buffers_error;
6817                     }
6818
6819                     ring_prod = RX_SGE_NEXT(ring_prod);
6820                 }
6821
6822                 fp->rx_sge_prod = ring_prod;
6823             }
6824         }
6825     }
6826
6827     return (0);
6828
6829 bxe_alloc_fp_buffers_error:
6830
6831     /* unwind what was already allocated */
6832     bxe_free_rx_bd_chain(fp);
6833     bxe_free_tpa_pool(fp);
6834     bxe_free_sge_chain(fp);
6835
6836     return (ENOBUFS);
6837 }
6838
6839 static void
6840 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6841 {
6842     bxe_dma_free(sc, &sc->fw_stats_dma);
6843
6844     sc->fw_stats_num = 0;
6845
6846     sc->fw_stats_req_size = 0;
6847     sc->fw_stats_req = NULL;
6848     sc->fw_stats_req_mapping = 0;
6849
6850     sc->fw_stats_data_size = 0;
6851     sc->fw_stats_data = NULL;
6852     sc->fw_stats_data_mapping = 0;
6853 }
6854
6855 static int
6856 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6857 {
6858     uint8_t num_queue_stats;
6859     int num_groups;
6860
6861     /* number of queues for statistics is number of eth queues */
6862     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6863
6864     /*
6865      * Total number of FW statistics requests =
6866      *   1 for port stats + 1 for PF stats + num of queues
6867      */
6868     sc->fw_stats_num = (2 + num_queue_stats);
6869
6870     /*
6871      * Request is built from stats_query_header and an array of
6872      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6873      * rules. The real number or requests is configured in the
6874      * stats_query_header.
6875      */
6876     num_groups =
6877         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6878          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6879
6880     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6881           sc->fw_stats_num, num_groups);
6882
6883     sc->fw_stats_req_size =
6884         (sizeof(struct stats_query_header) +
6885          (num_groups * sizeof(struct stats_query_cmd_group)));
6886
6887     /*
6888      * Data for statistics requests + stats_counter.
6889      * stats_counter holds per-STORM counters that are incremented when
6890      * STORM has finished with the current request. Memory for FCoE
6891      * offloaded statistics are counted anyway, even if they will not be sent.
6892      * VF stats are not accounted for here as the data of VF stats is stored
6893      * in memory allocated by the VF, not here.
6894      */
6895     sc->fw_stats_data_size =
6896         (sizeof(struct stats_counter) +
6897          sizeof(struct per_port_stats) +
6898          sizeof(struct per_pf_stats) +
6899          /* sizeof(struct fcoe_statistics_params) + */
6900          (sizeof(struct per_queue_stats) * num_queue_stats));
6901
6902     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6903                       &sc->fw_stats_dma, "fw stats") != 0) {
6904         bxe_free_fw_stats_mem(sc);
6905         return (-1);
6906     }
6907
6908     /* set up the shortcuts */
6909
6910     sc->fw_stats_req =
6911         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6912     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6913
6914     sc->fw_stats_data =
6915         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6916                                      sc->fw_stats_req_size);
6917     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6918                                  sc->fw_stats_req_size);
6919
6920     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6921           (uintmax_t)sc->fw_stats_req_mapping);
6922
6923     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6924           (uintmax_t)sc->fw_stats_data_mapping);
6925
6926     return (0);
6927 }
6928
6929 /*
6930  * Bits map:
6931  * 0-7  - Engine0 load counter.
6932  * 8-15 - Engine1 load counter.
6933  * 16   - Engine0 RESET_IN_PROGRESS bit.
6934  * 17   - Engine1 RESET_IN_PROGRESS bit.
6935  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6936  *        function on the engine
6937  * 19   - Engine1 ONE_IS_LOADED.
6938  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6939  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6940  *        for just the one belonging to its engine).
6941  */
6942 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6943 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6944 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6945 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6946 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6947 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6948 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6949 #define BXE_GLOBAL_RESET_BIT      0x00040000
6950
6951 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6952 static void
6953 bxe_set_reset_global(struct bxe_softc *sc)
6954 {
6955     uint32_t val;
6956     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6957     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6958     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6959     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6960 }
6961
6962 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6963 static void
6964 bxe_clear_reset_global(struct bxe_softc *sc)
6965 {
6966     uint32_t val;
6967     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6968     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6969     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6970     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6971 }
6972
6973 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6974 static uint8_t
6975 bxe_reset_is_global(struct bxe_softc *sc)
6976 {
6977     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6978     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6979     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6980 }
6981
6982 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6983 static void
6984 bxe_set_reset_done(struct bxe_softc *sc)
6985 {
6986     uint32_t val;
6987     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6988                                  BXE_PATH0_RST_IN_PROG_BIT;
6989
6990     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6991
6992     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6993     /* Clear the bit */
6994     val &= ~bit;
6995     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6996
6997     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6998 }
6999
7000 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
7001 static void
7002 bxe_set_reset_in_progress(struct bxe_softc *sc)
7003 {
7004     uint32_t val;
7005     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
7006                                  BXE_PATH0_RST_IN_PROG_BIT;
7007
7008     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7009
7010     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
7011     /* Set the bit */
7012     val |= bit;
7013     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
7014
7015     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7016 }
7017
7018 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
7019 static uint8_t
7020 bxe_reset_is_done(struct bxe_softc *sc,
7021                   int              engine)
7022 {
7023     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
7024     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
7025                             BXE_PATH0_RST_IN_PROG_BIT;
7026
7027     /* return false if bit is set */
7028     return (val & bit) ? FALSE : TRUE;
7029 }
7030
7031 /* get the load status for an engine, should be run under rtnl lock */
7032 static uint8_t
7033 bxe_get_load_status(struct bxe_softc *sc,
7034                     int              engine)
7035 {
7036     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
7037                              BXE_PATH0_LOAD_CNT_MASK;
7038     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
7039                               BXE_PATH0_LOAD_CNT_SHIFT;
7040     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
7041
7042     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
7043
7044     val = ((val & mask) >> shift);
7045
7046     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
7047
7048     return (val != 0);
7049 }
7050
7051 /* set pf load mark */
7052 /* XXX needs to be under rtnl lock */
7053 static void
7054 bxe_set_pf_load(struct bxe_softc *sc)
7055 {
7056     uint32_t val;
7057     uint32_t val1;
7058     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
7059                                   BXE_PATH0_LOAD_CNT_MASK;
7060     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
7061                                    BXE_PATH0_LOAD_CNT_SHIFT;
7062
7063     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7064
7065     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
7066     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
7067
7068     /* get the current counter value */
7069     val1 = ((val & mask) >> shift);
7070
7071     /* set bit of this PF */
7072     val1 |= (1 << SC_ABS_FUNC(sc));
7073
7074     /* clear the old value */
7075     val &= ~mask;
7076
7077     /* set the new one */
7078     val |= ((val1 << shift) & mask);
7079
7080     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
7081
7082     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7083 }
7084
7085 /* clear pf load mark */
7086 /* XXX needs to be under rtnl lock */
7087 static uint8_t
7088 bxe_clear_pf_load(struct bxe_softc *sc)
7089 {
7090     uint32_t val1, val;
7091     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
7092                                   BXE_PATH0_LOAD_CNT_MASK;
7093     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
7094                                    BXE_PATH0_LOAD_CNT_SHIFT;
7095
7096     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7097     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
7098     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
7099
7100     /* get the current counter value */
7101     val1 = (val & mask) >> shift;
7102
7103     /* clear bit of that PF */
7104     val1 &= ~(1 << SC_ABS_FUNC(sc));
7105
7106     /* clear the old value */
7107     val &= ~mask;
7108
7109     /* set the new one */
7110     val |= ((val1 << shift) & mask);
7111
7112     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
7113     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7114     return (val1 != 0);
7115 }
7116
7117 /* send load requrest to mcp and analyze response */
7118 static int
7119 bxe_nic_load_request(struct bxe_softc *sc,
7120                      uint32_t         *load_code)
7121 {
7122     /* init fw_seq */
7123     sc->fw_seq =
7124         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
7125          DRV_MSG_SEQ_NUMBER_MASK);
7126
7127     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
7128
7129     /* get the current FW pulse sequence */
7130     sc->fw_drv_pulse_wr_seq =
7131         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
7132          DRV_PULSE_SEQ_MASK);
7133
7134     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
7135           sc->fw_drv_pulse_wr_seq);
7136
7137     /* load request */
7138     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
7139                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
7140
7141     /* if the MCP fails to respond we must abort */
7142     if (!(*load_code)) {
7143         BLOGE(sc, "MCP response failure!\n");
7144         return (-1);
7145     }
7146
7147     /* if MCP refused then must abort */
7148     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
7149         BLOGE(sc, "MCP refused load request\n");
7150         return (-1);
7151     }
7152
7153     return (0);
7154 }
7155
7156 /*
7157  * Check whether another PF has already loaded FW to chip. In virtualized
7158  * environments a pf from anoth VM may have already initialized the device
7159  * including loading FW.
7160  */
7161 static int
7162 bxe_nic_load_analyze_req(struct bxe_softc *sc,
7163                          uint32_t         load_code)
7164 {
7165     uint32_t my_fw, loaded_fw;
7166
7167     /* is another pf loaded on this engine? */
7168     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
7169         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
7170         /* build my FW version dword */
7171         my_fw = (BCM_5710_FW_MAJOR_VERSION +
7172                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
7173                  (BCM_5710_FW_REVISION_VERSION << 16) +
7174                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
7175
7176         /* read loaded FW from chip */
7177         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
7178         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
7179               loaded_fw, my_fw);
7180
7181         /* abort nic load if version mismatch */
7182         if (my_fw != loaded_fw) {
7183             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
7184                   loaded_fw, my_fw);
7185             return (-1);
7186         }
7187     }
7188
7189     return (0);
7190 }
7191
7192 /* mark PMF if applicable */
7193 static void
7194 bxe_nic_load_pmf(struct bxe_softc *sc,
7195                  uint32_t         load_code)
7196 {
7197     uint32_t ncsi_oem_data_addr;
7198
7199     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
7200         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
7201         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
7202         /*
7203          * Barrier here for ordering between the writing to sc->port.pmf here
7204          * and reading it from the periodic task.
7205          */
7206         sc->port.pmf = 1;
7207         mb();
7208     } else {
7209         sc->port.pmf = 0;
7210     }
7211
7212     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
7213
7214     /* XXX needed? */
7215     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
7216         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
7217             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
7218             if (ncsi_oem_data_addr) {
7219                 REG_WR(sc,
7220                        (ncsi_oem_data_addr +
7221                         offsetof(struct glob_ncsi_oem_data, driver_version)),
7222                        0);
7223             }
7224         }
7225     }
7226 }
7227
7228 static void
7229 bxe_read_mf_cfg(struct bxe_softc *sc)
7230 {
7231     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
7232     int abs_func;
7233     int vn;
7234
7235     if (BXE_NOMCP(sc)) {
7236         return; /* what should be the default bvalue in this case */
7237     }
7238
7239     /*
7240      * The formula for computing the absolute function number is...
7241      * For 2 port configuration (4 functions per port):
7242      *   abs_func = 2 * vn + SC_PORT + SC_PATH
7243      * For 4 port configuration (2 functions per port):
7244      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
7245      */
7246     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
7247         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
7248         if (abs_func >= E1H_FUNC_MAX) {
7249             break;
7250         }
7251         sc->devinfo.mf_info.mf_config[vn] =
7252             MFCFG_RD(sc, func_mf_config[abs_func].config);
7253     }
7254
7255     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
7256         FUNC_MF_CFG_FUNC_DISABLED) {
7257         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
7258         sc->flags |= BXE_MF_FUNC_DIS;
7259     } else {
7260         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
7261         sc->flags &= ~BXE_MF_FUNC_DIS;
7262     }
7263 }
7264
7265 /* acquire split MCP access lock register */
7266 static int bxe_acquire_alr(struct bxe_softc *sc)
7267 {
7268     uint32_t j, val;
7269
7270     for (j = 0; j < 1000; j++) {
7271         val = (1UL << 31);
7272         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
7273         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
7274         if (val & (1L << 31))
7275             break;
7276
7277         DELAY(5000);
7278     }
7279
7280     if (!(val & (1L << 31))) {
7281         BLOGE(sc, "Cannot acquire MCP access lock register\n");
7282         return (-1);
7283     }
7284
7285     return (0);
7286 }
7287
7288 /* release split MCP access lock register */
7289 static void bxe_release_alr(struct bxe_softc *sc)
7290 {
7291     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
7292 }
7293
7294 static void
7295 bxe_fan_failure(struct bxe_softc *sc)
7296 {
7297     int port = SC_PORT(sc);
7298     uint32_t ext_phy_config;
7299
7300     /* mark the failure */
7301     ext_phy_config =
7302         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7303
7304     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7305     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7306     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7307              ext_phy_config);
7308
7309     /* log the failure */
7310     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7311               "the card to prevent permanent damage. "
7312               "Please contact OEM Support for assistance\n");
7313
7314     /* XXX */
7315 #if 1
7316     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7317 #else
7318     /*
7319      * Schedule device reset (unload)
7320      * This is due to some boards consuming sufficient power when driver is
7321      * up to overheat if fan fails.
7322      */
7323     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7324     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7325 #endif
7326 }
7327
7328 /* this function is called upon a link interrupt */
7329 static void
7330 bxe_link_attn(struct bxe_softc *sc)
7331 {
7332     uint32_t pause_enabled = 0;
7333     struct host_port_stats *pstats;
7334     int cmng_fns;
7335
7336     /* Make sure that we are synced with the current statistics */
7337     bxe_stats_handle(sc, STATS_EVENT_STOP);
7338
7339     elink_link_update(&sc->link_params, &sc->link_vars);
7340
7341     if (sc->link_vars.link_up) {
7342
7343         /* dropless flow control */
7344         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7345             pause_enabled = 0;
7346
7347             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7348                 pause_enabled = 1;
7349             }
7350
7351             REG_WR(sc,
7352                    (BAR_USTRORM_INTMEM +
7353                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7354                    pause_enabled);
7355         }
7356
7357         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7358             pstats = BXE_SP(sc, port_stats);
7359             /* reset old mac stats */
7360             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7361         }
7362
7363         if (sc->state == BXE_STATE_OPEN) {
7364             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7365         }
7366     }
7367
7368     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7369         cmng_fns = bxe_get_cmng_fns_mode(sc);
7370
7371         if (cmng_fns != CMNG_FNS_NONE) {
7372             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7373             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7374         } else {
7375             /* rate shaping and fairness are disabled */
7376             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7377         }
7378     }
7379
7380     bxe_link_report_locked(sc);
7381
7382     if (IS_MF(sc)) {
7383         ; // XXX bxe_link_sync_notify(sc);
7384     }
7385 }
7386
7387 static void
7388 bxe_attn_int_asserted(struct bxe_softc *sc,
7389                       uint32_t         asserted)
7390 {
7391     int port = SC_PORT(sc);
7392     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7393                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7394     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7395                                         NIG_REG_MASK_INTERRUPT_PORT0;
7396     uint32_t aeu_mask;
7397     uint32_t nig_mask = 0;
7398     uint32_t reg_addr;
7399     uint32_t igu_acked;
7400     uint32_t cnt;
7401
7402     if (sc->attn_state & asserted) {
7403         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7404     }
7405
7406     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7407
7408     aeu_mask = REG_RD(sc, aeu_addr);
7409
7410     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7411           aeu_mask, asserted);
7412
7413     aeu_mask &= ~(asserted & 0x3ff);
7414
7415     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7416
7417     REG_WR(sc, aeu_addr, aeu_mask);
7418
7419     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7420
7421     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7422     sc->attn_state |= asserted;
7423     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7424
7425     if (asserted & ATTN_HARD_WIRED_MASK) {
7426         if (asserted & ATTN_NIG_FOR_FUNC) {
7427
7428             BXE_PHY_LOCK(sc);
7429
7430             /* save nig interrupt mask */
7431             nig_mask = REG_RD(sc, nig_int_mask_addr);
7432
7433             /* If nig_mask is not set, no need to call the update function */
7434             if (nig_mask) {
7435                 REG_WR(sc, nig_int_mask_addr, 0);
7436
7437                 bxe_link_attn(sc);
7438             }
7439
7440             /* handle unicore attn? */
7441         }
7442
7443         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7444             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7445         }
7446
7447         if (asserted & GPIO_2_FUNC) {
7448             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7449         }
7450
7451         if (asserted & GPIO_3_FUNC) {
7452             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7453         }
7454
7455         if (asserted & GPIO_4_FUNC) {
7456             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7457         }
7458
7459         if (port == 0) {
7460             if (asserted & ATTN_GENERAL_ATTN_1) {
7461                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7462                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7463             }
7464             if (asserted & ATTN_GENERAL_ATTN_2) {
7465                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7466                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7467             }
7468             if (asserted & ATTN_GENERAL_ATTN_3) {
7469                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7470                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7471             }
7472         } else {
7473             if (asserted & ATTN_GENERAL_ATTN_4) {
7474                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7475                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7476             }
7477             if (asserted & ATTN_GENERAL_ATTN_5) {
7478                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7479                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7480             }
7481             if (asserted & ATTN_GENERAL_ATTN_6) {
7482                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7483                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7484             }
7485         }
7486     } /* hardwired */
7487
7488     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7489         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7490     } else {
7491         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7492     }
7493
7494     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7495           asserted,
7496           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7497     REG_WR(sc, reg_addr, asserted);
7498
7499     /* now set back the mask */
7500     if (asserted & ATTN_NIG_FOR_FUNC) {
7501         /*
7502          * Verify that IGU ack through BAR was written before restoring
7503          * NIG mask. This loop should exit after 2-3 iterations max.
7504          */
7505         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7506             cnt = 0;
7507
7508             do {
7509                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7510             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7511                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7512
7513             if (!igu_acked) {
7514                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7515             }
7516
7517             mb();
7518         }
7519
7520         REG_WR(sc, nig_int_mask_addr, nig_mask);
7521
7522         BXE_PHY_UNLOCK(sc);
7523     }
7524 }
7525
7526 static void
7527 bxe_print_next_block(struct bxe_softc *sc,
7528                      int              idx,
7529                      const char       *blk)
7530 {
7531     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7532 }
7533
7534 static int
7535 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7536                               uint32_t         sig,
7537                               int              par_num,
7538                               uint8_t          print)
7539 {
7540     uint32_t cur_bit = 0;
7541     int i = 0;
7542
7543     for (i = 0; sig; i++) {
7544         cur_bit = ((uint32_t)0x1 << i);
7545         if (sig & cur_bit) {
7546             switch (cur_bit) {
7547             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7548                 if (print)
7549                     bxe_print_next_block(sc, par_num++, "BRB");
7550                 break;
7551             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7552                 if (print)
7553                     bxe_print_next_block(sc, par_num++, "PARSER");
7554                 break;
7555             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7556                 if (print)
7557                     bxe_print_next_block(sc, par_num++, "TSDM");
7558                 break;
7559             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7560                 if (print)
7561                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7562                 break;
7563             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7564                 if (print)
7565                     bxe_print_next_block(sc, par_num++, "TCM");
7566                 break;
7567             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7568                 if (print)
7569                     bxe_print_next_block(sc, par_num++, "TSEMI");
7570                 break;
7571             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7572                 if (print)
7573                     bxe_print_next_block(sc, par_num++, "XPB");
7574                 break;
7575             }
7576
7577             /* Clear the bit */
7578             sig &= ~cur_bit;
7579         }
7580     }
7581
7582     return (par_num);
7583 }
7584
7585 static int
7586 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7587                               uint32_t         sig,
7588                               int              par_num,
7589                               uint8_t          *global,
7590                               uint8_t          print)
7591 {
7592     int i = 0;
7593     uint32_t cur_bit = 0;
7594     for (i = 0; sig; i++) {
7595         cur_bit = ((uint32_t)0x1 << i);
7596         if (sig & cur_bit) {
7597             switch (cur_bit) {
7598             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7599                 if (print)
7600                     bxe_print_next_block(sc, par_num++, "PBF");
7601                 break;
7602             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7603                 if (print)
7604                     bxe_print_next_block(sc, par_num++, "QM");
7605                 break;
7606             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7607                 if (print)
7608                     bxe_print_next_block(sc, par_num++, "TM");
7609                 break;
7610             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7611                 if (print)
7612                     bxe_print_next_block(sc, par_num++, "XSDM");
7613                 break;
7614             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7615                 if (print)
7616                     bxe_print_next_block(sc, par_num++, "XCM");
7617                 break;
7618             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7619                 if (print)
7620                     bxe_print_next_block(sc, par_num++, "XSEMI");
7621                 break;
7622             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7623                 if (print)
7624                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7625                 break;
7626             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7627                 if (print)
7628                     bxe_print_next_block(sc, par_num++, "NIG");
7629                 break;
7630             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7631                 if (print)
7632                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7633                 *global = TRUE;
7634                 break;
7635             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7636                 if (print)
7637                     bxe_print_next_block(sc, par_num++, "DEBUG");
7638                 break;
7639             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7640                 if (print)
7641                     bxe_print_next_block(sc, par_num++, "USDM");
7642                 break;
7643             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7644                 if (print)
7645                     bxe_print_next_block(sc, par_num++, "UCM");
7646                 break;
7647             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7648                 if (print)
7649                     bxe_print_next_block(sc, par_num++, "USEMI");
7650                 break;
7651             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7652                 if (print)
7653                     bxe_print_next_block(sc, par_num++, "UPB");
7654                 break;
7655             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7656                 if (print)
7657                     bxe_print_next_block(sc, par_num++, "CSDM");
7658                 break;
7659             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7660                 if (print)
7661                     bxe_print_next_block(sc, par_num++, "CCM");
7662                 break;
7663             }
7664
7665             /* Clear the bit */
7666             sig &= ~cur_bit;
7667         }
7668     }
7669
7670     return (par_num);
7671 }
7672
7673 static int
7674 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7675                               uint32_t         sig,
7676                               int              par_num,
7677                               uint8_t          print)
7678 {
7679     uint32_t cur_bit = 0;
7680     int i = 0;
7681
7682     for (i = 0; sig; i++) {
7683         cur_bit = ((uint32_t)0x1 << i);
7684         if (sig & cur_bit) {
7685             switch (cur_bit) {
7686             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7687                 if (print)
7688                     bxe_print_next_block(sc, par_num++, "CSEMI");
7689                 break;
7690             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7691                 if (print)
7692                     bxe_print_next_block(sc, par_num++, "PXP");
7693                 break;
7694             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7695                 if (print)
7696                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7697                 break;
7698             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7699                 if (print)
7700                     bxe_print_next_block(sc, par_num++, "CFC");
7701                 break;
7702             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7703                 if (print)
7704                     bxe_print_next_block(sc, par_num++, "CDU");
7705                 break;
7706             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7707                 if (print)
7708                     bxe_print_next_block(sc, par_num++, "DMAE");
7709                 break;
7710             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7711                 if (print)
7712                     bxe_print_next_block(sc, par_num++, "IGU");
7713                 break;
7714             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7715                 if (print)
7716                     bxe_print_next_block(sc, par_num++, "MISC");
7717                 break;
7718             }
7719
7720             /* Clear the bit */
7721             sig &= ~cur_bit;
7722         }
7723     }
7724
7725     return (par_num);
7726 }
7727
7728 static int
7729 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7730                               uint32_t         sig,
7731                               int              par_num,
7732                               uint8_t          *global,
7733                               uint8_t          print)
7734 {
7735     uint32_t cur_bit = 0;
7736     int i = 0;
7737
7738     for (i = 0; sig; i++) {
7739         cur_bit = ((uint32_t)0x1 << i);
7740         if (sig & cur_bit) {
7741             switch (cur_bit) {
7742             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7743                 if (print)
7744                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7745                 *global = TRUE;
7746                 break;
7747             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7748                 if (print)
7749                     bxe_print_next_block(sc, par_num++,
7750                               "MCP UMP RX");
7751                 *global = TRUE;
7752                 break;
7753             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7754                 if (print)
7755                     bxe_print_next_block(sc, par_num++,
7756                               "MCP UMP TX");
7757                 *global = TRUE;
7758                 break;
7759             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7760                 if (print)
7761                     bxe_print_next_block(sc, par_num++,
7762                               "MCP SCPAD");
7763                 *global = TRUE;
7764                 break;
7765             }
7766
7767             /* Clear the bit */
7768             sig &= ~cur_bit;
7769         }
7770     }
7771
7772     return (par_num);
7773 }
7774
7775 static int
7776 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7777                               uint32_t         sig,
7778                               int              par_num,
7779                               uint8_t          print)
7780 {
7781     uint32_t cur_bit = 0;
7782     int i = 0;
7783
7784     for (i = 0; sig; i++) {
7785         cur_bit = ((uint32_t)0x1 << i);
7786         if (sig & cur_bit) {
7787             switch (cur_bit) {
7788             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7789                 if (print)
7790                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7791                 break;
7792             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7793                 if (print)
7794                     bxe_print_next_block(sc, par_num++, "ATC");
7795                 break;
7796             }
7797
7798             /* Clear the bit */
7799             sig &= ~cur_bit;
7800         }
7801     }
7802
7803     return (par_num);
7804 }
7805
7806 static uint8_t
7807 bxe_parity_attn(struct bxe_softc *sc,
7808                 uint8_t          *global,
7809                 uint8_t          print,
7810                 uint32_t         *sig)
7811 {
7812     int par_num = 0;
7813
7814     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7815         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7816         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7817         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7818         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7819         BLOGE(sc, "Parity error: HW block parity attention:\n"
7820                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7821               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7822               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7823               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7824               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7825               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7826
7827         if (print)
7828             BLOGI(sc, "Parity errors detected in blocks: ");
7829
7830         par_num =
7831             bxe_check_blocks_with_parity0(sc, sig[0] &
7832                                           HW_PRTY_ASSERT_SET_0,
7833                                           par_num, print);
7834         par_num =
7835             bxe_check_blocks_with_parity1(sc, sig[1] &
7836                                           HW_PRTY_ASSERT_SET_1,
7837                                           par_num, global, print);
7838         par_num =
7839             bxe_check_blocks_with_parity2(sc, sig[2] &
7840                                           HW_PRTY_ASSERT_SET_2,
7841                                           par_num, print);
7842         par_num =
7843             bxe_check_blocks_with_parity3(sc, sig[3] &
7844                                           HW_PRTY_ASSERT_SET_3,
7845                                           par_num, global, print);
7846         par_num =
7847             bxe_check_blocks_with_parity4(sc, sig[4] &
7848                                           HW_PRTY_ASSERT_SET_4,
7849                                           par_num, print);
7850
7851         if (print)
7852             BLOGI(sc, "\n");
7853
7854         return (TRUE);
7855     }
7856
7857     return (FALSE);
7858 }
7859
7860 static uint8_t
7861 bxe_chk_parity_attn(struct bxe_softc *sc,
7862                     uint8_t          *global,
7863                     uint8_t          print)
7864 {
7865     struct attn_route attn = { {0} };
7866     int port = SC_PORT(sc);
7867
7868     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7869     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7870     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7871     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7872
7873     if (!CHIP_IS_E1x(sc))
7874         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7875
7876     return (bxe_parity_attn(sc, global, print, attn.sig));
7877 }
7878
7879 static void
7880 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7881                          uint32_t         attn)
7882 {
7883     uint32_t val;
7884
7885     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7886         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7887         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7888         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7889             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7890         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7891             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7892         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7893             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7894         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7895             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7896         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7897             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7898         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7899             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7900         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7901             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7902         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7903             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7904         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7905             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7906     }
7907
7908     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7909         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7910         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7911         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7912             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7913         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7914             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7915         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7916             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7917         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7918             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7919         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7920             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7921         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7922             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7923     }
7924
7925     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7926                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7927         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7928               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7929                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7930     }
7931 }
7932
7933 static void
7934 bxe_e1h_disable(struct bxe_softc *sc)
7935 {
7936     int port = SC_PORT(sc);
7937
7938     bxe_tx_disable(sc);
7939
7940     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7941 }
7942
7943 static void
7944 bxe_e1h_enable(struct bxe_softc *sc)
7945 {
7946     int port = SC_PORT(sc);
7947
7948     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7949
7950     // XXX bxe_tx_enable(sc);
7951 }
7952
7953 /*
7954  * called due to MCP event (on pmf):
7955  *   reread new bandwidth configuration
7956  *   configure FW
7957  *   notify others function about the change
7958  */
7959 static void
7960 bxe_config_mf_bw(struct bxe_softc *sc)
7961 {
7962     if (sc->link_vars.link_up) {
7963         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7964         // XXX bxe_link_sync_notify(sc);
7965     }
7966
7967     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7968 }
7969
7970 static void
7971 bxe_set_mf_bw(struct bxe_softc *sc)
7972 {
7973     bxe_config_mf_bw(sc);
7974     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7975 }
7976
7977 static void
7978 bxe_handle_eee_event(struct bxe_softc *sc)
7979 {
7980     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7981     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7982 }
7983
7984 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7985
7986 static void
7987 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7988 {
7989     struct eth_stats_info *ether_stat =
7990         &sc->sp->drv_info_to_mcp.ether_stat;
7991
7992     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7993             ETH_STAT_INFO_VERSION_LEN);
7994
7995     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7996     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7997                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7998                                           ether_stat->mac_local + MAC_PAD,
7999                                           MAC_PAD, ETH_ALEN);
8000
8001     ether_stat->mtu_size = sc->mtu;
8002
8003     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
8004     if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
8005         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
8006     }
8007
8008     // XXX ether_stat->feature_flags |= ???;
8009
8010     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
8011
8012     ether_stat->txq_size = sc->tx_ring_size;
8013     ether_stat->rxq_size = sc->rx_ring_size;
8014 }
8015
8016 static void
8017 bxe_handle_drv_info_req(struct bxe_softc *sc)
8018 {
8019     enum drv_info_opcode op_code;
8020     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
8021
8022     /* if drv_info version supported by MFW doesn't match - send NACK */
8023     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
8024         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
8025         return;
8026     }
8027
8028     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
8029                DRV_INFO_CONTROL_OP_CODE_SHIFT);
8030
8031     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
8032
8033     switch (op_code) {
8034     case ETH_STATS_OPCODE:
8035         bxe_drv_info_ether_stat(sc);
8036         break;
8037     case FCOE_STATS_OPCODE:
8038     case ISCSI_STATS_OPCODE:
8039     default:
8040         /* if op code isn't supported - send NACK */
8041         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
8042         return;
8043     }
8044
8045     /*
8046      * If we got drv_info attn from MFW then these fields are defined in
8047      * shmem2 for sure
8048      */
8049     SHMEM2_WR(sc, drv_info_host_addr_lo,
8050               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
8051     SHMEM2_WR(sc, drv_info_host_addr_hi,
8052               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
8053
8054     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
8055 }
8056
8057 static void
8058 bxe_dcc_event(struct bxe_softc *sc,
8059               uint32_t         dcc_event)
8060 {
8061     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
8062
8063     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
8064         /*
8065          * This is the only place besides the function initialization
8066          * where the sc->flags can change so it is done without any
8067          * locks
8068          */
8069         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
8070             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
8071             sc->flags |= BXE_MF_FUNC_DIS;
8072             bxe_e1h_disable(sc);
8073         } else {
8074             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
8075             sc->flags &= ~BXE_MF_FUNC_DIS;
8076             bxe_e1h_enable(sc);
8077         }
8078         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
8079     }
8080
8081     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
8082         bxe_config_mf_bw(sc);
8083         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
8084     }
8085
8086     /* Report results to MCP */
8087     if (dcc_event)
8088         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
8089     else
8090         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
8091 }
8092
8093 static void
8094 bxe_pmf_update(struct bxe_softc *sc)
8095 {
8096     int port = SC_PORT(sc);
8097     uint32_t val;
8098
8099     sc->port.pmf = 1;
8100     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
8101
8102     /*
8103      * We need the mb() to ensure the ordering between the writing to
8104      * sc->port.pmf here and reading it from the bxe_periodic_task().
8105      */
8106     mb();
8107
8108     /* queue a periodic task */
8109     // XXX schedule task...
8110
8111     // XXX bxe_dcbx_pmf_update(sc);
8112
8113     /* enable nig attention */
8114     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
8115     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8116         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
8117         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
8118     } else if (!CHIP_IS_E1x(sc)) {
8119         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
8120         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
8121     }
8122
8123     bxe_stats_handle(sc, STATS_EVENT_PMF);
8124 }
8125
8126 static int
8127 bxe_mc_assert(struct bxe_softc *sc)
8128 {
8129     char last_idx;
8130     int i, rc = 0;
8131     uint32_t row0, row1, row2, row3;
8132
8133     /* XSTORM */
8134     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
8135     if (last_idx)
8136         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
8137
8138     /* print the asserts */
8139     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
8140
8141         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
8142         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
8143         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
8144         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
8145
8146         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
8147             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
8148                   i, row3, row2, row1, row0);
8149             rc++;
8150         } else {
8151             break;
8152         }
8153     }
8154
8155     /* TSTORM */
8156     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
8157     if (last_idx) {
8158         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
8159     }
8160
8161     /* print the asserts */
8162     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
8163
8164         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
8165         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
8166         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
8167         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
8168
8169         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
8170             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
8171                   i, row3, row2, row1, row0);
8172             rc++;
8173         } else {
8174             break;
8175         }
8176     }
8177
8178     /* CSTORM */
8179     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
8180     if (last_idx) {
8181         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
8182     }
8183
8184     /* print the asserts */
8185     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
8186
8187         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
8188         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
8189         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
8190         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
8191
8192         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
8193             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
8194                   i, row3, row2, row1, row0);
8195             rc++;
8196         } else {
8197             break;
8198         }
8199     }
8200
8201     /* USTORM */
8202     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
8203     if (last_idx) {
8204         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
8205     }
8206
8207     /* print the asserts */
8208     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
8209
8210         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
8211         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
8212         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
8213         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
8214
8215         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
8216             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
8217                   i, row3, row2, row1, row0);
8218             rc++;
8219         } else {
8220             break;
8221         }
8222     }
8223
8224     return (rc);
8225 }
8226
8227 static void
8228 bxe_attn_int_deasserted3(struct bxe_softc *sc,
8229                          uint32_t         attn)
8230 {
8231     int func = SC_FUNC(sc);
8232     uint32_t val;
8233
8234     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
8235
8236         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
8237
8238             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
8239             bxe_read_mf_cfg(sc);
8240             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
8241                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
8242             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
8243
8244             if (val & DRV_STATUS_DCC_EVENT_MASK)
8245                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
8246
8247             if (val & DRV_STATUS_SET_MF_BW)
8248                 bxe_set_mf_bw(sc);
8249
8250             if (val & DRV_STATUS_DRV_INFO_REQ)
8251                 bxe_handle_drv_info_req(sc);
8252
8253 #if 0
8254             if (val & DRV_STATUS_VF_DISABLED)
8255                 bxe_vf_handle_flr_event(sc);
8256 #endif
8257
8258             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
8259                 bxe_pmf_update(sc);
8260
8261 #if 0
8262             if (sc->port.pmf &&
8263                 (val & DRV_STATUS_DCBX_NEGOTIATION_RESULTS) &&
8264                 (sc->dcbx_enabled > 0))
8265                 /* start dcbx state machine */
8266                 bxe_dcbx_set_params(sc, BXE_DCBX_STATE_NEG_RECEIVED);
8267 #endif
8268
8269 #if 0
8270             if (val & DRV_STATUS_AFEX_EVENT_MASK)
8271                 bxe_handle_afex_cmd(sc, val & DRV_STATUS_AFEX_EVENT_MASK);
8272 #endif
8273
8274             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
8275                 bxe_handle_eee_event(sc);
8276
8277             if (sc->link_vars.periodic_flags &
8278                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
8279                 /* sync with link */
8280                 BXE_PHY_LOCK(sc);
8281                 sc->link_vars.periodic_flags &=
8282                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
8283                 BXE_PHY_UNLOCK(sc);
8284                 if (IS_MF(sc))
8285                     ; // XXX bxe_link_sync_notify(sc);
8286                 bxe_link_report(sc);
8287             }
8288
8289             /*
8290              * Always call it here: bxe_link_report() will
8291              * prevent the link indication duplication.
8292              */
8293             bxe_link_status_update(sc);
8294
8295         } else if (attn & BXE_MC_ASSERT_BITS) {
8296
8297             BLOGE(sc, "MC assert!\n");
8298             bxe_mc_assert(sc);
8299             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8300             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8301             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8302             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8303             bxe_panic(sc, ("MC assert!\n"));
8304
8305         } else if (attn & BXE_MCP_ASSERT) {
8306
8307             BLOGE(sc, "MCP assert!\n");
8308             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8309             // XXX bxe_fw_dump(sc);
8310
8311         } else {
8312             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8313         }
8314     }
8315
8316     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8317         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8318         if (attn & BXE_GRC_TIMEOUT) {
8319             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8320             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8321         }
8322         if (attn & BXE_GRC_RSV) {
8323             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8324             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8325         }
8326         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8327     }
8328 }
8329
8330 static void
8331 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8332                          uint32_t         attn)
8333 {
8334     int port = SC_PORT(sc);
8335     int reg_offset;
8336     uint32_t val0, mask0, val1, mask1;
8337     uint32_t val;
8338
8339     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8340         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8341         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8342         /* CFC error attention */
8343         if (val & 0x2) {
8344             BLOGE(sc, "FATAL error from CFC\n");
8345         }
8346     }
8347
8348     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8349         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8350         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8351         /* RQ_USDMDP_FIFO_OVERFLOW */
8352         if (val & 0x18000) {
8353             BLOGE(sc, "FATAL error from PXP\n");
8354         }
8355
8356         if (!CHIP_IS_E1x(sc)) {
8357             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8358             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8359         }
8360     }
8361
8362 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8363 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8364
8365     if (attn & AEU_PXP2_HW_INT_BIT) {
8366         /*  CQ47854 workaround do not panic on
8367          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8368          */
8369         if (!CHIP_IS_E1x(sc)) {
8370             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8371             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8372             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8373             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8374             /*
8375              * If the olny PXP2_EOP_ERROR_BIT is set in
8376              * STS0 and STS1 - clear it
8377              *
8378              * probably we lose additional attentions between
8379              * STS0 and STS_CLR0, in this case user will not
8380              * be notified about them
8381              */
8382             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8383                 !(val1 & mask1))
8384                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8385
8386             /* print the register, since no one can restore it */
8387             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8388
8389             /*
8390              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8391              * then notify
8392              */
8393             if (val0 & PXP2_EOP_ERROR_BIT) {
8394                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8395
8396                 /*
8397                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8398                  * set then clear attention from PXP2 block without panic
8399                  */
8400                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8401                     ((val1 & mask1) == 0))
8402                     attn &= ~AEU_PXP2_HW_INT_BIT;
8403             }
8404         }
8405     }
8406
8407     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8408         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8409                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8410
8411         val = REG_RD(sc, reg_offset);
8412         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8413         REG_WR(sc, reg_offset, val);
8414
8415         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8416               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8417         bxe_panic(sc, ("HW block attention set2\n"));
8418     }
8419 }
8420
8421 static void
8422 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8423                          uint32_t         attn)
8424 {
8425     int port = SC_PORT(sc);
8426     int reg_offset;
8427     uint32_t val;
8428
8429     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8430         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8431         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8432         /* DORQ discard attention */
8433         if (val & 0x2) {
8434             BLOGE(sc, "FATAL error from DORQ\n");
8435         }
8436     }
8437
8438     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8439         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8440                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8441
8442         val = REG_RD(sc, reg_offset);
8443         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8444         REG_WR(sc, reg_offset, val);
8445
8446         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8447               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8448         bxe_panic(sc, ("HW block attention set1\n"));
8449     }
8450 }
8451
8452 static void
8453 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8454                          uint32_t         attn)
8455 {
8456     int port = SC_PORT(sc);
8457     int reg_offset;
8458     uint32_t val;
8459
8460     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8461                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8462
8463     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8464         val = REG_RD(sc, reg_offset);
8465         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8466         REG_WR(sc, reg_offset, val);
8467
8468         BLOGW(sc, "SPIO5 hw attention\n");
8469
8470         /* Fan failure attention */
8471         elink_hw_reset_phy(&sc->link_params);
8472         bxe_fan_failure(sc);
8473     }
8474
8475     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8476         BXE_PHY_LOCK(sc);
8477         elink_handle_module_detect_int(&sc->link_params);
8478         BXE_PHY_UNLOCK(sc);
8479     }
8480
8481     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8482         val = REG_RD(sc, reg_offset);
8483         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8484         REG_WR(sc, reg_offset, val);
8485
8486         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8487                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8488     }
8489 }
8490
8491 static void
8492 bxe_attn_int_deasserted(struct bxe_softc *sc,
8493                         uint32_t         deasserted)
8494 {
8495     struct attn_route attn;
8496     struct attn_route *group_mask;
8497     int port = SC_PORT(sc);
8498     int index;
8499     uint32_t reg_addr;
8500     uint32_t val;
8501     uint32_t aeu_mask;
8502     uint8_t global = FALSE;
8503
8504     /*
8505      * Need to take HW lock because MCP or other port might also
8506      * try to handle this event.
8507      */
8508     bxe_acquire_alr(sc);
8509
8510     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8511         /* XXX
8512          * In case of parity errors don't handle attentions so that
8513          * other function would "see" parity errors.
8514          */
8515         sc->recovery_state = BXE_RECOVERY_INIT;
8516         // XXX schedule a recovery task...
8517         /* disable HW interrupts */
8518         bxe_int_disable(sc);
8519         bxe_release_alr(sc);
8520         return;
8521     }
8522
8523     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8524     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8525     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8526     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8527     if (!CHIP_IS_E1x(sc)) {
8528         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8529     } else {
8530         attn.sig[4] = 0;
8531     }
8532
8533     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8534           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8535
8536     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8537         if (deasserted & (1 << index)) {
8538             group_mask = &sc->attn_group[index];
8539
8540             BLOGD(sc, DBG_INTR,
8541                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8542                   group_mask->sig[0], group_mask->sig[1],
8543                   group_mask->sig[2], group_mask->sig[3],
8544                   group_mask->sig[4]);
8545
8546             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8547             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8548             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8549             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8550             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8551         }
8552     }
8553
8554     bxe_release_alr(sc);
8555
8556     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8557         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8558                     COMMAND_REG_ATTN_BITS_CLR);
8559     } else {
8560         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8561     }
8562
8563     val = ~deasserted;
8564     BLOGD(sc, DBG_INTR,
8565           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8566           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8567     REG_WR(sc, reg_addr, val);
8568
8569     if (~sc->attn_state & deasserted) {
8570         BLOGE(sc, "IGU error\n");
8571     }
8572
8573     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8574                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8575
8576     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8577
8578     aeu_mask = REG_RD(sc, reg_addr);
8579
8580     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8581           aeu_mask, deasserted);
8582     aeu_mask |= (deasserted & 0x3ff);
8583     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8584
8585     REG_WR(sc, reg_addr, aeu_mask);
8586     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8587
8588     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8589     sc->attn_state &= ~deasserted;
8590     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8591 }
8592
8593 static void
8594 bxe_attn_int(struct bxe_softc *sc)
8595 {
8596     /* read local copy of bits */
8597     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8598     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8599     uint32_t attn_state = sc->attn_state;
8600
8601     /* look for changed bits */
8602     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8603     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8604
8605     BLOGD(sc, DBG_INTR,
8606           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8607           attn_bits, attn_ack, asserted, deasserted);
8608
8609     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8610         BLOGE(sc, "BAD attention state\n");
8611     }
8612
8613     /* handle bits that were raised */
8614     if (asserted) {
8615         bxe_attn_int_asserted(sc, asserted);
8616     }
8617
8618     if (deasserted) {
8619         bxe_attn_int_deasserted(sc, deasserted);
8620     }
8621 }
8622
8623 static uint16_t
8624 bxe_update_dsb_idx(struct bxe_softc *sc)
8625 {
8626     struct host_sp_status_block *def_sb = sc->def_sb;
8627     uint16_t rc = 0;
8628
8629     mb(); /* status block is written to by the chip */
8630
8631     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8632         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8633         rc |= BXE_DEF_SB_ATT_IDX;
8634     }
8635
8636     if (sc->def_idx != def_sb->sp_sb.running_index) {
8637         sc->def_idx = def_sb->sp_sb.running_index;
8638         rc |= BXE_DEF_SB_IDX;
8639     }
8640
8641     mb();
8642
8643     return (rc);
8644 }
8645
8646 static inline struct ecore_queue_sp_obj *
8647 bxe_cid_to_q_obj(struct bxe_softc *sc,
8648                  uint32_t         cid)
8649 {
8650     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8651     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8652 }
8653
8654 static void
8655 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8656 {
8657     struct ecore_mcast_ramrod_params rparam;
8658     int rc;
8659
8660     memset(&rparam, 0, sizeof(rparam));
8661
8662     rparam.mcast_obj = &sc->mcast_obj;
8663
8664     BXE_MCAST_LOCK(sc);
8665
8666     /* clear pending state for the last command */
8667     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8668
8669     /* if there are pending mcast commands - send them */
8670     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8671         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8672         if (rc < 0) {
8673             BLOGD(sc, DBG_SP,
8674                   "ERROR: Failed to send pending mcast commands (%d)\n",
8675                   rc);
8676         }
8677     }
8678
8679     BXE_MCAST_UNLOCK(sc);
8680 }
8681
8682 static void
8683 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8684                               union event_ring_elem *elem)
8685 {
8686     unsigned long ramrod_flags = 0;
8687     int rc = 0;
8688     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8689     struct ecore_vlan_mac_obj *vlan_mac_obj;
8690
8691     /* always push next commands out, don't wait here */
8692     bit_set(&ramrod_flags, RAMROD_CONT);
8693
8694     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8695     case ECORE_FILTER_MAC_PENDING:
8696         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8697         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8698         break;
8699
8700     case ECORE_FILTER_MCAST_PENDING:
8701         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8702         /*
8703          * This is only relevant for 57710 where multicast MACs are
8704          * configured as unicast MACs using the same ramrod.
8705          */
8706         bxe_handle_mcast_eqe(sc);
8707         return;
8708
8709     default:
8710         BLOGE(sc, "Unsupported classification command: %d\n",
8711               elem->message.data.eth_event.echo);
8712         return;
8713     }
8714
8715     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8716
8717     if (rc < 0) {
8718         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8719     } else if (rc > 0) {
8720         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8721     }
8722 }
8723
8724 static void
8725 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8726                        union event_ring_elem *elem)
8727 {
8728     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8729
8730     /* send rx_mode command again if was requested */
8731     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8732                                &sc->sp_state)) {
8733         bxe_set_storm_rx_mode(sc);
8734     }
8735 #if 0
8736     else if (bxe_test_and_clear_bit(ECORE_FILTER_ISCSI_ETH_START_SCHED,
8737                                     &sc->sp_state)) {
8738         bxe_set_iscsi_eth_rx_mode(sc, TRUE);
8739     }
8740     else if (bxe_test_and_clear_bit(ECORE_FILTER_ISCSI_ETH_STOP_SCHED,
8741                                     &sc->sp_state)) {
8742         bxe_set_iscsi_eth_rx_mode(sc, FALSE);
8743     }
8744 #endif
8745 }
8746
8747 static void
8748 bxe_update_eq_prod(struct bxe_softc *sc,
8749                    uint16_t         prod)
8750 {
8751     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8752     wmb(); /* keep prod updates ordered */
8753 }
8754
8755 static void
8756 bxe_eq_int(struct bxe_softc *sc)
8757 {
8758     uint16_t hw_cons, sw_cons, sw_prod;
8759     union event_ring_elem *elem;
8760     uint8_t echo;
8761     uint32_t cid;
8762     uint8_t opcode;
8763     int spqe_cnt = 0;
8764     struct ecore_queue_sp_obj *q_obj;
8765     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8766     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8767
8768     hw_cons = le16toh(*sc->eq_cons_sb);
8769
8770     /*
8771      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8772      * when we get to the next-page we need to adjust so the loop
8773      * condition below will be met. The next element is the size of a
8774      * regular element and hence incrementing by 1
8775      */
8776     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8777         hw_cons++;
8778     }
8779
8780     /*
8781      * This function may never run in parallel with itself for a
8782      * specific sc and no need for a read memory barrier here.
8783      */
8784     sw_cons = sc->eq_cons;
8785     sw_prod = sc->eq_prod;
8786
8787     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8788           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8789
8790     for (;
8791          sw_cons != hw_cons;
8792          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8793
8794         elem = &sc->eq[EQ_DESC(sw_cons)];
8795
8796 #if 0
8797         int rc;
8798         rc = bxe_iov_eq_sp_event(sc, elem);
8799         if (!rc) {
8800             BLOGE(sc, "bxe_iov_eq_sp_event returned %d\n", rc);
8801             goto next_spqe;
8802         }
8803 #endif
8804
8805         /* elem CID originates from FW, actually LE */
8806         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8807         opcode = elem->message.opcode;
8808
8809         /* handle eq element */
8810         switch (opcode) {
8811 #if 0
8812         case EVENT_RING_OPCODE_VF_PF_CHANNEL:
8813             BLOGD(sc, DBG_SP, "vf/pf channel element on eq\n");
8814             bxe_vf_mbx(sc, &elem->message.data.vf_pf_event);
8815             continue;
8816 #endif
8817
8818         case EVENT_RING_OPCODE_STAT_QUERY:
8819             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8820                   sc->stats_comp++);
8821             /* nothing to do with stats comp */
8822             goto next_spqe;
8823
8824         case EVENT_RING_OPCODE_CFC_DEL:
8825             /* handle according to cid range */
8826             /* we may want to verify here that the sc state is HALTING */
8827             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8828             q_obj = bxe_cid_to_q_obj(sc, cid);
8829             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8830                 break;
8831             }
8832             goto next_spqe;
8833
8834         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8835             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8836             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8837                 break;
8838             }
8839             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8840             goto next_spqe;
8841
8842         case EVENT_RING_OPCODE_START_TRAFFIC:
8843             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8844             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8845                 break;
8846             }
8847             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8848             goto next_spqe;
8849
8850         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8851             echo = elem->message.data.function_update_event.echo;
8852             if (echo == SWITCH_UPDATE) {
8853                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8854                 if (f_obj->complete_cmd(sc, f_obj,
8855                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8856                     break;
8857                 }
8858             }
8859             else {
8860                 BLOGD(sc, DBG_SP,
8861                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8862 #if 0
8863                 f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_AFEX_UPDATE);
8864                 /*
8865                  * We will perform the queues update from the sp_core_task as
8866                  * all queue SP operations should run with CORE_LOCK.
8867                  */
8868                 bxe_set_bit(BXE_SP_CORE_AFEX_F_UPDATE, &sc->sp_core_state);
8869                 taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8870 #endif
8871             }
8872             goto next_spqe;
8873
8874 #if 0
8875         case EVENT_RING_OPCODE_AFEX_VIF_LISTS:
8876             f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_AFEX_VIFLISTS);
8877             bxe_after_afex_vif_lists(sc, elem);
8878             goto next_spqe;
8879 #endif
8880
8881         case EVENT_RING_OPCODE_FORWARD_SETUP:
8882             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8883             if (q_obj->complete_cmd(sc, q_obj,
8884                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8885                 break;
8886             }
8887             goto next_spqe;
8888
8889         case EVENT_RING_OPCODE_FUNCTION_START:
8890             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8891             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8892                 break;
8893             }
8894             goto next_spqe;
8895
8896         case EVENT_RING_OPCODE_FUNCTION_STOP:
8897             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8898             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8899                 break;
8900             }
8901             goto next_spqe;
8902         }
8903
8904         switch (opcode | sc->state) {
8905         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8906         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8907             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8908             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8909             rss_raw->clear_pending(rss_raw);
8910             break;
8911
8912         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8913         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8914         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8915         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8916         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8917         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8918             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8919             bxe_handle_classification_eqe(sc, elem);
8920             break;
8921
8922         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8923         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8924         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8925             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8926             bxe_handle_mcast_eqe(sc);
8927             break;
8928
8929         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8930         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8931         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8932             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8933             bxe_handle_rx_mode_eqe(sc, elem);
8934             break;
8935
8936         default:
8937             /* unknown event log error and continue */
8938             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8939                   elem->message.opcode, sc->state);
8940         }
8941
8942 next_spqe:
8943         spqe_cnt++;
8944     } /* for */
8945
8946     mb();
8947     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8948
8949     sc->eq_cons = sw_cons;
8950     sc->eq_prod = sw_prod;
8951
8952     /* make sure that above mem writes were issued towards the memory */
8953     wmb();
8954
8955     /* update producer */
8956     bxe_update_eq_prod(sc, sc->eq_prod);
8957 }
8958
8959 static void
8960 bxe_handle_sp_tq(void *context,
8961                  int  pending)
8962 {
8963     struct bxe_softc *sc = (struct bxe_softc *)context;
8964     uint16_t status;
8965
8966     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8967
8968     /* what work needs to be performed? */
8969     status = bxe_update_dsb_idx(sc);
8970
8971     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8972
8973     /* HW attentions */
8974     if (status & BXE_DEF_SB_ATT_IDX) {
8975         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8976         bxe_attn_int(sc);
8977         status &= ~BXE_DEF_SB_ATT_IDX;
8978     }
8979
8980     /* SP events: STAT_QUERY and others */
8981     if (status & BXE_DEF_SB_IDX) {
8982         /* handle EQ completions */
8983         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8984         bxe_eq_int(sc);
8985         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8986                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8987         status &= ~BXE_DEF_SB_IDX;
8988     }
8989
8990     /* if status is non zero then something went wrong */
8991     if (__predict_false(status)) {
8992         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8993     }
8994
8995     /* ack status block only if something was actually handled */
8996     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8997                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8998
8999     /*
9000      * Must be called after the EQ processing (since eq leads to sriov
9001      * ramrod completion flows).
9002      * This flow may have been scheduled by the arrival of a ramrod
9003      * completion, or by the sriov code rescheduling itself.
9004      */
9005     // XXX bxe_iov_sp_task(sc);
9006
9007 #if 0
9008     /* AFEX - poll to check if VIFSET_ACK should be sent to MFW */
9009     if (bxe_test_and_clear_bit(ECORE_AFEX_PENDING_VIFSET_MCP_ACK,
9010                                &sc->sp_state)) {
9011         bxe_link_report(sc);
9012         bxe_fw_command(sc, DRV_MSG_CODE_AFEX_VIFSET_ACK, 0);
9013     }
9014 #endif
9015 }
9016
9017 static void
9018 bxe_handle_fp_tq(void *context,
9019                  int  pending)
9020 {
9021     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
9022     struct bxe_softc *sc = fp->sc;
9023     uint8_t more_tx = FALSE;
9024     uint8_t more_rx = FALSE;
9025
9026     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
9027
9028     /* XXX
9029      * IFF_DRV_RUNNING state can't be checked here since we process
9030      * slowpath events on a client queue during setup. Instead
9031      * we need to add a "process/continue" flag here that the driver
9032      * can use to tell the task here not to do anything.
9033      */
9034 #if 0
9035     if (!(if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
9036         return;
9037     }
9038 #endif
9039
9040     /* update the fastpath index */
9041     bxe_update_fp_sb_idx(fp);
9042
9043     /* XXX add loop here if ever support multiple tx CoS */
9044     /* fp->txdata[cos] */
9045     if (bxe_has_tx_work(fp)) {
9046         BXE_FP_TX_LOCK(fp);
9047         more_tx = bxe_txeof(sc, fp);
9048         BXE_FP_TX_UNLOCK(fp);
9049     }
9050
9051     if (bxe_has_rx_work(fp)) {
9052         more_rx = bxe_rxeof(sc, fp);
9053     }
9054
9055     if (more_rx /*|| more_tx*/) {
9056         /* still more work to do */
9057         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
9058         return;
9059     }
9060
9061     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
9062                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
9063 }
9064
9065 static void
9066 bxe_task_fp(struct bxe_fastpath *fp)
9067 {
9068     struct bxe_softc *sc = fp->sc;
9069     uint8_t more_tx = FALSE;
9070     uint8_t more_rx = FALSE;
9071
9072     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
9073
9074     /* update the fastpath index */
9075     bxe_update_fp_sb_idx(fp);
9076
9077     /* XXX add loop here if ever support multiple tx CoS */
9078     /* fp->txdata[cos] */
9079     if (bxe_has_tx_work(fp)) {
9080         BXE_FP_TX_LOCK(fp);
9081         more_tx = bxe_txeof(sc, fp);
9082         BXE_FP_TX_UNLOCK(fp);
9083     }
9084
9085     if (bxe_has_rx_work(fp)) {
9086         more_rx = bxe_rxeof(sc, fp);
9087     }
9088
9089     if (more_rx /*|| more_tx*/) {
9090         /* still more work to do, bail out if this ISR and process later */
9091         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
9092         return;
9093     }
9094
9095     /*
9096      * Here we write the fastpath index taken before doing any tx or rx work.
9097      * It is very well possible other hw events occurred up to this point and
9098      * they were actually processed accordingly above. Since we're going to
9099      * write an older fastpath index, an interrupt is coming which we might
9100      * not do any work in.
9101      */
9102     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
9103                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
9104 }
9105
9106 /*
9107  * Legacy interrupt entry point.
9108  *
9109  * Verifies that the controller generated the interrupt and
9110  * then calls a separate routine to handle the various
9111  * interrupt causes: link, RX, and TX.
9112  */
9113 static void
9114 bxe_intr_legacy(void *xsc)
9115 {
9116     struct bxe_softc *sc = (struct bxe_softc *)xsc;
9117     struct bxe_fastpath *fp;
9118     uint16_t status, mask;
9119     int i;
9120
9121     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
9122
9123 #if 0
9124     /* Don't handle any interrupts if we're not ready. */
9125     if (__predict_false(sc->intr_sem != 0)) {
9126         return;
9127     }
9128 #endif
9129
9130     /*
9131      * 0 for ustorm, 1 for cstorm
9132      * the bits returned from ack_int() are 0-15
9133      * bit 0 = attention status block
9134      * bit 1 = fast path status block
9135      * a mask of 0x2 or more = tx/rx event
9136      * a mask of 1 = slow path event
9137      */
9138
9139     status = bxe_ack_int(sc);
9140
9141     /* the interrupt is not for us */
9142     if (__predict_false(status == 0)) {
9143         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
9144         return;
9145     }
9146
9147     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
9148
9149     FOR_EACH_ETH_QUEUE(sc, i) {
9150         fp = &sc->fp[i];
9151         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
9152         if (status & mask) {
9153             /* acknowledge and disable further fastpath interrupts */
9154             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
9155             bxe_task_fp(fp);
9156             status &= ~mask;
9157         }
9158     }
9159
9160 #if 0
9161     if (CNIC_SUPPORT(sc)) {
9162         mask = 0x2;
9163         if (status & (mask | 0x1)) {
9164             ...
9165             status &= ~mask;
9166         }
9167     }
9168 #endif
9169
9170     if (__predict_false(status & 0x1)) {
9171         /* acknowledge and disable further slowpath interrupts */
9172         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
9173
9174         /* schedule slowpath handler */
9175         taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
9176
9177         status &= ~0x1;
9178     }
9179
9180     if (__predict_false(status)) {
9181         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
9182     }
9183 }
9184
9185 /* slowpath interrupt entry point */
9186 static void
9187 bxe_intr_sp(void *xsc)
9188 {
9189     struct bxe_softc *sc = (struct bxe_softc *)xsc;
9190
9191     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
9192
9193     /* acknowledge and disable further slowpath interrupts */
9194     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
9195
9196     /* schedule slowpath handler */
9197     taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
9198 }
9199
9200 /* fastpath interrupt entry point */
9201 static void
9202 bxe_intr_fp(void *xfp)
9203 {
9204     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
9205     struct bxe_softc *sc = fp->sc;
9206
9207     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
9208
9209     BLOGD(sc, DBG_INTR,
9210           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
9211           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
9212
9213 #if 0
9214     /* Don't handle any interrupts if we're not ready. */
9215     if (__predict_false(sc->intr_sem != 0)) {
9216         return;
9217     }
9218 #endif
9219
9220     /* acknowledge and disable further fastpath interrupts */
9221     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
9222
9223     bxe_task_fp(fp);
9224 }
9225
9226 /* Release all interrupts allocated by the driver. */
9227 static void
9228 bxe_interrupt_free(struct bxe_softc *sc)
9229 {
9230     int i;
9231
9232     switch (sc->interrupt_mode) {
9233     case INTR_MODE_INTX:
9234         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
9235         if (sc->intr[0].resource != NULL) {
9236             bus_release_resource(sc->dev,
9237                                  SYS_RES_IRQ,
9238                                  sc->intr[0].rid,
9239                                  sc->intr[0].resource);
9240         }
9241         break;
9242     case INTR_MODE_MSI:
9243         for (i = 0; i < sc->intr_count; i++) {
9244             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
9245             if (sc->intr[i].resource && sc->intr[i].rid) {
9246                 bus_release_resource(sc->dev,
9247                                      SYS_RES_IRQ,
9248                                      sc->intr[i].rid,
9249                                      sc->intr[i].resource);
9250             }
9251         }
9252         pci_release_msi(sc->dev);
9253         break;
9254     case INTR_MODE_MSIX:
9255         for (i = 0; i < sc->intr_count; i++) {
9256             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
9257             if (sc->intr[i].resource && sc->intr[i].rid) {
9258                 bus_release_resource(sc->dev,
9259                                      SYS_RES_IRQ,
9260                                      sc->intr[i].rid,
9261                                      sc->intr[i].resource);
9262             }
9263         }
9264         pci_release_msi(sc->dev);
9265         break;
9266     default:
9267         /* nothing to do as initial allocation failed */
9268         break;
9269     }
9270 }
9271
9272 /*
9273  * This function determines and allocates the appropriate
9274  * interrupt based on system capabilites and user request.
9275  *
9276  * The user may force a particular interrupt mode, specify
9277  * the number of receive queues, specify the method for
9278  * distribuitng received frames to receive queues, or use
9279  * the default settings which will automatically select the
9280  * best supported combination.  In addition, the OS may or
9281  * may not support certain combinations of these settings.
9282  * This routine attempts to reconcile the settings requested
9283  * by the user with the capabilites available from the system
9284  * to select the optimal combination of features.
9285  *
9286  * Returns:
9287  *   0 = Success, !0 = Failure.
9288  */
9289 static int
9290 bxe_interrupt_alloc(struct bxe_softc *sc)
9291 {
9292     int msix_count = 0;
9293     int msi_count = 0;
9294     int num_requested = 0;
9295     int num_allocated = 0;
9296     int rid, i, j;
9297     int rc;
9298
9299     /* get the number of available MSI/MSI-X interrupts from the OS */
9300     if (sc->interrupt_mode > 0) {
9301         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
9302             msix_count = pci_msix_count(sc->dev);
9303         }
9304
9305         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
9306             msi_count = pci_msi_count(sc->dev);
9307         }
9308
9309         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
9310               msi_count, msix_count);
9311     }
9312
9313     do { /* try allocating MSI-X interrupt resources (at least 2) */
9314         if (sc->interrupt_mode != INTR_MODE_MSIX) {
9315             break;
9316         }
9317
9318         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
9319             (msix_count < 2)) {
9320             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9321             break;
9322         }
9323
9324         /* ask for the necessary number of MSI-X vectors */
9325         num_requested = min((sc->num_queues + 1), msix_count);
9326
9327         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
9328
9329         num_allocated = num_requested;
9330         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
9331             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
9332             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9333             break;
9334         }
9335
9336         if (num_allocated < 2) { /* possible? */
9337             BLOGE(sc, "MSI-X allocation less than 2!\n");
9338             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9339             pci_release_msi(sc->dev);
9340             break;
9341         }
9342
9343         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
9344               num_requested, num_allocated);
9345
9346         /* best effort so use the number of vectors allocated to us */
9347         sc->intr_count = num_allocated;
9348         sc->num_queues = num_allocated - 1;
9349
9350         rid = 1; /* initial resource identifier */
9351
9352         /* allocate the MSI-X vectors */
9353         for (i = 0; i < num_allocated; i++) {
9354             sc->intr[i].rid = (rid + i);
9355
9356             if ((sc->intr[i].resource =
9357                  bus_alloc_resource_any(sc->dev,
9358                                         SYS_RES_IRQ,
9359                                         &sc->intr[i].rid,
9360                                         RF_ACTIVE)) == NULL) {
9361                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
9362                       i, (rid + i));
9363
9364                 for (j = (i - 1); j >= 0; j--) {
9365                     bus_release_resource(sc->dev,
9366                                          SYS_RES_IRQ,
9367                                          sc->intr[j].rid,
9368                                          sc->intr[j].resource);
9369                 }
9370
9371                 sc->intr_count = 0;
9372                 sc->num_queues = 0;
9373                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9374                 pci_release_msi(sc->dev);
9375                 break;
9376             }
9377
9378             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9379         }
9380     } while (0);
9381
9382     do { /* try allocating MSI vector resources (at least 2) */
9383         if (sc->interrupt_mode != INTR_MODE_MSI) {
9384             break;
9385         }
9386
9387         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9388             (msi_count < 1)) {
9389             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9390             break;
9391         }
9392
9393         /* ask for a single MSI vector */
9394         num_requested = 1;
9395
9396         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9397
9398         num_allocated = num_requested;
9399         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9400             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9401             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9402             break;
9403         }
9404
9405         if (num_allocated != 1) { /* possible? */
9406             BLOGE(sc, "MSI allocation is not 1!\n");
9407             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9408             pci_release_msi(sc->dev);
9409             break;
9410         }
9411
9412         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9413               num_requested, num_allocated);
9414
9415         /* best effort so use the number of vectors allocated to us */
9416         sc->intr_count = num_allocated;
9417         sc->num_queues = num_allocated;
9418
9419         rid = 1; /* initial resource identifier */
9420
9421         sc->intr[0].rid = rid;
9422
9423         if ((sc->intr[0].resource =
9424              bus_alloc_resource_any(sc->dev,
9425                                     SYS_RES_IRQ,
9426                                     &sc->intr[0].rid,
9427                                     RF_ACTIVE)) == NULL) {
9428             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9429             sc->intr_count = 0;
9430             sc->num_queues = 0;
9431             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9432             pci_release_msi(sc->dev);
9433             break;
9434         }
9435
9436         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9437     } while (0);
9438
9439     do { /* try allocating INTx vector resources */
9440         if (sc->interrupt_mode != INTR_MODE_INTX) {
9441             break;
9442         }
9443
9444         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9445
9446         /* only one vector for INTx */
9447         sc->intr_count = 1;
9448         sc->num_queues = 1;
9449
9450         rid = 0; /* initial resource identifier */
9451
9452         sc->intr[0].rid = rid;
9453
9454         if ((sc->intr[0].resource =
9455              bus_alloc_resource_any(sc->dev,
9456                                     SYS_RES_IRQ,
9457                                     &sc->intr[0].rid,
9458                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9459             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9460             sc->intr_count = 0;
9461             sc->num_queues = 0;
9462             sc->interrupt_mode = -1; /* Failed! */
9463             break;
9464         }
9465
9466         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9467     } while (0);
9468
9469     if (sc->interrupt_mode == -1) {
9470         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9471         rc = 1;
9472     } else {
9473         BLOGD(sc, DBG_LOAD,
9474               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9475               sc->interrupt_mode, sc->num_queues);
9476         rc = 0;
9477     }
9478
9479     return (rc);
9480 }
9481
9482 static void
9483 bxe_interrupt_detach(struct bxe_softc *sc)
9484 {
9485     struct bxe_fastpath *fp;
9486     int i;
9487
9488     /* release interrupt resources */
9489     for (i = 0; i < sc->intr_count; i++) {
9490         if (sc->intr[i].resource && sc->intr[i].tag) {
9491             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9492             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9493         }
9494     }
9495
9496     for (i = 0; i < sc->num_queues; i++) {
9497         fp = &sc->fp[i];
9498         if (fp->tq) {
9499             taskqueue_drain(fp->tq, &fp->tq_task);
9500             taskqueue_free(fp->tq);
9501             fp->tq = NULL;
9502         }
9503     }
9504
9505     if (sc->rx_mode_tq) {
9506         taskqueue_drain(sc->rx_mode_tq, &sc->rx_mode_tq_task);
9507         taskqueue_free(sc->rx_mode_tq);
9508         sc->rx_mode_tq = NULL;
9509     }
9510
9511     if (sc->sp_tq) {
9512         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9513         taskqueue_free(sc->sp_tq);
9514         sc->sp_tq = NULL;
9515     }
9516 }
9517
9518 /*
9519  * Enables interrupts and attach to the ISR.
9520  *
9521  * When using multiple MSI/MSI-X vectors the first vector
9522  * is used for slowpath operations while all remaining
9523  * vectors are used for fastpath operations.  If only a
9524  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9525  * ISR must look for both slowpath and fastpath completions.
9526  */
9527 static int
9528 bxe_interrupt_attach(struct bxe_softc *sc)
9529 {
9530     struct bxe_fastpath *fp;
9531     int rc = 0;
9532     int i;
9533
9534     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9535              "bxe%d_sp_tq", sc->unit);
9536     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9537     sc->sp_tq = taskqueue_create_fast(sc->sp_tq_name, M_NOWAIT,
9538                                       taskqueue_thread_enqueue,
9539                                       &sc->sp_tq);
9540     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9541                             "%s", sc->sp_tq_name);
9542
9543     snprintf(sc->rx_mode_tq_name, sizeof(sc->rx_mode_tq_name),
9544              "bxe%d_rx_mode_tq", sc->unit);
9545     TASK_INIT(&sc->rx_mode_tq_task, 0, bxe_handle_rx_mode_tq, sc);
9546     sc->rx_mode_tq = taskqueue_create_fast(sc->rx_mode_tq_name, M_NOWAIT,
9547                                            taskqueue_thread_enqueue,
9548                                            &sc->rx_mode_tq);
9549     taskqueue_start_threads(&sc->rx_mode_tq, 1, PWAIT, /* lower priority */
9550                             "%s", sc->rx_mode_tq_name);
9551
9552     for (i = 0; i < sc->num_queues; i++) {
9553         fp = &sc->fp[i];
9554         snprintf(fp->tq_name, sizeof(fp->tq_name),
9555                  "bxe%d_fp%d_tq", sc->unit, i);
9556         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9557         fp->tq = taskqueue_create_fast(fp->tq_name, M_NOWAIT,
9558                                        taskqueue_thread_enqueue,
9559                                        &fp->tq);
9560         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9561                                 "%s", fp->tq_name);
9562     }
9563
9564     /* setup interrupt handlers */
9565     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9566         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9567
9568         /*
9569          * Setup the interrupt handler. Note that we pass the driver instance
9570          * to the interrupt handler for the slowpath.
9571          */
9572         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9573                                  (INTR_TYPE_NET | INTR_MPSAFE),
9574                                  NULL, bxe_intr_sp, sc,
9575                                  &sc->intr[0].tag)) != 0) {
9576             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9577             goto bxe_interrupt_attach_exit;
9578         }
9579
9580         bus_describe_intr(sc->dev, sc->intr[0].resource,
9581                           sc->intr[0].tag, "sp");
9582
9583         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9584
9585         /* initialize the fastpath vectors (note the first was used for sp) */
9586         for (i = 0; i < sc->num_queues; i++) {
9587             fp = &sc->fp[i];
9588             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9589
9590             /*
9591              * Setup the interrupt handler. Note that we pass the
9592              * fastpath context to the interrupt handler in this
9593              * case.
9594              */
9595             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9596                                      (INTR_TYPE_NET | INTR_MPSAFE),
9597                                      NULL, bxe_intr_fp, fp,
9598                                      &sc->intr[i + 1].tag)) != 0) {
9599                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9600                       (i + 1), rc);
9601                 goto bxe_interrupt_attach_exit;
9602             }
9603
9604             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9605                               sc->intr[i + 1].tag, "fp%02d", i);
9606
9607             /* bind the fastpath instance to a cpu */
9608             if (sc->num_queues > 1) {
9609                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9610             }
9611
9612             fp->state = BXE_FP_STATE_IRQ;
9613         }
9614     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9615         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9616
9617         /*
9618          * Setup the interrupt handler. Note that we pass the
9619          * driver instance to the interrupt handler which
9620          * will handle both the slowpath and fastpath.
9621          */
9622         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9623                                  (INTR_TYPE_NET | INTR_MPSAFE),
9624                                  NULL, bxe_intr_legacy, sc,
9625                                  &sc->intr[0].tag)) != 0) {
9626             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9627             goto bxe_interrupt_attach_exit;
9628         }
9629
9630     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9631         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9632
9633         /*
9634          * Setup the interrupt handler. Note that we pass the
9635          * driver instance to the interrupt handler which
9636          * will handle both the slowpath and fastpath.
9637          */
9638         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9639                                  (INTR_TYPE_NET | INTR_MPSAFE),
9640                                  NULL, bxe_intr_legacy, sc,
9641                                  &sc->intr[0].tag)) != 0) {
9642             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9643             goto bxe_interrupt_attach_exit;
9644         }
9645     }
9646
9647 bxe_interrupt_attach_exit:
9648
9649     return (rc);
9650 }
9651
9652 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9653 static int  bxe_init_hw_common(struct bxe_softc *sc);
9654 static int  bxe_init_hw_port(struct bxe_softc *sc);
9655 static int  bxe_init_hw_func(struct bxe_softc *sc);
9656 static void bxe_reset_common(struct bxe_softc *sc);
9657 static void bxe_reset_port(struct bxe_softc *sc);
9658 static void bxe_reset_func(struct bxe_softc *sc);
9659 static int  bxe_gunzip_init(struct bxe_softc *sc);
9660 static void bxe_gunzip_end(struct bxe_softc *sc);
9661 static int  bxe_init_firmware(struct bxe_softc *sc);
9662 static void bxe_release_firmware(struct bxe_softc *sc);
9663
9664 static struct
9665 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9666     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9667     .init_hw_cmn      = bxe_init_hw_common,
9668     .init_hw_port     = bxe_init_hw_port,
9669     .init_hw_func     = bxe_init_hw_func,
9670
9671     .reset_hw_cmn     = bxe_reset_common,
9672     .reset_hw_port    = bxe_reset_port,
9673     .reset_hw_func    = bxe_reset_func,
9674
9675     .gunzip_init      = bxe_gunzip_init,
9676     .gunzip_end       = bxe_gunzip_end,
9677
9678     .init_fw          = bxe_init_firmware,
9679     .release_fw       = bxe_release_firmware,
9680 };
9681
9682 static void
9683 bxe_init_func_obj(struct bxe_softc *sc)
9684 {
9685     sc->dmae_ready = 0;
9686
9687     ecore_init_func_obj(sc,
9688                         &sc->func_obj,
9689                         BXE_SP(sc, func_rdata),
9690                         BXE_SP_MAPPING(sc, func_rdata),
9691                         BXE_SP(sc, func_afex_rdata),
9692                         BXE_SP_MAPPING(sc, func_afex_rdata),
9693                         &bxe_func_sp_drv);
9694 }
9695
9696 static int
9697 bxe_init_hw(struct bxe_softc *sc,
9698             uint32_t         load_code)
9699 {
9700     struct ecore_func_state_params func_params = { NULL };
9701     int rc;
9702
9703     /* prepare the parameters for function state transitions */
9704     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9705
9706     func_params.f_obj = &sc->func_obj;
9707     func_params.cmd = ECORE_F_CMD_HW_INIT;
9708
9709     func_params.params.hw_init.load_phase = load_code;
9710
9711     /*
9712      * Via a plethora of function pointers, we will eventually reach
9713      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9714      */
9715     rc = ecore_func_state_change(sc, &func_params);
9716
9717     return (rc);
9718 }
9719
9720 static void
9721 bxe_fill(struct bxe_softc *sc,
9722          uint32_t         addr,
9723          int              fill,
9724          uint32_t         len)
9725 {
9726     uint32_t i;
9727
9728     if (!(len % 4) && !(addr % 4)) {
9729         for (i = 0; i < len; i += 4) {
9730             REG_WR(sc, (addr + i), fill);
9731         }
9732     } else {
9733         for (i = 0; i < len; i++) {
9734             REG_WR8(sc, (addr + i), fill);
9735         }
9736     }
9737 }
9738
9739 /* writes FP SP data to FW - data_size in dwords */
9740 static void
9741 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9742                   int              fw_sb_id,
9743                   uint32_t         *sb_data_p,
9744                   uint32_t         data_size)
9745 {
9746     int index;
9747
9748     for (index = 0; index < data_size; index++) {
9749         REG_WR(sc,
9750                (BAR_CSTRORM_INTMEM +
9751                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9752                 (sizeof(uint32_t) * index)),
9753                *(sb_data_p + index));
9754     }
9755 }
9756
9757 static void
9758 bxe_zero_fp_sb(struct bxe_softc *sc,
9759                int              fw_sb_id)
9760 {
9761     struct hc_status_block_data_e2 sb_data_e2;
9762     struct hc_status_block_data_e1x sb_data_e1x;
9763     uint32_t *sb_data_p;
9764     uint32_t data_size = 0;
9765
9766     if (!CHIP_IS_E1x(sc)) {
9767         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9768         sb_data_e2.common.state = SB_DISABLED;
9769         sb_data_e2.common.p_func.vf_valid = FALSE;
9770         sb_data_p = (uint32_t *)&sb_data_e2;
9771         data_size = (sizeof(struct hc_status_block_data_e2) /
9772                      sizeof(uint32_t));
9773     } else {
9774         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9775         sb_data_e1x.common.state = SB_DISABLED;
9776         sb_data_e1x.common.p_func.vf_valid = FALSE;
9777         sb_data_p = (uint32_t *)&sb_data_e1x;
9778         data_size = (sizeof(struct hc_status_block_data_e1x) /
9779                      sizeof(uint32_t));
9780     }
9781
9782     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9783
9784     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9785              0, CSTORM_STATUS_BLOCK_SIZE);
9786     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9787              0, CSTORM_SYNC_BLOCK_SIZE);
9788 }
9789
9790 static void
9791 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9792                   struct hc_sp_status_block_data *sp_sb_data)
9793 {
9794     int i;
9795
9796     for (i = 0;
9797          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9798          i++) {
9799         REG_WR(sc,
9800                (BAR_CSTRORM_INTMEM +
9801                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9802                 (i * sizeof(uint32_t))),
9803                *((uint32_t *)sp_sb_data + i));
9804     }
9805 }
9806
9807 static void
9808 bxe_zero_sp_sb(struct bxe_softc *sc)
9809 {
9810     struct hc_sp_status_block_data sp_sb_data;
9811
9812     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9813
9814     sp_sb_data.state           = SB_DISABLED;
9815     sp_sb_data.p_func.vf_valid = FALSE;
9816
9817     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9818
9819     bxe_fill(sc,
9820              (BAR_CSTRORM_INTMEM +
9821               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9822               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9823     bxe_fill(sc,
9824              (BAR_CSTRORM_INTMEM +
9825               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9826               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9827 }
9828
9829 static void
9830 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9831                              int                       igu_sb_id,
9832                              int                       igu_seg_id)
9833 {
9834     hc_sm->igu_sb_id      = igu_sb_id;
9835     hc_sm->igu_seg_id     = igu_seg_id;
9836     hc_sm->timer_value    = 0xFF;
9837     hc_sm->time_to_expire = 0xFFFFFFFF;
9838 }
9839
9840 static void
9841 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9842 {
9843     /* zero out state machine indices */
9844
9845     /* rx indices */
9846     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9847
9848     /* tx indices */
9849     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9850     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9851     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9852     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9853
9854     /* map indices */
9855
9856     /* rx indices */
9857     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9858         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9859
9860     /* tx indices */
9861     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9862         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9863     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9864         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9865     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9866         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9867     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9868         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9869 }
9870
9871 static void
9872 bxe_init_sb(struct bxe_softc *sc,
9873             bus_addr_t       busaddr,
9874             int              vfid,
9875             uint8_t          vf_valid,
9876             int              fw_sb_id,
9877             int              igu_sb_id)
9878 {
9879     struct hc_status_block_data_e2  sb_data_e2;
9880     struct hc_status_block_data_e1x sb_data_e1x;
9881     struct hc_status_block_sm       *hc_sm_p;
9882     uint32_t *sb_data_p;
9883     int igu_seg_id;
9884     int data_size;
9885
9886     if (CHIP_INT_MODE_IS_BC(sc)) {
9887         igu_seg_id = HC_SEG_ACCESS_NORM;
9888     } else {
9889         igu_seg_id = IGU_SEG_ACCESS_NORM;
9890     }
9891
9892     bxe_zero_fp_sb(sc, fw_sb_id);
9893
9894     if (!CHIP_IS_E1x(sc)) {
9895         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9896         sb_data_e2.common.state = SB_ENABLED;
9897         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9898         sb_data_e2.common.p_func.vf_id = vfid;
9899         sb_data_e2.common.p_func.vf_valid = vf_valid;
9900         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9901         sb_data_e2.common.same_igu_sb_1b = TRUE;
9902         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9903         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9904         hc_sm_p = sb_data_e2.common.state_machine;
9905         sb_data_p = (uint32_t *)&sb_data_e2;
9906         data_size = (sizeof(struct hc_status_block_data_e2) /
9907                      sizeof(uint32_t));
9908         bxe_map_sb_state_machines(sb_data_e2.index_data);
9909     } else {
9910         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9911         sb_data_e1x.common.state = SB_ENABLED;
9912         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9913         sb_data_e1x.common.p_func.vf_id = 0xff;
9914         sb_data_e1x.common.p_func.vf_valid = FALSE;
9915         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9916         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9917         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9918         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9919         hc_sm_p = sb_data_e1x.common.state_machine;
9920         sb_data_p = (uint32_t *)&sb_data_e1x;
9921         data_size = (sizeof(struct hc_status_block_data_e1x) /
9922                      sizeof(uint32_t));
9923         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9924     }
9925
9926     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9927     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9928
9929     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9930
9931     /* write indices to HW - PCI guarantees endianity of regpairs */
9932     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9933 }
9934
9935 static inline uint8_t
9936 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9937 {
9938     if (CHIP_IS_E1x(fp->sc)) {
9939         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9940     } else {
9941         return (fp->cl_id);
9942     }
9943 }
9944
9945 static inline uint32_t
9946 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9947                            struct bxe_fastpath *fp)
9948 {
9949     uint32_t offset = BAR_USTRORM_INTMEM;
9950
9951 #if 0
9952     if (IS_VF(sc)) {
9953         return (PXP_VF_ADDR_USDM_QUEUES_START +
9954                 (sc->acquire_resp.resc.hw_qid[fp->index] *
9955                  sizeof(struct ustorm_queue_zone_data)));
9956     } else
9957 #endif
9958     if (!CHIP_IS_E1x(sc)) {
9959         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9960     } else {
9961         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9962     }
9963
9964     return (offset);
9965 }
9966
9967 static void
9968 bxe_init_eth_fp(struct bxe_softc *sc,
9969                 int              idx)
9970 {
9971     struct bxe_fastpath *fp = &sc->fp[idx];
9972     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9973     unsigned long q_type = 0;
9974     int cos;
9975
9976     fp->sc    = sc;
9977     fp->index = idx;
9978
9979     snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
9980              "bxe%d_fp%d_tx_lock", sc->unit, idx);
9981     mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
9982
9983     snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
9984              "bxe%d_fp%d_rx_lock", sc->unit, idx);
9985     mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
9986
9987     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9988     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9989
9990     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9991                     (SC_L_ID(sc) + idx) :
9992                     /* want client ID same as IGU SB ID for non-E1 */
9993                     fp->igu_sb_id;
9994     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9995
9996     /* setup sb indices */
9997     if (!CHIP_IS_E1x(sc)) {
9998         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9999         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
10000     } else {
10001         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
10002         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
10003     }
10004
10005     /* init shortcut */
10006     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
10007
10008     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
10009
10010     /*
10011      * XXX If multiple CoS is ever supported then each fastpath structure
10012      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
10013      */
10014     for (cos = 0; cos < sc->max_cos; cos++) {
10015         cids[cos] = idx;
10016     }
10017     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
10018
10019     /* nothing more for a VF to do */
10020     if (IS_VF(sc)) {
10021         return;
10022     }
10023
10024     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
10025                 fp->fw_sb_id, fp->igu_sb_id);
10026
10027     bxe_update_fp_sb_idx(fp);
10028
10029     /* Configure Queue State object */
10030     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
10031     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
10032
10033     ecore_init_queue_obj(sc,
10034                          &sc->sp_objs[idx].q_obj,
10035                          fp->cl_id,
10036                          cids,
10037                          sc->max_cos,
10038                          SC_FUNC(sc),
10039                          BXE_SP(sc, q_rdata),
10040                          BXE_SP_MAPPING(sc, q_rdata),
10041                          q_type);
10042
10043     /* configure classification DBs */
10044     ecore_init_mac_obj(sc,
10045                        &sc->sp_objs[idx].mac_obj,
10046                        fp->cl_id,
10047                        idx,
10048                        SC_FUNC(sc),
10049                        BXE_SP(sc, mac_rdata),
10050                        BXE_SP_MAPPING(sc, mac_rdata),
10051                        ECORE_FILTER_MAC_PENDING,
10052                        &sc->sp_state,
10053                        ECORE_OBJ_TYPE_RX_TX,
10054                        &sc->macs_pool);
10055
10056     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
10057           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
10058 }
10059
10060 static inline void
10061 bxe_update_rx_prod(struct bxe_softc    *sc,
10062                    struct bxe_fastpath *fp,
10063                    uint16_t            rx_bd_prod,
10064                    uint16_t            rx_cq_prod,
10065                    uint16_t            rx_sge_prod)
10066 {
10067     struct ustorm_eth_rx_producers rx_prods = { 0 };
10068     uint32_t i;
10069
10070     /* update producers */
10071     rx_prods.bd_prod  = rx_bd_prod;
10072     rx_prods.cqe_prod = rx_cq_prod;
10073     rx_prods.sge_prod = rx_sge_prod;
10074
10075     /*
10076      * Make sure that the BD and SGE data is updated before updating the
10077      * producers since FW might read the BD/SGE right after the producer
10078      * is updated.
10079      * This is only applicable for weak-ordered memory model archs such
10080      * as IA-64. The following barrier is also mandatory since FW will
10081      * assumes BDs must have buffers.
10082      */
10083     wmb();
10084
10085     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
10086         REG_WR(sc,
10087                (fp->ustorm_rx_prods_offset + (i * 4)),
10088                ((uint32_t *)&rx_prods)[i]);
10089     }
10090
10091     wmb(); /* keep prod updates ordered */
10092
10093     BLOGD(sc, DBG_RX,
10094           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
10095           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
10096 }
10097
10098 static void
10099 bxe_init_rx_rings(struct bxe_softc *sc)
10100 {
10101     struct bxe_fastpath *fp;
10102     int i;
10103
10104     for (i = 0; i < sc->num_queues; i++) {
10105         fp = &sc->fp[i];
10106
10107         fp->rx_bd_cons = 0;
10108
10109         /*
10110          * Activate the BD ring...
10111          * Warning, this will generate an interrupt (to the TSTORM)
10112          * so this can only be done after the chip is initialized
10113          */
10114         bxe_update_rx_prod(sc, fp,
10115                            fp->rx_bd_prod,
10116                            fp->rx_cq_prod,
10117                            fp->rx_sge_prod);
10118
10119         if (i != 0) {
10120             continue;
10121         }
10122
10123         if (CHIP_IS_E1(sc)) {
10124             REG_WR(sc,
10125                    (BAR_USTRORM_INTMEM +
10126                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
10127                    U64_LO(fp->rcq_dma.paddr));
10128             REG_WR(sc,
10129                    (BAR_USTRORM_INTMEM +
10130                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
10131                    U64_HI(fp->rcq_dma.paddr));
10132         }
10133     }
10134 }
10135
10136 static void
10137 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
10138 {
10139     SET_FLAG(fp->tx_db.data.header.header, DOORBELL_HDR_DB_TYPE, 1);
10140     fp->tx_db.data.zero_fill1 = 0;
10141     fp->tx_db.data.prod = 0;
10142
10143     fp->tx_pkt_prod = 0;
10144     fp->tx_pkt_cons = 0;
10145     fp->tx_bd_prod = 0;
10146     fp->tx_bd_cons = 0;
10147     fp->eth_q_stats.tx_pkts = 0;
10148 }
10149
10150 static inline void
10151 bxe_init_tx_rings(struct bxe_softc *sc)
10152 {
10153     int i;
10154
10155     for (i = 0; i < sc->num_queues; i++) {
10156 #if 0
10157         uint8_t cos;
10158         for (cos = 0; cos < sc->max_cos; cos++) {
10159             bxe_init_tx_ring_one(&sc->fp[i].txdata[cos]);
10160         }
10161 #else
10162         bxe_init_tx_ring_one(&sc->fp[i]);
10163 #endif
10164     }
10165 }
10166
10167 static void
10168 bxe_init_def_sb(struct bxe_softc *sc)
10169 {
10170     struct host_sp_status_block *def_sb = sc->def_sb;
10171     bus_addr_t mapping = sc->def_sb_dma.paddr;
10172     int igu_sp_sb_index;
10173     int igu_seg_id;
10174     int port = SC_PORT(sc);
10175     int func = SC_FUNC(sc);
10176     int reg_offset, reg_offset_en5;
10177     uint64_t section;
10178     int index, sindex;
10179     struct hc_sp_status_block_data sp_sb_data;
10180
10181     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
10182
10183     if (CHIP_INT_MODE_IS_BC(sc)) {
10184         igu_sp_sb_index = DEF_SB_IGU_ID;
10185         igu_seg_id = HC_SEG_ACCESS_DEF;
10186     } else {
10187         igu_sp_sb_index = sc->igu_dsb_id;
10188         igu_seg_id = IGU_SEG_ACCESS_DEF;
10189     }
10190
10191     /* attentions */
10192     section = ((uint64_t)mapping +
10193                offsetof(struct host_sp_status_block, atten_status_block));
10194     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
10195     sc->attn_state = 0;
10196
10197     reg_offset = (port) ?
10198                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
10199                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
10200     reg_offset_en5 = (port) ?
10201                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
10202                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
10203
10204     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
10205         /* take care of sig[0]..sig[4] */
10206         for (sindex = 0; sindex < 4; sindex++) {
10207             sc->attn_group[index].sig[sindex] =
10208                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
10209         }
10210
10211         if (!CHIP_IS_E1x(sc)) {
10212             /*
10213              * enable5 is separate from the rest of the registers,
10214              * and the address skip is 4 and not 16 between the
10215              * different groups
10216              */
10217             sc->attn_group[index].sig[4] =
10218                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
10219         } else {
10220             sc->attn_group[index].sig[4] = 0;
10221         }
10222     }
10223
10224     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10225         reg_offset = (port) ?
10226                          HC_REG_ATTN_MSG1_ADDR_L :
10227                          HC_REG_ATTN_MSG0_ADDR_L;
10228         REG_WR(sc, reg_offset, U64_LO(section));
10229         REG_WR(sc, (reg_offset + 4), U64_HI(section));
10230     } else if (!CHIP_IS_E1x(sc)) {
10231         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
10232         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
10233     }
10234
10235     section = ((uint64_t)mapping +
10236                offsetof(struct host_sp_status_block, sp_sb));
10237
10238     bxe_zero_sp_sb(sc);
10239
10240     /* PCI guarantees endianity of regpair */
10241     sp_sb_data.state           = SB_ENABLED;
10242     sp_sb_data.host_sb_addr.lo = U64_LO(section);
10243     sp_sb_data.host_sb_addr.hi = U64_HI(section);
10244     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
10245     sp_sb_data.igu_seg_id      = igu_seg_id;
10246     sp_sb_data.p_func.pf_id    = func;
10247     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
10248     sp_sb_data.p_func.vf_id    = 0xff;
10249
10250     bxe_wr_sp_sb_data(sc, &sp_sb_data);
10251
10252     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
10253 }
10254
10255 static void
10256 bxe_init_sp_ring(struct bxe_softc *sc)
10257 {
10258     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
10259     sc->spq_prod_idx = 0;
10260     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
10261     sc->spq_prod_bd = sc->spq;
10262     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
10263 }
10264
10265 static void
10266 bxe_init_eq_ring(struct bxe_softc *sc)
10267 {
10268     union event_ring_elem *elem;
10269     int i;
10270
10271     for (i = 1; i <= NUM_EQ_PAGES; i++) {
10272         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
10273
10274         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
10275                                                  BCM_PAGE_SIZE *
10276                                                  (i % NUM_EQ_PAGES)));
10277         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
10278                                                  BCM_PAGE_SIZE *
10279                                                  (i % NUM_EQ_PAGES)));
10280     }
10281
10282     sc->eq_cons    = 0;
10283     sc->eq_prod    = NUM_EQ_DESC;
10284     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
10285
10286     atomic_store_rel_long(&sc->eq_spq_left,
10287                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
10288                                NUM_EQ_DESC) - 1));
10289 }
10290
10291 static void
10292 bxe_init_internal_common(struct bxe_softc *sc)
10293 {
10294     int i;
10295
10296     if (IS_MF_SI(sc)) {
10297         /*
10298          * In switch independent mode, the TSTORM needs to accept
10299          * packets that failed classification, since approximate match
10300          * mac addresses aren't written to NIG LLH.
10301          */
10302         REG_WR8(sc,
10303                 (BAR_TSTRORM_INTMEM + TSTORM_ACCEPT_CLASSIFY_FAILED_OFFSET),
10304                 2);
10305     } else if (!CHIP_IS_E1(sc)) { /* 57710 doesn't support MF */
10306         REG_WR8(sc,
10307                 (BAR_TSTRORM_INTMEM + TSTORM_ACCEPT_CLASSIFY_FAILED_OFFSET),
10308                 0);
10309     }
10310
10311     /*
10312      * Zero this manually as its initialization is currently missing
10313      * in the initTool.
10314      */
10315     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
10316         REG_WR(sc,
10317                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
10318                0);
10319     }
10320
10321     if (!CHIP_IS_E1x(sc)) {
10322         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
10323                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
10324     }
10325 }
10326
10327 static void
10328 bxe_init_internal(struct bxe_softc *sc,
10329                   uint32_t         load_code)
10330 {
10331     switch (load_code) {
10332     case FW_MSG_CODE_DRV_LOAD_COMMON:
10333     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
10334         bxe_init_internal_common(sc);
10335         /* no break */
10336
10337     case FW_MSG_CODE_DRV_LOAD_PORT:
10338         /* nothing to do */
10339         /* no break */
10340
10341     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
10342         /* internal memory per function is initialized inside bxe_pf_init */
10343         break;
10344
10345     default:
10346         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
10347         break;
10348     }
10349 }
10350
10351 static void
10352 storm_memset_func_cfg(struct bxe_softc                         *sc,
10353                       struct tstorm_eth_function_common_config *tcfg,
10354                       uint16_t                                  abs_fid)
10355 {
10356     uint32_t addr;
10357     size_t size;
10358
10359     addr = (BAR_TSTRORM_INTMEM +
10360             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
10361     size = sizeof(struct tstorm_eth_function_common_config);
10362     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
10363 }
10364
10365 static void
10366 bxe_func_init(struct bxe_softc            *sc,
10367               struct bxe_func_init_params *p)
10368 {
10369     struct tstorm_eth_function_common_config tcfg = { 0 };
10370
10371     if (CHIP_IS_E1x(sc)) {
10372         storm_memset_func_cfg(sc, &tcfg, p->func_id);
10373     }
10374
10375     /* Enable the function in the FW */
10376     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
10377     storm_memset_func_en(sc, p->func_id, 1);
10378
10379     /* spq */
10380     if (p->func_flgs & FUNC_FLG_SPQ) {
10381         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
10382         REG_WR(sc,
10383                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
10384                p->spq_prod);
10385     }
10386 }
10387
10388 /*
10389  * Calculates the sum of vn_min_rates.
10390  * It's needed for further normalizing of the min_rates.
10391  * Returns:
10392  *   sum of vn_min_rates.
10393  *     or
10394  *   0 - if all the min_rates are 0.
10395  * In the later case fainess algorithm should be deactivated.
10396  * If all min rates are not zero then those that are zeroes will be set to 1.
10397  */
10398 static void
10399 bxe_calc_vn_min(struct bxe_softc       *sc,
10400                 struct cmng_init_input *input)
10401 {
10402     uint32_t vn_cfg;
10403     uint32_t vn_min_rate;
10404     int all_zero = 1;
10405     int vn;
10406
10407     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10408         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10409         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
10410                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
10411
10412         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10413             /* skip hidden VNs */
10414             vn_min_rate = 0;
10415         } else if (!vn_min_rate) {
10416             /* If min rate is zero - set it to 100 */
10417             vn_min_rate = DEF_MIN_RATE;
10418         } else {
10419             all_zero = 0;
10420         }
10421
10422         input->vnic_min_rate[vn] = vn_min_rate;
10423     }
10424
10425     /* if ETS or all min rates are zeros - disable fairness */
10426     if (BXE_IS_ETS_ENABLED(sc)) {
10427         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10428         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10429     } else if (all_zero) {
10430         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10431         BLOGD(sc, DBG_LOAD,
10432               "Fariness disabled (all MIN values are zeroes)\n");
10433     } else {
10434         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10435     }
10436 }
10437
10438 static inline uint16_t
10439 bxe_extract_max_cfg(struct bxe_softc *sc,
10440                     uint32_t         mf_cfg)
10441 {
10442     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10443                         FUNC_MF_CFG_MAX_BW_SHIFT);
10444
10445     if (!max_cfg) {
10446         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10447         max_cfg = 100;
10448     }
10449
10450     return (max_cfg);
10451 }
10452
10453 static void
10454 bxe_calc_vn_max(struct bxe_softc       *sc,
10455                 int                    vn,
10456                 struct cmng_init_input *input)
10457 {
10458     uint16_t vn_max_rate;
10459     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10460     uint32_t max_cfg;
10461
10462     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10463         vn_max_rate = 0;
10464     } else {
10465         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10466
10467         if (IS_MF_SI(sc)) {
10468             /* max_cfg in percents of linkspeed */
10469             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10470         } else { /* SD modes */
10471             /* max_cfg is absolute in 100Mb units */
10472             vn_max_rate = (max_cfg * 100);
10473         }
10474     }
10475
10476     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10477
10478     input->vnic_max_rate[vn] = vn_max_rate;
10479 }
10480
10481 static void
10482 bxe_cmng_fns_init(struct bxe_softc *sc,
10483                   uint8_t          read_cfg,
10484                   uint8_t          cmng_type)
10485 {
10486     struct cmng_init_input input;
10487     int vn;
10488
10489     memset(&input, 0, sizeof(struct cmng_init_input));
10490
10491     input.port_rate = sc->link_vars.line_speed;
10492
10493     if (cmng_type == CMNG_FNS_MINMAX) {
10494         /* read mf conf from shmem */
10495         if (read_cfg) {
10496             bxe_read_mf_cfg(sc);
10497         }
10498
10499         /* get VN min rate and enable fairness if not 0 */
10500         bxe_calc_vn_min(sc, &input);
10501
10502         /* get VN max rate */
10503         if (sc->port.pmf) {
10504             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10505                 bxe_calc_vn_max(sc, vn, &input);
10506             }
10507         }
10508
10509         /* always enable rate shaping and fairness */
10510         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10511
10512         ecore_init_cmng(&input, &sc->cmng);
10513         return;
10514     }
10515
10516     /* rate shaping and fairness are disabled */
10517     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10518 }
10519
10520 static int
10521 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10522 {
10523     if (CHIP_REV_IS_SLOW(sc)) {
10524         return (CMNG_FNS_NONE);
10525     }
10526
10527     if (IS_MF(sc)) {
10528         return (CMNG_FNS_MINMAX);
10529     }
10530
10531     return (CMNG_FNS_NONE);
10532 }
10533
10534 static void
10535 storm_memset_cmng(struct bxe_softc *sc,
10536                   struct cmng_init *cmng,
10537                   uint8_t          port)
10538 {
10539     int vn;
10540     int func;
10541     uint32_t addr;
10542     size_t size;
10543
10544     addr = (BAR_XSTRORM_INTMEM +
10545             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10546     size = sizeof(struct cmng_struct_per_port);
10547     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10548
10549     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10550         func = func_by_vn(sc, vn);
10551
10552         addr = (BAR_XSTRORM_INTMEM +
10553                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10554         size = sizeof(struct rate_shaping_vars_per_vn);
10555         ecore_storm_memset_struct(sc, addr, size,
10556                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10557
10558         addr = (BAR_XSTRORM_INTMEM +
10559                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10560         size = sizeof(struct fairness_vars_per_vn);
10561         ecore_storm_memset_struct(sc, addr, size,
10562                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10563     }
10564 }
10565
10566 static void
10567 bxe_pf_init(struct bxe_softc *sc)
10568 {
10569     struct bxe_func_init_params func_init = { 0 };
10570     struct event_ring_data eq_data = { { 0 } };
10571     uint16_t flags;
10572
10573     if (!CHIP_IS_E1x(sc)) {
10574         /* reset IGU PF statistics: MSIX + ATTN */
10575         /* PF */
10576         REG_WR(sc,
10577                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10578                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10579                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10580                0);
10581         /* ATTN */
10582         REG_WR(sc,
10583                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10584                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10585                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10586                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10587                0);
10588     }
10589
10590     /* function setup flags */
10591     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10592
10593     /*
10594      * This flag is relevant for E1x only.
10595      * E2 doesn't have a TPA configuration in a function level.
10596      */
10597     flags |= (if_getcapenable(sc->ifp) & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10598
10599     func_init.func_flgs = flags;
10600     func_init.pf_id     = SC_FUNC(sc);
10601     func_init.func_id   = SC_FUNC(sc);
10602     func_init.spq_map   = sc->spq_dma.paddr;
10603     func_init.spq_prod  = sc->spq_prod_idx;
10604
10605     bxe_func_init(sc, &func_init);
10606
10607     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10608
10609     /*
10610      * Congestion management values depend on the link rate.
10611      * There is no active link so initial link rate is set to 10Gbps.
10612      * When the link comes up the congestion management values are
10613      * re-calculated according to the actual link rate.
10614      */
10615     sc->link_vars.line_speed = SPEED_10000;
10616     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10617
10618     /* Only the PMF sets the HW */
10619     if (sc->port.pmf) {
10620         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10621     }
10622
10623     /* init Event Queue - PCI bus guarantees correct endainity */
10624     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10625     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10626     eq_data.producer     = sc->eq_prod;
10627     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10628     eq_data.sb_id        = DEF_SB_ID;
10629     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10630 }
10631
10632 static void
10633 bxe_hc_int_enable(struct bxe_softc *sc)
10634 {
10635     int port = SC_PORT(sc);
10636     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10637     uint32_t val = REG_RD(sc, addr);
10638     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10639     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10640                            (sc->intr_count == 1)) ? TRUE : FALSE;
10641     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10642
10643     if (msix) {
10644         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10645                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10646         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10647                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10648         if (single_msix) {
10649             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10650         }
10651     } else if (msi) {
10652         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10653         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10654                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10655                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10656     } else {
10657         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10658                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10659                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10660                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10661
10662         if (!CHIP_IS_E1(sc)) {
10663             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10664                   val, port, addr);
10665
10666             REG_WR(sc, addr, val);
10667
10668             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10669         }
10670     }
10671
10672     if (CHIP_IS_E1(sc)) {
10673         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10674     }
10675
10676     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10677           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10678
10679     REG_WR(sc, addr, val);
10680
10681     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10682     mb();
10683
10684     if (!CHIP_IS_E1(sc)) {
10685         /* init leading/trailing edge */
10686         if (IS_MF(sc)) {
10687             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10688             if (sc->port.pmf) {
10689                 /* enable nig and gpio3 attention */
10690                 val |= 0x1100;
10691             }
10692         } else {
10693             val = 0xffff;
10694         }
10695
10696         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10697         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10698     }
10699
10700     /* make sure that interrupts are indeed enabled from here on */
10701     mb();
10702 }
10703
10704 static void
10705 bxe_igu_int_enable(struct bxe_softc *sc)
10706 {
10707     uint32_t val;
10708     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10709     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10710                            (sc->intr_count == 1)) ? TRUE : FALSE;
10711     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10712
10713     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10714
10715     if (msix) {
10716         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10717                  IGU_PF_CONF_SINGLE_ISR_EN);
10718         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10719                 IGU_PF_CONF_ATTN_BIT_EN);
10720         if (single_msix) {
10721             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10722         }
10723     } else if (msi) {
10724         val &= ~IGU_PF_CONF_INT_LINE_EN;
10725         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10726                 IGU_PF_CONF_ATTN_BIT_EN |
10727                 IGU_PF_CONF_SINGLE_ISR_EN);
10728     } else {
10729         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10730         val |= (IGU_PF_CONF_INT_LINE_EN |
10731                 IGU_PF_CONF_ATTN_BIT_EN |
10732                 IGU_PF_CONF_SINGLE_ISR_EN);
10733     }
10734
10735     /* clean previous status - need to configure igu prior to ack*/
10736     if ((!msix) || single_msix) {
10737         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10738         bxe_ack_int(sc);
10739     }
10740
10741     val |= IGU_PF_CONF_FUNC_EN;
10742
10743     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10744           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10745
10746     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10747
10748     mb();
10749
10750     /* init leading/trailing edge */
10751     if (IS_MF(sc)) {
10752         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10753         if (sc->port.pmf) {
10754             /* enable nig and gpio3 attention */
10755             val |= 0x1100;
10756         }
10757     } else {
10758         val = 0xffff;
10759     }
10760
10761     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10762     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10763
10764     /* make sure that interrupts are indeed enabled from here on */
10765     mb();
10766 }
10767
10768 static void
10769 bxe_int_enable(struct bxe_softc *sc)
10770 {
10771     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10772         bxe_hc_int_enable(sc);
10773     } else {
10774         bxe_igu_int_enable(sc);
10775     }
10776 }
10777
10778 static void
10779 bxe_hc_int_disable(struct bxe_softc *sc)
10780 {
10781     int port = SC_PORT(sc);
10782     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10783     uint32_t val = REG_RD(sc, addr);
10784
10785     /*
10786      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10787      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10788      * block
10789      */
10790     if (CHIP_IS_E1(sc)) {
10791         /*
10792          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10793          * to prevent from HC sending interrupts after we exit the function
10794          */
10795         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10796
10797         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10798                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10799                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10800     } else {
10801         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10802                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10803                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10804                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10805     }
10806
10807     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10808
10809     /* flush all outstanding writes */
10810     mb();
10811
10812     REG_WR(sc, addr, val);
10813     if (REG_RD(sc, addr) != val) {
10814         BLOGE(sc, "proper val not read from HC IGU!\n");
10815     }
10816 }
10817
10818 static void
10819 bxe_igu_int_disable(struct bxe_softc *sc)
10820 {
10821     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10822
10823     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10824              IGU_PF_CONF_INT_LINE_EN |
10825              IGU_PF_CONF_ATTN_BIT_EN);
10826
10827     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10828
10829     /* flush all outstanding writes */
10830     mb();
10831
10832     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10833     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10834         BLOGE(sc, "proper val not read from IGU!\n");
10835     }
10836 }
10837
10838 static void
10839 bxe_int_disable(struct bxe_softc *sc)
10840 {
10841     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10842         bxe_hc_int_disable(sc);
10843     } else {
10844         bxe_igu_int_disable(sc);
10845     }
10846 }
10847
10848 static void
10849 bxe_nic_init(struct bxe_softc *sc,
10850              int              load_code)
10851 {
10852     int i;
10853
10854     for (i = 0; i < sc->num_queues; i++) {
10855         bxe_init_eth_fp(sc, i);
10856     }
10857
10858     rmb(); /* ensure status block indices were read */
10859
10860     bxe_init_rx_rings(sc);
10861     bxe_init_tx_rings(sc);
10862
10863     if (IS_VF(sc)) {
10864         return;
10865     }
10866
10867     /* initialize MOD_ABS interrupts */
10868     elink_init_mod_abs_int(sc, &sc->link_vars,
10869                            sc->devinfo.chip_id,
10870                            sc->devinfo.shmem_base,
10871                            sc->devinfo.shmem2_base,
10872                            SC_PORT(sc));
10873
10874     bxe_init_def_sb(sc);
10875     bxe_update_dsb_idx(sc);
10876     bxe_init_sp_ring(sc);
10877     bxe_init_eq_ring(sc);
10878     bxe_init_internal(sc, load_code);
10879     bxe_pf_init(sc);
10880     bxe_stats_init(sc);
10881
10882     /* flush all before enabling interrupts */
10883     mb();
10884
10885     bxe_int_enable(sc);
10886
10887     /* check for SPIO5 */
10888     bxe_attn_int_deasserted0(sc,
10889                              REG_RD(sc,
10890                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10891                                      SC_PORT(sc)*4)) &
10892                              AEU_INPUTS_ATTN_BITS_SPIO5);
10893 }
10894
10895 static inline void
10896 bxe_init_objs(struct bxe_softc *sc)
10897 {
10898     /* mcast rules must be added to tx if tx switching is enabled */
10899     ecore_obj_type o_type =
10900         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10901                                          ECORE_OBJ_TYPE_RX;
10902
10903     /* RX_MODE controlling object */
10904     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10905
10906     /* multicast configuration controlling object */
10907     ecore_init_mcast_obj(sc,
10908                          &sc->mcast_obj,
10909                          sc->fp[0].cl_id,
10910                          sc->fp[0].index,
10911                          SC_FUNC(sc),
10912                          SC_FUNC(sc),
10913                          BXE_SP(sc, mcast_rdata),
10914                          BXE_SP_MAPPING(sc, mcast_rdata),
10915                          ECORE_FILTER_MCAST_PENDING,
10916                          &sc->sp_state,
10917                          o_type);
10918
10919     /* Setup CAM credit pools */
10920     ecore_init_mac_credit_pool(sc,
10921                                &sc->macs_pool,
10922                                SC_FUNC(sc),
10923                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10924                                                  VNICS_PER_PATH(sc));
10925
10926     ecore_init_vlan_credit_pool(sc,
10927                                 &sc->vlans_pool,
10928                                 SC_ABS_FUNC(sc) >> 1,
10929                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10930                                                   VNICS_PER_PATH(sc));
10931
10932     /* RSS configuration object */
10933     ecore_init_rss_config_obj(sc,
10934                               &sc->rss_conf_obj,
10935                               sc->fp[0].cl_id,
10936                               sc->fp[0].index,
10937                               SC_FUNC(sc),
10938                               SC_FUNC(sc),
10939                               BXE_SP(sc, rss_rdata),
10940                               BXE_SP_MAPPING(sc, rss_rdata),
10941                               ECORE_FILTER_RSS_CONF_PENDING,
10942                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10943 }
10944
10945 /*
10946  * Initialize the function. This must be called before sending CLIENT_SETUP
10947  * for the first client.
10948  */
10949 static inline int
10950 bxe_func_start(struct bxe_softc *sc)
10951 {
10952     struct ecore_func_state_params func_params = { NULL };
10953     struct ecore_func_start_params *start_params = &func_params.params.start;
10954
10955     /* Prepare parameters for function state transitions */
10956     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10957
10958     func_params.f_obj = &sc->func_obj;
10959     func_params.cmd = ECORE_F_CMD_START;
10960
10961     /* Function parameters */
10962     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10963     start_params->sd_vlan_tag = OVLAN(sc);
10964
10965     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10966         start_params->network_cos_mode = STATIC_COS;
10967     } else { /* CHIP_IS_E1X */
10968         start_params->network_cos_mode = FW_WRR;
10969     }
10970
10971     start_params->gre_tunnel_mode = 0;
10972     start_params->gre_tunnel_rss  = 0;
10973
10974     return (ecore_func_state_change(sc, &func_params));
10975 }
10976
10977 static int
10978 bxe_set_power_state(struct bxe_softc *sc,
10979                     uint8_t          state)
10980 {
10981     uint16_t pmcsr;
10982
10983     /* If there is no power capability, silently succeed */
10984     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10985         BLOGW(sc, "No power capability\n");
10986         return (0);
10987     }
10988
10989     pmcsr = pci_read_config(sc->dev,
10990                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10991                             2);
10992
10993     switch (state) {
10994     case PCI_PM_D0:
10995         pci_write_config(sc->dev,
10996                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10997                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10998
10999         if (pmcsr & PCIM_PSTAT_DMASK) {
11000             /* delay required during transition out of D3hot */
11001             DELAY(20000);
11002         }
11003
11004         break;
11005
11006     case PCI_PM_D3hot:
11007         /* XXX if there are other clients above don't shut down the power */
11008
11009         /* don't shut down the power for emulation and FPGA */
11010         if (CHIP_REV_IS_SLOW(sc)) {
11011             return (0);
11012         }
11013
11014         pmcsr &= ~PCIM_PSTAT_DMASK;
11015         pmcsr |= PCIM_PSTAT_D3;
11016
11017         if (sc->wol) {
11018             pmcsr |= PCIM_PSTAT_PMEENABLE;
11019         }
11020
11021         pci_write_config(sc->dev,
11022                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
11023                          pmcsr, 4);
11024
11025         /*
11026          * No more memory access after this point until device is brought back
11027          * to D0 state.
11028          */
11029         break;
11030
11031     default:
11032         BLOGE(sc, "Can't support PCI power state = %d\n", state);
11033         return (-1);
11034     }
11035
11036     return (0);
11037 }
11038
11039
11040 /* return true if succeeded to acquire the lock */
11041 static uint8_t
11042 bxe_trylock_hw_lock(struct bxe_softc *sc,
11043                     uint32_t         resource)
11044 {
11045     uint32_t lock_status;
11046     uint32_t resource_bit = (1 << resource);
11047     int func = SC_FUNC(sc);
11048     uint32_t hw_lock_control_reg;
11049
11050     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
11051
11052     /* Validating that the resource is within range */
11053     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
11054         BLOGD(sc, DBG_LOAD,
11055               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
11056               resource, HW_LOCK_MAX_RESOURCE_VALUE);
11057         return (FALSE);
11058     }
11059
11060     if (func <= 5) {
11061         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
11062     } else {
11063         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
11064     }
11065
11066     /* try to acquire the lock */
11067     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
11068     lock_status = REG_RD(sc, hw_lock_control_reg);
11069     if (lock_status & resource_bit) {
11070         return (TRUE);
11071     }
11072
11073     BLOGE(sc, "Failed to get a resource lock 0x%x\n", resource);
11074
11075     return (FALSE);
11076 }
11077
11078 /*
11079  * Get the recovery leader resource id according to the engine this function
11080  * belongs to. Currently only only 2 engines is supported.
11081  */
11082 static int
11083 bxe_get_leader_lock_resource(struct bxe_softc *sc)
11084 {
11085     if (SC_PATH(sc)) {
11086         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
11087     } else {
11088         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
11089     }
11090 }
11091
11092 /* try to acquire a leader lock for current engine */
11093 static uint8_t
11094 bxe_trylock_leader_lock(struct bxe_softc *sc)
11095 {
11096     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
11097 }
11098
11099 static int
11100 bxe_release_leader_lock(struct bxe_softc *sc)
11101 {
11102     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
11103 }
11104
11105 /* close gates #2, #3 and #4 */
11106 static void
11107 bxe_set_234_gates(struct bxe_softc *sc,
11108                   uint8_t          close)
11109 {
11110     uint32_t val;
11111
11112     /* gates #2 and #4a are closed/opened for "not E1" only */
11113     if (!CHIP_IS_E1(sc)) {
11114         /* #4 */
11115         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
11116         /* #2 */
11117         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
11118     }
11119
11120     /* #3 */
11121     if (CHIP_IS_E1x(sc)) {
11122         /* prevent interrupts from HC on both ports */
11123         val = REG_RD(sc, HC_REG_CONFIG_1);
11124         REG_WR(sc, HC_REG_CONFIG_1,
11125                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
11126                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
11127
11128         val = REG_RD(sc, HC_REG_CONFIG_0);
11129         REG_WR(sc, HC_REG_CONFIG_0,
11130                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
11131                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
11132     } else {
11133         /* Prevent incomming interrupts in IGU */
11134         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
11135
11136         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
11137                (!close) ?
11138                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
11139                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
11140     }
11141
11142     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
11143           close ? "closing" : "opening");
11144
11145     wmb();
11146 }
11147
11148 /* poll for pending writes bit, it should get cleared in no more than 1s */
11149 static int
11150 bxe_er_poll_igu_vq(struct bxe_softc *sc)
11151 {
11152     uint32_t cnt = 1000;
11153     uint32_t pend_bits = 0;
11154
11155     do {
11156         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
11157
11158         if (pend_bits == 0) {
11159             break;
11160         }
11161
11162         DELAY(1000);
11163     } while (--cnt > 0);
11164
11165     if (cnt == 0) {
11166         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
11167         return (-1);
11168     }
11169
11170     return (0);
11171 }
11172
11173 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
11174
11175 static void
11176 bxe_clp_reset_prep(struct bxe_softc *sc,
11177                    uint32_t         *magic_val)
11178 {
11179     /* Do some magic... */
11180     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
11181     *magic_val = val & SHARED_MF_CLP_MAGIC;
11182     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
11183 }
11184
11185 /* restore the value of the 'magic' bit */
11186 static void
11187 bxe_clp_reset_done(struct bxe_softc *sc,
11188                    uint32_t         magic_val)
11189 {
11190     /* Restore the 'magic' bit value... */
11191     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
11192     MFCFG_WR(sc, shared_mf_config.clp_mb,
11193               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
11194 }
11195
11196 /* prepare for MCP reset, takes care of CLP configurations */
11197 static void
11198 bxe_reset_mcp_prep(struct bxe_softc *sc,
11199                    uint32_t         *magic_val)
11200 {
11201     uint32_t shmem;
11202     uint32_t validity_offset;
11203
11204     /* set `magic' bit in order to save MF config */
11205     if (!CHIP_IS_E1(sc)) {
11206         bxe_clp_reset_prep(sc, magic_val);
11207     }
11208
11209     /* get shmem offset */
11210     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
11211     validity_offset =
11212         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
11213
11214     /* Clear validity map flags */
11215     if (shmem > 0) {
11216         REG_WR(sc, shmem + validity_offset, 0);
11217     }
11218 }
11219
11220 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
11221 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
11222
11223 static void
11224 bxe_mcp_wait_one(struct bxe_softc *sc)
11225 {
11226     /* special handling for emulation and FPGA (10 times longer) */
11227     if (CHIP_REV_IS_SLOW(sc)) {
11228         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
11229     } else {
11230         DELAY((MCP_ONE_TIMEOUT) * 1000);
11231     }
11232 }
11233
11234 /* initialize shmem_base and waits for validity signature to appear */
11235 static int
11236 bxe_init_shmem(struct bxe_softc *sc)
11237 {
11238     int cnt = 0;
11239     uint32_t val = 0;
11240
11241     do {
11242         sc->devinfo.shmem_base     =
11243         sc->link_params.shmem_base =
11244             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
11245
11246         if (sc->devinfo.shmem_base) {
11247             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
11248             if (val & SHR_MEM_VALIDITY_MB)
11249                 return (0);
11250         }
11251
11252         bxe_mcp_wait_one(sc);
11253
11254     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
11255
11256     BLOGE(sc, "BAD MCP validity signature\n");
11257
11258     return (-1);
11259 }
11260
11261 static int
11262 bxe_reset_mcp_comp(struct bxe_softc *sc,
11263                    uint32_t         magic_val)
11264 {
11265     int rc = bxe_init_shmem(sc);
11266
11267     /* Restore the `magic' bit value */
11268     if (!CHIP_IS_E1(sc)) {
11269         bxe_clp_reset_done(sc, magic_val);
11270     }
11271
11272     return (rc);
11273 }
11274
11275 static void
11276 bxe_pxp_prep(struct bxe_softc *sc)
11277 {
11278     if (!CHIP_IS_E1(sc)) {
11279         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
11280         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
11281         wmb();
11282     }
11283 }
11284
11285 /*
11286  * Reset the whole chip except for:
11287  *      - PCIE core
11288  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
11289  *      - IGU
11290  *      - MISC (including AEU)
11291  *      - GRC
11292  *      - RBCN, RBCP
11293  */
11294 static void
11295 bxe_process_kill_chip_reset(struct bxe_softc *sc,
11296                             uint8_t          global)
11297 {
11298     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
11299     uint32_t global_bits2, stay_reset2;
11300
11301     /*
11302      * Bits that have to be set in reset_mask2 if we want to reset 'global'
11303      * (per chip) blocks.
11304      */
11305     global_bits2 =
11306         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
11307         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
11308
11309     /*
11310      * Don't reset the following blocks.
11311      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
11312      *            reset, as in 4 port device they might still be owned
11313      *            by the MCP (there is only one leader per path).
11314      */
11315     not_reset_mask1 =
11316         MISC_REGISTERS_RESET_REG_1_RST_HC |
11317         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
11318         MISC_REGISTERS_RESET_REG_1_RST_PXP;
11319
11320     not_reset_mask2 =
11321         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
11322         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
11323         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
11324         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
11325         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
11326         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
11327         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
11328         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
11329         MISC_REGISTERS_RESET_REG_2_RST_ATC |
11330         MISC_REGISTERS_RESET_REG_2_PGLC |
11331         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
11332         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
11333         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
11334         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
11335         MISC_REGISTERS_RESET_REG_2_UMAC0 |
11336         MISC_REGISTERS_RESET_REG_2_UMAC1;
11337
11338     /*
11339      * Keep the following blocks in reset:
11340      *  - all xxMACs are handled by the elink code.
11341      */
11342     stay_reset2 =
11343         MISC_REGISTERS_RESET_REG_2_XMAC |
11344         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
11345
11346     /* Full reset masks according to the chip */
11347     reset_mask1 = 0xffffffff;
11348
11349     if (CHIP_IS_E1(sc))
11350         reset_mask2 = 0xffff;
11351     else if (CHIP_IS_E1H(sc))
11352         reset_mask2 = 0x1ffff;
11353     else if (CHIP_IS_E2(sc))
11354         reset_mask2 = 0xfffff;
11355     else /* CHIP_IS_E3 */
11356         reset_mask2 = 0x3ffffff;
11357
11358     /* Don't reset global blocks unless we need to */
11359     if (!global)
11360         reset_mask2 &= ~global_bits2;
11361
11362     /*
11363      * In case of attention in the QM, we need to reset PXP
11364      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
11365      * because otherwise QM reset would release 'close the gates' shortly
11366      * before resetting the PXP, then the PSWRQ would send a write
11367      * request to PGLUE. Then when PXP is reset, PGLUE would try to
11368      * read the payload data from PSWWR, but PSWWR would not
11369      * respond. The write queue in PGLUE would stuck, dmae commands
11370      * would not return. Therefore it's important to reset the second
11371      * reset register (containing the
11372      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
11373      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
11374      * bit).
11375      */
11376     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
11377            reset_mask2 & (~not_reset_mask2));
11378
11379     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
11380            reset_mask1 & (~not_reset_mask1));
11381
11382     mb();
11383     wmb();
11384
11385     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
11386            reset_mask2 & (~stay_reset2));
11387
11388     mb();
11389     wmb();
11390
11391     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
11392     wmb();
11393 }
11394
11395 static int
11396 bxe_process_kill(struct bxe_softc *sc,
11397                  uint8_t          global)
11398 {
11399     int cnt = 1000;
11400     uint32_t val = 0;
11401     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
11402     uint32_t tags_63_32 = 0;
11403
11404     /* Empty the Tetris buffer, wait for 1s */
11405     do {
11406         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
11407         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
11408         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
11409         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
11410         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
11411         if (CHIP_IS_E3(sc)) {
11412             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
11413         }
11414
11415         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11416             ((port_is_idle_0 & 0x1) == 0x1) &&
11417             ((port_is_idle_1 & 0x1) == 0x1) &&
11418             (pgl_exp_rom2 == 0xffffffff) &&
11419             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11420             break;
11421         DELAY(1000);
11422     } while (cnt-- > 0);
11423
11424     if (cnt <= 0) {
11425         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11426                   "are still outstanding read requests after 1s! "
11427                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11428                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11429               sr_cnt, blk_cnt, port_is_idle_0,
11430               port_is_idle_1, pgl_exp_rom2);
11431         return (-1);
11432     }
11433
11434     mb();
11435
11436     /* Close gates #2, #3 and #4 */
11437     bxe_set_234_gates(sc, TRUE);
11438
11439     /* Poll for IGU VQs for 57712 and newer chips */
11440     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11441         return (-1);
11442     }
11443
11444     /* XXX indicate that "process kill" is in progress to MCP */
11445
11446     /* clear "unprepared" bit */
11447     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11448     mb();
11449
11450     /* Make sure all is written to the chip before the reset */
11451     wmb();
11452
11453     /*
11454      * Wait for 1ms to empty GLUE and PCI-E core queues,
11455      * PSWHST, GRC and PSWRD Tetris buffer.
11456      */
11457     DELAY(1000);
11458
11459     /* Prepare to chip reset: */
11460     /* MCP */
11461     if (global) {
11462         bxe_reset_mcp_prep(sc, &val);
11463     }
11464
11465     /* PXP */
11466     bxe_pxp_prep(sc);
11467     mb();
11468
11469     /* reset the chip */
11470     bxe_process_kill_chip_reset(sc, global);
11471     mb();
11472
11473     /* clear errors in PGB */
11474     if (!CHIP_IS_E1(sc))
11475         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11476
11477     /* Recover after reset: */
11478     /* MCP */
11479     if (global && bxe_reset_mcp_comp(sc, val)) {
11480         return (-1);
11481     }
11482
11483     /* XXX add resetting the NO_MCP mode DB here */
11484
11485     /* Open the gates #2, #3 and #4 */
11486     bxe_set_234_gates(sc, FALSE);
11487
11488     /* XXX
11489      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11490      * re-enable attentions
11491      */
11492
11493     return (0);
11494 }
11495
11496 static int
11497 bxe_leader_reset(struct bxe_softc *sc)
11498 {
11499     int rc = 0;
11500     uint8_t global = bxe_reset_is_global(sc);
11501     uint32_t load_code;
11502
11503     /*
11504      * If not going to reset MCP, load "fake" driver to reset HW while
11505      * driver is owner of the HW.
11506      */
11507     if (!global && !BXE_NOMCP(sc)) {
11508         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11509                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11510         if (!load_code) {
11511             BLOGE(sc, "MCP response failure, aborting\n");
11512             rc = -1;
11513             goto exit_leader_reset;
11514         }
11515
11516         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11517             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11518             BLOGE(sc, "MCP unexpected response, aborting\n");
11519             rc = -1;
11520             goto exit_leader_reset2;
11521         }
11522
11523         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11524         if (!load_code) {
11525             BLOGE(sc, "MCP response failure, aborting\n");
11526             rc = -1;
11527             goto exit_leader_reset2;
11528         }
11529     }
11530
11531     /* try to recover after the failure */
11532     if (bxe_process_kill(sc, global)) {
11533         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11534         rc = -1;
11535         goto exit_leader_reset2;
11536     }
11537
11538     /*
11539      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11540      * state.
11541      */
11542     bxe_set_reset_done(sc);
11543     if (global) {
11544         bxe_clear_reset_global(sc);
11545     }
11546
11547 exit_leader_reset2:
11548
11549     /* unload "fake driver" if it was loaded */
11550     if (!global && !BXE_NOMCP(sc)) {
11551         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11552         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11553     }
11554
11555 exit_leader_reset:
11556
11557     sc->is_leader = 0;
11558     bxe_release_leader_lock(sc);
11559
11560     mb();
11561     return (rc);
11562 }
11563
11564 /*
11565  * prepare INIT transition, parameters configured:
11566  *   - HC configuration
11567  *   - Queue's CDU context
11568  */
11569 static void
11570 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11571                    struct bxe_fastpath            *fp,
11572                    struct ecore_queue_init_params *init_params)
11573 {
11574     uint8_t cos;
11575     int cxt_index, cxt_offset;
11576
11577     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11578     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11579
11580     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11581     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11582
11583     /* HC rate */
11584     init_params->rx.hc_rate =
11585         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11586     init_params->tx.hc_rate =
11587         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11588
11589     /* FW SB ID */
11590     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11591
11592     /* CQ index among the SB indices */
11593     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11594     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11595
11596     /* set maximum number of COSs supported by this queue */
11597     init_params->max_cos = sc->max_cos;
11598
11599     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11600           fp->index, init_params->max_cos);
11601
11602     /* set the context pointers queue object */
11603     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11604         /* XXX change index/cid here if ever support multiple tx CoS */
11605         /* fp->txdata[cos]->cid */
11606         cxt_index = fp->index / ILT_PAGE_CIDS;
11607         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11608         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11609     }
11610 }
11611
11612 /* set flags that are common for the Tx-only and not normal connections */
11613 static unsigned long
11614 bxe_get_common_flags(struct bxe_softc    *sc,
11615                      struct bxe_fastpath *fp,
11616                      uint8_t             zero_stats)
11617 {
11618     unsigned long flags = 0;
11619
11620     /* PF driver will always initialize the Queue to an ACTIVE state */
11621     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11622
11623     /*
11624      * tx only connections collect statistics (on the same index as the
11625      * parent connection). The statistics are zeroed when the parent
11626      * connection is initialized.
11627      */
11628
11629     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11630     if (zero_stats) {
11631         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11632     }
11633
11634     /*
11635      * tx only connections can support tx-switching, though their
11636      * CoS-ness doesn't survive the loopback
11637      */
11638     if (sc->flags & BXE_TX_SWITCHING) {
11639         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11640     }
11641
11642     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11643
11644     return (flags);
11645 }
11646
11647 static unsigned long
11648 bxe_get_q_flags(struct bxe_softc    *sc,
11649                 struct bxe_fastpath *fp,
11650                 uint8_t             leading)
11651 {
11652     unsigned long flags = 0;
11653
11654     if (IS_MF_SD(sc)) {
11655         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11656     }
11657
11658     if (if_getcapenable(sc->ifp) & IFCAP_LRO) {
11659         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11660         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11661 #if 0
11662         if (fp->mode == TPA_MODE_GRO)
11663             __set_bit(ECORE_Q_FLG_TPA_GRO, &flags);
11664 #endif
11665     }
11666
11667     if (leading) {
11668         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11669         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11670     }
11671
11672     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11673
11674 #if 0
11675     /* configure silent vlan removal */
11676     if (IS_MF_AFEX(sc)) {
11677         bxe_set_bit(ECORE_Q_FLG_SILENT_VLAN_REM, &flags);
11678     }
11679 #endif
11680
11681     /* merge with common flags */
11682     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11683 }
11684
11685 static void
11686 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11687                       struct bxe_fastpath               *fp,
11688                       struct ecore_general_setup_params *gen_init,
11689                       uint8_t                           cos)
11690 {
11691     gen_init->stat_id = bxe_stats_id(fp);
11692     gen_init->spcl_id = fp->cl_id;
11693     gen_init->mtu = sc->mtu;
11694     gen_init->cos = cos;
11695 }
11696
11697 static void
11698 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11699                  struct bxe_fastpath           *fp,
11700                  struct rxq_pause_params       *pause,
11701                  struct ecore_rxq_setup_params *rxq_init)
11702 {
11703     uint8_t max_sge = 0;
11704     uint16_t sge_sz = 0;
11705     uint16_t tpa_agg_size = 0;
11706
11707     if (if_getcapenable(sc->ifp)  & IFCAP_LRO) {
11708         pause->sge_th_lo = SGE_TH_LO(sc);
11709         pause->sge_th_hi = SGE_TH_HI(sc);
11710
11711         /* validate SGE ring has enough to cross high threshold */
11712         if (sc->dropless_fc &&
11713             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11714             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11715             BLOGW(sc, "sge ring threshold limit\n");
11716         }
11717
11718         /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11719         tpa_agg_size = (2 * sc->mtu);
11720         if (tpa_agg_size < sc->max_aggregation_size) {
11721             tpa_agg_size = sc->max_aggregation_size;
11722         }
11723
11724         max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11725         max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11726                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11727         sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11728     }
11729
11730     /* pause - not for e1 */
11731     if (!CHIP_IS_E1(sc)) {
11732         pause->bd_th_lo = BD_TH_LO(sc);
11733         pause->bd_th_hi = BD_TH_HI(sc);
11734
11735         pause->rcq_th_lo = RCQ_TH_LO(sc);
11736         pause->rcq_th_hi = RCQ_TH_HI(sc);
11737
11738         /* validate rings have enough entries to cross high thresholds */
11739         if (sc->dropless_fc &&
11740             pause->bd_th_hi + FW_PREFETCH_CNT >
11741             sc->rx_ring_size) {
11742             BLOGW(sc, "rx bd ring threshold limit\n");
11743         }
11744
11745         if (sc->dropless_fc &&
11746             pause->rcq_th_hi + FW_PREFETCH_CNT >
11747             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11748             BLOGW(sc, "rcq ring threshold limit\n");
11749         }
11750
11751         pause->pri_map = 1;
11752     }
11753
11754     /* rxq setup */
11755     rxq_init->dscr_map   = fp->rx_dma.paddr;
11756     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11757     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11758     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11759
11760     /*
11761      * This should be a maximum number of data bytes that may be
11762      * placed on the BD (not including paddings).
11763      */
11764     rxq_init->buf_sz = (fp->rx_buf_size -
11765                         IP_HEADER_ALIGNMENT_PADDING);
11766
11767     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11768     rxq_init->tpa_agg_sz      = tpa_agg_size;
11769     rxq_init->sge_buf_sz      = sge_sz;
11770     rxq_init->max_sges_pkt    = max_sge;
11771     rxq_init->rss_engine_id   = SC_FUNC(sc);
11772     rxq_init->mcast_engine_id = SC_FUNC(sc);
11773
11774     /*
11775      * Maximum number or simultaneous TPA aggregation for this Queue.
11776      * For PF Clients it should be the maximum available number.
11777      * VF driver(s) may want to define it to a smaller value.
11778      */
11779     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11780
11781     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11782     rxq_init->fw_sb_id = fp->fw_sb_id;
11783
11784     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11785
11786     /*
11787      * configure silent vlan removal
11788      * if multi function mode is afex, then mask default vlan
11789      */
11790     if (IS_MF_AFEX(sc)) {
11791         rxq_init->silent_removal_value =
11792             sc->devinfo.mf_info.afex_def_vlan_tag;
11793         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11794     }
11795 }
11796
11797 static void
11798 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11799                  struct bxe_fastpath           *fp,
11800                  struct ecore_txq_setup_params *txq_init,
11801                  uint8_t                       cos)
11802 {
11803     /*
11804      * XXX If multiple CoS is ever supported then each fastpath structure
11805      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11806      * fp->txdata[cos]->tx_dma.paddr;
11807      */
11808     txq_init->dscr_map     = fp->tx_dma.paddr;
11809     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11810     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11811     txq_init->fw_sb_id     = fp->fw_sb_id;
11812
11813     /*
11814      * set the TSS leading client id for TX classfication to the
11815      * leading RSS client id
11816      */
11817     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11818 }
11819
11820 /*
11821  * This function performs 2 steps in a queue state machine:
11822  *   1) RESET->INIT
11823  *   2) INIT->SETUP
11824  */
11825 static int
11826 bxe_setup_queue(struct bxe_softc    *sc,
11827                 struct bxe_fastpath *fp,
11828                 uint8_t             leading)
11829 {
11830     struct ecore_queue_state_params q_params = { NULL };
11831     struct ecore_queue_setup_params *setup_params =
11832                         &q_params.params.setup;
11833 #if 0
11834     struct ecore_queue_setup_tx_only_params *tx_only_params =
11835                         &q_params.params.tx_only;
11836     uint8_t tx_index;
11837 #endif
11838     int rc;
11839
11840     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11841
11842     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11843
11844     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11845
11846     /* we want to wait for completion in this context */
11847     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11848
11849     /* prepare the INIT parameters */
11850     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11851
11852     /* Set the command */
11853     q_params.cmd = ECORE_Q_CMD_INIT;
11854
11855     /* Change the state to INIT */
11856     rc = ecore_queue_state_change(sc, &q_params);
11857     if (rc) {
11858         BLOGE(sc, "Queue(%d) INIT failed\n", fp->index);
11859         return (rc);
11860     }
11861
11862     BLOGD(sc, DBG_LOAD, "init complete\n");
11863
11864     /* now move the Queue to the SETUP state */
11865     memset(setup_params, 0, sizeof(*setup_params));
11866
11867     /* set Queue flags */
11868     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11869
11870     /* set general SETUP parameters */
11871     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11872                           FIRST_TX_COS_INDEX);
11873
11874     bxe_pf_rx_q_prep(sc, fp,
11875                      &setup_params->pause_params,
11876                      &setup_params->rxq_params);
11877
11878     bxe_pf_tx_q_prep(sc, fp,
11879                      &setup_params->txq_params,
11880                      FIRST_TX_COS_INDEX);
11881
11882     /* Set the command */
11883     q_params.cmd = ECORE_Q_CMD_SETUP;
11884
11885     /* change the state to SETUP */
11886     rc = ecore_queue_state_change(sc, &q_params);
11887     if (rc) {
11888         BLOGE(sc, "Queue(%d) SETUP failed\n", fp->index);
11889         return (rc);
11890     }
11891
11892 #if 0
11893     /* loop through the relevant tx-only indices */
11894     for (tx_index = FIRST_TX_ONLY_COS_INDEX;
11895          tx_index < sc->max_cos;
11896          tx_index++) {
11897         /* prepare and send tx-only ramrod*/
11898         rc = bxe_setup_tx_only(sc, fp, &q_params,
11899                                tx_only_params, tx_index, leading);
11900         if (rc) {
11901             BLOGE(sc, "Queue(%d.%d) TX_ONLY_SETUP failed\n",
11902                   fp->index, tx_index);
11903             return (rc);
11904         }
11905     }
11906 #endif
11907
11908     return (rc);
11909 }
11910
11911 static int
11912 bxe_setup_leading(struct bxe_softc *sc)
11913 {
11914     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11915 }
11916
11917 static int
11918 bxe_config_rss_pf(struct bxe_softc            *sc,
11919                   struct ecore_rss_config_obj *rss_obj,
11920                   uint8_t                     config_hash)
11921 {
11922     struct ecore_config_rss_params params = { NULL };
11923     int i;
11924
11925     /*
11926      * Although RSS is meaningless when there is a single HW queue we
11927      * still need it enabled in order to have HW Rx hash generated.
11928      */
11929
11930     params.rss_obj = rss_obj;
11931
11932     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11933
11934     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11935
11936     /* RSS configuration */
11937     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11938     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11939     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11940     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11941     if (rss_obj->udp_rss_v4) {
11942         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11943     }
11944     if (rss_obj->udp_rss_v6) {
11945         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11946     }
11947
11948     /* Hash bits */
11949     params.rss_result_mask = MULTI_MASK;
11950
11951     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11952
11953     if (config_hash) {
11954         /* RSS keys */
11955         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11956             params.rss_key[i] = arc4random();
11957         }
11958
11959         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11960     }
11961
11962     return (ecore_config_rss(sc, &params));
11963 }
11964
11965 static int
11966 bxe_config_rss_eth(struct bxe_softc *sc,
11967                    uint8_t          config_hash)
11968 {
11969     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11970 }
11971
11972 static int
11973 bxe_init_rss_pf(struct bxe_softc *sc)
11974 {
11975     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11976     int i;
11977
11978     /*
11979      * Prepare the initial contents of the indirection table if
11980      * RSS is enabled
11981      */
11982     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11983         sc->rss_conf_obj.ind_table[i] =
11984             (sc->fp->cl_id + (i % num_eth_queues));
11985     }
11986
11987     if (sc->udp_rss) {
11988         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11989     }
11990
11991     /*
11992      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11993      * per-port, so if explicit configuration is needed, do it only
11994      * for a PMF.
11995      *
11996      * For 57712 and newer it's a per-function configuration.
11997      */
11998     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11999 }
12000
12001 static int
12002 bxe_set_mac_one(struct bxe_softc          *sc,
12003                 uint8_t                   *mac,
12004                 struct ecore_vlan_mac_obj *obj,
12005                 uint8_t                   set,
12006                 int                       mac_type,
12007                 unsigned long             *ramrod_flags)
12008 {
12009     struct ecore_vlan_mac_ramrod_params ramrod_param;
12010     int rc;
12011
12012     memset(&ramrod_param, 0, sizeof(ramrod_param));
12013
12014     /* fill in general parameters */
12015     ramrod_param.vlan_mac_obj = obj;
12016     ramrod_param.ramrod_flags = *ramrod_flags;
12017
12018     /* fill a user request section if needed */
12019     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
12020         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
12021
12022         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
12023
12024         /* Set the command: ADD or DEL */
12025         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
12026                                             ECORE_VLAN_MAC_DEL;
12027     }
12028
12029     rc = ecore_config_vlan_mac(sc, &ramrod_param);
12030
12031     if (rc == ECORE_EXISTS) {
12032         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12033         /* do not treat adding same MAC as error */
12034         rc = 0;
12035     } else if (rc < 0) {
12036         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
12037     }
12038
12039     return (rc);
12040 }
12041
12042 static int
12043 bxe_set_eth_mac(struct bxe_softc *sc,
12044                 uint8_t          set)
12045 {
12046     unsigned long ramrod_flags = 0;
12047
12048     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
12049
12050     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
12051
12052     /* Eth MAC is set on RSS leading client (fp[0]) */
12053     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
12054                             &sc->sp_objs->mac_obj,
12055                             set, ECORE_ETH_MAC, &ramrod_flags));
12056 }
12057
12058 #if 0
12059 static void
12060 bxe_update_max_mf_config(struct bxe_softc *sc,
12061                          uint32_t         value)
12062 {
12063     /* load old values */
12064     uint32_t mf_cfg = sc->devinfo.mf_info.mf_config[SC_VN(sc)];
12065
12066     if (value != bxe_extract_max_cfg(sc, mf_cfg)) {
12067         /* leave all but MAX value */
12068         mf_cfg &= ~FUNC_MF_CFG_MAX_BW_MASK;
12069
12070         /* set new MAX value */
12071         mf_cfg |= ((value << FUNC_MF_CFG_MAX_BW_SHIFT) &
12072                    FUNC_MF_CFG_MAX_BW_MASK);
12073
12074         bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW, mf_cfg);
12075     }
12076 }
12077 #endif
12078
12079 static int
12080 bxe_get_cur_phy_idx(struct bxe_softc *sc)
12081 {
12082     uint32_t sel_phy_idx = 0;
12083
12084     if (sc->link_params.num_phys <= 1) {
12085         return (ELINK_INT_PHY);
12086     }
12087
12088     if (sc->link_vars.link_up) {
12089         sel_phy_idx = ELINK_EXT_PHY1;
12090         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
12091         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
12092             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
12093              ELINK_SUPPORTED_FIBRE))
12094             sel_phy_idx = ELINK_EXT_PHY2;
12095     } else {
12096         switch (elink_phy_selection(&sc->link_params)) {
12097         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
12098         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
12099         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
12100                sel_phy_idx = ELINK_EXT_PHY1;
12101                break;
12102         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
12103         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
12104                sel_phy_idx = ELINK_EXT_PHY2;
12105                break;
12106         }
12107     }
12108
12109     return (sel_phy_idx);
12110 }
12111
12112 static int
12113 bxe_get_link_cfg_idx(struct bxe_softc *sc)
12114 {
12115     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
12116
12117     /*
12118      * The selected activated PHY is always after swapping (in case PHY
12119      * swapping is enabled). So when swapping is enabled, we need to reverse
12120      * the configuration
12121      */
12122
12123     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
12124         if (sel_phy_idx == ELINK_EXT_PHY1)
12125             sel_phy_idx = ELINK_EXT_PHY2;
12126         else if (sel_phy_idx == ELINK_EXT_PHY2)
12127             sel_phy_idx = ELINK_EXT_PHY1;
12128     }
12129
12130     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
12131 }
12132
12133 static void
12134 bxe_set_requested_fc(struct bxe_softc *sc)
12135 {
12136     /*
12137      * Initialize link parameters structure variables
12138      * It is recommended to turn off RX FC for jumbo frames
12139      * for better performance
12140      */
12141     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
12142         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
12143     } else {
12144         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
12145     }
12146 }
12147
12148 static void
12149 bxe_calc_fc_adv(struct bxe_softc *sc)
12150 {
12151     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
12152     switch (sc->link_vars.ieee_fc &
12153             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
12154     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
12155     default:
12156         sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
12157                                            ADVERTISED_Pause);
12158         break;
12159
12160     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
12161         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
12162                                           ADVERTISED_Pause);
12163         break;
12164
12165     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
12166         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
12167         break;
12168     }
12169 }
12170
12171 static uint16_t
12172 bxe_get_mf_speed(struct bxe_softc *sc)
12173 {
12174     uint16_t line_speed = sc->link_vars.line_speed;
12175     if (IS_MF(sc)) {
12176         uint16_t maxCfg =
12177             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
12178
12179         /* calculate the current MAX line speed limit for the MF devices */
12180         if (IS_MF_SI(sc)) {
12181             line_speed = (line_speed * maxCfg) / 100;
12182         } else { /* SD mode */
12183             uint16_t vn_max_rate = maxCfg * 100;
12184
12185             if (vn_max_rate < line_speed) {
12186                 line_speed = vn_max_rate;
12187             }
12188         }
12189     }
12190
12191     return (line_speed);
12192 }
12193
12194 static void
12195 bxe_fill_report_data(struct bxe_softc            *sc,
12196                      struct bxe_link_report_data *data)
12197 {
12198     uint16_t line_speed = bxe_get_mf_speed(sc);
12199
12200     memset(data, 0, sizeof(*data));
12201
12202     /* fill the report data with the effective line speed */
12203     data->line_speed = line_speed;
12204
12205     /* Link is down */
12206     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
12207         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
12208     }
12209
12210     /* Full DUPLEX */
12211     if (sc->link_vars.duplex == DUPLEX_FULL) {
12212         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
12213     }
12214
12215     /* Rx Flow Control is ON */
12216     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
12217         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
12218     }
12219
12220     /* Tx Flow Control is ON */
12221     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
12222         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
12223     }
12224 }
12225
12226 /* report link status to OS, should be called under phy_lock */
12227 static void
12228 bxe_link_report_locked(struct bxe_softc *sc)
12229 {
12230     struct bxe_link_report_data cur_data;
12231
12232     /* reread mf_cfg */
12233     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
12234         bxe_read_mf_cfg(sc);
12235     }
12236
12237     /* Read the current link report info */
12238     bxe_fill_report_data(sc, &cur_data);
12239
12240     /* Don't report link down or exactly the same link status twice */
12241     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
12242         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
12243                       &sc->last_reported_link.link_report_flags) &&
12244          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
12245                       &cur_data.link_report_flags))) {
12246         return;
12247     }
12248
12249     sc->link_cnt++;
12250
12251     /* report new link params and remember the state for the next time */
12252     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
12253
12254     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
12255                      &cur_data.link_report_flags)) {
12256         if_link_state_change(sc->ifp, LINK_STATE_DOWN);
12257         BLOGI(sc, "NIC Link is Down\n");
12258     } else {
12259         const char *duplex;
12260         const char *flow;
12261
12262         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
12263                                    &cur_data.link_report_flags)) {
12264             duplex = "full";
12265         } else {
12266             duplex = "half";
12267         }
12268
12269         /*
12270          * Handle the FC at the end so that only these flags would be
12271          * possibly set. This way we may easily check if there is no FC
12272          * enabled.
12273          */
12274         if (cur_data.link_report_flags) {
12275             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
12276                              &cur_data.link_report_flags) &&
12277                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
12278                              &cur_data.link_report_flags)) {
12279                 flow = "ON - receive & transmit";
12280             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
12281                                     &cur_data.link_report_flags) &&
12282                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
12283                                      &cur_data.link_report_flags)) {
12284                 flow = "ON - receive";
12285             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
12286                                      &cur_data.link_report_flags) &&
12287                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
12288                                     &cur_data.link_report_flags)) {
12289                 flow = "ON - transmit";
12290             } else {
12291                 flow = "none"; /* possible? */
12292             }
12293         } else {
12294             flow = "none";
12295         }
12296
12297         if_link_state_change(sc->ifp, LINK_STATE_UP);
12298         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
12299               cur_data.line_speed, duplex, flow);
12300     }
12301 }
12302
12303 static void
12304 bxe_link_report(struct bxe_softc *sc)
12305 {
12306     BXE_PHY_LOCK(sc);
12307     bxe_link_report_locked(sc);
12308     BXE_PHY_UNLOCK(sc);
12309 }
12310
12311 static void
12312 bxe_link_status_update(struct bxe_softc *sc)
12313 {
12314     if (sc->state != BXE_STATE_OPEN) {
12315         return;
12316     }
12317
12318 #if 0
12319     /* read updated dcb configuration */
12320     if (IS_PF(sc))
12321         bxe_dcbx_pmf_update(sc);
12322 #endif
12323
12324     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
12325         elink_link_status_update(&sc->link_params, &sc->link_vars);
12326     } else {
12327         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
12328                                   ELINK_SUPPORTED_10baseT_Full |
12329                                   ELINK_SUPPORTED_100baseT_Half |
12330                                   ELINK_SUPPORTED_100baseT_Full |
12331                                   ELINK_SUPPORTED_1000baseT_Full |
12332                                   ELINK_SUPPORTED_2500baseX_Full |
12333                                   ELINK_SUPPORTED_10000baseT_Full |
12334                                   ELINK_SUPPORTED_TP |
12335                                   ELINK_SUPPORTED_FIBRE |
12336                                   ELINK_SUPPORTED_Autoneg |
12337                                   ELINK_SUPPORTED_Pause |
12338                                   ELINK_SUPPORTED_Asym_Pause);
12339         sc->port.advertising[0] = sc->port.supported[0];
12340
12341         sc->link_params.sc                = sc;
12342         sc->link_params.port              = SC_PORT(sc);
12343         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
12344         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
12345         sc->link_params.req_line_speed[0] = SPEED_10000;
12346         sc->link_params.speed_cap_mask[0] = 0x7f0000;
12347         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
12348
12349         if (CHIP_REV_IS_FPGA(sc)) {
12350             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
12351             sc->link_vars.line_speed  = ELINK_SPEED_1000;
12352             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
12353                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
12354         } else {
12355             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
12356             sc->link_vars.line_speed  = ELINK_SPEED_10000;
12357             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
12358                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
12359         }
12360
12361         sc->link_vars.link_up = 1;
12362
12363         sc->link_vars.duplex    = DUPLEX_FULL;
12364         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
12365
12366         if (IS_PF(sc)) {
12367             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
12368             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12369             bxe_link_report(sc);
12370         }
12371     }
12372
12373     if (IS_PF(sc)) {
12374         if (sc->link_vars.link_up) {
12375             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12376         } else {
12377             bxe_stats_handle(sc, STATS_EVENT_STOP);
12378         }
12379         bxe_link_report(sc);
12380     } else {
12381         bxe_link_report(sc);
12382         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12383     }
12384 }
12385
12386 static int
12387 bxe_initial_phy_init(struct bxe_softc *sc,
12388                      int              load_mode)
12389 {
12390     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
12391     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
12392     struct elink_params *lp = &sc->link_params;
12393
12394     bxe_set_requested_fc(sc);
12395
12396     if (CHIP_REV_IS_SLOW(sc)) {
12397         uint32_t bond = CHIP_BOND_ID(sc);
12398         uint32_t feat = 0;
12399
12400         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
12401             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
12402         } else if (bond & 0x4) {
12403             if (CHIP_IS_E3(sc)) {
12404                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
12405             } else {
12406                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
12407             }
12408         } else if (bond & 0x8) {
12409             if (CHIP_IS_E3(sc)) {
12410                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
12411             } else {
12412                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12413             }
12414         }
12415
12416         /* disable EMAC for E3 and above */
12417         if (bond & 0x2) {
12418             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12419         }
12420
12421         sc->link_params.feature_config_flags |= feat;
12422     }
12423
12424     BXE_PHY_LOCK(sc);
12425
12426     if (load_mode == LOAD_DIAG) {
12427         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
12428         /* Prefer doing PHY loopback at 10G speed, if possible */
12429         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
12430             if (lp->speed_cap_mask[cfg_idx] &
12431                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
12432                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
12433             } else {
12434                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
12435             }
12436         }
12437     }
12438
12439     if (load_mode == LOAD_LOOPBACK_EXT) {
12440         lp->loopback_mode = ELINK_LOOPBACK_EXT;
12441     }
12442
12443     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
12444
12445     BXE_PHY_UNLOCK(sc);
12446
12447     bxe_calc_fc_adv(sc);
12448
12449     if (sc->link_vars.link_up) {
12450         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12451         bxe_link_report(sc);
12452     }
12453
12454     if (!CHIP_REV_IS_SLOW(sc)) {
12455         bxe_periodic_start(sc);
12456     }
12457
12458     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
12459     return (rc);
12460 }
12461
12462 /* must be called under IF_ADDR_LOCK */
12463 static int
12464 bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
12465                          struct ecore_mcast_ramrod_params *p)
12466 {
12467     if_t ifp = sc->ifp;
12468     int mc_count = 0;
12469     int mcnt, i;
12470     struct ecore_mcast_list_elem *mc_mac;
12471     unsigned char *mta;
12472
12473     mc_count = if_multiaddr_count(ifp, -1);/* XXX they don't have a limit */
12474                                            /* should we enforce one? */
12475     ECORE_LIST_INIT(&p->mcast_list);
12476     p->mcast_list_len = 0;
12477
12478     if (!mc_count) {
12479         return (0);
12480     }
12481
12482     mta = malloc(sizeof(unsigned char) * ETHER_ADDR_LEN *
12483             mc_count, M_DEVBUF, M_NOWAIT);
12484
12485     if(mta == NULL) {
12486         BLOGE(sc, "Failed to allocate temp mcast list\n");
12487         return (-1);
12488     }
12489     
12490     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12491                     (M_NOWAIT | M_ZERO));
12492     if (!mc_mac) {
12493         free(mta, M_DEVBUF);
12494         BLOGE(sc, "Failed to allocate temp mcast list\n");
12495         return (-1);
12496     }
12497
12498     if_multiaddr_array(ifp, mta, &mcnt, mc_count); /* mta and mcnt not expected 
12499                                                       to be  different */
12500     for(i=0; i< mcnt; i++) {
12501
12502         bcopy((mta + (i * ETHER_ADDR_LEN)), mc_mac->mac, ETHER_ADDR_LEN);
12503         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &p->mcast_list);
12504
12505         BLOGD(sc, DBG_LOAD,
12506               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
12507               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12508               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
12509
12510         mc_mac++;
12511     }
12512
12513     p->mcast_list_len = mc_count;
12514     free(mta, M_DEVBUF);
12515
12516     return (0);
12517 }
12518
12519 static void
12520 bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12521 {
12522     struct ecore_mcast_list_elem *mc_mac =
12523         ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12524                                struct ecore_mcast_list_elem,
12525                                link);
12526
12527     if (mc_mac) {
12528         /* only a single free as all mc_macs are in the same heap array */
12529         free(mc_mac, M_DEVBUF);
12530     }
12531 }
12532
12533 static int
12534 bxe_set_mc_list(struct bxe_softc *sc)
12535 {
12536     struct ecore_mcast_ramrod_params rparam = { NULL };
12537     int rc = 0;
12538
12539     rparam.mcast_obj = &sc->mcast_obj;
12540
12541     BXE_MCAST_LOCK(sc);
12542
12543     /* first, clear all configured multicast MACs */
12544     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12545     if (rc < 0) {
12546         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12547         return (rc);
12548     }
12549
12550     /* configure a new MACs list */
12551     rc = bxe_init_mcast_macs_list(sc, &rparam);
12552     if (rc) {
12553         BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12554         BXE_MCAST_UNLOCK(sc);
12555         return (rc);
12556     }
12557
12558     /* Now add the new MACs */
12559     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12560     if (rc < 0) {
12561         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12562     }
12563
12564     bxe_free_mcast_macs_list(&rparam);
12565
12566     BXE_MCAST_UNLOCK(sc);
12567
12568     return (rc);
12569 }
12570
12571 static int
12572 bxe_set_uc_list(struct bxe_softc *sc)
12573 {
12574     if_t ifp = sc->ifp;
12575     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12576     struct ifaddr *ifa;
12577     unsigned long ramrod_flags = 0;
12578     int rc;
12579
12580 #if __FreeBSD_version < 800000
12581     IF_ADDR_LOCK(ifp);
12582 #else
12583     if_addr_rlock(ifp);
12584 #endif
12585
12586     /* first schedule a cleanup up of old configuration */
12587     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12588     if (rc < 0) {
12589         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12590 #if __FreeBSD_version < 800000
12591         IF_ADDR_UNLOCK(ifp);
12592 #else
12593         if_addr_runlock(ifp);
12594 #endif
12595         return (rc);
12596     }
12597
12598     ifa = if_getifaddr(ifp); /* XXX Is this structure */
12599     while (ifa) {
12600         if (ifa->ifa_addr->sa_family != AF_LINK) {
12601             ifa = TAILQ_NEXT(ifa, ifa_link);
12602             continue;
12603         }
12604
12605         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12606                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12607         if (rc == -EEXIST) {
12608             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12609             /* do not treat adding same MAC as an error */
12610             rc = 0;
12611         } else if (rc < 0) {
12612             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12613 #if __FreeBSD_version < 800000
12614             IF_ADDR_UNLOCK(ifp);
12615 #else
12616             if_addr_runlock(ifp);
12617 #endif
12618             return (rc);
12619         }
12620
12621         ifa = TAILQ_NEXT(ifa, ifa_link);
12622     }
12623
12624 #if __FreeBSD_version < 800000
12625     IF_ADDR_UNLOCK(ifp);
12626 #else
12627     if_addr_runlock(ifp);
12628 #endif
12629
12630     /* Execute the pending commands */
12631     bit_set(&ramrod_flags, RAMROD_CONT);
12632     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12633                             ECORE_UC_LIST_MAC, &ramrod_flags));
12634 }
12635
12636 static void
12637 bxe_handle_rx_mode_tq(void *context,
12638                       int  pending)
12639 {
12640     struct bxe_softc *sc = (struct bxe_softc *)context;
12641     if_t ifp = sc->ifp;
12642     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12643
12644     BXE_CORE_LOCK(sc);
12645
12646     if (sc->state != BXE_STATE_OPEN) {
12647         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12648         BXE_CORE_UNLOCK(sc);
12649         return;
12650     }
12651
12652     BLOGD(sc, DBG_SP, "if_flags(ifp)=0x%x\n", if_getflags(sc->ifp));
12653
12654     if (if_getflags(ifp) & IFF_PROMISC) {
12655         rx_mode = BXE_RX_MODE_PROMISC;
12656     } else if ((if_getflags(ifp) & IFF_ALLMULTI) ||
12657                ((if_getamcount(ifp) > BXE_MAX_MULTICAST) &&
12658                 CHIP_IS_E1(sc))) {
12659         rx_mode = BXE_RX_MODE_ALLMULTI;
12660     } else {
12661         if (IS_PF(sc)) {
12662             /* some multicasts */
12663             if (bxe_set_mc_list(sc) < 0) {
12664                 rx_mode = BXE_RX_MODE_ALLMULTI;
12665             }
12666             if (bxe_set_uc_list(sc) < 0) {
12667                 rx_mode = BXE_RX_MODE_PROMISC;
12668             }
12669         }
12670 #if 0
12671         else {
12672             /*
12673              * Configuring mcast to a VF involves sleeping (when we
12674              * wait for the PF's response). Since this function is
12675              * called from a non sleepable context we must schedule
12676              * a work item for this purpose
12677              */
12678             bxe_set_bit(BXE_SP_RTNL_VFPF_MCAST, &sc->sp_rtnl_state);
12679             schedule_delayed_work(&sc->sp_rtnl_task, 0);
12680         }
12681 #endif
12682     }
12683
12684     sc->rx_mode = rx_mode;
12685
12686     /* schedule the rx_mode command */
12687     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12688         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12689         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12690         BXE_CORE_UNLOCK(sc);
12691         return;
12692     }
12693
12694     if (IS_PF(sc)) {
12695         bxe_set_storm_rx_mode(sc);
12696     }
12697 #if 0
12698     else {
12699         /*
12700          * Configuring mcast to a VF involves sleeping (when we
12701          * wait for the PF's response). Since this function is
12702          * called from a non sleepable context we must schedule
12703          * a work item for this purpose
12704          */
12705         bxe_set_bit(BXE_SP_RTNL_VFPF_STORM_RX_MODE, &sc->sp_rtnl_state);
12706         schedule_delayed_work(&sc->sp_rtnl_task, 0);
12707     }
12708 #endif
12709
12710     BXE_CORE_UNLOCK(sc);
12711 }
12712
12713 static void
12714 bxe_set_rx_mode(struct bxe_softc *sc)
12715 {
12716     taskqueue_enqueue(sc->rx_mode_tq, &sc->rx_mode_tq_task);
12717 }
12718
12719 /* update flags in shmem */
12720 static void
12721 bxe_update_drv_flags(struct bxe_softc *sc,
12722                      uint32_t         flags,
12723                      uint32_t         set)
12724 {
12725     uint32_t drv_flags;
12726
12727     if (SHMEM2_HAS(sc, drv_flags)) {
12728         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12729         drv_flags = SHMEM2_RD(sc, drv_flags);
12730
12731         if (set) {
12732             SET_FLAGS(drv_flags, flags);
12733         } else {
12734             RESET_FLAGS(drv_flags, flags);
12735         }
12736
12737         SHMEM2_WR(sc, drv_flags, drv_flags);
12738         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12739
12740         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12741     }
12742 }
12743
12744 /* periodic timer callout routine, only runs when the interface is up */
12745
12746 static void
12747 bxe_periodic_callout_func(void *xsc)
12748 {
12749     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12750     int i;
12751
12752     if (!BXE_CORE_TRYLOCK(sc)) {
12753         /* just bail and try again next time */
12754
12755         if ((sc->state == BXE_STATE_OPEN) &&
12756             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12757             /* schedule the next periodic callout */
12758             callout_reset(&sc->periodic_callout, hz,
12759                           bxe_periodic_callout_func, sc);
12760         }
12761
12762         return;
12763     }
12764
12765     if ((sc->state != BXE_STATE_OPEN) ||
12766         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12767         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12768         BXE_CORE_UNLOCK(sc);
12769         return;
12770     }
12771
12772     /* Check for TX timeouts on any fastpath. */
12773     FOR_EACH_QUEUE(sc, i) {
12774         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12775             /* Ruh-Roh, chip was reset! */
12776             break;
12777         }
12778     }
12779
12780     if (!CHIP_REV_IS_SLOW(sc)) {
12781         /*
12782          * This barrier is needed to ensure the ordering between the writing
12783          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12784          * the reading here.
12785          */
12786         mb();
12787         if (sc->port.pmf) {
12788             BXE_PHY_LOCK(sc);
12789             elink_period_func(&sc->link_params, &sc->link_vars);
12790             BXE_PHY_UNLOCK(sc);
12791         }
12792     }
12793
12794     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12795         int mb_idx = SC_FW_MB_IDX(sc);
12796         uint32_t drv_pulse;
12797         uint32_t mcp_pulse;
12798
12799         ++sc->fw_drv_pulse_wr_seq;
12800         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12801
12802         drv_pulse = sc->fw_drv_pulse_wr_seq;
12803         bxe_drv_pulse(sc);
12804
12805         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12806                      MCP_PULSE_SEQ_MASK);
12807
12808         /*
12809          * The delta between driver pulse and mcp response should
12810          * be 1 (before mcp response) or 0 (after mcp response).
12811          */
12812         if ((drv_pulse != mcp_pulse) &&
12813             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12814             /* someone lost a heartbeat... */
12815             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12816                   drv_pulse, mcp_pulse);
12817         }
12818     }
12819
12820     /* state is BXE_STATE_OPEN */
12821     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12822
12823 #if 0
12824     /* sample VF bulletin board for new posts from PF */
12825     if (IS_VF(sc)) {
12826         bxe_sample_bulletin(sc);
12827     }
12828 #endif
12829
12830     BXE_CORE_UNLOCK(sc);
12831
12832     if ((sc->state == BXE_STATE_OPEN) &&
12833         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12834         /* schedule the next periodic callout */
12835         callout_reset(&sc->periodic_callout, hz,
12836                       bxe_periodic_callout_func, sc);
12837     }
12838 }
12839
12840 static void
12841 bxe_periodic_start(struct bxe_softc *sc)
12842 {
12843     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12844     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12845 }
12846
12847 static void
12848 bxe_periodic_stop(struct bxe_softc *sc)
12849 {
12850     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12851     callout_drain(&sc->periodic_callout);
12852 }
12853
12854 /* start the controller */
12855 static __noinline int
12856 bxe_nic_load(struct bxe_softc *sc,
12857              int              load_mode)
12858 {
12859     uint32_t val;
12860     int load_code = 0;
12861     int i, rc = 0;
12862
12863     BXE_CORE_LOCK_ASSERT(sc);
12864
12865     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12866
12867     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12868
12869     if (IS_PF(sc)) {
12870         /* must be called before memory allocation and HW init */
12871         bxe_ilt_set_info(sc);
12872     }
12873
12874     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12875
12876     bxe_set_fp_rx_buf_size(sc);
12877
12878     if (bxe_alloc_fp_buffers(sc) != 0) {
12879         BLOGE(sc, "Failed to allocate fastpath memory\n");
12880         sc->state = BXE_STATE_CLOSED;
12881         rc = ENOMEM;
12882         goto bxe_nic_load_error0;
12883     }
12884
12885     if (bxe_alloc_mem(sc) != 0) {
12886         sc->state = BXE_STATE_CLOSED;
12887         rc = ENOMEM;
12888         goto bxe_nic_load_error0;
12889     }
12890
12891     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12892         sc->state = BXE_STATE_CLOSED;
12893         rc = ENOMEM;
12894         goto bxe_nic_load_error0;
12895     }
12896
12897     if (IS_PF(sc)) {
12898         /* set pf load just before approaching the MCP */
12899         bxe_set_pf_load(sc);
12900
12901         /* if MCP exists send load request and analyze response */
12902         if (!BXE_NOMCP(sc)) {
12903             /* attempt to load pf */
12904             if (bxe_nic_load_request(sc, &load_code) != 0) {
12905                 sc->state = BXE_STATE_CLOSED;
12906                 rc = ENXIO;
12907                 goto bxe_nic_load_error1;
12908             }
12909
12910             /* what did the MCP say? */
12911             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12912                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12913                 sc->state = BXE_STATE_CLOSED;
12914                 rc = ENXIO;
12915                 goto bxe_nic_load_error2;
12916             }
12917         } else {
12918             BLOGI(sc, "Device has no MCP!\n");
12919             load_code = bxe_nic_load_no_mcp(sc);
12920         }
12921
12922         /* mark PMF if applicable */
12923         bxe_nic_load_pmf(sc, load_code);
12924
12925         /* Init Function state controlling object */
12926         bxe_init_func_obj(sc);
12927
12928         /* Initialize HW */
12929         if (bxe_init_hw(sc, load_code) != 0) {
12930             BLOGE(sc, "HW init failed\n");
12931             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12932             sc->state = BXE_STATE_CLOSED;
12933             rc = ENXIO;
12934             goto bxe_nic_load_error2;
12935         }
12936     }
12937
12938     /* attach interrupts */
12939     if (bxe_interrupt_attach(sc) != 0) {
12940         sc->state = BXE_STATE_CLOSED;
12941         rc = ENXIO;
12942         goto bxe_nic_load_error2;
12943     }
12944
12945     bxe_nic_init(sc, load_code);
12946
12947     /* Init per-function objects */
12948     if (IS_PF(sc)) {
12949         bxe_init_objs(sc);
12950         // XXX bxe_iov_nic_init(sc);
12951
12952         /* set AFEX default VLAN tag to an invalid value */
12953         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12954         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12955
12956         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12957         rc = bxe_func_start(sc);
12958         if (rc) {
12959             BLOGE(sc, "Function start failed!\n");
12960             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12961             sc->state = BXE_STATE_ERROR;
12962             goto bxe_nic_load_error3;
12963         }
12964
12965         /* send LOAD_DONE command to MCP */
12966         if (!BXE_NOMCP(sc)) {
12967             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12968             if (!load_code) {
12969                 BLOGE(sc, "MCP response failure, aborting\n");
12970                 sc->state = BXE_STATE_ERROR;
12971                 rc = ENXIO;
12972                 goto bxe_nic_load_error3;
12973             }
12974         }
12975
12976         rc = bxe_setup_leading(sc);
12977         if (rc) {
12978             BLOGE(sc, "Setup leading failed!\n");
12979             sc->state = BXE_STATE_ERROR;
12980             goto bxe_nic_load_error3;
12981         }
12982
12983         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12984             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12985             if (rc) {
12986                 BLOGE(sc, "Queue(%d) setup failed\n", i);
12987                 sc->state = BXE_STATE_ERROR;
12988                 goto bxe_nic_load_error3;
12989             }
12990         }
12991
12992         rc = bxe_init_rss_pf(sc);
12993         if (rc) {
12994             BLOGE(sc, "PF RSS init failed\n");
12995             sc->state = BXE_STATE_ERROR;
12996             goto bxe_nic_load_error3;
12997         }
12998     }
12999     /* XXX VF */
13000 #if 0
13001     else { /* VF */
13002         FOR_EACH_ETH_QUEUE(sc, i) {
13003             rc = bxe_vfpf_setup_q(sc, i);
13004             if (rc) {
13005                 BLOGE(sc, "Queue(%d) setup failed\n", i);
13006                 sc->state = BXE_STATE_ERROR;
13007                 goto bxe_nic_load_error3;
13008             }
13009         }
13010     }
13011 #endif
13012
13013     /* now when Clients are configured we are ready to work */
13014     sc->state = BXE_STATE_OPEN;
13015
13016     /* Configure a ucast MAC */
13017     if (IS_PF(sc)) {
13018         rc = bxe_set_eth_mac(sc, TRUE);
13019     }
13020 #if 0
13021     else { /* IS_VF(sc) */
13022         rc = bxe_vfpf_set_mac(sc);
13023     }
13024 #endif
13025     if (rc) {
13026         BLOGE(sc, "Setting Ethernet MAC failed\n");
13027         sc->state = BXE_STATE_ERROR;
13028         goto bxe_nic_load_error3;
13029     }
13030
13031 #if 0
13032     if (IS_PF(sc) && sc->pending_max) {
13033         /* for AFEX */
13034         bxe_update_max_mf_config(sc, sc->pending_max);
13035         sc->pending_max = 0;
13036     }
13037 #endif
13038
13039     if (sc->port.pmf) {
13040         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
13041         if (rc) {
13042             sc->state = BXE_STATE_ERROR;
13043             goto bxe_nic_load_error3;
13044         }
13045     }
13046
13047     sc->link_params.feature_config_flags &=
13048         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
13049
13050     /* start fast path */
13051
13052     /* Initialize Rx filter */
13053     bxe_set_rx_mode(sc);
13054
13055     /* start the Tx */
13056     switch (/* XXX load_mode */LOAD_OPEN) {
13057     case LOAD_NORMAL:
13058     case LOAD_OPEN:
13059         break;
13060
13061     case LOAD_DIAG:
13062     case LOAD_LOOPBACK_EXT:
13063         sc->state = BXE_STATE_DIAG;
13064         break;
13065
13066     default:
13067         break;
13068     }
13069
13070     if (sc->port.pmf) {
13071         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
13072     } else {
13073         bxe_link_status_update(sc);
13074     }
13075
13076     /* start the periodic timer callout */
13077     bxe_periodic_start(sc);
13078
13079     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
13080         /* mark driver is loaded in shmem2 */
13081         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
13082         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
13083                   (val |
13084                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
13085                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
13086     }
13087
13088     /* wait for all pending SP commands to complete */
13089     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
13090         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
13091         bxe_periodic_stop(sc);
13092         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
13093         return (ENXIO);
13094     }
13095
13096 #if 0
13097     /* If PMF - send ADMIN DCBX msg to MFW to initiate DCBX FSM */
13098     if (sc->port.pmf && (sc->state != BXE_STATE_DIAG)) {
13099         bxe_dcbx_init(sc, FALSE);
13100     }
13101 #endif
13102
13103     /* Tell the stack the driver is running! */
13104     if_setdrvflags(sc->ifp, IFF_DRV_RUNNING);
13105
13106     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
13107
13108     return (0);
13109
13110 bxe_nic_load_error3:
13111
13112     if (IS_PF(sc)) {
13113         bxe_int_disable_sync(sc, 1);
13114
13115         /* clean out queued objects */
13116         bxe_squeeze_objects(sc);
13117     }
13118
13119     bxe_interrupt_detach(sc);
13120
13121 bxe_nic_load_error2:
13122
13123     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
13124         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
13125         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
13126     }
13127
13128     sc->port.pmf = 0;
13129
13130 bxe_nic_load_error1:
13131
13132     /* clear pf_load status, as it was already set */
13133     if (IS_PF(sc)) {
13134         bxe_clear_pf_load(sc);
13135     }
13136
13137 bxe_nic_load_error0:
13138
13139     bxe_free_fw_stats_mem(sc);
13140     bxe_free_fp_buffers(sc);
13141     bxe_free_mem(sc);
13142
13143     return (rc);
13144 }
13145
13146 static int
13147 bxe_init_locked(struct bxe_softc *sc)
13148 {
13149     int other_engine = SC_PATH(sc) ? 0 : 1;
13150     uint8_t other_load_status, load_status;
13151     uint8_t global = FALSE;
13152     int rc;
13153
13154     BXE_CORE_LOCK_ASSERT(sc);
13155
13156     /* check if the driver is already running */
13157     if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
13158         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
13159         return (0);
13160     }
13161
13162     bxe_set_power_state(sc, PCI_PM_D0);
13163
13164     /*
13165      * If parity occurred during the unload, then attentions and/or
13166      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
13167      * loaded on the current engine to complete the recovery. Parity recovery
13168      * is only relevant for PF driver.
13169      */
13170     if (IS_PF(sc)) {
13171         other_load_status = bxe_get_load_status(sc, other_engine);
13172         load_status = bxe_get_load_status(sc, SC_PATH(sc));
13173
13174         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
13175             bxe_chk_parity_attn(sc, &global, TRUE)) {
13176             do {
13177                 /*
13178                  * If there are attentions and they are in global blocks, set
13179                  * the GLOBAL_RESET bit regardless whether it will be this
13180                  * function that will complete the recovery or not.
13181                  */
13182                 if (global) {
13183                     bxe_set_reset_global(sc);
13184                 }
13185
13186                 /*
13187                  * Only the first function on the current engine should try
13188                  * to recover in open. In case of attentions in global blocks
13189                  * only the first in the chip should try to recover.
13190                  */
13191                 if ((!load_status && (!global || !other_load_status)) &&
13192                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
13193                     BLOGI(sc, "Recovered during init\n");
13194                     break;
13195                 }
13196
13197                 /* recovery has failed... */
13198                 bxe_set_power_state(sc, PCI_PM_D3hot);
13199                 sc->recovery_state = BXE_RECOVERY_FAILED;
13200
13201                 BLOGE(sc, "Recovery flow hasn't properly "
13202                           "completed yet, try again later. "
13203                           "If you still see this message after a "
13204                           "few retries then power cycle is required.\n");
13205
13206                 rc = ENXIO;
13207                 goto bxe_init_locked_done;
13208             } while (0);
13209         }
13210     }
13211
13212     sc->recovery_state = BXE_RECOVERY_DONE;
13213
13214     rc = bxe_nic_load(sc, LOAD_OPEN);
13215
13216 bxe_init_locked_done:
13217
13218     if (rc) {
13219         /* Tell the stack the driver is NOT running! */
13220         BLOGE(sc, "Initialization failed, "
13221                   "stack notified driver is NOT running!\n");
13222         if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
13223     }
13224
13225     return (rc);
13226 }
13227
13228 static int
13229 bxe_stop_locked(struct bxe_softc *sc)
13230 {
13231     BXE_CORE_LOCK_ASSERT(sc);
13232     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
13233 }
13234
13235 /*
13236  * Handles controller initialization when called from an unlocked routine.
13237  * ifconfig calls this function.
13238  *
13239  * Returns:
13240  *   void
13241  */
13242 static void
13243 bxe_init(void *xsc)
13244 {
13245     struct bxe_softc *sc = (struct bxe_softc *)xsc;
13246
13247     BXE_CORE_LOCK(sc);
13248     bxe_init_locked(sc);
13249     BXE_CORE_UNLOCK(sc);
13250 }
13251
13252 static int
13253 bxe_init_ifnet(struct bxe_softc *sc)
13254 {
13255     if_t ifp;
13256     int capabilities;
13257
13258     /* ifconfig entrypoint for media type/status reporting */
13259     ifmedia_init(&sc->ifmedia, IFM_IMASK,
13260                  bxe_ifmedia_update,
13261                  bxe_ifmedia_status);
13262
13263     /* set the default interface values */
13264     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
13265     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
13266     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
13267
13268     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
13269
13270     /* allocate the ifnet structure */
13271     if ((ifp = if_gethandle(IFT_ETHER)) == NULL) {
13272         BLOGE(sc, "Interface allocation failed!\n");
13273         return (ENXIO);
13274     }
13275
13276     if_setsoftc(ifp, sc);
13277     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
13278     if_setflags(ifp, (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST));
13279     if_setioctlfn(ifp, bxe_ioctl);
13280     if_setstartfn(ifp, bxe_tx_start);
13281     if_setgetcounterfn(ifp, bxe_get_counter);
13282 #if __FreeBSD_version >= 800000
13283     if_settransmitfn(ifp, bxe_tx_mq_start);
13284     if_setqflushfn(ifp, bxe_mq_flush);
13285 #endif
13286 #ifdef FreeBSD8_0
13287     if_settimer(ifp, 0);
13288 #endif
13289     if_setinitfn(ifp, bxe_init);
13290     if_setmtu(ifp, sc->mtu);
13291     if_sethwassist(ifp, (CSUM_IP      |
13292                         CSUM_TCP      |
13293                         CSUM_UDP      |
13294                         CSUM_TSO      |
13295                         CSUM_TCP_IPV6 |
13296                         CSUM_UDP_IPV6));
13297
13298     capabilities =
13299 #if __FreeBSD_version < 700000
13300         (IFCAP_VLAN_MTU       |
13301          IFCAP_VLAN_HWTAGGING |
13302          IFCAP_HWCSUM         |
13303          IFCAP_JUMBO_MTU      |
13304          IFCAP_LRO);
13305 #else
13306         (IFCAP_VLAN_MTU       |
13307          IFCAP_VLAN_HWTAGGING |
13308          IFCAP_VLAN_HWTSO     |
13309          IFCAP_VLAN_HWFILTER  |
13310          IFCAP_VLAN_HWCSUM    |
13311          IFCAP_HWCSUM         |
13312          IFCAP_JUMBO_MTU      |
13313          IFCAP_LRO            |
13314          IFCAP_TSO4           |
13315          IFCAP_TSO6           |
13316          IFCAP_WOL_MAGIC);
13317 #endif
13318     if_setcapabilitiesbit(ifp, capabilities, 0); /* XXX */
13319     if_setbaudrate(ifp, IF_Gbps(10));
13320 /* XXX */
13321     if_setsendqlen(ifp, sc->tx_ring_size);
13322     if_setsendqready(ifp);
13323 /* XXX */
13324
13325     sc->ifp = ifp;
13326
13327     /* attach to the Ethernet interface list */
13328     ether_ifattach(ifp, sc->link_params.mac_addr);
13329
13330     return (0);
13331 }
13332
13333 static void
13334 bxe_deallocate_bars(struct bxe_softc *sc)
13335 {
13336     int i;
13337
13338     for (i = 0; i < MAX_BARS; i++) {
13339         if (sc->bar[i].resource != NULL) {
13340             bus_release_resource(sc->dev,
13341                                  SYS_RES_MEMORY,
13342                                  sc->bar[i].rid,
13343                                  sc->bar[i].resource);
13344             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
13345                   i, PCIR_BAR(i));
13346         }
13347     }
13348 }
13349
13350 static int
13351 bxe_allocate_bars(struct bxe_softc *sc)
13352 {
13353     u_int flags;
13354     int i;
13355
13356     memset(sc->bar, 0, sizeof(sc->bar));
13357
13358     for (i = 0; i < MAX_BARS; i++) {
13359
13360         /* memory resources reside at BARs 0, 2, 4 */
13361         /* Run `pciconf -lb` to see mappings */
13362         if ((i != 0) && (i != 2) && (i != 4)) {
13363             continue;
13364         }
13365
13366         sc->bar[i].rid = PCIR_BAR(i);
13367
13368         flags = RF_ACTIVE;
13369         if (i == 0) {
13370             flags |= RF_SHAREABLE;
13371         }
13372
13373         if ((sc->bar[i].resource =
13374              bus_alloc_resource_any(sc->dev,
13375                                     SYS_RES_MEMORY,
13376                                     &sc->bar[i].rid,
13377                                     flags)) == NULL) {
13378 #if 0
13379             /* BAR4 doesn't exist for E1 */
13380             BLOGE(sc, "PCI BAR%d [%02x] memory allocation failed\n",
13381                   i, PCIR_BAR(i));
13382 #endif
13383             return (0);
13384         }
13385
13386         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
13387         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
13388         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
13389
13390         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%ld) -> %p\n",
13391               i, PCIR_BAR(i),
13392               (void *)rman_get_start(sc->bar[i].resource),
13393               (void *)rman_get_end(sc->bar[i].resource),
13394               rman_get_size(sc->bar[i].resource),
13395               (void *)sc->bar[i].kva);
13396     }
13397
13398     return (0);
13399 }
13400
13401 static void
13402 bxe_get_function_num(struct bxe_softc *sc)
13403 {
13404     uint32_t val = 0;
13405
13406     /*
13407      * Read the ME register to get the function number. The ME register
13408      * holds the relative-function number and absolute-function number. The
13409      * absolute-function number appears only in E2 and above. Before that
13410      * these bits always contained zero, therefore we cannot blindly use them.
13411      */
13412
13413     val = REG_RD(sc, BAR_ME_REGISTER);
13414
13415     sc->pfunc_rel =
13416         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
13417     sc->path_id =
13418         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
13419
13420     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13421         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
13422     } else {
13423         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
13424     }
13425
13426     BLOGD(sc, DBG_LOAD,
13427           "Relative function %d, Absolute function %d, Path %d\n",
13428           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
13429 }
13430
13431 static uint32_t
13432 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
13433 {
13434     uint32_t shmem2_size;
13435     uint32_t offset;
13436     uint32_t mf_cfg_offset_value;
13437
13438     /* Non 57712 */
13439     offset = (SHMEM_RD(sc, func_mb) +
13440               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
13441
13442     /* 57712 plus */
13443     if (sc->devinfo.shmem2_base != 0) {
13444         shmem2_size = SHMEM2_RD(sc, size);
13445         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
13446             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
13447             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
13448                 offset = mf_cfg_offset_value;
13449             }
13450         }
13451     }
13452
13453     return (offset);
13454 }
13455
13456 static uint32_t
13457 bxe_pcie_capability_read(struct bxe_softc *sc,
13458                          int    reg,
13459                          int    width)
13460 {
13461     int pcie_reg;
13462
13463     /* ensure PCIe capability is enabled */
13464     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
13465         if (pcie_reg != 0) {
13466             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
13467             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
13468         }
13469     }
13470
13471     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
13472
13473     return (0);
13474 }
13475
13476 static uint8_t
13477 bxe_is_pcie_pending(struct bxe_softc *sc)
13478 {
13479     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
13480             PCIM_EXP_STA_TRANSACTION_PND);
13481 }
13482
13483 /*
13484  * Walk the PCI capabiites list for the device to find what features are
13485  * supported. These capabilites may be enabled/disabled by firmware so it's
13486  * best to walk the list rather than make assumptions.
13487  */
13488 static void
13489 bxe_probe_pci_caps(struct bxe_softc *sc)
13490 {
13491     uint16_t link_status;
13492     int reg;
13493
13494     /* check if PCI Power Management is enabled */
13495     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
13496         if (reg != 0) {
13497             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
13498
13499             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
13500             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
13501         }
13502     }
13503
13504     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
13505
13506     /* handle PCIe 2.0 workarounds for 57710 */
13507     if (CHIP_IS_E1(sc)) {
13508         /* workaround for 57710 errata E4_57710_27462 */
13509         sc->devinfo.pcie_link_speed =
13510             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
13511
13512         /* workaround for 57710 errata E4_57710_27488 */
13513         sc->devinfo.pcie_link_width =
13514             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13515         if (sc->devinfo.pcie_link_speed > 1) {
13516             sc->devinfo.pcie_link_width =
13517                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
13518         }
13519     } else {
13520         sc->devinfo.pcie_link_speed =
13521             (link_status & PCIM_LINK_STA_SPEED);
13522         sc->devinfo.pcie_link_width =
13523             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13524     }
13525
13526     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
13527           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
13528
13529     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
13530     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
13531
13532     /* check if MSI capability is enabled */
13533     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
13534         if (reg != 0) {
13535             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13536
13537             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13538             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13539         }
13540     }
13541
13542     /* check if MSI-X capability is enabled */
13543     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13544         if (reg != 0) {
13545             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13546
13547             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13548             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13549         }
13550     }
13551 }
13552
13553 static int
13554 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13555 {
13556     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13557     uint32_t val;
13558
13559     /* get the outer vlan if we're in switch-dependent mode */
13560
13561     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13562     mf_info->ext_id = (uint16_t)val;
13563
13564     mf_info->multi_vnics_mode = 1;
13565
13566     if (!VALID_OVLAN(mf_info->ext_id)) {
13567         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13568         return (1);
13569     }
13570
13571     /* get the capabilities */
13572     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13573         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13574         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13575     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13576                FUNC_MF_CFG_PROTOCOL_FCOE) {
13577         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13578     } else {
13579         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13580     }
13581
13582     mf_info->vnics_per_port =
13583         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13584
13585     return (0);
13586 }
13587
13588 static uint32_t
13589 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13590 {
13591     uint32_t retval = 0;
13592     uint32_t val;
13593
13594     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13595
13596     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13597         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13598             retval |= MF_PROTO_SUPPORT_ETHERNET;
13599         }
13600         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13601             retval |= MF_PROTO_SUPPORT_ISCSI;
13602         }
13603         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13604             retval |= MF_PROTO_SUPPORT_FCOE;
13605         }
13606     }
13607
13608     return (retval);
13609 }
13610
13611 static int
13612 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13613 {
13614     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13615     uint32_t val;
13616
13617     /*
13618      * There is no outer vlan if we're in switch-independent mode.
13619      * If the mac is valid then assume multi-function.
13620      */
13621
13622     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13623
13624     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13625
13626     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13627
13628     mf_info->vnics_per_port =
13629         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13630
13631     return (0);
13632 }
13633
13634 static int
13635 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13636 {
13637     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13638     uint32_t e1hov_tag;
13639     uint32_t func_config;
13640     uint32_t niv_config;
13641
13642     mf_info->multi_vnics_mode = 1;
13643
13644     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13645     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13646     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13647
13648     mf_info->ext_id =
13649         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13650                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13651
13652     mf_info->default_vlan =
13653         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13654                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13655
13656     mf_info->niv_allowed_priorities =
13657         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13658                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13659
13660     mf_info->niv_default_cos =
13661         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13662                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13663
13664     mf_info->afex_vlan_mode =
13665         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13666          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13667
13668     mf_info->niv_mba_enabled =
13669         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13670          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13671
13672     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13673
13674     mf_info->vnics_per_port =
13675         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13676
13677     return (0);
13678 }
13679
13680 static int
13681 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13682 {
13683     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13684     uint32_t mf_cfg1;
13685     uint32_t mf_cfg2;
13686     uint32_t ovlan1;
13687     uint32_t ovlan2;
13688     uint8_t i, j;
13689
13690     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13691           SC_PORT(sc));
13692     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13693           mf_info->mf_config[SC_VN(sc)]);
13694     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13695           mf_info->multi_vnics_mode);
13696     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13697           mf_info->vnics_per_port);
13698     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13699           mf_info->ext_id);
13700     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13701           mf_info->min_bw[0], mf_info->min_bw[1],
13702           mf_info->min_bw[2], mf_info->min_bw[3]);
13703     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13704           mf_info->max_bw[0], mf_info->max_bw[1],
13705           mf_info->max_bw[2], mf_info->max_bw[3]);
13706     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13707           sc->mac_addr_str);
13708
13709     /* various MF mode sanity checks... */
13710
13711     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13712         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13713               SC_PORT(sc));
13714         return (1);
13715     }
13716
13717     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13718         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13719               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13720         return (1);
13721     }
13722
13723     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13724         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13725         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13726             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13727                   SC_VN(sc), OVLAN(sc));
13728             return (1);
13729         }
13730
13731         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13732             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13733                   mf_info->multi_vnics_mode, OVLAN(sc));
13734             return (1);
13735         }
13736
13737         /*
13738          * Verify all functions are either MF or SF mode. If MF, make sure
13739          * sure that all non-hidden functions have a valid ovlan. If SF,
13740          * make sure that all non-hidden functions have an invalid ovlan.
13741          */
13742         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13743             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13744             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13745             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13746                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13747                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13748                 BLOGE(sc, "mf_mode=SD function %d MF config "
13749                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13750                       i, mf_info->multi_vnics_mode, ovlan1);
13751                 return (1);
13752             }
13753         }
13754
13755         /* Verify all funcs on the same port each have a different ovlan. */
13756         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13757             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13758             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13759             /* iterate from the next function on the port to the max func */
13760             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13761                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13762                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13763                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13764                     VALID_OVLAN(ovlan1) &&
13765                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13766                     VALID_OVLAN(ovlan2) &&
13767                     (ovlan1 == ovlan2)) {
13768                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13769                               "have the same ovlan (%d)\n",
13770                           i, j, ovlan1);
13771                     return (1);
13772                 }
13773             }
13774         }
13775     } /* MULTI_FUNCTION_SD */
13776
13777     return (0);
13778 }
13779
13780 static int
13781 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13782 {
13783     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13784     uint32_t val, mac_upper;
13785     uint8_t i, vnic;
13786
13787     /* initialize mf_info defaults */
13788     mf_info->vnics_per_port   = 1;
13789     mf_info->multi_vnics_mode = FALSE;
13790     mf_info->path_has_ovlan   = FALSE;
13791     mf_info->mf_mode          = SINGLE_FUNCTION;
13792
13793     if (!CHIP_IS_MF_CAP(sc)) {
13794         return (0);
13795     }
13796
13797     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13798         BLOGE(sc, "Invalid mf_cfg_base!\n");
13799         return (1);
13800     }
13801
13802     /* get the MF mode (switch dependent / independent / single-function) */
13803
13804     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13805
13806     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13807     {
13808     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13809
13810         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13811
13812         /* check for legal upper mac bytes */
13813         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13814             mf_info->mf_mode = MULTI_FUNCTION_SI;
13815         } else {
13816             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13817         }
13818
13819         break;
13820
13821     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13822     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13823
13824         /* get outer vlan configuration */
13825         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13826
13827         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13828             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13829             mf_info->mf_mode = MULTI_FUNCTION_SD;
13830         } else {
13831             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13832         }
13833
13834         break;
13835
13836     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13837
13838         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13839         return (0);
13840
13841     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13842
13843         /*
13844          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13845          * and the MAC address is valid.
13846          */
13847         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13848
13849         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13850             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13851             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13852         } else {
13853             BLOGE(sc, "Invalid config for AFEX mode\n");
13854         }
13855
13856         break;
13857
13858     default:
13859
13860         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13861               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13862
13863         return (1);
13864     }
13865
13866     /* set path mf_mode (which could be different than function mf_mode) */
13867     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13868         mf_info->path_has_ovlan = TRUE;
13869     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13870         /*
13871          * Decide on path multi vnics mode. If we're not in MF mode and in
13872          * 4-port mode, this is good enough to check vnic-0 of the other port
13873          * on the same path
13874          */
13875         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13876             uint8_t other_port = !(PORT_ID(sc) & 1);
13877             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13878
13879             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13880
13881             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13882         }
13883     }
13884
13885     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13886         /* invalid MF config */
13887         if (SC_VN(sc) >= 1) {
13888             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13889             return (1);
13890         }
13891
13892         return (0);
13893     }
13894
13895     /* get the MF configuration */
13896     mf_info->mf_config[SC_VN(sc)] =
13897         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13898
13899     switch(mf_info->mf_mode)
13900     {
13901     case MULTI_FUNCTION_SD:
13902
13903         bxe_get_shmem_mf_cfg_info_sd(sc);
13904         break;
13905
13906     case MULTI_FUNCTION_SI:
13907
13908         bxe_get_shmem_mf_cfg_info_si(sc);
13909         break;
13910
13911     case MULTI_FUNCTION_AFEX:
13912
13913         bxe_get_shmem_mf_cfg_info_niv(sc);
13914         break;
13915
13916     default:
13917
13918         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13919               mf_info->mf_mode);
13920         return (1);
13921     }
13922
13923     /* get the congestion management parameters */
13924
13925     vnic = 0;
13926     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13927         /* get min/max bw */
13928         val = MFCFG_RD(sc, func_mf_config[i].config);
13929         mf_info->min_bw[vnic] =
13930             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13931         mf_info->max_bw[vnic] =
13932             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13933         vnic++;
13934     }
13935
13936     return (bxe_check_valid_mf_cfg(sc));
13937 }
13938
13939 static int
13940 bxe_get_shmem_info(struct bxe_softc *sc)
13941 {
13942     int port;
13943     uint32_t mac_hi, mac_lo, val;
13944
13945     port = SC_PORT(sc);
13946     mac_hi = mac_lo = 0;
13947
13948     sc->link_params.sc   = sc;
13949     sc->link_params.port = port;
13950
13951     /* get the hardware config info */
13952     sc->devinfo.hw_config =
13953         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13954     sc->devinfo.hw_config2 =
13955         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13956
13957     sc->link_params.hw_led_mode =
13958         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13959          SHARED_HW_CFG_LED_MODE_SHIFT);
13960
13961     /* get the port feature config */
13962     sc->port.config =
13963         SHMEM_RD(sc, dev_info.port_feature_config[port].config),
13964
13965     /* get the link params */
13966     sc->link_params.speed_cap_mask[0] =
13967         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13968     sc->link_params.speed_cap_mask[1] =
13969         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13970
13971     /* get the lane config */
13972     sc->link_params.lane_config =
13973         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13974
13975     /* get the link config */
13976     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13977     sc->port.link_config[ELINK_INT_PHY] = val;
13978     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13979     sc->port.link_config[ELINK_EXT_PHY1] =
13980         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13981
13982     /* get the override preemphasis flag and enable it or turn it off */
13983     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13984     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13985         sc->link_params.feature_config_flags |=
13986             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13987     } else {
13988         sc->link_params.feature_config_flags &=
13989             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13990     }
13991
13992     /* get the initial value of the link params */
13993     sc->link_params.multi_phy_config =
13994         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13995
13996     /* get external phy info */
13997     sc->port.ext_phy_config =
13998         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13999
14000     /* get the multifunction configuration */
14001     bxe_get_mf_cfg_info(sc);
14002
14003     /* get the mac address */
14004     if (IS_MF(sc)) {
14005         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
14006         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
14007     } else {
14008         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
14009         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
14010     }
14011
14012     if ((mac_lo == 0) && (mac_hi == 0)) {
14013         *sc->mac_addr_str = 0;
14014         BLOGE(sc, "No Ethernet address programmed!\n");
14015     } else {
14016         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
14017         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
14018         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
14019         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
14020         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
14021         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
14022         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
14023                  "%02x:%02x:%02x:%02x:%02x:%02x",
14024                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
14025                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
14026                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
14027         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
14028     }
14029
14030 #if 0
14031     if (!IS_MF(sc) &&
14032         ((sc->port.config & PORT_FEAT_CFG_STORAGE_PERSONALITY_MASK) ==
14033          PORT_FEAT_CFG_STORAGE_PERSONALITY_FCOE)) {
14034         sc->flags |= BXE_NO_ISCSI;
14035     }
14036     if (!IS_MF(sc) &&
14037         ((sc->port.config & PORT_FEAT_CFG_STORAGE_PERSONALITY_MASK) ==
14038          PORT_FEAT_CFG_STORAGE_PERSONALITY_ISCSI)) {
14039         sc->flags |= BXE_NO_FCOE_FLAG;
14040     }
14041 #endif
14042
14043     return (0);
14044 }
14045
14046 static void
14047 bxe_get_tunable_params(struct bxe_softc *sc)
14048 {
14049     /* sanity checks */
14050
14051     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
14052         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
14053         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
14054         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
14055         bxe_interrupt_mode = INTR_MODE_MSIX;
14056     }
14057
14058     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
14059         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
14060         bxe_queue_count = 0;
14061     }
14062
14063     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
14064         if (bxe_max_rx_bufs == 0) {
14065             bxe_max_rx_bufs = RX_BD_USABLE;
14066         } else {
14067             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
14068             bxe_max_rx_bufs = 2048;
14069         }
14070     }
14071
14072     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
14073         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
14074         bxe_hc_rx_ticks = 25;
14075     }
14076
14077     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
14078         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
14079         bxe_hc_tx_ticks = 50;
14080     }
14081
14082     if (bxe_max_aggregation_size == 0) {
14083         bxe_max_aggregation_size = TPA_AGG_SIZE;
14084     }
14085
14086     if (bxe_max_aggregation_size > 0xffff) {
14087         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
14088               bxe_max_aggregation_size);
14089         bxe_max_aggregation_size = TPA_AGG_SIZE;
14090     }
14091
14092     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
14093         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
14094         bxe_mrrs = -1;
14095     }
14096
14097     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
14098         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
14099         bxe_autogreeen = 0;
14100     }
14101
14102     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
14103         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
14104         bxe_udp_rss = 0;
14105     }
14106
14107     /* pull in user settings */
14108
14109     sc->interrupt_mode       = bxe_interrupt_mode;
14110     sc->max_rx_bufs          = bxe_max_rx_bufs;
14111     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
14112     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
14113     sc->max_aggregation_size = bxe_max_aggregation_size;
14114     sc->mrrs                 = bxe_mrrs;
14115     sc->autogreeen           = bxe_autogreeen;
14116     sc->udp_rss              = bxe_udp_rss;
14117
14118     if (bxe_interrupt_mode == INTR_MODE_INTX) {
14119         sc->num_queues = 1;
14120     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
14121         sc->num_queues =
14122             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
14123                 MAX_RSS_CHAINS);
14124         if (sc->num_queues > mp_ncpus) {
14125             sc->num_queues = mp_ncpus;
14126         }
14127     }
14128
14129     BLOGD(sc, DBG_LOAD,
14130           "User Config: "
14131           "debug=0x%lx "
14132           "interrupt_mode=%d "
14133           "queue_count=%d "
14134           "hc_rx_ticks=%d "
14135           "hc_tx_ticks=%d "
14136           "rx_budget=%d "
14137           "max_aggregation_size=%d "
14138           "mrrs=%d "
14139           "autogreeen=%d "
14140           "udp_rss=%d\n",
14141           bxe_debug,
14142           sc->interrupt_mode,
14143           sc->num_queues,
14144           sc->hc_rx_ticks,
14145           sc->hc_tx_ticks,
14146           bxe_rx_budget,
14147           sc->max_aggregation_size,
14148           sc->mrrs,
14149           sc->autogreeen,
14150           sc->udp_rss);
14151 }
14152
14153 static void
14154 bxe_media_detect(struct bxe_softc *sc)
14155 {
14156     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
14157     switch (sc->link_params.phy[phy_idx].media_type) {
14158     case ELINK_ETH_PHY_SFPP_10G_FIBER:
14159     case ELINK_ETH_PHY_XFP_FIBER:
14160         BLOGI(sc, "Found 10Gb Fiber media.\n");
14161         sc->media = IFM_10G_SR;
14162         break;
14163     case ELINK_ETH_PHY_SFP_1G_FIBER:
14164         BLOGI(sc, "Found 1Gb Fiber media.\n");
14165         sc->media = IFM_1000_SX;
14166         break;
14167     case ELINK_ETH_PHY_KR:
14168     case ELINK_ETH_PHY_CX4:
14169         BLOGI(sc, "Found 10GBase-CX4 media.\n");
14170         sc->media = IFM_10G_CX4;
14171         break;
14172     case ELINK_ETH_PHY_DA_TWINAX:
14173         BLOGI(sc, "Found 10Gb Twinax media.\n");
14174         sc->media = IFM_10G_TWINAX;
14175         break;
14176     case ELINK_ETH_PHY_BASE_T:
14177         if (sc->link_params.speed_cap_mask[0] &
14178             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
14179             BLOGI(sc, "Found 10GBase-T media.\n");
14180             sc->media = IFM_10G_T;
14181         } else {
14182             BLOGI(sc, "Found 1000Base-T media.\n");
14183             sc->media = IFM_1000_T;
14184         }
14185         break;
14186     case ELINK_ETH_PHY_NOT_PRESENT:
14187         BLOGI(sc, "Media not present.\n");
14188         sc->media = 0;
14189         break;
14190     case ELINK_ETH_PHY_UNSPECIFIED:
14191     default:
14192         BLOGI(sc, "Unknown media!\n");
14193         sc->media = 0;
14194         break;
14195     }
14196 }
14197
14198 #define GET_FIELD(value, fname)                     \
14199     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
14200 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
14201 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
14202
14203 static int
14204 bxe_get_igu_cam_info(struct bxe_softc *sc)
14205 {
14206     int pfid = SC_FUNC(sc);
14207     int igu_sb_id;
14208     uint32_t val;
14209     uint8_t fid, igu_sb_cnt = 0;
14210
14211     sc->igu_base_sb = 0xff;
14212
14213     if (CHIP_INT_MODE_IS_BC(sc)) {
14214         int vn = SC_VN(sc);
14215         igu_sb_cnt = sc->igu_sb_cnt;
14216         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
14217                            FP_SB_MAX_E1x);
14218         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
14219                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
14220         return (0);
14221     }
14222
14223     /* IGU in normal mode - read CAM */
14224     for (igu_sb_id = 0;
14225          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
14226          igu_sb_id++) {
14227         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
14228         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
14229             continue;
14230         }
14231         fid = IGU_FID(val);
14232         if ((fid & IGU_FID_ENCODE_IS_PF)) {
14233             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
14234                 continue;
14235             }
14236             if (IGU_VEC(val) == 0) {
14237                 /* default status block */
14238                 sc->igu_dsb_id = igu_sb_id;
14239             } else {
14240                 if (sc->igu_base_sb == 0xff) {
14241                     sc->igu_base_sb = igu_sb_id;
14242                 }
14243                 igu_sb_cnt++;
14244             }
14245         }
14246     }
14247
14248     /*
14249      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
14250      * that number of CAM entries will not be equal to the value advertised in
14251      * PCI. Driver should use the minimal value of both as the actual status
14252      * block count
14253      */
14254     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
14255
14256     if (igu_sb_cnt == 0) {
14257         BLOGE(sc, "CAM configuration error\n");
14258         return (-1);
14259     }
14260
14261     return (0);
14262 }
14263
14264 /*
14265  * Gather various information from the device config space, the device itself,
14266  * shmem, and the user input.
14267  */
14268 static int
14269 bxe_get_device_info(struct bxe_softc *sc)
14270 {
14271     uint32_t val;
14272     int rc;
14273
14274     /* Get the data for the device */
14275     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
14276     sc->devinfo.device_id    = pci_get_device(sc->dev);
14277     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
14278     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
14279
14280     /* get the chip revision (chip metal comes from pci config space) */
14281     sc->devinfo.chip_id     =
14282     sc->link_params.chip_id =
14283         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
14284          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
14285          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
14286          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
14287
14288     /* force 57811 according to MISC register */
14289     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
14290         if (CHIP_IS_57810(sc)) {
14291             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
14292                                    (sc->devinfo.chip_id & 0x0000ffff));
14293         } else if (CHIP_IS_57810_MF(sc)) {
14294             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
14295                                    (sc->devinfo.chip_id & 0x0000ffff));
14296         }
14297         sc->devinfo.chip_id |= 0x1;
14298     }
14299
14300     BLOGD(sc, DBG_LOAD,
14301           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
14302           sc->devinfo.chip_id,
14303           ((sc->devinfo.chip_id >> 16) & 0xffff),
14304           ((sc->devinfo.chip_id >> 12) & 0xf),
14305           ((sc->devinfo.chip_id >>  4) & 0xff),
14306           ((sc->devinfo.chip_id >>  0) & 0xf));
14307
14308     val = (REG_RD(sc, 0x2874) & 0x55);
14309     if ((sc->devinfo.chip_id & 0x1) ||
14310         (CHIP_IS_E1(sc) && val) ||
14311         (CHIP_IS_E1H(sc) && (val == 0x55))) {
14312         sc->flags |= BXE_ONE_PORT_FLAG;
14313         BLOGD(sc, DBG_LOAD, "single port device\n");
14314     }
14315
14316     /* set the doorbell size */
14317     sc->doorbell_size = (1 << BXE_DB_SHIFT);
14318
14319     /* determine whether the device is in 2 port or 4 port mode */
14320     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
14321     if (CHIP_IS_E2E3(sc)) {
14322         /*
14323          * Read port4mode_en_ovwr[0]:
14324          *   If 1, four port mode is in port4mode_en_ovwr[1].
14325          *   If 0, four port mode is in port4mode_en[0].
14326          */
14327         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
14328         if (val & 1) {
14329             val = ((val >> 1) & 1);
14330         } else {
14331             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
14332         }
14333
14334         sc->devinfo.chip_port_mode =
14335             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
14336
14337         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
14338     }
14339
14340     /* get the function and path info for the device */
14341     bxe_get_function_num(sc);
14342
14343     /* get the shared memory base address */
14344     sc->devinfo.shmem_base     =
14345     sc->link_params.shmem_base =
14346         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
14347     sc->devinfo.shmem2_base =
14348         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
14349                                   MISC_REG_GENERIC_CR_0));
14350
14351     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
14352           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
14353
14354     if (!sc->devinfo.shmem_base) {
14355         /* this should ONLY prevent upcoming shmem reads */
14356         BLOGI(sc, "MCP not active\n");
14357         sc->flags |= BXE_NO_MCP_FLAG;
14358         return (0);
14359     }
14360
14361     /* make sure the shared memory contents are valid */
14362     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
14363     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
14364         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
14365         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
14366         return (0);
14367     }
14368     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
14369
14370     /* get the bootcode version */
14371     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
14372     snprintf(sc->devinfo.bc_ver_str,
14373              sizeof(sc->devinfo.bc_ver_str),
14374              "%d.%d.%d",
14375              ((sc->devinfo.bc_ver >> 24) & 0xff),
14376              ((sc->devinfo.bc_ver >> 16) & 0xff),
14377              ((sc->devinfo.bc_ver >>  8) & 0xff));
14378     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
14379
14380     /* get the bootcode shmem address */
14381     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
14382     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
14383
14384     /* clean indirect addresses as they're not used */
14385     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
14386     if (IS_PF(sc)) {
14387         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
14388         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
14389         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
14390         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
14391         if (CHIP_IS_E1x(sc)) {
14392             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
14393             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
14394             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
14395             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
14396         }
14397
14398         /*
14399          * Enable internal target-read (in case we are probed after PF
14400          * FLR). Must be done prior to any BAR read access. Only for
14401          * 57712 and up
14402          */
14403         if (!CHIP_IS_E1x(sc)) {
14404             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
14405         }
14406     }
14407
14408     /* get the nvram size */
14409     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
14410     sc->devinfo.flash_size =
14411         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
14412     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
14413
14414     /* get PCI capabilites */
14415     bxe_probe_pci_caps(sc);
14416
14417     bxe_set_power_state(sc, PCI_PM_D0);
14418
14419     /* get various configuration parameters from shmem */
14420     bxe_get_shmem_info(sc);
14421
14422     if (sc->devinfo.pcie_msix_cap_reg != 0) {
14423         val = pci_read_config(sc->dev,
14424                               (sc->devinfo.pcie_msix_cap_reg +
14425                                PCIR_MSIX_CTRL),
14426                               2);
14427         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
14428     } else {
14429         sc->igu_sb_cnt = 1;
14430     }
14431
14432     sc->igu_base_addr = BAR_IGU_INTMEM;
14433
14434     /* initialize IGU parameters */
14435     if (CHIP_IS_E1x(sc)) {
14436         sc->devinfo.int_block = INT_BLOCK_HC;
14437         sc->igu_dsb_id = DEF_SB_IGU_ID;
14438         sc->igu_base_sb = 0;
14439     } else {
14440         sc->devinfo.int_block = INT_BLOCK_IGU;
14441
14442         /* do not allow device reset during IGU info preocessing */
14443         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14444
14445         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
14446
14447         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
14448             int tout = 5000;
14449
14450             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
14451
14452             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
14453             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
14454             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
14455
14456             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14457                 tout--;
14458                 DELAY(1000);
14459             }
14460
14461             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14462                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
14463                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14464                 return (-1);
14465             }
14466         }
14467
14468         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
14469             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
14470             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
14471         } else {
14472             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
14473         }
14474
14475         rc = bxe_get_igu_cam_info(sc);
14476
14477         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14478
14479         if (rc) {
14480             return (rc);
14481         }
14482     }
14483
14484     /*
14485      * Get base FW non-default (fast path) status block ID. This value is
14486      * used to initialize the fw_sb_id saved on the fp/queue structure to
14487      * determine the id used by the FW.
14488      */
14489     if (CHIP_IS_E1x(sc)) {
14490         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
14491     } else {
14492         /*
14493          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
14494          * the same queue are indicated on the same IGU SB). So we prefer
14495          * FW and IGU SBs to be the same value.
14496          */
14497         sc->base_fw_ndsb = sc->igu_base_sb;
14498     }
14499
14500     BLOGD(sc, DBG_LOAD,
14501           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
14502           sc->igu_dsb_id, sc->igu_base_sb,
14503           sc->igu_sb_cnt, sc->base_fw_ndsb);
14504
14505     elink_phy_probe(&sc->link_params);
14506
14507     return (0);
14508 }
14509
14510 static void
14511 bxe_link_settings_supported(struct bxe_softc *sc,
14512                             uint32_t         switch_cfg)
14513 {
14514     uint32_t cfg_size = 0;
14515     uint32_t idx;
14516     uint8_t port = SC_PORT(sc);
14517
14518     /* aggregation of supported attributes of all external phys */
14519     sc->port.supported[0] = 0;
14520     sc->port.supported[1] = 0;
14521
14522     switch (sc->link_params.num_phys) {
14523     case 1:
14524         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
14525         cfg_size = 1;
14526         break;
14527     case 2:
14528         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
14529         cfg_size = 1;
14530         break;
14531     case 3:
14532         if (sc->link_params.multi_phy_config &
14533             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
14534             sc->port.supported[1] =
14535                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14536             sc->port.supported[0] =
14537                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14538         } else {
14539             sc->port.supported[0] =
14540                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14541             sc->port.supported[1] =
14542                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14543         }
14544         cfg_size = 2;
14545         break;
14546     }
14547
14548     if (!(sc->port.supported[0] || sc->port.supported[1])) {
14549         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14550               SHMEM_RD(sc,
14551                        dev_info.port_hw_config[port].external_phy_config),
14552               SHMEM_RD(sc,
14553                        dev_info.port_hw_config[port].external_phy_config2));
14554         return;
14555     }
14556
14557     if (CHIP_IS_E3(sc))
14558         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14559     else {
14560         switch (switch_cfg) {
14561         case ELINK_SWITCH_CFG_1G:
14562             sc->port.phy_addr =
14563                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14564             break;
14565         case ELINK_SWITCH_CFG_10G:
14566             sc->port.phy_addr =
14567                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14568             break;
14569         default:
14570             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14571                   sc->port.link_config[0]);
14572             return;
14573         }
14574     }
14575
14576     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14577
14578     /* mask what we support according to speed_cap_mask per configuration */
14579     for (idx = 0; idx < cfg_size; idx++) {
14580         if (!(sc->link_params.speed_cap_mask[idx] &
14581               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14582             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14583         }
14584
14585         if (!(sc->link_params.speed_cap_mask[idx] &
14586               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14587             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14588         }
14589
14590         if (!(sc->link_params.speed_cap_mask[idx] &
14591               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14592             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14593         }
14594
14595         if (!(sc->link_params.speed_cap_mask[idx] &
14596               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14597             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14598         }
14599
14600         if (!(sc->link_params.speed_cap_mask[idx] &
14601               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14602             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14603         }
14604
14605         if (!(sc->link_params.speed_cap_mask[idx] &
14606               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14607             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14608         }
14609
14610         if (!(sc->link_params.speed_cap_mask[idx] &
14611               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14612             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14613         }
14614
14615         if (!(sc->link_params.speed_cap_mask[idx] &
14616               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14617             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14618         }
14619     }
14620
14621     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14622           sc->port.supported[0], sc->port.supported[1]);
14623 }
14624
14625 static void
14626 bxe_link_settings_requested(struct bxe_softc *sc)
14627 {
14628     uint32_t link_config;
14629     uint32_t idx;
14630     uint32_t cfg_size = 0;
14631
14632     sc->port.advertising[0] = 0;
14633     sc->port.advertising[1] = 0;
14634
14635     switch (sc->link_params.num_phys) {
14636     case 1:
14637     case 2:
14638         cfg_size = 1;
14639         break;
14640     case 3:
14641         cfg_size = 2;
14642         break;
14643     }
14644
14645     for (idx = 0; idx < cfg_size; idx++) {
14646         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14647         link_config = sc->port.link_config[idx];
14648
14649         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14650         case PORT_FEATURE_LINK_SPEED_AUTO:
14651             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14652                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14653                 sc->port.advertising[idx] |= sc->port.supported[idx];
14654                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14655                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14656                     sc->port.advertising[idx] |=
14657                         (ELINK_SUPPORTED_100baseT_Half |
14658                          ELINK_SUPPORTED_100baseT_Full);
14659             } else {
14660                 /* force 10G, no AN */
14661                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14662                 sc->port.advertising[idx] |=
14663                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14664                 continue;
14665             }
14666             break;
14667
14668         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14669             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14670                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14671                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14672                                               ADVERTISED_TP);
14673             } else {
14674                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14675                           "speed_cap_mask=0x%08x\n",
14676                       link_config, sc->link_params.speed_cap_mask[idx]);
14677                 return;
14678             }
14679             break;
14680
14681         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14682             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14683                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14684                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14685                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14686                                               ADVERTISED_TP);
14687             } else {
14688                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14689                           "speed_cap_mask=0x%08x\n",
14690                       link_config, sc->link_params.speed_cap_mask[idx]);
14691                 return;
14692             }
14693             break;
14694
14695         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14696             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14697                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14698                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14699                                               ADVERTISED_TP);
14700             } else {
14701                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14702                           "speed_cap_mask=0x%08x\n",
14703                       link_config, sc->link_params.speed_cap_mask[idx]);
14704                 return;
14705             }
14706             break;
14707
14708         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14709             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14710                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14711                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14712                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14713                                               ADVERTISED_TP);
14714             } else {
14715                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14716                           "speed_cap_mask=0x%08x\n",
14717                       link_config, sc->link_params.speed_cap_mask[idx]);
14718                 return;
14719             }
14720             break;
14721
14722         case PORT_FEATURE_LINK_SPEED_1G:
14723             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14724                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14725                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14726                                               ADVERTISED_TP);
14727             } else {
14728                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14729                           "speed_cap_mask=0x%08x\n",
14730                       link_config, sc->link_params.speed_cap_mask[idx]);
14731                 return;
14732             }
14733             break;
14734
14735         case PORT_FEATURE_LINK_SPEED_2_5G:
14736             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14737                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14738                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14739                                               ADVERTISED_TP);
14740             } else {
14741                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14742                           "speed_cap_mask=0x%08x\n",
14743                       link_config, sc->link_params.speed_cap_mask[idx]);
14744                 return;
14745             }
14746             break;
14747
14748         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14749             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14750                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14751                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14752                                               ADVERTISED_FIBRE);
14753             } else {
14754                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14755                           "speed_cap_mask=0x%08x\n",
14756                       link_config, sc->link_params.speed_cap_mask[idx]);
14757                 return;
14758             }
14759             break;
14760
14761         case PORT_FEATURE_LINK_SPEED_20G:
14762             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14763             break;
14764
14765         default:
14766             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14767                       "speed_cap_mask=0x%08x\n",
14768                   link_config, sc->link_params.speed_cap_mask[idx]);
14769             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14770             sc->port.advertising[idx] = sc->port.supported[idx];
14771             break;
14772         }
14773
14774         sc->link_params.req_flow_ctrl[idx] =
14775             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14776
14777         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14778             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14779                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14780             } else {
14781                 bxe_set_requested_fc(sc);
14782             }
14783         }
14784
14785         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14786                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14787               sc->link_params.req_line_speed[idx],
14788               sc->link_params.req_duplex[idx],
14789               sc->link_params.req_flow_ctrl[idx],
14790               sc->port.advertising[idx]);
14791     }
14792 }
14793
14794 static void
14795 bxe_get_phy_info(struct bxe_softc *sc)
14796 {
14797     uint8_t port = SC_PORT(sc);
14798     uint32_t config = sc->port.config;
14799     uint32_t eee_mode;
14800
14801     /* shmem data already read in bxe_get_shmem_info() */
14802
14803     BLOGD(sc, DBG_LOAD, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14804                         "link_config0=0x%08x\n",
14805                sc->link_params.lane_config,
14806                sc->link_params.speed_cap_mask[0],
14807                sc->port.link_config[0]);
14808
14809     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14810     bxe_link_settings_requested(sc);
14811
14812     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14813         sc->link_params.feature_config_flags |=
14814             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14815     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14816         sc->link_params.feature_config_flags &=
14817             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14818     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14819         sc->link_params.feature_config_flags |=
14820             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14821     }
14822
14823     /* configure link feature according to nvram value */
14824     eee_mode =
14825         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14826           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14827          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14828     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14829         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14830                                     ELINK_EEE_MODE_ENABLE_LPI |
14831                                     ELINK_EEE_MODE_OUTPUT_TIME);
14832     } else {
14833         sc->link_params.eee_mode = 0;
14834     }
14835
14836     /* get the media type */
14837     bxe_media_detect(sc);
14838 }
14839
14840 static void
14841 bxe_get_params(struct bxe_softc *sc)
14842 {
14843     /* get user tunable params */
14844     bxe_get_tunable_params(sc);
14845
14846     /* select the RX and TX ring sizes */
14847     sc->tx_ring_size = TX_BD_USABLE;
14848     sc->rx_ring_size = RX_BD_USABLE;
14849
14850     /* XXX disable WoL */
14851     sc->wol = 0;
14852 }
14853
14854 static void
14855 bxe_set_modes_bitmap(struct bxe_softc *sc)
14856 {
14857     uint32_t flags = 0;
14858
14859     if (CHIP_REV_IS_FPGA(sc)) {
14860         SET_FLAGS(flags, MODE_FPGA);
14861     } else if (CHIP_REV_IS_EMUL(sc)) {
14862         SET_FLAGS(flags, MODE_EMUL);
14863     } else {
14864         SET_FLAGS(flags, MODE_ASIC);
14865     }
14866
14867     if (CHIP_IS_MODE_4_PORT(sc)) {
14868         SET_FLAGS(flags, MODE_PORT4);
14869     } else {
14870         SET_FLAGS(flags, MODE_PORT2);
14871     }
14872
14873     if (CHIP_IS_E2(sc)) {
14874         SET_FLAGS(flags, MODE_E2);
14875     } else if (CHIP_IS_E3(sc)) {
14876         SET_FLAGS(flags, MODE_E3);
14877         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14878             SET_FLAGS(flags, MODE_E3_A0);
14879         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14880             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14881         }
14882     }
14883
14884     if (IS_MF(sc)) {
14885         SET_FLAGS(flags, MODE_MF);
14886         switch (sc->devinfo.mf_info.mf_mode) {
14887         case MULTI_FUNCTION_SD:
14888             SET_FLAGS(flags, MODE_MF_SD);
14889             break;
14890         case MULTI_FUNCTION_SI:
14891             SET_FLAGS(flags, MODE_MF_SI);
14892             break;
14893         case MULTI_FUNCTION_AFEX:
14894             SET_FLAGS(flags, MODE_MF_AFEX);
14895             break;
14896         }
14897     } else {
14898         SET_FLAGS(flags, MODE_SF);
14899     }
14900
14901 #if defined(__LITTLE_ENDIAN)
14902     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14903 #else /* __BIG_ENDIAN */
14904     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14905 #endif
14906
14907     INIT_MODE_FLAGS(sc) = flags;
14908 }
14909
14910 static int
14911 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14912 {
14913     struct bxe_fastpath *fp;
14914     bus_addr_t busaddr;
14915     int max_agg_queues;
14916     int max_segments;
14917     bus_size_t max_size;
14918     bus_size_t max_seg_size;
14919     char buf[32];
14920     int rc;
14921     int i, j;
14922
14923     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14924
14925     /* allocate the parent bus DMA tag */
14926     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14927                             1,                        /* alignment */
14928                             0,                        /* boundary limit */
14929                             BUS_SPACE_MAXADDR,        /* restricted low */
14930                             BUS_SPACE_MAXADDR,        /* restricted hi */
14931                             NULL,                     /* addr filter() */
14932                             NULL,                     /* addr filter() arg */
14933                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14934                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14935                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14936                             0,                        /* flags */
14937                             NULL,                     /* lock() */
14938                             NULL,                     /* lock() arg */
14939                             &sc->parent_dma_tag);     /* returned dma tag */
14940     if (rc != 0) {
14941         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14942         return (1);
14943     }
14944
14945     /************************/
14946     /* DEFAULT STATUS BLOCK */
14947     /************************/
14948
14949     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14950                       &sc->def_sb_dma, "default status block") != 0) {
14951         /* XXX */
14952         bus_dma_tag_destroy(sc->parent_dma_tag);
14953         return (1);
14954     }
14955
14956     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14957
14958     /***************/
14959     /* EVENT QUEUE */
14960     /***************/
14961
14962     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14963                       &sc->eq_dma, "event queue") != 0) {
14964         /* XXX */
14965         bxe_dma_free(sc, &sc->def_sb_dma);
14966         sc->def_sb = NULL;
14967         bus_dma_tag_destroy(sc->parent_dma_tag);
14968         return (1);
14969     }
14970
14971     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14972
14973     /*************/
14974     /* SLOW PATH */
14975     /*************/
14976
14977     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14978                       &sc->sp_dma, "slow path") != 0) {
14979         /* XXX */
14980         bxe_dma_free(sc, &sc->eq_dma);
14981         sc->eq = NULL;
14982         bxe_dma_free(sc, &sc->def_sb_dma);
14983         sc->def_sb = NULL;
14984         bus_dma_tag_destroy(sc->parent_dma_tag);
14985         return (1);
14986     }
14987
14988     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14989
14990     /*******************/
14991     /* SLOW PATH QUEUE */
14992     /*******************/
14993
14994     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14995                       &sc->spq_dma, "slow path queue") != 0) {
14996         /* XXX */
14997         bxe_dma_free(sc, &sc->sp_dma);
14998         sc->sp = NULL;
14999         bxe_dma_free(sc, &sc->eq_dma);
15000         sc->eq = NULL;
15001         bxe_dma_free(sc, &sc->def_sb_dma);
15002         sc->def_sb = NULL;
15003         bus_dma_tag_destroy(sc->parent_dma_tag);
15004         return (1);
15005     }
15006
15007     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
15008
15009     /***************************/
15010     /* FW DECOMPRESSION BUFFER */
15011     /***************************/
15012
15013     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
15014                       "fw decompression buffer") != 0) {
15015         /* XXX */
15016         bxe_dma_free(sc, &sc->spq_dma);
15017         sc->spq = NULL;
15018         bxe_dma_free(sc, &sc->sp_dma);
15019         sc->sp = NULL;
15020         bxe_dma_free(sc, &sc->eq_dma);
15021         sc->eq = NULL;
15022         bxe_dma_free(sc, &sc->def_sb_dma);
15023         sc->def_sb = NULL;
15024         bus_dma_tag_destroy(sc->parent_dma_tag);
15025         return (1);
15026     }
15027
15028     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
15029
15030     if ((sc->gz_strm =
15031          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
15032         /* XXX */
15033         bxe_dma_free(sc, &sc->gz_buf_dma);
15034         sc->gz_buf = NULL;
15035         bxe_dma_free(sc, &sc->spq_dma);
15036         sc->spq = NULL;
15037         bxe_dma_free(sc, &sc->sp_dma);
15038         sc->sp = NULL;
15039         bxe_dma_free(sc, &sc->eq_dma);
15040         sc->eq = NULL;
15041         bxe_dma_free(sc, &sc->def_sb_dma);
15042         sc->def_sb = NULL;
15043         bus_dma_tag_destroy(sc->parent_dma_tag);
15044         return (1);
15045     }
15046
15047     /*************/
15048     /* FASTPATHS */
15049     /*************/
15050
15051     /* allocate DMA memory for each fastpath structure */
15052     for (i = 0; i < sc->num_queues; i++) {
15053         fp = &sc->fp[i];
15054         fp->sc    = sc;
15055         fp->index = i;
15056
15057         /*******************/
15058         /* FP STATUS BLOCK */
15059         /*******************/
15060
15061         snprintf(buf, sizeof(buf), "fp %d status block", i);
15062         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
15063                           &fp->sb_dma, buf) != 0) {
15064             /* XXX unwind and free previous fastpath allocations */
15065             BLOGE(sc, "Failed to alloc %s\n", buf);
15066             return (1);
15067         } else {
15068             if (CHIP_IS_E2E3(sc)) {
15069                 fp->status_block.e2_sb =
15070                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
15071             } else {
15072                 fp->status_block.e1x_sb =
15073                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
15074             }
15075         }
15076
15077         /******************/
15078         /* FP TX BD CHAIN */
15079         /******************/
15080
15081         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
15082         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
15083                           &fp->tx_dma, buf) != 0) {
15084             /* XXX unwind and free previous fastpath allocations */
15085             BLOGE(sc, "Failed to alloc %s\n", buf);
15086             return (1);
15087         } else {
15088             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
15089         }
15090
15091         /* link together the tx bd chain pages */
15092         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
15093             /* index into the tx bd chain array to last entry per page */
15094             struct eth_tx_next_bd *tx_next_bd =
15095                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
15096             /* point to the next page and wrap from last page */
15097             busaddr = (fp->tx_dma.paddr +
15098                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
15099             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
15100             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
15101         }
15102
15103         /******************/
15104         /* FP RX BD CHAIN */
15105         /******************/
15106
15107         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
15108         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
15109                           &fp->rx_dma, buf) != 0) {
15110             /* XXX unwind and free previous fastpath allocations */
15111             BLOGE(sc, "Failed to alloc %s\n", buf);
15112             return (1);
15113         } else {
15114             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
15115         }
15116
15117         /* link together the rx bd chain pages */
15118         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
15119             /* index into the rx bd chain array to last entry per page */
15120             struct eth_rx_bd *rx_bd =
15121                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
15122             /* point to the next page and wrap from last page */
15123             busaddr = (fp->rx_dma.paddr +
15124                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
15125             rx_bd->addr_hi = htole32(U64_HI(busaddr));
15126             rx_bd->addr_lo = htole32(U64_LO(busaddr));
15127         }
15128
15129         /*******************/
15130         /* FP RX RCQ CHAIN */
15131         /*******************/
15132
15133         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
15134         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
15135                           &fp->rcq_dma, buf) != 0) {
15136             /* XXX unwind and free previous fastpath allocations */
15137             BLOGE(sc, "Failed to alloc %s\n", buf);
15138             return (1);
15139         } else {
15140             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
15141         }
15142
15143         /* link together the rcq chain pages */
15144         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
15145             /* index into the rcq chain array to last entry per page */
15146             struct eth_rx_cqe_next_page *rx_cqe_next =
15147                 (struct eth_rx_cqe_next_page *)
15148                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
15149             /* point to the next page and wrap from last page */
15150             busaddr = (fp->rcq_dma.paddr +
15151                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
15152             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
15153             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
15154         }
15155
15156         /*******************/
15157         /* FP RX SGE CHAIN */
15158         /*******************/
15159
15160         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
15161         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
15162                           &fp->rx_sge_dma, buf) != 0) {
15163             /* XXX unwind and free previous fastpath allocations */
15164             BLOGE(sc, "Failed to alloc %s\n", buf);
15165             return (1);
15166         } else {
15167             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
15168         }
15169
15170         /* link together the sge chain pages */
15171         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
15172             /* index into the rcq chain array to last entry per page */
15173             struct eth_rx_sge *rx_sge =
15174                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
15175             /* point to the next page and wrap from last page */
15176             busaddr = (fp->rx_sge_dma.paddr +
15177                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
15178             rx_sge->addr_hi = htole32(U64_HI(busaddr));
15179             rx_sge->addr_lo = htole32(U64_LO(busaddr));
15180         }
15181
15182         /***********************/
15183         /* FP TX MBUF DMA MAPS */
15184         /***********************/
15185
15186         /* set required sizes before mapping to conserve resources */
15187         if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
15188             max_size     = BXE_TSO_MAX_SIZE;
15189             max_segments = BXE_TSO_MAX_SEGMENTS;
15190             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
15191         } else {
15192             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
15193             max_segments = BXE_MAX_SEGMENTS;
15194             max_seg_size = MCLBYTES;
15195         }
15196
15197         /* create a dma tag for the tx mbufs */
15198         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15199                                 1,                  /* alignment */
15200                                 0,                  /* boundary limit */
15201                                 BUS_SPACE_MAXADDR,  /* restricted low */
15202                                 BUS_SPACE_MAXADDR,  /* restricted hi */
15203                                 NULL,               /* addr filter() */
15204                                 NULL,               /* addr filter() arg */
15205                                 max_size,           /* max map size */
15206                                 max_segments,       /* num discontinuous */
15207                                 max_seg_size,       /* max seg size */
15208                                 0,                  /* flags */
15209                                 NULL,               /* lock() */
15210                                 NULL,               /* lock() arg */
15211                                 &fp->tx_mbuf_tag);  /* returned dma tag */
15212         if (rc != 0) {
15213             /* XXX unwind and free previous fastpath allocations */
15214             BLOGE(sc, "Failed to create dma tag for "
15215                       "'fp %d tx mbufs' (%d)\n",
15216                   i, rc);
15217             return (1);
15218         }
15219
15220         /* create dma maps for each of the tx mbuf clusters */
15221         for (j = 0; j < TX_BD_TOTAL; j++) {
15222             if (bus_dmamap_create(fp->tx_mbuf_tag,
15223                                   BUS_DMA_NOWAIT,
15224                                   &fp->tx_mbuf_chain[j].m_map)) {
15225                 /* XXX unwind and free previous fastpath allocations */
15226                 BLOGE(sc, "Failed to create dma map for "
15227                           "'fp %d tx mbuf %d' (%d)\n",
15228                       i, j, rc);
15229                 return (1);
15230             }
15231         }
15232
15233         /***********************/
15234         /* FP RX MBUF DMA MAPS */
15235         /***********************/
15236
15237         /* create a dma tag for the rx mbufs */
15238         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15239                                 1,                  /* alignment */
15240                                 0,                  /* boundary limit */
15241                                 BUS_SPACE_MAXADDR,  /* restricted low */
15242                                 BUS_SPACE_MAXADDR,  /* restricted hi */
15243                                 NULL,               /* addr filter() */
15244                                 NULL,               /* addr filter() arg */
15245                                 MJUM9BYTES,         /* max map size */
15246                                 1,                  /* num discontinuous */
15247                                 MJUM9BYTES,         /* max seg size */
15248                                 0,                  /* flags */
15249                                 NULL,               /* lock() */
15250                                 NULL,               /* lock() arg */
15251                                 &fp->rx_mbuf_tag);  /* returned dma tag */
15252         if (rc != 0) {
15253             /* XXX unwind and free previous fastpath allocations */
15254             BLOGE(sc, "Failed to create dma tag for "
15255                       "'fp %d rx mbufs' (%d)\n",
15256                   i, rc);
15257             return (1);
15258         }
15259
15260         /* create dma maps for each of the rx mbuf clusters */
15261         for (j = 0; j < RX_BD_TOTAL; j++) {
15262             if (bus_dmamap_create(fp->rx_mbuf_tag,
15263                                   BUS_DMA_NOWAIT,
15264                                   &fp->rx_mbuf_chain[j].m_map)) {
15265                 /* XXX unwind and free previous fastpath allocations */
15266                 BLOGE(sc, "Failed to create dma map for "
15267                           "'fp %d rx mbuf %d' (%d)\n",
15268                       i, j, rc);
15269                 return (1);
15270             }
15271         }
15272
15273         /* create dma map for the spare rx mbuf cluster */
15274         if (bus_dmamap_create(fp->rx_mbuf_tag,
15275                               BUS_DMA_NOWAIT,
15276                               &fp->rx_mbuf_spare_map)) {
15277             /* XXX unwind and free previous fastpath allocations */
15278             BLOGE(sc, "Failed to create dma map for "
15279                       "'fp %d spare rx mbuf' (%d)\n",
15280                   i, rc);
15281             return (1);
15282         }
15283
15284         /***************************/
15285         /* FP RX SGE MBUF DMA MAPS */
15286         /***************************/
15287
15288         /* create a dma tag for the rx sge mbufs */
15289         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15290                                 1,                  /* alignment */
15291                                 0,                  /* boundary limit */
15292                                 BUS_SPACE_MAXADDR,  /* restricted low */
15293                                 BUS_SPACE_MAXADDR,  /* restricted hi */
15294                                 NULL,               /* addr filter() */
15295                                 NULL,               /* addr filter() arg */
15296                                 BCM_PAGE_SIZE,      /* max map size */
15297                                 1,                  /* num discontinuous */
15298                                 BCM_PAGE_SIZE,      /* max seg size */
15299                                 0,                  /* flags */
15300                                 NULL,               /* lock() */
15301                                 NULL,               /* lock() arg */
15302                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
15303         if (rc != 0) {
15304             /* XXX unwind and free previous fastpath allocations */
15305             BLOGE(sc, "Failed to create dma tag for "
15306                       "'fp %d rx sge mbufs' (%d)\n",
15307                   i, rc);
15308             return (1);
15309         }
15310
15311         /* create dma maps for the rx sge mbuf clusters */
15312         for (j = 0; j < RX_SGE_TOTAL; j++) {
15313             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
15314                                   BUS_DMA_NOWAIT,
15315                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
15316                 /* XXX unwind and free previous fastpath allocations */
15317                 BLOGE(sc, "Failed to create dma map for "
15318                           "'fp %d rx sge mbuf %d' (%d)\n",
15319                       i, j, rc);
15320                 return (1);
15321             }
15322         }
15323
15324         /* create dma map for the spare rx sge mbuf cluster */
15325         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
15326                               BUS_DMA_NOWAIT,
15327                               &fp->rx_sge_mbuf_spare_map)) {
15328             /* XXX unwind and free previous fastpath allocations */
15329             BLOGE(sc, "Failed to create dma map for "
15330                       "'fp %d spare rx sge mbuf' (%d)\n",
15331                   i, rc);
15332             return (1);
15333         }
15334
15335         /***************************/
15336         /* FP RX TPA MBUF DMA MAPS */
15337         /***************************/
15338
15339         /* create dma maps for the rx tpa mbuf clusters */
15340         max_agg_queues = MAX_AGG_QS(sc);
15341
15342         for (j = 0; j < max_agg_queues; j++) {
15343             if (bus_dmamap_create(fp->rx_mbuf_tag,
15344                                   BUS_DMA_NOWAIT,
15345                                   &fp->rx_tpa_info[j].bd.m_map)) {
15346                 /* XXX unwind and free previous fastpath allocations */
15347                 BLOGE(sc, "Failed to create dma map for "
15348                           "'fp %d rx tpa mbuf %d' (%d)\n",
15349                       i, j, rc);
15350                 return (1);
15351             }
15352         }
15353
15354         /* create dma map for the spare rx tpa mbuf cluster */
15355         if (bus_dmamap_create(fp->rx_mbuf_tag,
15356                               BUS_DMA_NOWAIT,
15357                               &fp->rx_tpa_info_mbuf_spare_map)) {
15358             /* XXX unwind and free previous fastpath allocations */
15359             BLOGE(sc, "Failed to create dma map for "
15360                       "'fp %d spare rx tpa mbuf' (%d)\n",
15361                   i, rc);
15362             return (1);
15363         }
15364
15365         bxe_init_sge_ring_bit_mask(fp);
15366     }
15367
15368     return (0);
15369 }
15370
15371 static void
15372 bxe_free_hsi_mem(struct bxe_softc *sc)
15373 {
15374     struct bxe_fastpath *fp;
15375     int max_agg_queues;
15376     int i, j;
15377
15378     if (sc->parent_dma_tag == NULL) {
15379         return; /* assume nothing was allocated */
15380     }
15381
15382     for (i = 0; i < sc->num_queues; i++) {
15383         fp = &sc->fp[i];
15384
15385         /*******************/
15386         /* FP STATUS BLOCK */
15387         /*******************/
15388
15389         bxe_dma_free(sc, &fp->sb_dma);
15390         memset(&fp->status_block, 0, sizeof(fp->status_block));
15391
15392         /******************/
15393         /* FP TX BD CHAIN */
15394         /******************/
15395
15396         bxe_dma_free(sc, &fp->tx_dma);
15397         fp->tx_chain = NULL;
15398
15399         /******************/
15400         /* FP RX BD CHAIN */
15401         /******************/
15402
15403         bxe_dma_free(sc, &fp->rx_dma);
15404         fp->rx_chain = NULL;
15405
15406         /*******************/
15407         /* FP RX RCQ CHAIN */
15408         /*******************/
15409
15410         bxe_dma_free(sc, &fp->rcq_dma);
15411         fp->rcq_chain = NULL;
15412
15413         /*******************/
15414         /* FP RX SGE CHAIN */
15415         /*******************/
15416
15417         bxe_dma_free(sc, &fp->rx_sge_dma);
15418         fp->rx_sge_chain = NULL;
15419
15420         /***********************/
15421         /* FP TX MBUF DMA MAPS */
15422         /***********************/
15423
15424         if (fp->tx_mbuf_tag != NULL) {
15425             for (j = 0; j < TX_BD_TOTAL; j++) {
15426                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
15427                     bus_dmamap_unload(fp->tx_mbuf_tag,
15428                                       fp->tx_mbuf_chain[j].m_map);
15429                     bus_dmamap_destroy(fp->tx_mbuf_tag,
15430                                        fp->tx_mbuf_chain[j].m_map);
15431                 }
15432             }
15433
15434             bus_dma_tag_destroy(fp->tx_mbuf_tag);
15435             fp->tx_mbuf_tag = NULL;
15436         }
15437
15438         /***********************/
15439         /* FP RX MBUF DMA MAPS */
15440         /***********************/
15441
15442         if (fp->rx_mbuf_tag != NULL) {
15443             for (j = 0; j < RX_BD_TOTAL; j++) {
15444                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
15445                     bus_dmamap_unload(fp->rx_mbuf_tag,
15446                                       fp->rx_mbuf_chain[j].m_map);
15447                     bus_dmamap_destroy(fp->rx_mbuf_tag,
15448                                        fp->rx_mbuf_chain[j].m_map);
15449                 }
15450             }
15451
15452             if (fp->rx_mbuf_spare_map != NULL) {
15453                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
15454                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
15455             }
15456
15457             /***************************/
15458             /* FP RX TPA MBUF DMA MAPS */
15459             /***************************/
15460
15461             max_agg_queues = MAX_AGG_QS(sc);
15462
15463             for (j = 0; j < max_agg_queues; j++) {
15464                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
15465                     bus_dmamap_unload(fp->rx_mbuf_tag,
15466                                       fp->rx_tpa_info[j].bd.m_map);
15467                     bus_dmamap_destroy(fp->rx_mbuf_tag,
15468                                        fp->rx_tpa_info[j].bd.m_map);
15469                 }
15470             }
15471
15472             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
15473                 bus_dmamap_unload(fp->rx_mbuf_tag,
15474                                   fp->rx_tpa_info_mbuf_spare_map);
15475                 bus_dmamap_destroy(fp->rx_mbuf_tag,
15476                                    fp->rx_tpa_info_mbuf_spare_map);
15477             }
15478
15479             bus_dma_tag_destroy(fp->rx_mbuf_tag);
15480             fp->rx_mbuf_tag = NULL;
15481         }
15482
15483         /***************************/
15484         /* FP RX SGE MBUF DMA MAPS */
15485         /***************************/
15486
15487         if (fp->rx_sge_mbuf_tag != NULL) {
15488             for (j = 0; j < RX_SGE_TOTAL; j++) {
15489                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
15490                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15491                                       fp->rx_sge_mbuf_chain[j].m_map);
15492                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15493                                        fp->rx_sge_mbuf_chain[j].m_map);
15494                 }
15495             }
15496
15497             if (fp->rx_sge_mbuf_spare_map != NULL) {
15498                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15499                                   fp->rx_sge_mbuf_spare_map);
15500                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15501                                    fp->rx_sge_mbuf_spare_map);
15502             }
15503
15504             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
15505             fp->rx_sge_mbuf_tag = NULL;
15506         }
15507     }
15508
15509     /***************************/
15510     /* FW DECOMPRESSION BUFFER */
15511     /***************************/
15512
15513     bxe_dma_free(sc, &sc->gz_buf_dma);
15514     sc->gz_buf = NULL;
15515     free(sc->gz_strm, M_DEVBUF);
15516     sc->gz_strm = NULL;
15517
15518     /*******************/
15519     /* SLOW PATH QUEUE */
15520     /*******************/
15521
15522     bxe_dma_free(sc, &sc->spq_dma);
15523     sc->spq = NULL;
15524
15525     /*************/
15526     /* SLOW PATH */
15527     /*************/
15528
15529     bxe_dma_free(sc, &sc->sp_dma);
15530     sc->sp = NULL;
15531
15532     /***************/
15533     /* EVENT QUEUE */
15534     /***************/
15535
15536     bxe_dma_free(sc, &sc->eq_dma);
15537     sc->eq = NULL;
15538
15539     /************************/
15540     /* DEFAULT STATUS BLOCK */
15541     /************************/
15542
15543     bxe_dma_free(sc, &sc->def_sb_dma);
15544     sc->def_sb = NULL;
15545
15546     bus_dma_tag_destroy(sc->parent_dma_tag);
15547     sc->parent_dma_tag = NULL;
15548 }
15549
15550 /*
15551  * Previous driver DMAE transaction may have occurred when pre-boot stage
15552  * ended and boot began. This would invalidate the addresses of the
15553  * transaction, resulting in was-error bit set in the PCI causing all
15554  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15555  * the interrupt which detected this from the pglueb and the was-done bit
15556  */
15557 static void
15558 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15559 {
15560     uint32_t val;
15561
15562     if (!CHIP_IS_E1x(sc)) {
15563         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15564         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15565             BLOGD(sc, DBG_LOAD,
15566                   "Clearing 'was-error' bit that was set in pglueb");
15567             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15568         }
15569     }
15570 }
15571
15572 static int
15573 bxe_prev_mcp_done(struct bxe_softc *sc)
15574 {
15575     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15576                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15577     if (!rc) {
15578         BLOGE(sc, "MCP response failure, aborting\n");
15579         return (-1);
15580     }
15581
15582     return (0);
15583 }
15584
15585 static struct bxe_prev_list_node *
15586 bxe_prev_path_get_entry(struct bxe_softc *sc)
15587 {
15588     struct bxe_prev_list_node *tmp;
15589
15590     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15591         if ((sc->pcie_bus == tmp->bus) &&
15592             (sc->pcie_device == tmp->slot) &&
15593             (SC_PATH(sc) == tmp->path)) {
15594             return (tmp);
15595         }
15596     }
15597
15598     return (NULL);
15599 }
15600
15601 static uint8_t
15602 bxe_prev_is_path_marked(struct bxe_softc *sc)
15603 {
15604     struct bxe_prev_list_node *tmp;
15605     int rc = FALSE;
15606
15607     mtx_lock(&bxe_prev_mtx);
15608
15609     tmp = bxe_prev_path_get_entry(sc);
15610     if (tmp) {
15611         if (tmp->aer) {
15612             BLOGD(sc, DBG_LOAD,
15613                   "Path %d/%d/%d was marked by AER\n",
15614                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15615         } else {
15616             rc = TRUE;
15617             BLOGD(sc, DBG_LOAD,
15618                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15619                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15620         }
15621     }
15622
15623     mtx_unlock(&bxe_prev_mtx);
15624
15625     return (rc);
15626 }
15627
15628 static int
15629 bxe_prev_mark_path(struct bxe_softc *sc,
15630                    uint8_t          after_undi)
15631 {
15632     struct bxe_prev_list_node *tmp;
15633
15634     mtx_lock(&bxe_prev_mtx);
15635
15636     /* Check whether the entry for this path already exists */
15637     tmp = bxe_prev_path_get_entry(sc);
15638     if (tmp) {
15639         if (!tmp->aer) {
15640             BLOGD(sc, DBG_LOAD,
15641                   "Re-marking AER in path %d/%d/%d\n",
15642                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15643         } else {
15644             BLOGD(sc, DBG_LOAD,
15645                   "Removing AER indication from path %d/%d/%d\n",
15646                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15647             tmp->aer = 0;
15648         }
15649
15650         mtx_unlock(&bxe_prev_mtx);
15651         return (0);
15652     }
15653
15654     mtx_unlock(&bxe_prev_mtx);
15655
15656     /* Create an entry for this path and add it */
15657     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15658                  (M_NOWAIT | M_ZERO));
15659     if (!tmp) {
15660         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15661         return (-1);
15662     }
15663
15664     tmp->bus  = sc->pcie_bus;
15665     tmp->slot = sc->pcie_device;
15666     tmp->path = SC_PATH(sc);
15667     tmp->aer  = 0;
15668     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15669
15670     mtx_lock(&bxe_prev_mtx);
15671
15672     BLOGD(sc, DBG_LOAD,
15673           "Marked path %d/%d/%d - finished previous unload\n",
15674           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15675     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15676
15677     mtx_unlock(&bxe_prev_mtx);
15678
15679     return (0);
15680 }
15681
15682 static int
15683 bxe_do_flr(struct bxe_softc *sc)
15684 {
15685     int i;
15686
15687     /* only E2 and onwards support FLR */
15688     if (CHIP_IS_E1x(sc)) {
15689         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15690         return (-1);
15691     }
15692
15693     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15694     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15695         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15696               sc->devinfo.bc_ver);
15697         return (-1);
15698     }
15699
15700     /* Wait for Transaction Pending bit clean */
15701     for (i = 0; i < 4; i++) {
15702         if (i) {
15703             DELAY(((1 << (i - 1)) * 100) * 1000);
15704         }
15705
15706         if (!bxe_is_pcie_pending(sc)) {
15707             goto clear;
15708         }
15709     }
15710
15711     BLOGE(sc, "PCIE transaction is not cleared, "
15712               "proceeding with reset anyway\n");
15713
15714 clear:
15715
15716     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15717     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15718
15719     return (0);
15720 }
15721
15722 struct bxe_mac_vals {
15723     uint32_t xmac_addr;
15724     uint32_t xmac_val;
15725     uint32_t emac_addr;
15726     uint32_t emac_val;
15727     uint32_t umac_addr;
15728     uint32_t umac_val;
15729     uint32_t bmac_addr;
15730     uint32_t bmac_val[2];
15731 };
15732
15733 static void
15734 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15735                           struct bxe_mac_vals *vals)
15736 {
15737     uint32_t val, base_addr, offset, mask, reset_reg;
15738     uint8_t mac_stopped = FALSE;
15739     uint8_t port = SC_PORT(sc);
15740     uint32_t wb_data[2];
15741
15742     /* reset addresses as they also mark which values were changed */
15743     vals->bmac_addr = 0;
15744     vals->umac_addr = 0;
15745     vals->xmac_addr = 0;
15746     vals->emac_addr = 0;
15747
15748     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15749
15750     if (!CHIP_IS_E3(sc)) {
15751         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15752         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15753         if ((mask & reset_reg) && val) {
15754             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15755             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15756                                     : NIG_REG_INGRESS_BMAC0_MEM;
15757             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15758                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15759
15760             /*
15761              * use rd/wr since we cannot use dmae. This is safe
15762              * since MCP won't access the bus due to the request
15763              * to unload, and no function on the path can be
15764              * loaded at this time.
15765              */
15766             wb_data[0] = REG_RD(sc, base_addr + offset);
15767             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15768             vals->bmac_addr = base_addr + offset;
15769             vals->bmac_val[0] = wb_data[0];
15770             vals->bmac_val[1] = wb_data[1];
15771             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15772             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15773             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15774         }
15775
15776         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15777         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15778         vals->emac_val = REG_RD(sc, vals->emac_addr);
15779         REG_WR(sc, vals->emac_addr, 0);
15780         mac_stopped = TRUE;
15781     } else {
15782         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15783             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15784             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15785             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15786             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15787             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15788             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15789             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15790             REG_WR(sc, vals->xmac_addr, 0);
15791             mac_stopped = TRUE;
15792         }
15793
15794         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15795         if (mask & reset_reg) {
15796             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15797             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15798             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15799             vals->umac_val = REG_RD(sc, vals->umac_addr);
15800             REG_WR(sc, vals->umac_addr, 0);
15801             mac_stopped = TRUE;
15802         }
15803     }
15804
15805     if (mac_stopped) {
15806         DELAY(20000);
15807     }
15808 }
15809
15810 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15811 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15812 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15813 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15814
15815 static void
15816 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15817                          uint8_t          port,
15818                          uint8_t          inc)
15819 {
15820     uint16_t rcq, bd;
15821     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15822
15823     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15824     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15825
15826     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15827     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15828
15829     BLOGD(sc, DBG_LOAD,
15830           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15831           port, bd, rcq);
15832 }
15833
15834 static int
15835 bxe_prev_unload_common(struct bxe_softc *sc)
15836 {
15837     uint32_t reset_reg, tmp_reg = 0, rc;
15838     uint8_t prev_undi = FALSE;
15839     struct bxe_mac_vals mac_vals;
15840     uint32_t timer_count = 1000;
15841     uint32_t prev_brb;
15842
15843     /*
15844      * It is possible a previous function received 'common' answer,
15845      * but hasn't loaded yet, therefore creating a scenario of
15846      * multiple functions receiving 'common' on the same path.
15847      */
15848     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15849
15850     memset(&mac_vals, 0, sizeof(mac_vals));
15851
15852     if (bxe_prev_is_path_marked(sc)) {
15853         return (bxe_prev_mcp_done(sc));
15854     }
15855
15856     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15857
15858     /* Reset should be performed after BRB is emptied */
15859     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15860         /* Close the MAC Rx to prevent BRB from filling up */
15861         bxe_prev_unload_close_mac(sc, &mac_vals);
15862
15863         /* close LLH filters towards the BRB */
15864         elink_set_rx_filter(&sc->link_params, 0);
15865
15866         /*
15867          * Check if the UNDI driver was previously loaded.
15868          * UNDI driver initializes CID offset for normal bell to 0x7
15869          */
15870         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15871             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15872             if (tmp_reg == 0x7) {
15873                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15874                 prev_undi = TRUE;
15875                 /* clear the UNDI indication */
15876                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15877                 /* clear possible idle check errors */
15878                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15879             }
15880         }
15881
15882         /* wait until BRB is empty */
15883         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15884         while (timer_count) {
15885             prev_brb = tmp_reg;
15886
15887             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15888             if (!tmp_reg) {
15889                 break;
15890             }
15891
15892             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15893
15894             /* reset timer as long as BRB actually gets emptied */
15895             if (prev_brb > tmp_reg) {
15896                 timer_count = 1000;
15897             } else {
15898                 timer_count--;
15899             }
15900
15901             /* If UNDI resides in memory, manually increment it */
15902             if (prev_undi) {
15903                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15904             }
15905
15906             DELAY(10);
15907         }
15908
15909         if (!timer_count) {
15910             BLOGE(sc, "Failed to empty BRB\n");
15911         }
15912     }
15913
15914     /* No packets are in the pipeline, path is ready for reset */
15915     bxe_reset_common(sc);
15916
15917     if (mac_vals.xmac_addr) {
15918         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15919     }
15920     if (mac_vals.umac_addr) {
15921         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15922     }
15923     if (mac_vals.emac_addr) {
15924         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15925     }
15926     if (mac_vals.bmac_addr) {
15927         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15928         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15929     }
15930
15931     rc = bxe_prev_mark_path(sc, prev_undi);
15932     if (rc) {
15933         bxe_prev_mcp_done(sc);
15934         return (rc);
15935     }
15936
15937     return (bxe_prev_mcp_done(sc));
15938 }
15939
15940 static int
15941 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15942 {
15943     int rc;
15944
15945     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15946
15947     /* Test if previous unload process was already finished for this path */
15948     if (bxe_prev_is_path_marked(sc)) {
15949         return (bxe_prev_mcp_done(sc));
15950     }
15951
15952     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15953
15954     /*
15955      * If function has FLR capabilities, and existing FW version matches
15956      * the one required, then FLR will be sufficient to clean any residue
15957      * left by previous driver
15958      */
15959     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15960     if (!rc) {
15961         /* fw version is good */
15962         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15963         rc = bxe_do_flr(sc);
15964     }
15965
15966     if (!rc) {
15967         /* FLR was performed */
15968         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15969         return (0);
15970     }
15971
15972     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15973
15974     /* Close the MCP request, return failure*/
15975     rc = bxe_prev_mcp_done(sc);
15976     if (!rc) {
15977         rc = BXE_PREV_WAIT_NEEDED;
15978     }
15979
15980     return (rc);
15981 }
15982
15983 static int
15984 bxe_prev_unload(struct bxe_softc *sc)
15985 {
15986     int time_counter = 10;
15987     uint32_t fw, hw_lock_reg, hw_lock_val;
15988     uint32_t rc = 0;
15989
15990     /*
15991      * Clear HW from errors which may have resulted from an interrupted
15992      * DMAE transaction.
15993      */
15994     bxe_prev_interrupted_dmae(sc);
15995
15996     /* Release previously held locks */
15997     hw_lock_reg =
15998         (SC_FUNC(sc) <= 5) ?
15999             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
16000             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
16001
16002     hw_lock_val = (REG_RD(sc, hw_lock_reg));
16003     if (hw_lock_val) {
16004         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
16005             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
16006             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
16007                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
16008         }
16009         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
16010         REG_WR(sc, hw_lock_reg, 0xffffffff);
16011     } else {
16012         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
16013     }
16014
16015     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
16016         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
16017         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
16018     }
16019
16020     do {
16021         /* Lock MCP using an unload request */
16022         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
16023         if (!fw) {
16024             BLOGE(sc, "MCP response failure, aborting\n");
16025             rc = -1;
16026             break;
16027         }
16028
16029         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
16030             rc = bxe_prev_unload_common(sc);
16031             break;
16032         }
16033
16034         /* non-common reply from MCP night require looping */
16035         rc = bxe_prev_unload_uncommon(sc);
16036         if (rc != BXE_PREV_WAIT_NEEDED) {
16037             break;
16038         }
16039
16040         DELAY(20000);
16041     } while (--time_counter);
16042
16043     if (!time_counter || rc) {
16044         BLOGE(sc, "Failed to unload previous driver!\n");
16045         rc = -1;
16046     }
16047
16048     return (rc);
16049 }
16050
16051 void
16052 bxe_dcbx_set_state(struct bxe_softc *sc,
16053                    uint8_t          dcb_on,
16054                    uint32_t         dcbx_enabled)
16055 {
16056     if (!CHIP_IS_E1x(sc)) {
16057         sc->dcb_state = dcb_on;
16058         sc->dcbx_enabled = dcbx_enabled;
16059     } else {
16060         sc->dcb_state = FALSE;
16061         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
16062     }
16063     BLOGD(sc, DBG_LOAD,
16064           "DCB state [%s:%s]\n",
16065           dcb_on ? "ON" : "OFF",
16066           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
16067           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
16068           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
16069           "on-chip with negotiation" : "invalid");
16070 }
16071
16072 /* must be called after sriov-enable */
16073 static int
16074 bxe_set_qm_cid_count(struct bxe_softc *sc)
16075 {
16076     int cid_count = BXE_L2_MAX_CID(sc);
16077
16078     if (IS_SRIOV(sc)) {
16079         cid_count += BXE_VF_CIDS;
16080     }
16081
16082     if (CNIC_SUPPORT(sc)) {
16083         cid_count += CNIC_CID_MAX;
16084     }
16085
16086     return (roundup(cid_count, QM_CID_ROUND));
16087 }
16088
16089 static void
16090 bxe_init_multi_cos(struct bxe_softc *sc)
16091 {
16092     int pri, cos;
16093
16094     uint32_t pri_map = 0; /* XXX change to user config */
16095
16096     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
16097         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
16098         if (cos < sc->max_cos) {
16099             sc->prio_to_cos[pri] = cos;
16100         } else {
16101             BLOGW(sc, "Invalid COS %d for priority %d "
16102                       "(max COS is %d), setting to 0\n",
16103                   cos, pri, (sc->max_cos - 1));
16104             sc->prio_to_cos[pri] = 0;
16105         }
16106     }
16107 }
16108
16109 static int
16110 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
16111 {
16112     struct bxe_softc *sc;
16113     int error, result;
16114
16115     result = 0;
16116     error = sysctl_handle_int(oidp, &result, 0, req);
16117
16118     if (error || !req->newptr) {
16119         return (error);
16120     }
16121
16122     if (result == 1) {
16123         sc = (struct bxe_softc *)arg1;
16124         BLOGI(sc, "... dumping driver state ...\n");
16125         /* XXX */
16126     }
16127
16128     return (error);
16129 }
16130
16131 static int
16132 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
16133 {
16134     struct bxe_softc *sc = (struct bxe_softc *)arg1;
16135     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
16136     uint32_t *offset;
16137     uint64_t value = 0;
16138     int index = (int)arg2;
16139
16140     if (index >= BXE_NUM_ETH_STATS) {
16141         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
16142         return (-1);
16143     }
16144
16145     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
16146
16147     switch (bxe_eth_stats_arr[index].size) {
16148     case 4:
16149         value = (uint64_t)*offset;
16150         break;
16151     case 8:
16152         value = HILO_U64(*offset, *(offset + 1));
16153         break;
16154     default:
16155         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
16156               index, bxe_eth_stats_arr[index].size);
16157         return (-1);
16158     }
16159
16160     return (sysctl_handle_64(oidp, &value, 0, req));
16161 }
16162
16163 static int
16164 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
16165 {
16166     struct bxe_softc *sc = (struct bxe_softc *)arg1;
16167     uint32_t *eth_stats;
16168     uint32_t *offset;
16169     uint64_t value = 0;
16170     uint32_t q_stat = (uint32_t)arg2;
16171     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
16172     uint32_t index = (q_stat & 0xffff);
16173
16174     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
16175
16176     if (index >= BXE_NUM_ETH_Q_STATS) {
16177         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
16178         return (-1);
16179     }
16180
16181     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
16182
16183     switch (bxe_eth_q_stats_arr[index].size) {
16184     case 4:
16185         value = (uint64_t)*offset;
16186         break;
16187     case 8:
16188         value = HILO_U64(*offset, *(offset + 1));
16189         break;
16190     default:
16191         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
16192               index, bxe_eth_q_stats_arr[index].size);
16193         return (-1);
16194     }
16195
16196     return (sysctl_handle_64(oidp, &value, 0, req));
16197 }
16198
16199 static void
16200 bxe_add_sysctls(struct bxe_softc *sc)
16201 {
16202     struct sysctl_ctx_list *ctx;
16203     struct sysctl_oid_list *children;
16204     struct sysctl_oid *queue_top, *queue;
16205     struct sysctl_oid_list *queue_top_children, *queue_children;
16206     char queue_num_buf[32];
16207     uint32_t q_stat;
16208     int i, j;
16209
16210     ctx = device_get_sysctl_ctx(sc->dev);
16211     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
16212
16213     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
16214                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
16215                       "version");
16216
16217     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
16218                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
16219                       "bootcode version");
16220
16221     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
16222              BCM_5710_FW_MAJOR_VERSION,
16223              BCM_5710_FW_MINOR_VERSION,
16224              BCM_5710_FW_REVISION_VERSION,
16225              BCM_5710_FW_ENGINEERING_VERSION);
16226     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
16227                       CTLFLAG_RD, sc->fw_ver_str, 0,
16228                       "firmware version");
16229
16230     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
16231         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
16232          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
16233          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
16234          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
16235                                                                 "Unknown"));
16236     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
16237                       CTLFLAG_RD, sc->mf_mode_str, 0,
16238                       "multifunction mode");
16239
16240     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
16241                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
16242                     "multifunction vnics per port");
16243
16244     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
16245                       CTLFLAG_RD, sc->mac_addr_str, 0,
16246                       "mac address");
16247
16248     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
16249         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
16250          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
16251          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
16252                                               "???GT/s"),
16253         sc->devinfo.pcie_link_width);
16254     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
16255                       CTLFLAG_RD, sc->pci_link_str, 0,
16256                       "pci link status");
16257
16258     sc->debug = bxe_debug;
16259     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
16260                     CTLFLAG_RW, &sc->debug,
16261                     "debug logging mode");
16262
16263     sc->rx_budget = bxe_rx_budget;
16264     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
16265                     CTLFLAG_RW, &sc->rx_budget, 0,
16266                     "rx processing budget");
16267
16268     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
16269                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
16270                     bxe_sysctl_state, "IU", "dump driver state");
16271
16272     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
16273         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
16274                         bxe_eth_stats_arr[i].string,
16275                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
16276                         bxe_sysctl_eth_stat, "LU",
16277                         bxe_eth_stats_arr[i].string);
16278     }
16279
16280     /* add a new parent node for all queues "dev.bxe.#.queue" */
16281     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
16282                                 CTLFLAG_RD, NULL, "queue");
16283     queue_top_children = SYSCTL_CHILDREN(queue_top);
16284
16285     for (i = 0; i < sc->num_queues; i++) {
16286         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
16287         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
16288         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
16289                                 queue_num_buf, CTLFLAG_RD, NULL,
16290                                 "single queue");
16291         queue_children = SYSCTL_CHILDREN(queue);
16292
16293         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
16294             q_stat = ((i << 16) | j);
16295             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
16296                             bxe_eth_q_stats_arr[j].string,
16297                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
16298                             bxe_sysctl_eth_q_stat, "LU",
16299                             bxe_eth_q_stats_arr[j].string);
16300         }
16301     }
16302 }
16303
16304 /*
16305  * Device attach function.
16306  *
16307  * Allocates device resources, performs secondary chip identification, and
16308  * initializes driver instance variables. This function is called from driver
16309  * load after a successful probe.
16310  *
16311  * Returns:
16312  *   0 = Success, >0 = Failure
16313  */
16314 static int
16315 bxe_attach(device_t dev)
16316 {
16317     struct bxe_softc *sc;
16318
16319     sc = device_get_softc(dev);
16320
16321     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
16322
16323     sc->state = BXE_STATE_CLOSED;
16324
16325     sc->dev  = dev;
16326     sc->unit = device_get_unit(dev);
16327
16328     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
16329
16330     sc->pcie_bus    = pci_get_bus(dev);
16331     sc->pcie_device = pci_get_slot(dev);
16332     sc->pcie_func   = pci_get_function(dev);
16333
16334     /* enable bus master capability */
16335     pci_enable_busmaster(dev);
16336
16337     /* get the BARs */
16338     if (bxe_allocate_bars(sc) != 0) {
16339         return (ENXIO);
16340     }
16341
16342     /* initialize the mutexes */
16343     bxe_init_mutexes(sc);
16344
16345     /* prepare the periodic callout */
16346     callout_init(&sc->periodic_callout, 0);
16347
16348     /* prepare the chip taskqueue */
16349     sc->chip_tq_flags = CHIP_TQ_NONE;
16350     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
16351              "bxe%d_chip_tq", sc->unit);
16352     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
16353     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
16354                                    taskqueue_thread_enqueue,
16355                                    &sc->chip_tq);
16356     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
16357                             "%s", sc->chip_tq_name);
16358
16359     /* get device info and set params */
16360     if (bxe_get_device_info(sc) != 0) {
16361         BLOGE(sc, "getting device info\n");
16362         bxe_deallocate_bars(sc);
16363         pci_disable_busmaster(dev);
16364         return (ENXIO);
16365     }
16366
16367     /* get final misc params */
16368     bxe_get_params(sc);
16369
16370     /* set the default MTU (changed via ifconfig) */
16371     sc->mtu = ETHERMTU;
16372
16373     bxe_set_modes_bitmap(sc);
16374
16375     /* XXX
16376      * If in AFEX mode and the function is configured for FCoE
16377      * then bail... no L2 allowed.
16378      */
16379
16380     /* get phy settings from shmem and 'and' against admin settings */
16381     bxe_get_phy_info(sc);
16382
16383     /* initialize the FreeBSD ifnet interface */
16384     if (bxe_init_ifnet(sc) != 0) {
16385         bxe_release_mutexes(sc);
16386         bxe_deallocate_bars(sc);
16387         pci_disable_busmaster(dev);
16388         return (ENXIO);
16389     }
16390
16391     /* allocate device interrupts */
16392     if (bxe_interrupt_alloc(sc) != 0) {
16393         if (sc->ifp != NULL) {
16394             ether_ifdetach(sc->ifp);
16395         }
16396         ifmedia_removeall(&sc->ifmedia);
16397         bxe_release_mutexes(sc);
16398         bxe_deallocate_bars(sc);
16399         pci_disable_busmaster(dev);
16400         return (ENXIO);
16401     }
16402
16403     /* allocate ilt */
16404     if (bxe_alloc_ilt_mem(sc) != 0) {
16405         bxe_interrupt_free(sc);
16406         if (sc->ifp != NULL) {
16407             ether_ifdetach(sc->ifp);
16408         }
16409         ifmedia_removeall(&sc->ifmedia);
16410         bxe_release_mutexes(sc);
16411         bxe_deallocate_bars(sc);
16412         pci_disable_busmaster(dev);
16413         return (ENXIO);
16414     }
16415
16416     /* allocate the host hardware/software hsi structures */
16417     if (bxe_alloc_hsi_mem(sc) != 0) {
16418         bxe_free_ilt_mem(sc);
16419         bxe_interrupt_free(sc);
16420         if (sc->ifp != NULL) {
16421             ether_ifdetach(sc->ifp);
16422         }
16423         ifmedia_removeall(&sc->ifmedia);
16424         bxe_release_mutexes(sc);
16425         bxe_deallocate_bars(sc);
16426         pci_disable_busmaster(dev);
16427         return (ENXIO);
16428     }
16429
16430     /* need to reset chip if UNDI was active */
16431     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16432         /* init fw_seq */
16433         sc->fw_seq =
16434             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16435              DRV_MSG_SEQ_NUMBER_MASK);
16436         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16437         bxe_prev_unload(sc);
16438     }
16439
16440 #if 1
16441     /* XXX */
16442     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16443 #else
16444     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16445         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16446         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16447         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16448         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16449         bxe_dcbx_init_params(sc);
16450     } else {
16451         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16452     }
16453 #endif
16454
16455     /* calculate qm_cid_count */
16456     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16457     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16458
16459     sc->max_cos = 1;
16460     bxe_init_multi_cos(sc);
16461
16462     bxe_add_sysctls(sc);
16463
16464     return (0);
16465 }
16466
16467 /*
16468  * Device detach function.
16469  *
16470  * Stops the controller, resets the controller, and releases resources.
16471  *
16472  * Returns:
16473  *   0 = Success, >0 = Failure
16474  */
16475 static int
16476 bxe_detach(device_t dev)
16477 {
16478     struct bxe_softc *sc;
16479     if_t ifp;
16480
16481     sc = device_get_softc(dev);
16482
16483     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16484
16485     ifp = sc->ifp;
16486     if (ifp != NULL && if_vlantrunkinuse(ifp)) {
16487         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16488         return(EBUSY);
16489     }
16490
16491     /* stop the periodic callout */
16492     bxe_periodic_stop(sc);
16493
16494     /* stop the chip taskqueue */
16495     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16496     if (sc->chip_tq) {
16497         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16498         taskqueue_free(sc->chip_tq);
16499         sc->chip_tq = NULL;
16500     }
16501
16502     /* stop and reset the controller if it was open */
16503     if (sc->state != BXE_STATE_CLOSED) {
16504         BXE_CORE_LOCK(sc);
16505         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16506         BXE_CORE_UNLOCK(sc);
16507     }
16508
16509     /* release the network interface */
16510     if (ifp != NULL) {
16511         ether_ifdetach(ifp);
16512     }
16513     ifmedia_removeall(&sc->ifmedia);
16514
16515     /* XXX do the following based on driver state... */
16516
16517     /* free the host hardware/software hsi structures */
16518     bxe_free_hsi_mem(sc);
16519
16520     /* free ilt */
16521     bxe_free_ilt_mem(sc);
16522
16523     /* release the interrupts */
16524     bxe_interrupt_free(sc);
16525
16526     /* Release the mutexes*/
16527     bxe_release_mutexes(sc);
16528
16529     /* Release the PCIe BAR mapped memory */
16530     bxe_deallocate_bars(sc);
16531
16532     /* Release the FreeBSD interface. */
16533     if (sc->ifp != NULL) {
16534         if_free(sc->ifp);
16535     }
16536
16537     pci_disable_busmaster(dev);
16538
16539     return (0);
16540 }
16541
16542 /*
16543  * Device shutdown function.
16544  *
16545  * Stops and resets the controller.
16546  *
16547  * Returns:
16548  *   Nothing
16549  */
16550 static int
16551 bxe_shutdown(device_t dev)
16552 {
16553     struct bxe_softc *sc;
16554
16555     sc = device_get_softc(dev);
16556
16557     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16558
16559     /* stop the periodic callout */
16560     bxe_periodic_stop(sc);
16561
16562     BXE_CORE_LOCK(sc);
16563     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16564     BXE_CORE_UNLOCK(sc);
16565
16566     return (0);
16567 }
16568
16569 void
16570 bxe_igu_ack_sb(struct bxe_softc *sc,
16571                uint8_t          igu_sb_id,
16572                uint8_t          segment,
16573                uint16_t         index,
16574                uint8_t          op,
16575                uint8_t          update)
16576 {
16577     uint32_t igu_addr = sc->igu_base_addr;
16578     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16579     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16580 }
16581
16582 static void
16583 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16584                      uint8_t          func,
16585                      uint8_t          idu_sb_id,
16586                      uint8_t          is_pf)
16587 {
16588     uint32_t data, ctl, cnt = 100;
16589     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16590     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16591     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16592     uint32_t sb_bit =  1 << (idu_sb_id%32);
16593     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16594     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16595
16596     /* Not supported in BC mode */
16597     if (CHIP_INT_MODE_IS_BC(sc)) {
16598         return;
16599     }
16600
16601     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16602              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16603             IGU_REGULAR_CLEANUP_SET |
16604             IGU_REGULAR_BCLEANUP);
16605
16606     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16607            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16608            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16609
16610     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16611             data, igu_addr_data);
16612     REG_WR(sc, igu_addr_data, data);
16613
16614     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16615                       BUS_SPACE_BARRIER_WRITE);
16616     mb();
16617
16618     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16619             ctl, igu_addr_ctl);
16620     REG_WR(sc, igu_addr_ctl, ctl);
16621
16622     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16623                       BUS_SPACE_BARRIER_WRITE);
16624     mb();
16625
16626     /* wait for clean up to finish */
16627     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16628         DELAY(20000);
16629     }
16630
16631     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16632         BLOGD(sc, DBG_LOAD,
16633               "Unable to finish IGU cleanup: "
16634               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16635               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16636     }
16637 }
16638
16639 static void
16640 bxe_igu_clear_sb(struct bxe_softc *sc,
16641                  uint8_t          idu_sb_id)
16642 {
16643     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16644 }
16645
16646
16647
16648
16649
16650
16651
16652 /*******************/
16653 /* ECORE CALLBACKS */
16654 /*******************/
16655
16656 static void
16657 bxe_reset_common(struct bxe_softc *sc)
16658 {
16659     uint32_t val = 0x1400;
16660
16661     /* reset_common */
16662     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16663
16664     if (CHIP_IS_E3(sc)) {
16665         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16666         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16667     }
16668
16669     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16670 }
16671
16672 static void
16673 bxe_common_init_phy(struct bxe_softc *sc)
16674 {
16675     uint32_t shmem_base[2];
16676     uint32_t shmem2_base[2];
16677
16678     /* Avoid common init in case MFW supports LFA */
16679     if (SHMEM2_RD(sc, size) >
16680         (uint32_t)offsetof(struct shmem2_region,
16681                            lfa_host_addr[SC_PORT(sc)])) {
16682         return;
16683     }
16684
16685     shmem_base[0]  = sc->devinfo.shmem_base;
16686     shmem2_base[0] = sc->devinfo.shmem2_base;
16687
16688     if (!CHIP_IS_E1x(sc)) {
16689         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16690         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16691     }
16692
16693     BXE_PHY_LOCK(sc);
16694     elink_common_init_phy(sc, shmem_base, shmem2_base,
16695                           sc->devinfo.chip_id, 0);
16696     BXE_PHY_UNLOCK(sc);
16697 }
16698
16699 static void
16700 bxe_pf_disable(struct bxe_softc *sc)
16701 {
16702     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16703
16704     val &= ~IGU_PF_CONF_FUNC_EN;
16705
16706     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16707     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16708     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16709 }
16710
16711 static void
16712 bxe_init_pxp(struct bxe_softc *sc)
16713 {
16714     uint16_t devctl;
16715     int r_order, w_order;
16716
16717     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16718
16719     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16720
16721     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16722
16723     if (sc->mrrs == -1) {
16724         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16725     } else {
16726         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16727         r_order = sc->mrrs;
16728     }
16729
16730     ecore_init_pxp_arb(sc, r_order, w_order);
16731 }
16732
16733 static uint32_t
16734 bxe_get_pretend_reg(struct bxe_softc *sc)
16735 {
16736     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16737     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16738     return (base + (SC_ABS_FUNC(sc)) * stride);
16739 }
16740
16741 /*
16742  * Called only on E1H or E2.
16743  * When pretending to be PF, the pretend value is the function number 0..7.
16744  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16745  * combination.
16746  */
16747 static int
16748 bxe_pretend_func(struct bxe_softc *sc,
16749                  uint16_t         pretend_func_val)
16750 {
16751     uint32_t pretend_reg;
16752
16753     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16754         return (-1);
16755     }
16756
16757     /* get my own pretend register */
16758     pretend_reg = bxe_get_pretend_reg(sc);
16759     REG_WR(sc, pretend_reg, pretend_func_val);
16760     REG_RD(sc, pretend_reg);
16761     return (0);
16762 }
16763
16764 static void
16765 bxe_iov_init_dmae(struct bxe_softc *sc)
16766 {
16767     return;
16768 #if 0
16769     BLOGD(sc, DBG_LOAD, "SRIOV is %s\n", IS_SRIOV(sc) ? "ON" : "OFF");
16770
16771     if (!IS_SRIOV(sc)) {
16772         return;
16773     }
16774
16775     REG_WR(sc, DMAE_REG_BACKWARD_COMP_EN, 0);
16776 #endif
16777 }
16778
16779 #if 0
16780 static int
16781 bxe_iov_init_ilt(struct bxe_softc *sc,
16782                  uint16_t         line)
16783 {
16784     return (line);
16785 #if 0
16786     int i;
16787     struct ecore_ilt* ilt = sc->ilt;
16788
16789     if (!IS_SRIOV(sc)) {
16790         return (line);
16791     }
16792
16793     /* set vfs ilt lines */
16794     for (i = 0; i < BXE_VF_CIDS/ILT_PAGE_CIDS ; i++) {
16795         struct hw_dma *hw_cxt = SC_VF_CXT_PAGE(sc,i);
16796         ilt->lines[line+i].page = hw_cxt->addr;
16797         ilt->lines[line+i].page_mapping = hw_cxt->mapping;
16798         ilt->lines[line+i].size = hw_cxt->size; /* doesn't matter */
16799     }
16800     return (line+i);
16801 #endif
16802 }
16803 #endif
16804
16805 static void
16806 bxe_iov_init_dq(struct bxe_softc *sc)
16807 {
16808     return;
16809 #if 0
16810     if (!IS_SRIOV(sc)) {
16811         return;
16812     }
16813
16814     /* Set the DQ such that the CID reflect the abs_vfid */
16815     REG_WR(sc, DORQ_REG_VF_NORM_VF_BASE, 0);
16816     REG_WR(sc, DORQ_REG_MAX_RVFID_SIZE, ilog2(BNX2X_MAX_NUM_OF_VFS));
16817
16818     /*
16819      * Set VFs starting CID. If its > 0 the preceding CIDs are belong to
16820      * the PF L2 queues
16821      */
16822     REG_WR(sc, DORQ_REG_VF_NORM_CID_BASE, BNX2X_FIRST_VF_CID);
16823
16824     /* The VF window size is the log2 of the max number of CIDs per VF */
16825     REG_WR(sc, DORQ_REG_VF_NORM_CID_WND_SIZE, BNX2X_VF_CID_WND);
16826
16827     /*
16828      * The VF doorbell size  0 - *B, 4 - 128B. We set it here to match
16829      * the Pf doorbell size although the 2 are independent.
16830      */
16831     REG_WR(sc, DORQ_REG_VF_NORM_CID_OFST,
16832            BNX2X_DB_SHIFT - BNX2X_DB_MIN_SHIFT);
16833
16834     /*
16835      * No security checks for now -
16836      * configure single rule (out of 16) mask = 0x1, value = 0x0,
16837      * CID range 0 - 0x1ffff
16838      */
16839     REG_WR(sc, DORQ_REG_VF_TYPE_MASK_0, 1);
16840     REG_WR(sc, DORQ_REG_VF_TYPE_VALUE_0, 0);
16841     REG_WR(sc, DORQ_REG_VF_TYPE_MIN_MCID_0, 0);
16842     REG_WR(sc, DORQ_REG_VF_TYPE_MAX_MCID_0, 0x1ffff);
16843
16844     /* set the number of VF alllowed doorbells to the full DQ range */
16845     REG_WR(sc, DORQ_REG_VF_NORM_MAX_CID_COUNT, 0x20000);
16846
16847     /* set the VF doorbell threshold */
16848     REG_WR(sc, DORQ_REG_VF_USAGE_CT_LIMIT, 4);
16849 #endif
16850 }
16851
16852 /* send a NIG loopback debug packet */
16853 static void
16854 bxe_lb_pckt(struct bxe_softc *sc)
16855 {
16856     uint32_t wb_write[3];
16857
16858     /* Ethernet source and destination addresses */
16859     wb_write[0] = 0x55555555;
16860     wb_write[1] = 0x55555555;
16861     wb_write[2] = 0x20;     /* SOP */
16862     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16863
16864     /* NON-IP protocol */
16865     wb_write[0] = 0x09000000;
16866     wb_write[1] = 0x55555555;
16867     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16868     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16869 }
16870
16871 /*
16872  * Some of the internal memories are not directly readable from the driver.
16873  * To test them we send debug packets.
16874  */
16875 static int
16876 bxe_int_mem_test(struct bxe_softc *sc)
16877 {
16878     int factor;
16879     int count, i;
16880     uint32_t val = 0;
16881
16882     if (CHIP_REV_IS_FPGA(sc)) {
16883         factor = 120;
16884     } else if (CHIP_REV_IS_EMUL(sc)) {
16885         factor = 200;
16886     } else {
16887         factor = 1;
16888     }
16889
16890     /* disable inputs of parser neighbor blocks */
16891     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16892     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16893     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16894     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16895
16896     /*  write 0 to parser credits for CFC search request */
16897     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16898
16899     /* send Ethernet packet */
16900     bxe_lb_pckt(sc);
16901
16902     /* TODO do i reset NIG statistic? */
16903     /* Wait until NIG register shows 1 packet of size 0x10 */
16904     count = 1000 * factor;
16905     while (count) {
16906         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16907         val = *BXE_SP(sc, wb_data[0]);
16908         if (val == 0x10) {
16909             break;
16910         }
16911
16912         DELAY(10000);
16913         count--;
16914     }
16915
16916     if (val != 0x10) {
16917         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16918         return (-1);
16919     }
16920
16921     /* wait until PRS register shows 1 packet */
16922     count = (1000 * factor);
16923     while (count) {
16924         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16925         if (val == 1) {
16926             break;
16927         }
16928
16929         DELAY(10000);
16930         count--;
16931     }
16932
16933     if (val != 0x1) {
16934         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16935         return (-2);
16936     }
16937
16938     /* Reset and init BRB, PRS */
16939     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16940     DELAY(50000);
16941     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16942     DELAY(50000);
16943     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16944     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16945
16946     /* Disable inputs of parser neighbor blocks */
16947     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16948     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16949     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16950     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16951
16952     /* Write 0 to parser credits for CFC search request */
16953     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16954
16955     /* send 10 Ethernet packets */
16956     for (i = 0; i < 10; i++) {
16957         bxe_lb_pckt(sc);
16958     }
16959
16960     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16961     count = (1000 * factor);
16962     while (count) {
16963         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16964         val = *BXE_SP(sc, wb_data[0]);
16965         if (val == 0xb0) {
16966             break;
16967         }
16968
16969         DELAY(10000);
16970         count--;
16971     }
16972
16973     if (val != 0xb0) {
16974         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16975         return (-3);
16976     }
16977
16978     /* Wait until PRS register shows 2 packets */
16979     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16980     if (val != 2) {
16981         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16982     }
16983
16984     /* Write 1 to parser credits for CFC search request */
16985     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16986
16987     /* Wait until PRS register shows 3 packets */
16988     DELAY(10000 * factor);
16989
16990     /* Wait until NIG register shows 1 packet of size 0x10 */
16991     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16992     if (val != 3) {
16993         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16994     }
16995
16996     /* clear NIG EOP FIFO */
16997     for (i = 0; i < 11; i++) {
16998         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16999     }
17000
17001     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
17002     if (val != 1) {
17003         BLOGE(sc, "clear of NIG failed\n");
17004         return (-4);
17005     }
17006
17007     /* Reset and init BRB, PRS, NIG */
17008     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
17009     DELAY(50000);
17010     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
17011     DELAY(50000);
17012     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17013     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17014     if (!CNIC_SUPPORT(sc)) {
17015         /* set NIC mode */
17016         REG_WR(sc, PRS_REG_NIC_MODE, 1);
17017     }
17018
17019     /* Enable inputs of parser neighbor blocks */
17020     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
17021     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
17022     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
17023     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
17024
17025     return (0);
17026 }
17027
17028 static void
17029 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
17030 {
17031     int is_required;
17032     uint32_t val;
17033     int port;
17034
17035     is_required = 0;
17036     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
17037            SHARED_HW_CFG_FAN_FAILURE_MASK);
17038
17039     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
17040         is_required = 1;
17041     }
17042     /*
17043      * The fan failure mechanism is usually related to the PHY type since
17044      * the power consumption of the board is affected by the PHY. Currently,
17045      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
17046      */
17047     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
17048         for (port = PORT_0; port < PORT_MAX; port++) {
17049             is_required |= elink_fan_failure_det_req(sc,
17050                                                      sc->devinfo.shmem_base,
17051                                                      sc->devinfo.shmem2_base,
17052                                                      port);
17053         }
17054     }
17055
17056     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
17057
17058     if (is_required == 0) {
17059         return;
17060     }
17061
17062     /* Fan failure is indicated by SPIO 5 */
17063     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
17064
17065     /* set to active low mode */
17066     val = REG_RD(sc, MISC_REG_SPIO_INT);
17067     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
17068     REG_WR(sc, MISC_REG_SPIO_INT, val);
17069
17070     /* enable interrupt to signal the IGU */
17071     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17072     val |= MISC_SPIO_SPIO5;
17073     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
17074 }
17075
17076 static void
17077 bxe_enable_blocks_attention(struct bxe_softc *sc)
17078 {
17079     uint32_t val;
17080
17081     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
17082     if (!CHIP_IS_E1x(sc)) {
17083         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
17084     } else {
17085         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
17086     }
17087     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17088     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17089     /*
17090      * mask read length error interrupts in brb for parser
17091      * (parsing unit and 'checksum and crc' unit)
17092      * these errors are legal (PU reads fixed length and CAC can cause
17093      * read length error on truncated packets)
17094      */
17095     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
17096     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
17097     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
17098     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
17099     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
17100     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
17101 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
17102 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
17103     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
17104     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
17105     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
17106 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
17107 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
17108     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
17109     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
17110     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
17111     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
17112 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
17113 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
17114
17115     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
17116            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
17117            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
17118     if (!CHIP_IS_E1x(sc)) {
17119         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
17120                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
17121     }
17122     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
17123
17124     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
17125     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
17126     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
17127 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
17128
17129     if (!CHIP_IS_E1x(sc)) {
17130         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
17131         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
17132     }
17133
17134     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
17135     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
17136 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
17137     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
17138 }
17139
17140 /**
17141  * bxe_init_hw_common - initialize the HW at the COMMON phase.
17142  *
17143  * @sc:     driver handle
17144  */
17145 static int
17146 bxe_init_hw_common(struct bxe_softc *sc)
17147 {
17148     uint8_t abs_func_id;
17149     uint32_t val;
17150
17151     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
17152           SC_ABS_FUNC(sc));
17153
17154     /*
17155      * take the RESET lock to protect undi_unload flow from accessing
17156      * registers while we are resetting the chip
17157      */
17158     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
17159
17160     bxe_reset_common(sc);
17161
17162     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
17163
17164     val = 0xfffc;
17165     if (CHIP_IS_E3(sc)) {
17166         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
17167         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
17168     }
17169
17170     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
17171
17172     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
17173
17174     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
17175     BLOGD(sc, DBG_LOAD, "after misc block init\n");
17176
17177     if (!CHIP_IS_E1x(sc)) {
17178         /*
17179          * 4-port mode or 2-port mode we need to turn off master-enable for
17180          * everyone. After that we turn it back on for self. So, we disregard
17181          * multi-function, and always disable all functions on the given path,
17182          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
17183          */
17184         for (abs_func_id = SC_PATH(sc);
17185              abs_func_id < (E2_FUNC_MAX * 2);
17186              abs_func_id += 2) {
17187             if (abs_func_id == SC_ABS_FUNC(sc)) {
17188                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17189                 continue;
17190             }
17191
17192             bxe_pretend_func(sc, abs_func_id);
17193
17194             /* clear pf enable */
17195             bxe_pf_disable(sc);
17196
17197             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
17198         }
17199     }
17200
17201     BLOGD(sc, DBG_LOAD, "after pf disable\n");
17202
17203     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
17204
17205     if (CHIP_IS_E1(sc)) {
17206         /*
17207          * enable HW interrupt from PXP on USDM overflow
17208          * bit 16 on INT_MASK_0
17209          */
17210         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
17211     }
17212
17213     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
17214     bxe_init_pxp(sc);
17215
17216 #ifdef __BIG_ENDIAN
17217     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
17218     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
17219     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
17220     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
17221     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
17222     /* make sure this value is 0 */
17223     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
17224
17225     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
17226     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
17227     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
17228     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
17229     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
17230 #endif
17231
17232     ecore_ilt_init_page_size(sc, INITOP_SET);
17233
17234     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
17235         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
17236     }
17237
17238     /* let the HW do it's magic... */
17239     DELAY(100000);
17240
17241     /* finish PXP init */
17242     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
17243     if (val != 1) {
17244         BLOGE(sc, "PXP2 CFG failed\n");
17245         return (-1);
17246     }
17247     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
17248     if (val != 1) {
17249         BLOGE(sc, "PXP2 RD_INIT failed\n");
17250         return (-1);
17251     }
17252
17253     BLOGD(sc, DBG_LOAD, "after pxp init\n");
17254
17255     /*
17256      * Timer bug workaround for E2 only. We need to set the entire ILT to have
17257      * entries with value "0" and valid bit on. This needs to be done by the
17258      * first PF that is loaded in a path (i.e. common phase)
17259      */
17260     if (!CHIP_IS_E1x(sc)) {
17261 /*
17262  * In E2 there is a bug in the timers block that can cause function 6 / 7
17263  * (i.e. vnic3) to start even if it is marked as "scan-off".
17264  * This occurs when a different function (func2,3) is being marked
17265  * as "scan-off". Real-life scenario for example: if a driver is being
17266  * load-unloaded while func6,7 are down. This will cause the timer to access
17267  * the ilt, translate to a logical address and send a request to read/write.
17268  * Since the ilt for the function that is down is not valid, this will cause
17269  * a translation error which is unrecoverable.
17270  * The Workaround is intended to make sure that when this happens nothing
17271  * fatal will occur. The workaround:
17272  *  1.  First PF driver which loads on a path will:
17273  *      a.  After taking the chip out of reset, by using pretend,
17274  *          it will write "0" to the following registers of
17275  *          the other vnics.
17276  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
17277  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
17278  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
17279  *          And for itself it will write '1' to
17280  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
17281  *          dmae-operations (writing to pram for example.)
17282  *          note: can be done for only function 6,7 but cleaner this
17283  *            way.
17284  *      b.  Write zero+valid to the entire ILT.
17285  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
17286  *          VNIC3 (of that port). The range allocated will be the
17287  *          entire ILT. This is needed to prevent  ILT range error.
17288  *  2.  Any PF driver load flow:
17289  *      a.  ILT update with the physical addresses of the allocated
17290  *          logical pages.
17291  *      b.  Wait 20msec. - note that this timeout is needed to make
17292  *          sure there are no requests in one of the PXP internal
17293  *          queues with "old" ILT addresses.
17294  *      c.  PF enable in the PGLC.
17295  *      d.  Clear the was_error of the PF in the PGLC. (could have
17296  *          occurred while driver was down)
17297  *      e.  PF enable in the CFC (WEAK + STRONG)
17298  *      f.  Timers scan enable
17299  *  3.  PF driver unload flow:
17300  *      a.  Clear the Timers scan_en.
17301  *      b.  Polling for scan_on=0 for that PF.
17302  *      c.  Clear the PF enable bit in the PXP.
17303  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
17304  *      e.  Write zero+valid to all ILT entries (The valid bit must
17305  *          stay set)
17306  *      f.  If this is VNIC 3 of a port then also init
17307  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
17308  *          to the last enrty in the ILT.
17309  *
17310  *      Notes:
17311  *      Currently the PF error in the PGLC is non recoverable.
17312  *      In the future the there will be a recovery routine for this error.
17313  *      Currently attention is masked.
17314  *      Having an MCP lock on the load/unload process does not guarantee that
17315  *      there is no Timer disable during Func6/7 enable. This is because the
17316  *      Timers scan is currently being cleared by the MCP on FLR.
17317  *      Step 2.d can be done only for PF6/7 and the driver can also check if
17318  *      there is error before clearing it. But the flow above is simpler and
17319  *      more general.
17320  *      All ILT entries are written by zero+valid and not just PF6/7
17321  *      ILT entries since in the future the ILT entries allocation for
17322  *      PF-s might be dynamic.
17323  */
17324         struct ilt_client_info ilt_cli;
17325         struct ecore_ilt ilt;
17326
17327         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
17328         memset(&ilt, 0, sizeof(struct ecore_ilt));
17329
17330         /* initialize dummy TM client */
17331         ilt_cli.start      = 0;
17332         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
17333         ilt_cli.client_num = ILT_CLIENT_TM;
17334
17335         /*
17336          * Step 1: set zeroes to all ilt page entries with valid bit on
17337          * Step 2: set the timers first/last ilt entry to point
17338          * to the entire range to prevent ILT range error for 3rd/4th
17339          * vnic (this code assumes existence of the vnic)
17340          *
17341          * both steps performed by call to ecore_ilt_client_init_op()
17342          * with dummy TM client
17343          *
17344          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
17345          * and his brother are split registers
17346          */
17347
17348         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
17349         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
17350         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
17351
17352         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
17353         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
17354         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
17355     }
17356
17357     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
17358     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
17359
17360     if (!CHIP_IS_E1x(sc)) {
17361         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
17362                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
17363
17364         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
17365         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
17366
17367         /* let the HW do it's magic... */
17368         do {
17369             DELAY(200000);
17370             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
17371         } while (factor-- && (val != 1));
17372
17373         if (val != 1) {
17374             BLOGE(sc, "ATC_INIT failed\n");
17375             return (-1);
17376         }
17377     }
17378
17379     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
17380
17381     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
17382
17383     bxe_iov_init_dmae(sc);
17384
17385     /* clean the DMAE memory */
17386     sc->dmae_ready = 1;
17387     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
17388
17389     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
17390
17391     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
17392
17393     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
17394
17395     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
17396
17397     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
17398     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17399     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17400     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17401
17402     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17403
17404     /* QM queues pointers table */
17405     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17406
17407     /* soft reset pulse */
17408     REG_WR(sc, QM_REG_SOFT_RESET, 1);
17409     REG_WR(sc, QM_REG_SOFT_RESET, 0);
17410
17411     if (CNIC_SUPPORT(sc))
17412         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17413
17414     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17415     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17416     if (!CHIP_REV_IS_SLOW(sc)) {
17417         /* enable hw interrupt from doorbell Q */
17418         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17419     }
17420
17421     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17422
17423     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17424     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17425
17426     if (!CHIP_IS_E1(sc)) {
17427         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17428     }
17429
17430     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17431         if (IS_MF_AFEX(sc)) {
17432             /*
17433              * configure that AFEX and VLAN headers must be
17434              * received in AFEX mode
17435              */
17436             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17437             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17438             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17439             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17440             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17441         } else {
17442             /*
17443              * Bit-map indicating which L2 hdrs may appear
17444              * after the basic Ethernet header
17445              */
17446             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17447                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17448         }
17449     }
17450
17451     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17452     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17453     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17454     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17455
17456     if (!CHIP_IS_E1x(sc)) {
17457         /* reset VFC memories */
17458         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17459                VFC_MEMORIES_RST_REG_CAM_RST |
17460                VFC_MEMORIES_RST_REG_RAM_RST);
17461         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17462                VFC_MEMORIES_RST_REG_CAM_RST |
17463                VFC_MEMORIES_RST_REG_RAM_RST);
17464
17465         DELAY(20000);
17466     }
17467
17468     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17469     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17470     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17471     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17472
17473     /* sync semi rtc */
17474     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17475            0x80000000);
17476     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17477            0x80000000);
17478
17479     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17480     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17481     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17482
17483     if (!CHIP_IS_E1x(sc)) {
17484         if (IS_MF_AFEX(sc)) {
17485             /*
17486              * configure that AFEX and VLAN headers must be
17487              * sent in AFEX mode
17488              */
17489             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17490             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17491             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17492             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17493             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17494         } else {
17495             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17496                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17497         }
17498     }
17499
17500     REG_WR(sc, SRC_REG_SOFT_RST, 1);
17501
17502     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17503
17504     if (CNIC_SUPPORT(sc)) {
17505         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17506         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17507         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17508         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17509         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17510         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17511         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17512         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17513         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17514         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17515     }
17516     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17517
17518     if (sizeof(union cdu_context) != 1024) {
17519         /* we currently assume that a context is 1024 bytes */
17520         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17521               (long)sizeof(union cdu_context));
17522     }
17523
17524     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17525     val = (4 << 24) + (0 << 12) + 1024;
17526     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17527
17528     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17529
17530     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17531     /* enable context validation interrupt from CFC */
17532     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17533
17534     /* set the thresholds to prevent CFC/CDU race */
17535     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17536     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17537
17538     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17539         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17540     }
17541
17542     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17543     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17544
17545     /* Reset PCIE errors for debug */
17546     REG_WR(sc, 0x2814, 0xffffffff);
17547     REG_WR(sc, 0x3820, 0xffffffff);
17548
17549     if (!CHIP_IS_E1x(sc)) {
17550         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17551                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17552                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17553         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17554                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17555                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17556                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17557         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17558                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17559                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17560                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17561     }
17562
17563     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17564
17565     if (!CHIP_IS_E1(sc)) {
17566         /* in E3 this done in per-port section */
17567         if (!CHIP_IS_E3(sc))
17568             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17569     }
17570
17571     if (CHIP_IS_E1H(sc)) {
17572         /* not applicable for E2 (and above ...) */
17573         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17574     }
17575
17576     if (CHIP_REV_IS_SLOW(sc)) {
17577         DELAY(200000);
17578     }
17579
17580     /* finish CFC init */
17581     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17582     if (val != 1) {
17583         BLOGE(sc, "CFC LL_INIT failed\n");
17584         return (-1);
17585     }
17586     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17587     if (val != 1) {
17588         BLOGE(sc, "CFC AC_INIT failed\n");
17589         return (-1);
17590     }
17591     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17592     if (val != 1) {
17593         BLOGE(sc, "CFC CAM_INIT failed\n");
17594         return (-1);
17595     }
17596     REG_WR(sc, CFC_REG_DEBUG0, 0);
17597
17598     if (CHIP_IS_E1(sc)) {
17599         /* read NIG statistic to see if this is our first up since powerup */
17600         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17601         val = *BXE_SP(sc, wb_data[0]);
17602
17603         /* do internal memory self test */
17604         if ((val == 0) && bxe_int_mem_test(sc)) {
17605             BLOGE(sc, "internal mem self test failed\n");
17606             return (-1);
17607         }
17608     }
17609
17610     bxe_setup_fan_failure_detection(sc);
17611
17612     /* clear PXP2 attentions */
17613     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17614
17615     bxe_enable_blocks_attention(sc);
17616
17617     if (!CHIP_REV_IS_SLOW(sc)) {
17618         ecore_enable_blocks_parity(sc);
17619     }
17620
17621     if (!BXE_NOMCP(sc)) {
17622         if (CHIP_IS_E1x(sc)) {
17623             bxe_common_init_phy(sc);
17624         }
17625     }
17626
17627     return (0);
17628 }
17629
17630 /**
17631  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17632  *
17633  * @sc:     driver handle
17634  */
17635 static int
17636 bxe_init_hw_common_chip(struct bxe_softc *sc)
17637 {
17638     int rc = bxe_init_hw_common(sc);
17639
17640     if (rc) {
17641         return (rc);
17642     }
17643
17644     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17645     if (!BXE_NOMCP(sc)) {
17646         bxe_common_init_phy(sc);
17647     }
17648
17649     return (0);
17650 }
17651
17652 static int
17653 bxe_init_hw_port(struct bxe_softc *sc)
17654 {
17655     int port = SC_PORT(sc);
17656     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17657     uint32_t low, high;
17658     uint32_t val;
17659
17660     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17661
17662     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17663
17664     ecore_init_block(sc, BLOCK_MISC, init_phase);
17665     ecore_init_block(sc, BLOCK_PXP, init_phase);
17666     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17667
17668     /*
17669      * Timers bug workaround: disables the pf_master bit in pglue at
17670      * common phase, we need to enable it here before any dmae access are
17671      * attempted. Therefore we manually added the enable-master to the
17672      * port phase (it also happens in the function phase)
17673      */
17674     if (!CHIP_IS_E1x(sc)) {
17675         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17676     }
17677
17678     ecore_init_block(sc, BLOCK_ATC, init_phase);
17679     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17680     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17681     ecore_init_block(sc, BLOCK_QM, init_phase);
17682
17683     ecore_init_block(sc, BLOCK_TCM, init_phase);
17684     ecore_init_block(sc, BLOCK_UCM, init_phase);
17685     ecore_init_block(sc, BLOCK_CCM, init_phase);
17686     ecore_init_block(sc, BLOCK_XCM, init_phase);
17687
17688     /* QM cid (connection) count */
17689     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17690
17691     if (CNIC_SUPPORT(sc)) {
17692         ecore_init_block(sc, BLOCK_TM, init_phase);
17693         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17694         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17695     }
17696
17697     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17698
17699     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17700
17701     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17702         if (IS_MF(sc)) {
17703             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17704         } else if (sc->mtu > 4096) {
17705             if (BXE_ONE_PORT(sc)) {
17706                 low = 160;
17707             } else {
17708                 val = sc->mtu;
17709                 /* (24*1024 + val*4)/256 */
17710                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17711             }
17712         } else {
17713             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17714         }
17715         high = (low + 56); /* 14*1024/256 */
17716         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17717         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17718     }
17719
17720     if (CHIP_IS_MODE_4_PORT(sc)) {
17721         REG_WR(sc, SC_PORT(sc) ?
17722                BRB1_REG_MAC_GUARANTIED_1 :
17723                BRB1_REG_MAC_GUARANTIED_0, 40);
17724     }
17725
17726     ecore_init_block(sc, BLOCK_PRS, init_phase);
17727     if (CHIP_IS_E3B0(sc)) {
17728         if (IS_MF_AFEX(sc)) {
17729             /* configure headers for AFEX mode */
17730             REG_WR(sc, SC_PORT(sc) ?
17731                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17732                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17733             REG_WR(sc, SC_PORT(sc) ?
17734                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17735                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17736             REG_WR(sc, SC_PORT(sc) ?
17737                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17738                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17739         } else {
17740             /* Ovlan exists only if we are in multi-function +
17741              * switch-dependent mode, in switch-independent there
17742              * is no ovlan headers
17743              */
17744             REG_WR(sc, SC_PORT(sc) ?
17745                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17746                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17747                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17748         }
17749     }
17750
17751     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17752     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17753     ecore_init_block(sc, BLOCK_USDM, init_phase);
17754     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17755
17756     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17757     ecore_init_block(sc, BLOCK_USEM, init_phase);
17758     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17759     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17760
17761     ecore_init_block(sc, BLOCK_UPB, init_phase);
17762     ecore_init_block(sc, BLOCK_XPB, init_phase);
17763
17764     ecore_init_block(sc, BLOCK_PBF, init_phase);
17765
17766     if (CHIP_IS_E1x(sc)) {
17767         /* configure PBF to work without PAUSE mtu 9000 */
17768         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17769
17770         /* update threshold */
17771         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17772         /* update init credit */
17773         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17774
17775         /* probe changes */
17776         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17777         DELAY(50);
17778         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17779     }
17780
17781     if (CNIC_SUPPORT(sc)) {
17782         ecore_init_block(sc, BLOCK_SRC, init_phase);
17783     }
17784
17785     ecore_init_block(sc, BLOCK_CDU, init_phase);
17786     ecore_init_block(sc, BLOCK_CFC, init_phase);
17787
17788     if (CHIP_IS_E1(sc)) {
17789         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17790         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17791     }
17792     ecore_init_block(sc, BLOCK_HC, init_phase);
17793
17794     ecore_init_block(sc, BLOCK_IGU, init_phase);
17795
17796     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17797     /* init aeu_mask_attn_func_0/1:
17798      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17799      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17800      *             bits 4-7 are used for "per vn group attention" */
17801     val = IS_MF(sc) ? 0xF7 : 0x7;
17802     /* Enable DCBX attention for all but E1 */
17803     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17804     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17805
17806     ecore_init_block(sc, BLOCK_NIG, init_phase);
17807
17808     if (!CHIP_IS_E1x(sc)) {
17809         /* Bit-map indicating which L2 hdrs may appear after the
17810          * basic Ethernet header
17811          */
17812         if (IS_MF_AFEX(sc)) {
17813             REG_WR(sc, SC_PORT(sc) ?
17814                    NIG_REG_P1_HDRS_AFTER_BASIC :
17815                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17816         } else {
17817             REG_WR(sc, SC_PORT(sc) ?
17818                    NIG_REG_P1_HDRS_AFTER_BASIC :
17819                    NIG_REG_P0_HDRS_AFTER_BASIC,
17820                    IS_MF_SD(sc) ? 7 : 6);
17821         }
17822
17823         if (CHIP_IS_E3(sc)) {
17824             REG_WR(sc, SC_PORT(sc) ?
17825                    NIG_REG_LLH1_MF_MODE :
17826                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17827         }
17828     }
17829     if (!CHIP_IS_E3(sc)) {
17830         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17831     }
17832
17833     if (!CHIP_IS_E1(sc)) {
17834         /* 0x2 disable mf_ov, 0x1 enable */
17835         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17836                (IS_MF_SD(sc) ? 0x1 : 0x2));
17837
17838         if (!CHIP_IS_E1x(sc)) {
17839             val = 0;
17840             switch (sc->devinfo.mf_info.mf_mode) {
17841             case MULTI_FUNCTION_SD:
17842                 val = 1;
17843                 break;
17844             case MULTI_FUNCTION_SI:
17845             case MULTI_FUNCTION_AFEX:
17846                 val = 2;
17847                 break;
17848             }
17849
17850             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17851                         NIG_REG_LLH0_CLS_TYPE), val);
17852         }
17853         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17854         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17855         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17856     }
17857
17858     /* If SPIO5 is set to generate interrupts, enable it for this port */
17859     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17860     if (val & MISC_SPIO_SPIO5) {
17861         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17862                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17863         val = REG_RD(sc, reg_addr);
17864         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17865         REG_WR(sc, reg_addr, val);
17866     }
17867
17868     return (0);
17869 }
17870
17871 static uint32_t
17872 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17873                        uint32_t         reg,
17874                        uint32_t         expected,
17875                        uint32_t         poll_count)
17876 {
17877     uint32_t cur_cnt = poll_count;
17878     uint32_t val;
17879
17880     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17881         DELAY(FLR_WAIT_INTERVAL);
17882     }
17883
17884     return (val);
17885 }
17886
17887 static int
17888 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17889                               uint32_t         reg,
17890                               char             *msg,
17891                               uint32_t         poll_cnt)
17892 {
17893     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17894
17895     if (val != 0) {
17896         BLOGE(sc, "%s usage count=%d\n", msg, val);
17897         return (1);
17898     }
17899
17900     return (0);
17901 }
17902
17903 /* Common routines with VF FLR cleanup */
17904 static uint32_t
17905 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17906 {
17907     /* adjust polling timeout */
17908     if (CHIP_REV_IS_EMUL(sc)) {
17909         return (FLR_POLL_CNT * 2000);
17910     }
17911
17912     if (CHIP_REV_IS_FPGA(sc)) {
17913         return (FLR_POLL_CNT * 120);
17914     }
17915
17916     return (FLR_POLL_CNT);
17917 }
17918
17919 static int
17920 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17921                            uint32_t         poll_cnt)
17922 {
17923     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17924     if (bxe_flr_clnup_poll_hw_counter(sc,
17925                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17926                                       "CFC PF usage counter timed out",
17927                                       poll_cnt)) {
17928         return (1);
17929     }
17930
17931     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17932     if (bxe_flr_clnup_poll_hw_counter(sc,
17933                                       DORQ_REG_PF_USAGE_CNT,
17934                                       "DQ PF usage counter timed out",
17935                                       poll_cnt)) {
17936         return (1);
17937     }
17938
17939     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17940     if (bxe_flr_clnup_poll_hw_counter(sc,
17941                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17942                                       "QM PF usage counter timed out",
17943                                       poll_cnt)) {
17944         return (1);
17945     }
17946
17947     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17948     if (bxe_flr_clnup_poll_hw_counter(sc,
17949                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17950                                       "Timers VNIC usage counter timed out",
17951                                       poll_cnt)) {
17952         return (1);
17953     }
17954
17955     if (bxe_flr_clnup_poll_hw_counter(sc,
17956                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17957                                       "Timers NUM_SCANS usage counter timed out",
17958                                       poll_cnt)) {
17959         return (1);
17960     }
17961
17962     /* Wait DMAE PF usage counter to zero */
17963     if (bxe_flr_clnup_poll_hw_counter(sc,
17964                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17965                                       "DMAE dommand register timed out",
17966                                       poll_cnt)) {
17967         return (1);
17968     }
17969
17970     return (0);
17971 }
17972
17973 #define OP_GEN_PARAM(param)                                            \
17974     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17975 #define OP_GEN_TYPE(type)                                           \
17976     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17977 #define OP_GEN_AGG_VECT(index)                                             \
17978     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17979
17980 static int
17981 bxe_send_final_clnup(struct bxe_softc *sc,
17982                      uint8_t          clnup_func,
17983                      uint32_t         poll_cnt)
17984 {
17985     uint32_t op_gen_command = 0;
17986     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17987                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17988     int ret = 0;
17989
17990     if (REG_RD(sc, comp_addr)) {
17991         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17992         return (1);
17993     }
17994
17995     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17996     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17997     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17998     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17999
18000     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
18001     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
18002
18003     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
18004         BLOGE(sc, "FW final cleanup did not succeed\n");
18005         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
18006               (REG_RD(sc, comp_addr)));
18007         bxe_panic(sc, ("FLR cleanup failed\n"));
18008         return (1);
18009     }
18010
18011     /* Zero completion for nxt FLR */
18012     REG_WR(sc, comp_addr, 0);
18013
18014     return (ret);
18015 }
18016
18017 static void
18018 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
18019                        struct pbf_pN_buf_regs *regs,
18020                        uint32_t               poll_count)
18021 {
18022     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
18023     uint32_t cur_cnt = poll_count;
18024
18025     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
18026     crd = crd_start = REG_RD(sc, regs->crd);
18027     init_crd = REG_RD(sc, regs->init_crd);
18028
18029     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
18030     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
18031     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
18032
18033     while ((crd != init_crd) &&
18034            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
18035             (init_crd - crd_start))) {
18036         if (cur_cnt--) {
18037             DELAY(FLR_WAIT_INTERVAL);
18038             crd = REG_RD(sc, regs->crd);
18039             crd_freed = REG_RD(sc, regs->crd_freed);
18040         } else {
18041             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
18042             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
18043             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
18044             break;
18045         }
18046     }
18047
18048     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
18049           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
18050 }
18051
18052 static void
18053 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
18054                        struct pbf_pN_cmd_regs *regs,
18055                        uint32_t               poll_count)
18056 {
18057     uint32_t occup, to_free, freed, freed_start;
18058     uint32_t cur_cnt = poll_count;
18059
18060     occup = to_free = REG_RD(sc, regs->lines_occup);
18061     freed = freed_start = REG_RD(sc, regs->lines_freed);
18062
18063     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
18064     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
18065
18066     while (occup &&
18067            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
18068         if (cur_cnt--) {
18069             DELAY(FLR_WAIT_INTERVAL);
18070             occup = REG_RD(sc, regs->lines_occup);
18071             freed = REG_RD(sc, regs->lines_freed);
18072         } else {
18073             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
18074             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
18075             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
18076             break;
18077         }
18078     }
18079
18080     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
18081           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
18082 }
18083
18084 static void
18085 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
18086 {
18087     struct pbf_pN_cmd_regs cmd_regs[] = {
18088         {0, (CHIP_IS_E3B0(sc)) ?
18089             PBF_REG_TQ_OCCUPANCY_Q0 :
18090             PBF_REG_P0_TQ_OCCUPANCY,
18091             (CHIP_IS_E3B0(sc)) ?
18092             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
18093             PBF_REG_P0_TQ_LINES_FREED_CNT},
18094         {1, (CHIP_IS_E3B0(sc)) ?
18095             PBF_REG_TQ_OCCUPANCY_Q1 :
18096             PBF_REG_P1_TQ_OCCUPANCY,
18097             (CHIP_IS_E3B0(sc)) ?
18098             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
18099             PBF_REG_P1_TQ_LINES_FREED_CNT},
18100         {4, (CHIP_IS_E3B0(sc)) ?
18101             PBF_REG_TQ_OCCUPANCY_LB_Q :
18102             PBF_REG_P4_TQ_OCCUPANCY,
18103             (CHIP_IS_E3B0(sc)) ?
18104             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
18105             PBF_REG_P4_TQ_LINES_FREED_CNT}
18106     };
18107
18108     struct pbf_pN_buf_regs buf_regs[] = {
18109         {0, (CHIP_IS_E3B0(sc)) ?
18110             PBF_REG_INIT_CRD_Q0 :
18111             PBF_REG_P0_INIT_CRD ,
18112             (CHIP_IS_E3B0(sc)) ?
18113             PBF_REG_CREDIT_Q0 :
18114             PBF_REG_P0_CREDIT,
18115             (CHIP_IS_E3B0(sc)) ?
18116             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
18117             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
18118         {1, (CHIP_IS_E3B0(sc)) ?
18119             PBF_REG_INIT_CRD_Q1 :
18120             PBF_REG_P1_INIT_CRD,
18121             (CHIP_IS_E3B0(sc)) ?
18122             PBF_REG_CREDIT_Q1 :
18123             PBF_REG_P1_CREDIT,
18124             (CHIP_IS_E3B0(sc)) ?
18125             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
18126             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
18127         {4, (CHIP_IS_E3B0(sc)) ?
18128             PBF_REG_INIT_CRD_LB_Q :
18129             PBF_REG_P4_INIT_CRD,
18130             (CHIP_IS_E3B0(sc)) ?
18131             PBF_REG_CREDIT_LB_Q :
18132             PBF_REG_P4_CREDIT,
18133             (CHIP_IS_E3B0(sc)) ?
18134             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
18135             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
18136     };
18137
18138     int i;
18139
18140     /* Verify the command queues are flushed P0, P1, P4 */
18141     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
18142         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
18143     }
18144
18145     /* Verify the transmission buffers are flushed P0, P1, P4 */
18146     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
18147         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
18148     }
18149 }
18150
18151 static void
18152 bxe_hw_enable_status(struct bxe_softc *sc)
18153 {
18154     uint32_t val;
18155
18156     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
18157     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
18158
18159     val = REG_RD(sc, PBF_REG_DISABLE_PF);
18160     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
18161
18162     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
18163     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
18164
18165     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
18166     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
18167
18168     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
18169     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
18170
18171     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
18172     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
18173
18174     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
18175     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
18176
18177     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
18178     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
18179 }
18180
18181 static int
18182 bxe_pf_flr_clnup(struct bxe_softc *sc)
18183 {
18184     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
18185
18186     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
18187
18188     /* Re-enable PF target read access */
18189     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
18190
18191     /* Poll HW usage counters */
18192     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
18193     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
18194         return (-1);
18195     }
18196
18197     /* Zero the igu 'trailing edge' and 'leading edge' */
18198
18199     /* Send the FW cleanup command */
18200     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
18201         return (-1);
18202     }
18203
18204     /* ATC cleanup */
18205
18206     /* Verify TX hw is flushed */
18207     bxe_tx_hw_flushed(sc, poll_cnt);
18208
18209     /* Wait 100ms (not adjusted according to platform) */
18210     DELAY(100000);
18211
18212     /* Verify no pending pci transactions */
18213     if (bxe_is_pcie_pending(sc)) {
18214         BLOGE(sc, "PCIE Transactions still pending\n");
18215     }
18216
18217     /* Debug */
18218     bxe_hw_enable_status(sc);
18219
18220     /*
18221      * Master enable - Due to WB DMAE writes performed before this
18222      * register is re-initialized as part of the regular function init
18223      */
18224     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
18225
18226     return (0);
18227 }
18228
18229 #if 0
18230 static void
18231 bxe_init_searcher(struct bxe_softc *sc)
18232 {
18233     int port = SC_PORT(sc);
18234     ecore_src_init_t2(sc, sc->t2, sc->t2_mapping, SRC_CONN_NUM);
18235     /* T1 hash bits value determines the T1 number of entries */
18236     REG_WR(sc, SRC_REG_NUMBER_HASH_BITS0 + port*4, SRC_HASH_BITS);
18237 }
18238 #endif
18239
18240 static int
18241 bxe_init_hw_func(struct bxe_softc *sc)
18242 {
18243     int port = SC_PORT(sc);
18244     int func = SC_FUNC(sc);
18245     int init_phase = PHASE_PF0 + func;
18246     struct ecore_ilt *ilt = sc->ilt;
18247     uint16_t cdu_ilt_start;
18248     uint32_t addr, val;
18249     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
18250     int i, main_mem_width, rc;
18251
18252     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
18253
18254     /* FLR cleanup */
18255     if (!CHIP_IS_E1x(sc)) {
18256         rc = bxe_pf_flr_clnup(sc);
18257         if (rc) {
18258             BLOGE(sc, "FLR cleanup failed!\n");
18259             // XXX bxe_fw_dump(sc);
18260             // XXX bxe_idle_chk(sc);
18261             return (rc);
18262         }
18263     }
18264
18265     /* set MSI reconfigure capability */
18266     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18267         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
18268         val = REG_RD(sc, addr);
18269         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
18270         REG_WR(sc, addr, val);
18271     }
18272
18273     ecore_init_block(sc, BLOCK_PXP, init_phase);
18274     ecore_init_block(sc, BLOCK_PXP2, init_phase);
18275
18276     ilt = sc->ilt;
18277     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
18278
18279 #if 0
18280     if (IS_SRIOV(sc)) {
18281         cdu_ilt_start += BXE_FIRST_VF_CID/ILT_PAGE_CIDS;
18282     }
18283     cdu_ilt_start = bxe_iov_init_ilt(sc, cdu_ilt_start);
18284
18285 #if (BXE_FIRST_VF_CID > 0)
18286     /*
18287      * If BXE_FIRST_VF_CID > 0 then the PF L2 cids precedes
18288      * those of the VFs, so start line should be reset
18289      */
18290     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
18291 #endif
18292 #endif
18293
18294     for (i = 0; i < L2_ILT_LINES(sc); i++) {
18295         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
18296         ilt->lines[cdu_ilt_start + i].page_mapping =
18297             sc->context[i].vcxt_dma.paddr;
18298         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
18299     }
18300     ecore_ilt_init_op(sc, INITOP_SET);
18301
18302 #if 0
18303     if (!CONFIGURE_NIC_MODE(sc)) {
18304         bxe_init_searcher(sc);
18305         REG_WR(sc, PRS_REG_NIC_MODE, 0);
18306         BLOGD(sc, DBG_LOAD, "NIC MODE disabled\n");
18307     } else
18308 #endif
18309     {
18310         /* Set NIC mode */
18311         REG_WR(sc, PRS_REG_NIC_MODE, 1);
18312         BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
18313     }
18314
18315     if (!CHIP_IS_E1x(sc)) {
18316         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
18317
18318         /* Turn on a single ISR mode in IGU if driver is going to use
18319          * INT#x or MSI
18320          */
18321         if (sc->interrupt_mode != INTR_MODE_MSIX) {
18322             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
18323         }
18324
18325         /*
18326          * Timers workaround bug: function init part.
18327          * Need to wait 20msec after initializing ILT,
18328          * needed to make sure there are no requests in
18329          * one of the PXP internal queues with "old" ILT addresses
18330          */
18331         DELAY(20000);
18332
18333         /*
18334          * Master enable - Due to WB DMAE writes performed before this
18335          * register is re-initialized as part of the regular function
18336          * init
18337          */
18338         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
18339         /* Enable the function in IGU */
18340         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
18341     }
18342
18343     sc->dmae_ready = 1;
18344
18345     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
18346
18347     if (!CHIP_IS_E1x(sc))
18348         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
18349
18350     ecore_init_block(sc, BLOCK_ATC, init_phase);
18351     ecore_init_block(sc, BLOCK_DMAE, init_phase);
18352     ecore_init_block(sc, BLOCK_NIG, init_phase);
18353     ecore_init_block(sc, BLOCK_SRC, init_phase);
18354     ecore_init_block(sc, BLOCK_MISC, init_phase);
18355     ecore_init_block(sc, BLOCK_TCM, init_phase);
18356     ecore_init_block(sc, BLOCK_UCM, init_phase);
18357     ecore_init_block(sc, BLOCK_CCM, init_phase);
18358     ecore_init_block(sc, BLOCK_XCM, init_phase);
18359     ecore_init_block(sc, BLOCK_TSEM, init_phase);
18360     ecore_init_block(sc, BLOCK_USEM, init_phase);
18361     ecore_init_block(sc, BLOCK_CSEM, init_phase);
18362     ecore_init_block(sc, BLOCK_XSEM, init_phase);
18363
18364     if (!CHIP_IS_E1x(sc))
18365         REG_WR(sc, QM_REG_PF_EN, 1);
18366
18367     if (!CHIP_IS_E1x(sc)) {
18368         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18369         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18370         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18371         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18372     }
18373     ecore_init_block(sc, BLOCK_QM, init_phase);
18374
18375     ecore_init_block(sc, BLOCK_TM, init_phase);
18376     ecore_init_block(sc, BLOCK_DORQ, init_phase);
18377
18378     bxe_iov_init_dq(sc);
18379
18380     ecore_init_block(sc, BLOCK_BRB1, init_phase);
18381     ecore_init_block(sc, BLOCK_PRS, init_phase);
18382     ecore_init_block(sc, BLOCK_TSDM, init_phase);
18383     ecore_init_block(sc, BLOCK_CSDM, init_phase);
18384     ecore_init_block(sc, BLOCK_USDM, init_phase);
18385     ecore_init_block(sc, BLOCK_XSDM, init_phase);
18386     ecore_init_block(sc, BLOCK_UPB, init_phase);
18387     ecore_init_block(sc, BLOCK_XPB, init_phase);
18388     ecore_init_block(sc, BLOCK_PBF, init_phase);
18389     if (!CHIP_IS_E1x(sc))
18390         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
18391
18392     ecore_init_block(sc, BLOCK_CDU, init_phase);
18393
18394     ecore_init_block(sc, BLOCK_CFC, init_phase);
18395
18396     if (!CHIP_IS_E1x(sc))
18397         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
18398
18399     if (IS_MF(sc)) {
18400         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
18401         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
18402     }
18403
18404     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
18405
18406     /* HC init per function */
18407     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18408         if (CHIP_IS_E1H(sc)) {
18409             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18410
18411             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18412             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18413         }
18414         ecore_init_block(sc, BLOCK_HC, init_phase);
18415
18416     } else {
18417         int num_segs, sb_idx, prod_offset;
18418
18419         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18420
18421         if (!CHIP_IS_E1x(sc)) {
18422             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18423             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18424         }
18425
18426         ecore_init_block(sc, BLOCK_IGU, init_phase);
18427
18428         if (!CHIP_IS_E1x(sc)) {
18429             int dsb_idx = 0;
18430             /**
18431              * Producer memory:
18432              * E2 mode: address 0-135 match to the mapping memory;
18433              * 136 - PF0 default prod; 137 - PF1 default prod;
18434              * 138 - PF2 default prod; 139 - PF3 default prod;
18435              * 140 - PF0 attn prod;    141 - PF1 attn prod;
18436              * 142 - PF2 attn prod;    143 - PF3 attn prod;
18437              * 144-147 reserved.
18438              *
18439              * E1.5 mode - In backward compatible mode;
18440              * for non default SB; each even line in the memory
18441              * holds the U producer and each odd line hold
18442              * the C producer. The first 128 producers are for
18443              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18444              * producers are for the DSB for each PF.
18445              * Each PF has five segments: (the order inside each
18446              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18447              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18448              * 144-147 attn prods;
18449              */
18450             /* non-default-status-blocks */
18451             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18452                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18453             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18454                 prod_offset = (sc->igu_base_sb + sb_idx) *
18455                     num_segs;
18456
18457                 for (i = 0; i < num_segs; i++) {
18458                     addr = IGU_REG_PROD_CONS_MEMORY +
18459                             (prod_offset + i) * 4;
18460                     REG_WR(sc, addr, 0);
18461                 }
18462                 /* send consumer update with value 0 */
18463                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18464                            USTORM_ID, 0, IGU_INT_NOP, 1);
18465                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18466             }
18467
18468             /* default-status-blocks */
18469             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18470                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18471
18472             if (CHIP_IS_MODE_4_PORT(sc))
18473                 dsb_idx = SC_FUNC(sc);
18474             else
18475                 dsb_idx = SC_VN(sc);
18476
18477             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18478                        IGU_BC_BASE_DSB_PROD + dsb_idx :
18479                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
18480
18481             /*
18482              * igu prods come in chunks of E1HVN_MAX (4) -
18483              * does not matters what is the current chip mode
18484              */
18485             for (i = 0; i < (num_segs * E1HVN_MAX);
18486                  i += E1HVN_MAX) {
18487                 addr = IGU_REG_PROD_CONS_MEMORY +
18488                             (prod_offset + i)*4;
18489                 REG_WR(sc, addr, 0);
18490             }
18491             /* send consumer update with 0 */
18492             if (CHIP_INT_MODE_IS_BC(sc)) {
18493                 bxe_ack_sb(sc, sc->igu_dsb_id,
18494                            USTORM_ID, 0, IGU_INT_NOP, 1);
18495                 bxe_ack_sb(sc, sc->igu_dsb_id,
18496                            CSTORM_ID, 0, IGU_INT_NOP, 1);
18497                 bxe_ack_sb(sc, sc->igu_dsb_id,
18498                            XSTORM_ID, 0, IGU_INT_NOP, 1);
18499                 bxe_ack_sb(sc, sc->igu_dsb_id,
18500                            TSTORM_ID, 0, IGU_INT_NOP, 1);
18501                 bxe_ack_sb(sc, sc->igu_dsb_id,
18502                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18503             } else {
18504                 bxe_ack_sb(sc, sc->igu_dsb_id,
18505                            USTORM_ID, 0, IGU_INT_NOP, 1);
18506                 bxe_ack_sb(sc, sc->igu_dsb_id,
18507                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18508             }
18509             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18510
18511             /* !!! these should become driver const once
18512                rf-tool supports split-68 const */
18513             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18514             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18515             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18516             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18517             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18518             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18519         }
18520     }
18521
18522     /* Reset PCIE errors for debug */
18523     REG_WR(sc, 0x2114, 0xffffffff);
18524     REG_WR(sc, 0x2120, 0xffffffff);
18525
18526     if (CHIP_IS_E1x(sc)) {
18527         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18528         main_mem_base = HC_REG_MAIN_MEMORY +
18529                 SC_PORT(sc) * (main_mem_size * 4);
18530         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18531         main_mem_width = 8;
18532
18533         val = REG_RD(sc, main_mem_prty_clr);
18534         if (val) {
18535             BLOGD(sc, DBG_LOAD,
18536                   "Parity errors in HC block during function init (0x%x)!\n",
18537                   val);
18538         }
18539
18540         /* Clear "false" parity errors in MSI-X table */
18541         for (i = main_mem_base;
18542              i < main_mem_base + main_mem_size * 4;
18543              i += main_mem_width) {
18544             bxe_read_dmae(sc, i, main_mem_width / 4);
18545             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18546                            i, main_mem_width / 4);
18547         }
18548         /* Clear HC parity attention */
18549         REG_RD(sc, main_mem_prty_clr);
18550     }
18551
18552 #if 1
18553     /* Enable STORMs SP logging */
18554     REG_WR8(sc, BAR_USTRORM_INTMEM +
18555            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18556     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18557            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18558     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18559            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18560     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18561            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18562 #endif
18563
18564     elink_phy_probe(&sc->link_params);
18565
18566     return (0);
18567 }
18568
18569 static void
18570 bxe_link_reset(struct bxe_softc *sc)
18571 {
18572     if (!BXE_NOMCP(sc)) {
18573         BXE_PHY_LOCK(sc);
18574         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18575         BXE_PHY_UNLOCK(sc);
18576     } else {
18577         if (!CHIP_REV_IS_SLOW(sc)) {
18578             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18579         }
18580     }
18581 }
18582
18583 static void
18584 bxe_reset_port(struct bxe_softc *sc)
18585 {
18586     int port = SC_PORT(sc);
18587     uint32_t val;
18588
18589     /* reset physical Link */
18590     bxe_link_reset(sc);
18591
18592     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18593
18594     /* Do not rcv packets to BRB */
18595     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18596     /* Do not direct rcv packets that are not for MCP to the BRB */
18597     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18598                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18599
18600     /* Configure AEU */
18601     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18602
18603     DELAY(100000);
18604
18605     /* Check for BRB port occupancy */
18606     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18607     if (val) {
18608         BLOGD(sc, DBG_LOAD,
18609               "BRB1 is not empty, %d blocks are occupied\n", val);
18610     }
18611
18612     /* TODO: Close Doorbell port? */
18613 }
18614
18615 static void
18616 bxe_ilt_wr(struct bxe_softc *sc,
18617            uint32_t         index,
18618            bus_addr_t       addr)
18619 {
18620     int reg;
18621     uint32_t wb_write[2];
18622
18623     if (CHIP_IS_E1(sc)) {
18624         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18625     } else {
18626         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18627     }
18628
18629     wb_write[0] = ONCHIP_ADDR1(addr);
18630     wb_write[1] = ONCHIP_ADDR2(addr);
18631     REG_WR_DMAE(sc, reg, wb_write, 2);
18632 }
18633
18634 static void
18635 bxe_clear_func_ilt(struct bxe_softc *sc,
18636                    uint32_t         func)
18637 {
18638     uint32_t i, base = FUNC_ILT_BASE(func);
18639     for (i = base; i < base + ILT_PER_FUNC; i++) {
18640         bxe_ilt_wr(sc, i, 0);
18641     }
18642 }
18643
18644 static void
18645 bxe_reset_func(struct bxe_softc *sc)
18646 {
18647     struct bxe_fastpath *fp;
18648     int port = SC_PORT(sc);
18649     int func = SC_FUNC(sc);
18650     int i;
18651
18652     /* Disable the function in the FW */
18653     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18654     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18655     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18656     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18657
18658     /* FP SBs */
18659     FOR_EACH_ETH_QUEUE(sc, i) {
18660         fp = &sc->fp[i];
18661         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18662                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18663                 SB_DISABLED);
18664     }
18665
18666 #if 0
18667     if (CNIC_LOADED(sc)) {
18668         /* CNIC SB */
18669         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18670                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET
18671                 (bxe_cnic_fw_sb_id(sc)), SB_DISABLED);
18672     }
18673 #endif
18674
18675     /* SP SB */
18676     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18677             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18678             SB_DISABLED);
18679
18680     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18681         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18682     }
18683
18684     /* Configure IGU */
18685     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18686         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18687         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18688     } else {
18689         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18690         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18691     }
18692
18693     if (CNIC_LOADED(sc)) {
18694         /* Disable Timer scan */
18695         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18696         /*
18697          * Wait for at least 10ms and up to 2 second for the timers
18698          * scan to complete
18699          */
18700         for (i = 0; i < 200; i++) {
18701             DELAY(10000);
18702             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18703                 break;
18704         }
18705     }
18706
18707     /* Clear ILT */
18708     bxe_clear_func_ilt(sc, func);
18709
18710     /*
18711      * Timers workaround bug for E2: if this is vnic-3,
18712      * we need to set the entire ilt range for this timers.
18713      */
18714     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18715         struct ilt_client_info ilt_cli;
18716         /* use dummy TM client */
18717         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18718         ilt_cli.start = 0;
18719         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18720         ilt_cli.client_num = ILT_CLIENT_TM;
18721
18722         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18723     }
18724
18725     /* this assumes that reset_port() called before reset_func()*/
18726     if (!CHIP_IS_E1x(sc)) {
18727         bxe_pf_disable(sc);
18728     }
18729
18730     sc->dmae_ready = 0;
18731 }
18732
18733 static int
18734 bxe_gunzip_init(struct bxe_softc *sc)
18735 {
18736     return (0);
18737 }
18738
18739 static void
18740 bxe_gunzip_end(struct bxe_softc *sc)
18741 {
18742     return;
18743 }
18744
18745 static int
18746 bxe_init_firmware(struct bxe_softc *sc)
18747 {
18748     if (CHIP_IS_E1(sc)) {
18749         ecore_init_e1_firmware(sc);
18750         sc->iro_array = e1_iro_arr;
18751     } else if (CHIP_IS_E1H(sc)) {
18752         ecore_init_e1h_firmware(sc);
18753         sc->iro_array = e1h_iro_arr;
18754     } else if (!CHIP_IS_E1x(sc)) {
18755         ecore_init_e2_firmware(sc);
18756         sc->iro_array = e2_iro_arr;
18757     } else {
18758         BLOGE(sc, "Unsupported chip revision\n");
18759         return (-1);
18760     }
18761
18762     return (0);
18763 }
18764
18765 static void
18766 bxe_release_firmware(struct bxe_softc *sc)
18767 {
18768     /* Do nothing */
18769     return;
18770 }
18771
18772 static int
18773 ecore_gunzip(struct bxe_softc *sc,
18774              const uint8_t    *zbuf,
18775              int              len)
18776 {
18777     /* XXX : Implement... */
18778     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18779     return (FALSE);
18780 }
18781
18782 static void
18783 ecore_reg_wr_ind(struct bxe_softc *sc,
18784                  uint32_t         addr,
18785                  uint32_t         val)
18786 {
18787     bxe_reg_wr_ind(sc, addr, val);
18788 }
18789
18790 static void
18791 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18792                           bus_addr_t       phys_addr,
18793                           uint32_t         addr,
18794                           uint32_t         len)
18795 {
18796     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18797 }
18798
18799 void
18800 ecore_storm_memset_struct(struct bxe_softc *sc,
18801                           uint32_t         addr,
18802                           size_t           size,
18803                           uint32_t         *data)
18804 {
18805     uint8_t i;
18806     for (i = 0; i < size/4; i++) {
18807         REG_WR(sc, addr + (i * 4), data[i]);
18808     }
18809 }
18810