]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/dev/bxe/bxe.c
MFC r298294
[FreeBSD/stable/8.git] / sys / dev / bxe / bxe.c
1 /*-
2  * Copyright (c) 2007-2014 QLogic Corporation. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS'
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #define BXE_DRIVER_VERSION "1.78.81"
31
32 #include "bxe.h"
33 #include "ecore_sp.h"
34 #include "ecore_init.h"
35 #include "ecore_init_ops.h"
36
37 #include "57710_int_offsets.h"
38 #include "57711_int_offsets.h"
39 #include "57712_int_offsets.h"
40
41 /*
42  * CTLTYPE_U64 and sysctl_handle_64 were added in r217616. Define these
43  * explicitly here for older kernels that don't include this changeset.
44  */
45 #ifndef CTLTYPE_U64
46 #define CTLTYPE_U64      CTLTYPE_QUAD
47 #define sysctl_handle_64 sysctl_handle_quad
48 #endif
49
50 /*
51  * CSUM_TCP_IPV6 and CSUM_UDP_IPV6 were added in r236170. Define these
52  * here as zero(0) for older kernels that don't include this changeset
53  * thereby masking the functionality.
54  */
55 #ifndef CSUM_TCP_IPV6
56 #define CSUM_TCP_IPV6 0
57 #define CSUM_UDP_IPV6 0
58 #endif
59
60 /*
61  * pci_find_cap was added in r219865. Re-define this at pci_find_extcap
62  * for older kernels that don't include this changeset.
63  */
64 #if __FreeBSD_version < 900035
65 #define pci_find_cap pci_find_extcap
66 #endif
67
68 #define BXE_DEF_SB_ATT_IDX 0x0001
69 #define BXE_DEF_SB_IDX     0x0002
70
71 /*
72  * FLR Support - bxe_pf_flr_clnup() is called during nic_load in the per
73  * function HW initialization.
74  */
75 #define FLR_WAIT_USEC     10000 /* 10 msecs */
76 #define FLR_WAIT_INTERVAL 50    /* usecs */
77 #define FLR_POLL_CNT      (FLR_WAIT_USEC / FLR_WAIT_INTERVAL) /* 200 */
78
79 struct pbf_pN_buf_regs {
80     int pN;
81     uint32_t init_crd;
82     uint32_t crd;
83     uint32_t crd_freed;
84 };
85
86 struct pbf_pN_cmd_regs {
87     int pN;
88     uint32_t lines_occup;
89     uint32_t lines_freed;
90 };
91
92 /*
93  * PCI Device ID Table used by bxe_probe().
94  */
95 #define BXE_DEVDESC_MAX 64
96 static struct bxe_device_type bxe_devs[] = {
97     {
98         BRCM_VENDORID,
99         CHIP_NUM_57710,
100         PCI_ANY_ID, PCI_ANY_ID,
101         "QLogic NetXtreme II BCM57710 10GbE"
102     },
103     {
104         BRCM_VENDORID,
105         CHIP_NUM_57711,
106         PCI_ANY_ID, PCI_ANY_ID,
107         "QLogic NetXtreme II BCM57711 10GbE"
108     },
109     {
110         BRCM_VENDORID,
111         CHIP_NUM_57711E,
112         PCI_ANY_ID, PCI_ANY_ID,
113         "QLogic NetXtreme II BCM57711E 10GbE"
114     },
115     {
116         BRCM_VENDORID,
117         CHIP_NUM_57712,
118         PCI_ANY_ID, PCI_ANY_ID,
119         "QLogic NetXtreme II BCM57712 10GbE"
120     },
121     {
122         BRCM_VENDORID,
123         CHIP_NUM_57712_MF,
124         PCI_ANY_ID, PCI_ANY_ID,
125         "QLogic NetXtreme II BCM57712 MF 10GbE"
126     },
127     {
128         BRCM_VENDORID,
129         CHIP_NUM_57800,
130         PCI_ANY_ID, PCI_ANY_ID,
131         "QLogic NetXtreme II BCM57800 10GbE"
132     },
133     {
134         BRCM_VENDORID,
135         CHIP_NUM_57800_MF,
136         PCI_ANY_ID, PCI_ANY_ID,
137         "QLogic NetXtreme II BCM57800 MF 10GbE"
138     },
139     {
140         BRCM_VENDORID,
141         CHIP_NUM_57810,
142         PCI_ANY_ID, PCI_ANY_ID,
143         "QLogic NetXtreme II BCM57810 10GbE"
144     },
145     {
146         BRCM_VENDORID,
147         CHIP_NUM_57810_MF,
148         PCI_ANY_ID, PCI_ANY_ID,
149         "QLogic NetXtreme II BCM57810 MF 10GbE"
150     },
151     {
152         BRCM_VENDORID,
153         CHIP_NUM_57811,
154         PCI_ANY_ID, PCI_ANY_ID,
155         "QLogic NetXtreme II BCM57811 10GbE"
156     },
157     {
158         BRCM_VENDORID,
159         CHIP_NUM_57811_MF,
160         PCI_ANY_ID, PCI_ANY_ID,
161         "QLogic NetXtreme II BCM57811 MF 10GbE"
162     },
163     {
164         BRCM_VENDORID,
165         CHIP_NUM_57840_4_10,
166         PCI_ANY_ID, PCI_ANY_ID,
167         "QLogic NetXtreme II BCM57840 4x10GbE"
168     },
169     {
170         BRCM_VENDORID,
171         CHIP_NUM_57840_MF,
172         PCI_ANY_ID, PCI_ANY_ID,
173         "QLogic NetXtreme II BCM57840 MF 10GbE"
174     },
175     {
176         0, 0, 0, 0, NULL
177     }
178 };
179
180 MALLOC_DECLARE(M_BXE_ILT);
181 MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
182
183 /*
184  * FreeBSD device entry points.
185  */
186 static int bxe_probe(device_t);
187 static int bxe_attach(device_t);
188 static int bxe_detach(device_t);
189 static int bxe_shutdown(device_t);
190
191 /*
192  * FreeBSD KLD module/device interface event handler method.
193  */
194 static device_method_t bxe_methods[] = {
195     /* Device interface (device_if.h) */
196     DEVMETHOD(device_probe,     bxe_probe),
197     DEVMETHOD(device_attach,    bxe_attach),
198     DEVMETHOD(device_detach,    bxe_detach),
199     DEVMETHOD(device_shutdown,  bxe_shutdown),
200     /* Bus interface (bus_if.h) */
201     DEVMETHOD(bus_print_child,  bus_generic_print_child),
202     DEVMETHOD(bus_driver_added, bus_generic_driver_added),
203     KOBJMETHOD_END
204 };
205
206 /*
207  * FreeBSD KLD Module data declaration
208  */
209 static driver_t bxe_driver = {
210     "bxe",                   /* module name */
211     bxe_methods,             /* event handler */
212     sizeof(struct bxe_softc) /* extra data */
213 };
214
215 /*
216  * FreeBSD dev class is needed to manage dev instances and
217  * to associate with a bus type
218  */
219 static devclass_t bxe_devclass;
220
221 MODULE_DEPEND(bxe, pci, 1, 1, 1);
222 MODULE_DEPEND(bxe, ether, 1, 1, 1);
223 DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
224
225 /* resources needed for unloading a previously loaded device */
226
227 #define BXE_PREV_WAIT_NEEDED 1
228 struct mtx bxe_prev_mtx;
229 MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
230 struct bxe_prev_list_node {
231     LIST_ENTRY(bxe_prev_list_node) node;
232     uint8_t bus;
233     uint8_t slot;
234     uint8_t path;
235     uint8_t aer; /* XXX automatic error recovery */
236     uint8_t undi;
237 };
238 static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
239
240 static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
241
242 /* Tunable device values... */
243
244 SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
245
246 /* Debug */
247 unsigned long bxe_debug = 0;
248 TUNABLE_ULONG("hw.bxe.debug", &bxe_debug);
249 SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, (CTLFLAG_RDTUN),
250              &bxe_debug, 0, "Debug logging mode");
251
252 /* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
253 static int bxe_interrupt_mode = INTR_MODE_MSIX;
254 TUNABLE_INT("hw.bxe.interrupt_mode", &bxe_interrupt_mode);
255 SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
256            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
257
258 /* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
259 static int bxe_queue_count = 4;
260 TUNABLE_INT("hw.bxe.queue_count", &bxe_queue_count);
261 SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
262            &bxe_queue_count, 0, "Multi-Queue queue count");
263
264 /* max number of buffers per queue (default RX_BD_USABLE) */
265 static int bxe_max_rx_bufs = 0;
266 TUNABLE_INT("hw.bxe.max_rx_bufs", &bxe_max_rx_bufs);
267 SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
268            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
269
270 /* Host interrupt coalescing RX tick timer (usecs) */
271 static int bxe_hc_rx_ticks = 25;
272 TUNABLE_INT("hw.bxe.hc_rx_ticks", &bxe_hc_rx_ticks);
273 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
274            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
275
276 /* Host interrupt coalescing TX tick timer (usecs) */
277 static int bxe_hc_tx_ticks = 50;
278 TUNABLE_INT("hw.bxe.hc_tx_ticks", &bxe_hc_tx_ticks);
279 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
280            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
281
282 /* Maximum number of Rx packets to process at a time */
283 static int bxe_rx_budget = 0xffffffff;
284 TUNABLE_INT("hw.bxe.rx_budget", &bxe_rx_budget);
285 SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
286            &bxe_rx_budget, 0, "Rx processing budget");
287
288 /* Maximum LRO aggregation size */
289 static int bxe_max_aggregation_size = 0;
290 TUNABLE_INT("hw.bxe.max_aggregation_size", &bxe_max_aggregation_size);
291 SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
292            &bxe_max_aggregation_size, 0, "max aggregation size");
293
294 /* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
295 static int bxe_mrrs = -1;
296 TUNABLE_INT("hw.bxe.mrrs", &bxe_mrrs);
297 SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
298            &bxe_mrrs, 0, "PCIe maximum read request size");
299
300 /* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
301 static int bxe_autogreeen = 0;
302 TUNABLE_INT("hw.bxe.autogreeen", &bxe_autogreeen);
303 SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
304            &bxe_autogreeen, 0, "AutoGrEEEn support");
305
306 /* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
307 static int bxe_udp_rss = 0;
308 TUNABLE_INT("hw.bxe.udp_rss", &bxe_udp_rss);
309 SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
310            &bxe_udp_rss, 0, "UDP RSS support");
311
312
313 #define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
314
315 #define STATS_OFFSET32(stat_name)                   \
316     (offsetof(struct bxe_eth_stats, stat_name) / 4)
317
318 #define Q_STATS_OFFSET32(stat_name)                   \
319     (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
320
321 static const struct {
322     uint32_t offset;
323     uint32_t size;
324     uint32_t flags;
325 #define STATS_FLAGS_PORT  1
326 #define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
327 #define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
328     char string[STAT_NAME_LEN];
329 } bxe_eth_stats_arr[] = {
330     { STATS_OFFSET32(total_bytes_received_hi),
331                 8, STATS_FLAGS_BOTH, "rx_bytes" },
332     { STATS_OFFSET32(error_bytes_received_hi),
333                 8, STATS_FLAGS_BOTH, "rx_error_bytes" },
334     { STATS_OFFSET32(total_unicast_packets_received_hi),
335                 8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
336     { STATS_OFFSET32(total_multicast_packets_received_hi),
337                 8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
338     { STATS_OFFSET32(total_broadcast_packets_received_hi),
339                 8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
340     { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
341                 8, STATS_FLAGS_PORT, "rx_crc_errors" },
342     { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
343                 8, STATS_FLAGS_PORT, "rx_align_errors" },
344     { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
345                 8, STATS_FLAGS_PORT, "rx_undersize_packets" },
346     { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
347                 8, STATS_FLAGS_PORT, "rx_oversize_packets" },
348     { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
349                 8, STATS_FLAGS_PORT, "rx_fragments" },
350     { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
351                 8, STATS_FLAGS_PORT, "rx_jabbers" },
352     { STATS_OFFSET32(no_buff_discard_hi),
353                 8, STATS_FLAGS_BOTH, "rx_discards" },
354     { STATS_OFFSET32(mac_filter_discard),
355                 4, STATS_FLAGS_PORT, "rx_filtered_packets" },
356     { STATS_OFFSET32(mf_tag_discard),
357                 4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
358     { STATS_OFFSET32(pfc_frames_received_hi),
359                 8, STATS_FLAGS_PORT, "pfc_frames_received" },
360     { STATS_OFFSET32(pfc_frames_sent_hi),
361                 8, STATS_FLAGS_PORT, "pfc_frames_sent" },
362     { STATS_OFFSET32(brb_drop_hi),
363                 8, STATS_FLAGS_PORT, "rx_brb_discard" },
364     { STATS_OFFSET32(brb_truncate_hi),
365                 8, STATS_FLAGS_PORT, "rx_brb_truncate" },
366     { STATS_OFFSET32(pause_frames_received_hi),
367                 8, STATS_FLAGS_PORT, "rx_pause_frames" },
368     { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
369                 8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
370     { STATS_OFFSET32(nig_timer_max),
371                 4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
372     { STATS_OFFSET32(total_bytes_transmitted_hi),
373                 8, STATS_FLAGS_BOTH, "tx_bytes" },
374     { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
375                 8, STATS_FLAGS_PORT, "tx_error_bytes" },
376     { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
377                 8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
378     { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
379                 8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
380     { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
381                 8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
382     { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
383                 8, STATS_FLAGS_PORT, "tx_mac_errors" },
384     { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
385                 8, STATS_FLAGS_PORT, "tx_carrier_errors" },
386     { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
387                 8, STATS_FLAGS_PORT, "tx_single_collisions" },
388     { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
389                 8, STATS_FLAGS_PORT, "tx_multi_collisions" },
390     { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
391                 8, STATS_FLAGS_PORT, "tx_deferred" },
392     { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
393                 8, STATS_FLAGS_PORT, "tx_excess_collisions" },
394     { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
395                 8, STATS_FLAGS_PORT, "tx_late_collisions" },
396     { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
397                 8, STATS_FLAGS_PORT, "tx_total_collisions" },
398     { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
399                 8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
400     { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
401                 8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
402     { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
403                 8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
404     { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
405                 8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
406     { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
407                 8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
408     { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
409                 8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
410     { STATS_OFFSET32(etherstatspktsover1522octets_hi),
411                 8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
412     { STATS_OFFSET32(pause_frames_sent_hi),
413                 8, STATS_FLAGS_PORT, "tx_pause_frames" },
414     { STATS_OFFSET32(total_tpa_aggregations_hi),
415                 8, STATS_FLAGS_FUNC, "tpa_aggregations" },
416     { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
417                 8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
418     { STATS_OFFSET32(total_tpa_bytes_hi),
419                 8, STATS_FLAGS_FUNC, "tpa_bytes"},
420     { STATS_OFFSET32(eee_tx_lpi),
421                 4, STATS_FLAGS_PORT, "eee_tx_lpi"},
422     { STATS_OFFSET32(rx_calls),
423                 4, STATS_FLAGS_FUNC, "rx_calls"},
424     { STATS_OFFSET32(rx_pkts),
425                 4, STATS_FLAGS_FUNC, "rx_pkts"},
426     { STATS_OFFSET32(rx_tpa_pkts),
427                 4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
428     { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
429                 4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
430     { STATS_OFFSET32(rx_bxe_service_rxsgl),
431                 4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
432     { STATS_OFFSET32(rx_jumbo_sge_pkts),
433                 4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
434     { STATS_OFFSET32(rx_soft_errors),
435                 4, STATS_FLAGS_FUNC, "rx_soft_errors"},
436     { STATS_OFFSET32(rx_hw_csum_errors),
437                 4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
438     { STATS_OFFSET32(rx_ofld_frames_csum_ip),
439                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
440     { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
441                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
442     { STATS_OFFSET32(rx_budget_reached),
443                 4, STATS_FLAGS_FUNC, "rx_budget_reached"},
444     { STATS_OFFSET32(tx_pkts),
445                 4, STATS_FLAGS_FUNC, "tx_pkts"},
446     { STATS_OFFSET32(tx_soft_errors),
447                 4, STATS_FLAGS_FUNC, "tx_soft_errors"},
448     { STATS_OFFSET32(tx_ofld_frames_csum_ip),
449                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
450     { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
451                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
452     { STATS_OFFSET32(tx_ofld_frames_csum_udp),
453                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
454     { STATS_OFFSET32(tx_ofld_frames_lso),
455                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
456     { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
457                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
458     { STATS_OFFSET32(tx_encap_failures),
459                 4, STATS_FLAGS_FUNC, "tx_encap_failures"},
460     { STATS_OFFSET32(tx_hw_queue_full),
461                 4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
462     { STATS_OFFSET32(tx_hw_max_queue_depth),
463                 4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
464     { STATS_OFFSET32(tx_dma_mapping_failure),
465                 4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
466     { STATS_OFFSET32(tx_max_drbr_queue_depth),
467                 4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
468     { STATS_OFFSET32(tx_window_violation_std),
469                 4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
470     { STATS_OFFSET32(tx_window_violation_tso),
471                 4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
472     { STATS_OFFSET32(tx_chain_lost_mbuf),
473                 4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
474     { STATS_OFFSET32(tx_frames_deferred),
475                 4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
476     { STATS_OFFSET32(tx_queue_xoff),
477                 4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
478     { STATS_OFFSET32(mbuf_defrag_attempts),
479                 4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
480     { STATS_OFFSET32(mbuf_defrag_failures),
481                 4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
482     { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
483                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
484     { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
485                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
486     { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
487                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
488     { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
489                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
490     { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
491                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
492     { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
493                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
494     { STATS_OFFSET32(mbuf_alloc_tx),
495                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
496     { STATS_OFFSET32(mbuf_alloc_rx),
497                 4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
498     { STATS_OFFSET32(mbuf_alloc_sge),
499                 4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
500     { STATS_OFFSET32(mbuf_alloc_tpa),
501                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"},
502     { STATS_OFFSET32(tx_queue_full_return),
503                 4, STATS_FLAGS_FUNC, "tx_queue_full_return"}
504 };
505
506 static const struct {
507     uint32_t offset;
508     uint32_t size;
509     char string[STAT_NAME_LEN];
510 } bxe_eth_q_stats_arr[] = {
511     { Q_STATS_OFFSET32(total_bytes_received_hi),
512                 8, "rx_bytes" },
513     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
514                 8, "rx_ucast_packets" },
515     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
516                 8, "rx_mcast_packets" },
517     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
518                 8, "rx_bcast_packets" },
519     { Q_STATS_OFFSET32(no_buff_discard_hi),
520                 8, "rx_discards" },
521     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
522                 8, "tx_bytes" },
523     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
524                 8, "tx_ucast_packets" },
525     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
526                 8, "tx_mcast_packets" },
527     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
528                 8, "tx_bcast_packets" },
529     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
530                 8, "tpa_aggregations" },
531     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
532                 8, "tpa_aggregated_frames"},
533     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
534                 8, "tpa_bytes"},
535     { Q_STATS_OFFSET32(rx_calls),
536                 4, "rx_calls"},
537     { Q_STATS_OFFSET32(rx_pkts),
538                 4, "rx_pkts"},
539     { Q_STATS_OFFSET32(rx_tpa_pkts),
540                 4, "rx_tpa_pkts"},
541     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
542                 4, "rx_erroneous_jumbo_sge_pkts"},
543     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
544                 4, "rx_bxe_service_rxsgl"},
545     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
546                 4, "rx_jumbo_sge_pkts"},
547     { Q_STATS_OFFSET32(rx_soft_errors),
548                 4, "rx_soft_errors"},
549     { Q_STATS_OFFSET32(rx_hw_csum_errors),
550                 4, "rx_hw_csum_errors"},
551     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
552                 4, "rx_ofld_frames_csum_ip"},
553     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
554                 4, "rx_ofld_frames_csum_tcp_udp"},
555     { Q_STATS_OFFSET32(rx_budget_reached),
556                 4, "rx_budget_reached"},
557     { Q_STATS_OFFSET32(tx_pkts),
558                 4, "tx_pkts"},
559     { Q_STATS_OFFSET32(tx_soft_errors),
560                 4, "tx_soft_errors"},
561     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
562                 4, "tx_ofld_frames_csum_ip"},
563     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
564                 4, "tx_ofld_frames_csum_tcp"},
565     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
566                 4, "tx_ofld_frames_csum_udp"},
567     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
568                 4, "tx_ofld_frames_lso"},
569     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
570                 4, "tx_ofld_frames_lso_hdr_splits"},
571     { Q_STATS_OFFSET32(tx_encap_failures),
572                 4, "tx_encap_failures"},
573     { Q_STATS_OFFSET32(tx_hw_queue_full),
574                 4, "tx_hw_queue_full"},
575     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
576                 4, "tx_hw_max_queue_depth"},
577     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
578                 4, "tx_dma_mapping_failure"},
579     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
580                 4, "tx_max_drbr_queue_depth"},
581     { Q_STATS_OFFSET32(tx_window_violation_std),
582                 4, "tx_window_violation_std"},
583     { Q_STATS_OFFSET32(tx_window_violation_tso),
584                 4, "tx_window_violation_tso"},
585     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
586                 4, "tx_chain_lost_mbuf"},
587     { Q_STATS_OFFSET32(tx_frames_deferred),
588                 4, "tx_frames_deferred"},
589     { Q_STATS_OFFSET32(tx_queue_xoff),
590                 4, "tx_queue_xoff"},
591     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
592                 4, "mbuf_defrag_attempts"},
593     { Q_STATS_OFFSET32(mbuf_defrag_failures),
594                 4, "mbuf_defrag_failures"},
595     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
596                 4, "mbuf_rx_bd_alloc_failed"},
597     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
598                 4, "mbuf_rx_bd_mapping_failed"},
599     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
600                 4, "mbuf_rx_tpa_alloc_failed"},
601     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
602                 4, "mbuf_rx_tpa_mapping_failed"},
603     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
604                 4, "mbuf_rx_sge_alloc_failed"},
605     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
606                 4, "mbuf_rx_sge_mapping_failed"},
607     { Q_STATS_OFFSET32(mbuf_alloc_tx),
608                 4, "mbuf_alloc_tx"},
609     { Q_STATS_OFFSET32(mbuf_alloc_rx),
610                 4, "mbuf_alloc_rx"},
611     { Q_STATS_OFFSET32(mbuf_alloc_sge),
612                 4, "mbuf_alloc_sge"},
613     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
614                 4, "mbuf_alloc_tpa"},
615     { Q_STATS_OFFSET32(tx_queue_full_return),
616                 4, "tx_queue_full_return"}
617 };
618
619 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
620 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
621
622
623 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
624                                  uint8_t          read_cfg,
625                                  uint8_t          cmng_type);
626 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
627 static void    storm_memset_cmng(struct bxe_softc *sc,
628                                  struct cmng_init *cmng,
629                                  uint8_t          port);
630 static void    bxe_set_reset_global(struct bxe_softc *sc);
631 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
632 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
633                                  int              engine);
634 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
635 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
636                                    uint8_t          *global,
637                                    uint8_t          print);
638 static void    bxe_int_disable(struct bxe_softc *sc);
639 static int     bxe_release_leader_lock(struct bxe_softc *sc);
640 static void    bxe_pf_disable(struct bxe_softc *sc);
641 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
642 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
643                                       struct bxe_fastpath *fp,
644                                       uint16_t            rx_bd_prod,
645                                       uint16_t            rx_cq_prod,
646                                       uint16_t            rx_sge_prod);
647 static void    bxe_link_report_locked(struct bxe_softc *sc);
648 static void    bxe_link_report(struct bxe_softc *sc);
649 static void    bxe_link_status_update(struct bxe_softc *sc);
650 static void    bxe_periodic_callout_func(void *xsc);
651 static void    bxe_periodic_start(struct bxe_softc *sc);
652 static void    bxe_periodic_stop(struct bxe_softc *sc);
653 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
654                                     uint16_t prev_index,
655                                     uint16_t index);
656 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
657                                      int                 queue);
658 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
659                                      uint16_t            index);
660 static uint8_t bxe_txeof(struct bxe_softc *sc,
661                          struct bxe_fastpath *fp);
662 static void    bxe_task_fp(struct bxe_fastpath *fp);
663 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
664                                      struct mbuf      *m,
665                                      uint8_t          contents);
666 static int     bxe_alloc_mem(struct bxe_softc *sc);
667 static void    bxe_free_mem(struct bxe_softc *sc);
668 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
669 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
670 static int     bxe_interrupt_attach(struct bxe_softc *sc);
671 static void    bxe_interrupt_detach(struct bxe_softc *sc);
672 static void    bxe_set_rx_mode(struct bxe_softc *sc);
673 static int     bxe_init_locked(struct bxe_softc *sc);
674 static int     bxe_stop_locked(struct bxe_softc *sc);
675 static __noinline int bxe_nic_load(struct bxe_softc *sc,
676                                    int              load_mode);
677 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
678                                      uint32_t         unload_mode,
679                                      uint8_t          keep_link);
680
681 static void bxe_handle_sp_tq(void *context, int pending);
682 static void bxe_handle_fp_tq(void *context, int pending);
683
684 static int bxe_add_cdev(struct bxe_softc *sc);
685 static void bxe_del_cdev(struct bxe_softc *sc);
686 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
687 static void bxe_free_buf_rings(struct bxe_softc *sc);
688
689 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
690 uint32_t
691 calc_crc32(uint8_t  *crc32_packet,
692            uint32_t crc32_length,
693            uint32_t crc32_seed,
694            uint8_t  complement)
695 {
696    uint32_t byte         = 0;
697    uint32_t bit          = 0;
698    uint8_t  msb          = 0;
699    uint32_t temp         = 0;
700    uint32_t shft         = 0;
701    uint8_t  current_byte = 0;
702    uint32_t crc32_result = crc32_seed;
703    const uint32_t CRC32_POLY = 0x1edc6f41;
704
705    if ((crc32_packet == NULL) ||
706        (crc32_length == 0) ||
707        ((crc32_length % 8) != 0))
708     {
709         return (crc32_result);
710     }
711
712     for (byte = 0; byte < crc32_length; byte = byte + 1)
713     {
714         current_byte = crc32_packet[byte];
715         for (bit = 0; bit < 8; bit = bit + 1)
716         {
717             /* msb = crc32_result[31]; */
718             msb = (uint8_t)(crc32_result >> 31);
719
720             crc32_result = crc32_result << 1;
721
722             /* it (msb != current_byte[bit]) */
723             if (msb != (0x1 & (current_byte >> bit)))
724             {
725                 crc32_result = crc32_result ^ CRC32_POLY;
726                 /* crc32_result[0] = 1 */
727                 crc32_result |= 1;
728             }
729         }
730     }
731
732     /* Last step is to:
733      * 1. "mirror" every bit
734      * 2. swap the 4 bytes
735      * 3. complement each bit
736      */
737
738     /* Mirror */
739     temp = crc32_result;
740     shft = sizeof(crc32_result) * 8 - 1;
741
742     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
743     {
744         temp <<= 1;
745         temp |= crc32_result & 1;
746         shft-- ;
747     }
748
749     /* temp[31-bit] = crc32_result[bit] */
750     temp <<= shft;
751
752     /* Swap */
753     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
754     {
755         uint32_t t0, t1, t2, t3;
756         t0 = (0x000000ff & (temp >> 24));
757         t1 = (0x0000ff00 & (temp >> 8));
758         t2 = (0x00ff0000 & (temp << 8));
759         t3 = (0xff000000 & (temp << 24));
760         crc32_result = t0 | t1 | t2 | t3;
761     }
762
763     /* Complement */
764     if (complement)
765     {
766         crc32_result = ~crc32_result;
767     }
768
769     return (crc32_result);
770 }
771
772 int
773 bxe_test_bit(int                    nr,
774              volatile unsigned long *addr)
775 {
776     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
777 }
778
779 void
780 bxe_set_bit(unsigned int           nr,
781             volatile unsigned long *addr)
782 {
783     atomic_set_acq_long(addr, (1 << nr));
784 }
785
786 void
787 bxe_clear_bit(int                    nr,
788               volatile unsigned long *addr)
789 {
790     atomic_clear_acq_long(addr, (1 << nr));
791 }
792
793 int
794 bxe_test_and_set_bit(int                    nr,
795                        volatile unsigned long *addr)
796 {
797     unsigned long x;
798     nr = (1 << nr);
799     do {
800         x = *addr;
801     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
802     // if (x & nr) bit_was_set; else bit_was_not_set;
803     return (x & nr);
804 }
805
806 int
807 bxe_test_and_clear_bit(int                    nr,
808                        volatile unsigned long *addr)
809 {
810     unsigned long x;
811     nr = (1 << nr);
812     do {
813         x = *addr;
814     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
815     // if (x & nr) bit_was_set; else bit_was_not_set;
816     return (x & nr);
817 }
818
819 int
820 bxe_cmpxchg(volatile int *addr,
821             int          old,
822             int          new)
823 {
824     int x;
825     do {
826         x = *addr;
827     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
828     return (x);
829 }
830
831 /*
832  * Get DMA memory from the OS.
833  *
834  * Validates that the OS has provided DMA buffers in response to a
835  * bus_dmamap_load call and saves the physical address of those buffers.
836  * When the callback is used the OS will return 0 for the mapping function
837  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
838  * failures back to the caller.
839  *
840  * Returns:
841  *   Nothing.
842  */
843 static void
844 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
845 {
846     struct bxe_dma *dma = arg;
847
848     if (error) {
849         dma->paddr = 0;
850         dma->nseg  = 0;
851         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
852     } else {
853         dma->paddr = segs->ds_addr;
854         dma->nseg  = nseg;
855     }
856 }
857
858 /*
859  * Allocate a block of memory and map it for DMA. No partial completions
860  * allowed and release any resources acquired if we can't acquire all
861  * resources.
862  *
863  * Returns:
864  *   0 = Success, !0 = Failure
865  */
866 int
867 bxe_dma_alloc(struct bxe_softc *sc,
868               bus_size_t       size,
869               struct bxe_dma   *dma,
870               const char       *msg)
871 {
872     int rc;
873
874     if (dma->size > 0) {
875         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
876               (unsigned long)dma->size);
877         return (1);
878     }
879
880     memset(dma, 0, sizeof(*dma)); /* sanity */
881     dma->sc   = sc;
882     dma->size = size;
883     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
884
885     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
886                             BCM_PAGE_SIZE,      /* alignment */
887                             0,                  /* boundary limit */
888                             BUS_SPACE_MAXADDR,  /* restricted low */
889                             BUS_SPACE_MAXADDR,  /* restricted hi */
890                             NULL,               /* addr filter() */
891                             NULL,               /* addr filter() arg */
892                             size,               /* max map size */
893                             1,                  /* num discontinuous */
894                             size,               /* max seg size */
895                             BUS_DMA_ALLOCNOW,   /* flags */
896                             NULL,               /* lock() */
897                             NULL,               /* lock() arg */
898                             &dma->tag);         /* returned dma tag */
899     if (rc != 0) {
900         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
901         memset(dma, 0, sizeof(*dma));
902         return (1);
903     }
904
905     rc = bus_dmamem_alloc(dma->tag,
906                           (void **)&dma->vaddr,
907                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
908                           &dma->map);
909     if (rc != 0) {
910         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
911         bus_dma_tag_destroy(dma->tag);
912         memset(dma, 0, sizeof(*dma));
913         return (1);
914     }
915
916     rc = bus_dmamap_load(dma->tag,
917                          dma->map,
918                          dma->vaddr,
919                          size,
920                          bxe_dma_map_addr, /* BLOGD in here */
921                          dma,
922                          BUS_DMA_NOWAIT);
923     if (rc != 0) {
924         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
925         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
926         bus_dma_tag_destroy(dma->tag);
927         memset(dma, 0, sizeof(*dma));
928         return (1);
929     }
930
931     return (0);
932 }
933
934 void
935 bxe_dma_free(struct bxe_softc *sc,
936              struct bxe_dma   *dma)
937 {
938     if (dma->size > 0) {
939         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
940
941         bus_dmamap_sync(dma->tag, dma->map,
942                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
943         bus_dmamap_unload(dma->tag, dma->map);
944         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
945         bus_dma_tag_destroy(dma->tag);
946     }
947
948     memset(dma, 0, sizeof(*dma));
949 }
950
951 /*
952  * These indirect read and write routines are only during init.
953  * The locking is handled by the MCP.
954  */
955
956 void
957 bxe_reg_wr_ind(struct bxe_softc *sc,
958                uint32_t         addr,
959                uint32_t         val)
960 {
961     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
962     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
963     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
964 }
965
966 uint32_t
967 bxe_reg_rd_ind(struct bxe_softc *sc,
968                uint32_t         addr)
969 {
970     uint32_t val;
971
972     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
973     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
974     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
975
976     return (val);
977 }
978
979 static int
980 bxe_acquire_hw_lock(struct bxe_softc *sc,
981                     uint32_t         resource)
982 {
983     uint32_t lock_status;
984     uint32_t resource_bit = (1 << resource);
985     int func = SC_FUNC(sc);
986     uint32_t hw_lock_control_reg;
987     int cnt;
988
989     /* validate the resource is within range */
990     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
991         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
992             " resource_bit 0x%x\n", resource, resource_bit);
993         return (-1);
994     }
995
996     if (func <= 5) {
997         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
998     } else {
999         hw_lock_control_reg =
1000                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1001     }
1002
1003     /* validate the resource is not already taken */
1004     lock_status = REG_RD(sc, hw_lock_control_reg);
1005     if (lock_status & resource_bit) {
1006         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1007               resource, lock_status, resource_bit);
1008         return (-1);
1009     }
1010
1011     /* try every 5ms for 5 seconds */
1012     for (cnt = 0; cnt < 1000; cnt++) {
1013         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1014         lock_status = REG_RD(sc, hw_lock_control_reg);
1015         if (lock_status & resource_bit) {
1016             return (0);
1017         }
1018         DELAY(5000);
1019     }
1020
1021     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1022         resource, resource_bit);
1023     return (-1);
1024 }
1025
1026 static int
1027 bxe_release_hw_lock(struct bxe_softc *sc,
1028                     uint32_t         resource)
1029 {
1030     uint32_t lock_status;
1031     uint32_t resource_bit = (1 << resource);
1032     int func = SC_FUNC(sc);
1033     uint32_t hw_lock_control_reg;
1034
1035     /* validate the resource is within range */
1036     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1037         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1038             " resource_bit 0x%x\n", resource, resource_bit);
1039         return (-1);
1040     }
1041
1042     if (func <= 5) {
1043         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1044     } else {
1045         hw_lock_control_reg =
1046                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1047     }
1048
1049     /* validate the resource is currently taken */
1050     lock_status = REG_RD(sc, hw_lock_control_reg);
1051     if (!(lock_status & resource_bit)) {
1052         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1053               resource, lock_status, resource_bit);
1054         return (-1);
1055     }
1056
1057     REG_WR(sc, hw_lock_control_reg, resource_bit);
1058     return (0);
1059 }
1060 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1061 {
1062         BXE_PHY_LOCK(sc);
1063         bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1064 }
1065
1066 static void bxe_release_phy_lock(struct bxe_softc *sc)
1067 {
1068         bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1069         BXE_PHY_UNLOCK(sc);
1070 }
1071 /*
1072  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1073  * had we done things the other way around, if two pfs from the same port
1074  * would attempt to access nvram at the same time, we could run into a
1075  * scenario such as:
1076  * pf A takes the port lock.
1077  * pf B succeeds in taking the same lock since they are from the same port.
1078  * pf A takes the per pf misc lock. Performs eeprom access.
1079  * pf A finishes. Unlocks the per pf misc lock.
1080  * Pf B takes the lock and proceeds to perform it's own access.
1081  * pf A unlocks the per port lock, while pf B is still working (!).
1082  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1083  * access corrupted by pf B).*
1084  */
1085 static int
1086 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1087 {
1088     int port = SC_PORT(sc);
1089     int count, i;
1090     uint32_t val = 0;
1091
1092     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1093     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1094
1095     /* adjust timeout for emulation/FPGA */
1096     count = NVRAM_TIMEOUT_COUNT;
1097     if (CHIP_REV_IS_SLOW(sc)) {
1098         count *= 100;
1099     }
1100
1101     /* request access to nvram interface */
1102     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1103            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1104
1105     for (i = 0; i < count*10; i++) {
1106         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1107         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1108             break;
1109         }
1110
1111         DELAY(5);
1112     }
1113
1114     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1115         BLOGE(sc, "Cannot get access to nvram interface "
1116             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1117             port, val);
1118         return (-1);
1119     }
1120
1121     return (0);
1122 }
1123
1124 static int
1125 bxe_release_nvram_lock(struct bxe_softc *sc)
1126 {
1127     int port = SC_PORT(sc);
1128     int count, i;
1129     uint32_t val = 0;
1130
1131     /* adjust timeout for emulation/FPGA */
1132     count = NVRAM_TIMEOUT_COUNT;
1133     if (CHIP_REV_IS_SLOW(sc)) {
1134         count *= 100;
1135     }
1136
1137     /* relinquish nvram interface */
1138     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1139            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1140
1141     for (i = 0; i < count*10; i++) {
1142         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1143         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1144             break;
1145         }
1146
1147         DELAY(5);
1148     }
1149
1150     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1151         BLOGE(sc, "Cannot free access to nvram interface "
1152             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1153             port, val);
1154         return (-1);
1155     }
1156
1157     /* release HW lock: protect against other PFs in PF Direct Assignment */
1158     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1159
1160     return (0);
1161 }
1162
1163 static void
1164 bxe_enable_nvram_access(struct bxe_softc *sc)
1165 {
1166     uint32_t val;
1167
1168     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1169
1170     /* enable both bits, even on read */
1171     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1172            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1173 }
1174
1175 static void
1176 bxe_disable_nvram_access(struct bxe_softc *sc)
1177 {
1178     uint32_t val;
1179
1180     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1181
1182     /* disable both bits, even after read */
1183     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1184            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1185                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1186 }
1187
1188 static int
1189 bxe_nvram_read_dword(struct bxe_softc *sc,
1190                      uint32_t         offset,
1191                      uint32_t         *ret_val,
1192                      uint32_t         cmd_flags)
1193 {
1194     int count, i, rc;
1195     uint32_t val;
1196
1197     /* build the command word */
1198     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1199
1200     /* need to clear DONE bit separately */
1201     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1202
1203     /* address of the NVRAM to read from */
1204     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1205            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1206
1207     /* issue a read command */
1208     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1209
1210     /* adjust timeout for emulation/FPGA */
1211     count = NVRAM_TIMEOUT_COUNT;
1212     if (CHIP_REV_IS_SLOW(sc)) {
1213         count *= 100;
1214     }
1215
1216     /* wait for completion */
1217     *ret_val = 0;
1218     rc = -1;
1219     for (i = 0; i < count; i++) {
1220         DELAY(5);
1221         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1222
1223         if (val & MCPR_NVM_COMMAND_DONE) {
1224             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1225             /* we read nvram data in cpu order
1226              * but ethtool sees it as an array of bytes
1227              * converting to big-endian will do the work
1228              */
1229             *ret_val = htobe32(val);
1230             rc = 0;
1231             break;
1232         }
1233     }
1234
1235     if (rc == -1) {
1236         BLOGE(sc, "nvram read timeout expired "
1237             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1238             offset, cmd_flags, val);
1239     }
1240
1241     return (rc);
1242 }
1243
1244 static int
1245 bxe_nvram_read(struct bxe_softc *sc,
1246                uint32_t         offset,
1247                uint8_t          *ret_buf,
1248                int              buf_size)
1249 {
1250     uint32_t cmd_flags;
1251     uint32_t val;
1252     int rc;
1253
1254     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1255         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1256               offset, buf_size);
1257         return (-1);
1258     }
1259
1260     if ((offset + buf_size) > sc->devinfo.flash_size) {
1261         BLOGE(sc, "Invalid parameter, "
1262                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1263               offset, buf_size, sc->devinfo.flash_size);
1264         return (-1);
1265     }
1266
1267     /* request access to nvram interface */
1268     rc = bxe_acquire_nvram_lock(sc);
1269     if (rc) {
1270         return (rc);
1271     }
1272
1273     /* enable access to nvram interface */
1274     bxe_enable_nvram_access(sc);
1275
1276     /* read the first word(s) */
1277     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1278     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1279         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1280         memcpy(ret_buf, &val, 4);
1281
1282         /* advance to the next dword */
1283         offset += sizeof(uint32_t);
1284         ret_buf += sizeof(uint32_t);
1285         buf_size -= sizeof(uint32_t);
1286         cmd_flags = 0;
1287     }
1288
1289     if (rc == 0) {
1290         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1291         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1292         memcpy(ret_buf, &val, 4);
1293     }
1294
1295     /* disable access to nvram interface */
1296     bxe_disable_nvram_access(sc);
1297     bxe_release_nvram_lock(sc);
1298
1299     return (rc);
1300 }
1301
1302 static int
1303 bxe_nvram_write_dword(struct bxe_softc *sc,
1304                       uint32_t         offset,
1305                       uint32_t         val,
1306                       uint32_t         cmd_flags)
1307 {
1308     int count, i, rc;
1309
1310     /* build the command word */
1311     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1312
1313     /* need to clear DONE bit separately */
1314     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1315
1316     /* write the data */
1317     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1318
1319     /* address of the NVRAM to write to */
1320     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1321            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1322
1323     /* issue the write command */
1324     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1325
1326     /* adjust timeout for emulation/FPGA */
1327     count = NVRAM_TIMEOUT_COUNT;
1328     if (CHIP_REV_IS_SLOW(sc)) {
1329         count *= 100;
1330     }
1331
1332     /* wait for completion */
1333     rc = -1;
1334     for (i = 0; i < count; i++) {
1335         DELAY(5);
1336         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1337         if (val & MCPR_NVM_COMMAND_DONE) {
1338             rc = 0;
1339             break;
1340         }
1341     }
1342
1343     if (rc == -1) {
1344         BLOGE(sc, "nvram write timeout expired "
1345             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1346             offset, cmd_flags, val);
1347     }
1348
1349     return (rc);
1350 }
1351
1352 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1353
1354 static int
1355 bxe_nvram_write1(struct bxe_softc *sc,
1356                  uint32_t         offset,
1357                  uint8_t          *data_buf,
1358                  int              buf_size)
1359 {
1360     uint32_t cmd_flags;
1361     uint32_t align_offset;
1362     uint32_t val;
1363     int rc;
1364
1365     if ((offset + buf_size) > sc->devinfo.flash_size) {
1366         BLOGE(sc, "Invalid parameter, "
1367                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1368               offset, buf_size, sc->devinfo.flash_size);
1369         return (-1);
1370     }
1371
1372     /* request access to nvram interface */
1373     rc = bxe_acquire_nvram_lock(sc);
1374     if (rc) {
1375         return (rc);
1376     }
1377
1378     /* enable access to nvram interface */
1379     bxe_enable_nvram_access(sc);
1380
1381     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1382     align_offset = (offset & ~0x03);
1383     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1384
1385     if (rc == 0) {
1386         val &= ~(0xff << BYTE_OFFSET(offset));
1387         val |= (*data_buf << BYTE_OFFSET(offset));
1388
1389         /* nvram data is returned as an array of bytes
1390          * convert it back to cpu order
1391          */
1392         val = be32toh(val);
1393
1394         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1395     }
1396
1397     /* disable access to nvram interface */
1398     bxe_disable_nvram_access(sc);
1399     bxe_release_nvram_lock(sc);
1400
1401     return (rc);
1402 }
1403
1404 static int
1405 bxe_nvram_write(struct bxe_softc *sc,
1406                 uint32_t         offset,
1407                 uint8_t          *data_buf,
1408                 int              buf_size)
1409 {
1410     uint32_t cmd_flags;
1411     uint32_t val;
1412     uint32_t written_so_far;
1413     int rc;
1414
1415     if (buf_size == 1) {
1416         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1417     }
1418
1419     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1420         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1421               offset, buf_size);
1422         return (-1);
1423     }
1424
1425     if (buf_size == 0) {
1426         return (0); /* nothing to do */
1427     }
1428
1429     if ((offset + buf_size) > sc->devinfo.flash_size) {
1430         BLOGE(sc, "Invalid parameter, "
1431                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1432               offset, buf_size, sc->devinfo.flash_size);
1433         return (-1);
1434     }
1435
1436     /* request access to nvram interface */
1437     rc = bxe_acquire_nvram_lock(sc);
1438     if (rc) {
1439         return (rc);
1440     }
1441
1442     /* enable access to nvram interface */
1443     bxe_enable_nvram_access(sc);
1444
1445     written_so_far = 0;
1446     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1447     while ((written_so_far < buf_size) && (rc == 0)) {
1448         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1449             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1450         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1451             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1452         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1453             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1454         }
1455
1456         memcpy(&val, data_buf, 4);
1457
1458         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1459
1460         /* advance to the next dword */
1461         offset += sizeof(uint32_t);
1462         data_buf += sizeof(uint32_t);
1463         written_so_far += sizeof(uint32_t);
1464         cmd_flags = 0;
1465     }
1466
1467     /* disable access to nvram interface */
1468     bxe_disable_nvram_access(sc);
1469     bxe_release_nvram_lock(sc);
1470
1471     return (rc);
1472 }
1473
1474 /* copy command into DMAE command memory and set DMAE command Go */
1475 void
1476 bxe_post_dmae(struct bxe_softc    *sc,
1477               struct dmae_cmd *dmae,
1478               int                 idx)
1479 {
1480     uint32_t cmd_offset;
1481     int i;
1482
1483     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1484     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1485         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1486     }
1487
1488     REG_WR(sc, dmae_reg_go_c[idx], 1);
1489 }
1490
1491 uint32_t
1492 bxe_dmae_opcode_add_comp(uint32_t opcode,
1493                          uint8_t  comp_type)
1494 {
1495     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1496                       DMAE_CMD_C_TYPE_ENABLE));
1497 }
1498
1499 uint32_t
1500 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1501 {
1502     return (opcode & ~DMAE_CMD_SRC_RESET);
1503 }
1504
1505 uint32_t
1506 bxe_dmae_opcode(struct bxe_softc *sc,
1507                 uint8_t          src_type,
1508                 uint8_t          dst_type,
1509                 uint8_t          with_comp,
1510                 uint8_t          comp_type)
1511 {
1512     uint32_t opcode = 0;
1513
1514     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1515                (dst_type << DMAE_CMD_DST_SHIFT));
1516
1517     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1518
1519     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1520
1521     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1522                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1523
1524     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1525
1526 #ifdef __BIG_ENDIAN
1527     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1528 #else
1529     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1530 #endif
1531
1532     if (with_comp) {
1533         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1534     }
1535
1536     return (opcode);
1537 }
1538
1539 static void
1540 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1541                         struct dmae_cmd *dmae,
1542                         uint8_t             src_type,
1543                         uint8_t             dst_type)
1544 {
1545     memset(dmae, 0, sizeof(struct dmae_cmd));
1546
1547     /* set the opcode */
1548     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1549                                    TRUE, DMAE_COMP_PCI);
1550
1551     /* fill in the completion parameters */
1552     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1553     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1554     dmae->comp_val     = DMAE_COMP_VAL;
1555 }
1556
1557 /* issue a DMAE command over the init channel and wait for completion */
1558 static int
1559 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1560                          struct dmae_cmd *dmae)
1561 {
1562     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1563     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1564
1565     BXE_DMAE_LOCK(sc);
1566
1567     /* reset completion */
1568     *wb_comp = 0;
1569
1570     /* post the command on the channel used for initializations */
1571     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1572
1573     /* wait for completion */
1574     DELAY(5);
1575
1576     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1577         if (!timeout ||
1578             (sc->recovery_state != BXE_RECOVERY_DONE &&
1579              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1580             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1581                 *wb_comp, sc->recovery_state);
1582             BXE_DMAE_UNLOCK(sc);
1583             return (DMAE_TIMEOUT);
1584         }
1585
1586         timeout--;
1587         DELAY(50);
1588     }
1589
1590     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1591         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1592                 *wb_comp, sc->recovery_state);
1593         BXE_DMAE_UNLOCK(sc);
1594         return (DMAE_PCI_ERROR);
1595     }
1596
1597     BXE_DMAE_UNLOCK(sc);
1598     return (0);
1599 }
1600
1601 void
1602 bxe_read_dmae(struct bxe_softc *sc,
1603               uint32_t         src_addr,
1604               uint32_t         len32)
1605 {
1606     struct dmae_cmd dmae;
1607     uint32_t *data;
1608     int i, rc;
1609
1610     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1611
1612     if (!sc->dmae_ready) {
1613         data = BXE_SP(sc, wb_data[0]);
1614
1615         for (i = 0; i < len32; i++) {
1616             data[i] = (CHIP_IS_E1(sc)) ?
1617                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1618                           REG_RD(sc, (src_addr + (i * 4)));
1619         }
1620
1621         return;
1622     }
1623
1624     /* set opcode and fixed command fields */
1625     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1626
1627     /* fill in addresses and len */
1628     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1629     dmae.src_addr_hi = 0;
1630     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1631     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1632     dmae.len         = len32;
1633
1634     /* issue the command and wait for completion */
1635     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1636         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1637     };
1638 }
1639
1640 void
1641 bxe_write_dmae(struct bxe_softc *sc,
1642                bus_addr_t       dma_addr,
1643                uint32_t         dst_addr,
1644                uint32_t         len32)
1645 {
1646     struct dmae_cmd dmae;
1647     int rc;
1648
1649     if (!sc->dmae_ready) {
1650         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1651
1652         if (CHIP_IS_E1(sc)) {
1653             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1654         } else {
1655             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1656         }
1657
1658         return;
1659     }
1660
1661     /* set opcode and fixed command fields */
1662     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1663
1664     /* fill in addresses and len */
1665     dmae.src_addr_lo = U64_LO(dma_addr);
1666     dmae.src_addr_hi = U64_HI(dma_addr);
1667     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1668     dmae.dst_addr_hi = 0;
1669     dmae.len         = len32;
1670
1671     /* issue the command and wait for completion */
1672     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1673         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1674     }
1675 }
1676
1677 void
1678 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1679                         bus_addr_t       phys_addr,
1680                         uint32_t         addr,
1681                         uint32_t         len)
1682 {
1683     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1684     int offset = 0;
1685
1686     while (len > dmae_wr_max) {
1687         bxe_write_dmae(sc,
1688                        (phys_addr + offset), /* src DMA address */
1689                        (addr + offset),      /* dst GRC address */
1690                        dmae_wr_max);
1691         offset += (dmae_wr_max * 4);
1692         len -= dmae_wr_max;
1693     }
1694
1695     bxe_write_dmae(sc,
1696                    (phys_addr + offset), /* src DMA address */
1697                    (addr + offset),      /* dst GRC address */
1698                    len);
1699 }
1700
1701 void
1702 bxe_set_ctx_validation(struct bxe_softc   *sc,
1703                        struct eth_context *cxt,
1704                        uint32_t           cid)
1705 {
1706     /* ustorm cxt validation */
1707     cxt->ustorm_ag_context.cdu_usage =
1708         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1709             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1710     /* xcontext validation */
1711     cxt->xstorm_ag_context.cdu_reserved =
1712         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1713             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1714 }
1715
1716 static void
1717 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1718                             uint8_t          port,
1719                             uint8_t          fw_sb_id,
1720                             uint8_t          sb_index,
1721                             uint8_t          ticks)
1722 {
1723     uint32_t addr =
1724         (BAR_CSTRORM_INTMEM +
1725          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1726
1727     REG_WR8(sc, addr, ticks);
1728
1729     BLOGD(sc, DBG_LOAD,
1730           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1731           port, fw_sb_id, sb_index, ticks);
1732 }
1733
1734 static void
1735 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1736                             uint8_t          port,
1737                             uint16_t         fw_sb_id,
1738                             uint8_t          sb_index,
1739                             uint8_t          disable)
1740 {
1741     uint32_t enable_flag =
1742         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1743     uint32_t addr =
1744         (BAR_CSTRORM_INTMEM +
1745          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1746     uint8_t flags;
1747
1748     /* clear and set */
1749     flags = REG_RD8(sc, addr);
1750     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1751     flags |= enable_flag;
1752     REG_WR8(sc, addr, flags);
1753
1754     BLOGD(sc, DBG_LOAD,
1755           "port %d fw_sb_id %d sb_index %d disable %d\n",
1756           port, fw_sb_id, sb_index, disable);
1757 }
1758
1759 void
1760 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1761                              uint8_t          fw_sb_id,
1762                              uint8_t          sb_index,
1763                              uint8_t          disable,
1764                              uint16_t         usec)
1765 {
1766     int port = SC_PORT(sc);
1767     uint8_t ticks = (usec / 4); /* XXX ??? */
1768
1769     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1770
1771     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1772     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1773 }
1774
1775 void
1776 elink_cb_udelay(struct bxe_softc *sc,
1777                 uint32_t         usecs)
1778 {
1779     DELAY(usecs);
1780 }
1781
1782 uint32_t
1783 elink_cb_reg_read(struct bxe_softc *sc,
1784                   uint32_t         reg_addr)
1785 {
1786     return (REG_RD(sc, reg_addr));
1787 }
1788
1789 void
1790 elink_cb_reg_write(struct bxe_softc *sc,
1791                    uint32_t         reg_addr,
1792                    uint32_t         val)
1793 {
1794     REG_WR(sc, reg_addr, val);
1795 }
1796
1797 void
1798 elink_cb_reg_wb_write(struct bxe_softc *sc,
1799                       uint32_t         offset,
1800                       uint32_t         *wb_write,
1801                       uint16_t         len)
1802 {
1803     REG_WR_DMAE(sc, offset, wb_write, len);
1804 }
1805
1806 void
1807 elink_cb_reg_wb_read(struct bxe_softc *sc,
1808                      uint32_t         offset,
1809                      uint32_t         *wb_write,
1810                      uint16_t         len)
1811 {
1812     REG_RD_DMAE(sc, offset, wb_write, len);
1813 }
1814
1815 uint8_t
1816 elink_cb_path_id(struct bxe_softc *sc)
1817 {
1818     return (SC_PATH(sc));
1819 }
1820
1821 void
1822 elink_cb_event_log(struct bxe_softc     *sc,
1823                    const elink_log_id_t elink_log_id,
1824                    ...)
1825 {
1826     /* XXX */
1827     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1828 }
1829
1830 static int
1831 bxe_set_spio(struct bxe_softc *sc,
1832              int              spio,
1833              uint32_t         mode)
1834 {
1835     uint32_t spio_reg;
1836
1837     /* Only 2 SPIOs are configurable */
1838     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1839         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1840         return (-1);
1841     }
1842
1843     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1844
1845     /* read SPIO and mask except the float bits */
1846     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1847
1848     switch (mode) {
1849     case MISC_SPIO_OUTPUT_LOW:
1850         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1851         /* clear FLOAT and set CLR */
1852         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1853         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1854         break;
1855
1856     case MISC_SPIO_OUTPUT_HIGH:
1857         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1858         /* clear FLOAT and set SET */
1859         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1860         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1861         break;
1862
1863     case MISC_SPIO_INPUT_HI_Z:
1864         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1865         /* set FLOAT */
1866         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1867         break;
1868
1869     default:
1870         break;
1871     }
1872
1873     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1874     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1875
1876     return (0);
1877 }
1878
1879 static int
1880 bxe_gpio_read(struct bxe_softc *sc,
1881               int              gpio_num,
1882               uint8_t          port)
1883 {
1884     /* The GPIO should be swapped if swap register is set and active */
1885     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1886                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1887     int gpio_shift = (gpio_num +
1888                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1889     uint32_t gpio_mask = (1 << gpio_shift);
1890     uint32_t gpio_reg;
1891
1892     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1893         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1894             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1895             gpio_mask);
1896         return (-1);
1897     }
1898
1899     /* read GPIO value */
1900     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1901
1902     /* get the requested pin value */
1903     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1904 }
1905
1906 static int
1907 bxe_gpio_write(struct bxe_softc *sc,
1908                int              gpio_num,
1909                uint32_t         mode,
1910                uint8_t          port)
1911 {
1912     /* The GPIO should be swapped if swap register is set and active */
1913     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1914                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1915     int gpio_shift = (gpio_num +
1916                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1917     uint32_t gpio_mask = (1 << gpio_shift);
1918     uint32_t gpio_reg;
1919
1920     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1921         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1922             " gpio_shift %d gpio_mask 0x%x\n",
1923             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1924         return (-1);
1925     }
1926
1927     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1928
1929     /* read GPIO and mask except the float bits */
1930     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1931
1932     switch (mode) {
1933     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1934         BLOGD(sc, DBG_PHY,
1935               "Set GPIO %d (shift %d) -> output low\n",
1936               gpio_num, gpio_shift);
1937         /* clear FLOAT and set CLR */
1938         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1939         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1940         break;
1941
1942     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1943         BLOGD(sc, DBG_PHY,
1944               "Set GPIO %d (shift %d) -> output high\n",
1945               gpio_num, gpio_shift);
1946         /* clear FLOAT and set SET */
1947         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1948         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1949         break;
1950
1951     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1952         BLOGD(sc, DBG_PHY,
1953               "Set GPIO %d (shift %d) -> input\n",
1954               gpio_num, gpio_shift);
1955         /* set FLOAT */
1956         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1957         break;
1958
1959     default:
1960         break;
1961     }
1962
1963     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1964     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1965
1966     return (0);
1967 }
1968
1969 static int
1970 bxe_gpio_mult_write(struct bxe_softc *sc,
1971                     uint8_t          pins,
1972                     uint32_t         mode)
1973 {
1974     uint32_t gpio_reg;
1975
1976     /* any port swapping should be handled by caller */
1977
1978     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1979
1980     /* read GPIO and mask except the float bits */
1981     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1982     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1983     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
1984     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
1985
1986     switch (mode) {
1987     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1988         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
1989         /* set CLR */
1990         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
1991         break;
1992
1993     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1994         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
1995         /* set SET */
1996         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
1997         break;
1998
1999     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2000         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2001         /* set FLOAT */
2002         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2003         break;
2004
2005     default:
2006         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2007             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2008         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2009         return (-1);
2010     }
2011
2012     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2013     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2014
2015     return (0);
2016 }
2017
2018 static int
2019 bxe_gpio_int_write(struct bxe_softc *sc,
2020                    int              gpio_num,
2021                    uint32_t         mode,
2022                    uint8_t          port)
2023 {
2024     /* The GPIO should be swapped if swap register is set and active */
2025     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2026                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2027     int gpio_shift = (gpio_num +
2028                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2029     uint32_t gpio_mask = (1 << gpio_shift);
2030     uint32_t gpio_reg;
2031
2032     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2033         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2034             " gpio_shift %d gpio_mask 0x%x\n",
2035             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2036         return (-1);
2037     }
2038
2039     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2040
2041     /* read GPIO int */
2042     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2043
2044     switch (mode) {
2045     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2046         BLOGD(sc, DBG_PHY,
2047               "Clear GPIO INT %d (shift %d) -> output low\n",
2048               gpio_num, gpio_shift);
2049         /* clear SET and set CLR */
2050         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2051         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2052         break;
2053
2054     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2055         BLOGD(sc, DBG_PHY,
2056               "Set GPIO INT %d (shift %d) -> output high\n",
2057               gpio_num, gpio_shift);
2058         /* clear CLR and set SET */
2059         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2060         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2061         break;
2062
2063     default:
2064         break;
2065     }
2066
2067     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2068     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2069
2070     return (0);
2071 }
2072
2073 uint32_t
2074 elink_cb_gpio_read(struct bxe_softc *sc,
2075                    uint16_t         gpio_num,
2076                    uint8_t          port)
2077 {
2078     return (bxe_gpio_read(sc, gpio_num, port));
2079 }
2080
2081 uint8_t
2082 elink_cb_gpio_write(struct bxe_softc *sc,
2083                     uint16_t         gpio_num,
2084                     uint8_t          mode, /* 0=low 1=high */
2085                     uint8_t          port)
2086 {
2087     return (bxe_gpio_write(sc, gpio_num, mode, port));
2088 }
2089
2090 uint8_t
2091 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2092                          uint8_t          pins,
2093                          uint8_t          mode) /* 0=low 1=high */
2094 {
2095     return (bxe_gpio_mult_write(sc, pins, mode));
2096 }
2097
2098 uint8_t
2099 elink_cb_gpio_int_write(struct bxe_softc *sc,
2100                         uint16_t         gpio_num,
2101                         uint8_t          mode, /* 0=low 1=high */
2102                         uint8_t          port)
2103 {
2104     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2105 }
2106
2107 void
2108 elink_cb_notify_link_changed(struct bxe_softc *sc)
2109 {
2110     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2111                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2112 }
2113
2114 /* send the MCP a request, block until there is a reply */
2115 uint32_t
2116 elink_cb_fw_command(struct bxe_softc *sc,
2117                     uint32_t         command,
2118                     uint32_t         param)
2119 {
2120     int mb_idx = SC_FW_MB_IDX(sc);
2121     uint32_t seq;
2122     uint32_t rc = 0;
2123     uint32_t cnt = 1;
2124     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2125
2126     BXE_FWMB_LOCK(sc);
2127
2128     seq = ++sc->fw_seq;
2129     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2130     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2131
2132     BLOGD(sc, DBG_PHY,
2133           "wrote command 0x%08x to FW MB param 0x%08x\n",
2134           (command | seq), param);
2135
2136     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2137     do {
2138         DELAY(delay * 1000);
2139         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2140     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2141
2142     BLOGD(sc, DBG_PHY,
2143           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2144           cnt*delay, rc, seq);
2145
2146     /* is this a reply to our command? */
2147     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2148         rc &= FW_MSG_CODE_MASK;
2149     } else {
2150         /* Ruh-roh! */
2151         BLOGE(sc, "FW failed to respond!\n");
2152         // XXX bxe_fw_dump(sc);
2153         rc = 0;
2154     }
2155
2156     BXE_FWMB_UNLOCK(sc);
2157     return (rc);
2158 }
2159
2160 static uint32_t
2161 bxe_fw_command(struct bxe_softc *sc,
2162                uint32_t         command,
2163                uint32_t         param)
2164 {
2165     return (elink_cb_fw_command(sc, command, param));
2166 }
2167
2168 static void
2169 __storm_memset_dma_mapping(struct bxe_softc *sc,
2170                            uint32_t         addr,
2171                            bus_addr_t       mapping)
2172 {
2173     REG_WR(sc, addr, U64_LO(mapping));
2174     REG_WR(sc, (addr + 4), U64_HI(mapping));
2175 }
2176
2177 static void
2178 storm_memset_spq_addr(struct bxe_softc *sc,
2179                       bus_addr_t       mapping,
2180                       uint16_t         abs_fid)
2181 {
2182     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2183                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2184     __storm_memset_dma_mapping(sc, addr, mapping);
2185 }
2186
2187 static void
2188 storm_memset_vf_to_pf(struct bxe_softc *sc,
2189                       uint16_t         abs_fid,
2190                       uint16_t         pf_id)
2191 {
2192     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2193     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2194     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2195     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2196 }
2197
2198 static void
2199 storm_memset_func_en(struct bxe_softc *sc,
2200                      uint16_t         abs_fid,
2201                      uint8_t          enable)
2202 {
2203     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2204     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2205     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2206     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2207 }
2208
2209 static void
2210 storm_memset_eq_data(struct bxe_softc       *sc,
2211                      struct event_ring_data *eq_data,
2212                      uint16_t               pfid)
2213 {
2214     uint32_t addr;
2215     size_t size;
2216
2217     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2218     size = sizeof(struct event_ring_data);
2219     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2220 }
2221
2222 static void
2223 storm_memset_eq_prod(struct bxe_softc *sc,
2224                      uint16_t         eq_prod,
2225                      uint16_t         pfid)
2226 {
2227     uint32_t addr = (BAR_CSTRORM_INTMEM +
2228                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2229     REG_WR16(sc, addr, eq_prod);
2230 }
2231
2232 /*
2233  * Post a slowpath command.
2234  *
2235  * A slowpath command is used to propogate a configuration change through
2236  * the controller in a controlled manner, allowing each STORM processor and
2237  * other H/W blocks to phase in the change.  The commands sent on the
2238  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2239  * completion of the ramrod will occur in different ways.  Here's a
2240  * breakdown of ramrods and how they complete:
2241  *
2242  * RAMROD_CMD_ID_ETH_PORT_SETUP
2243  *   Used to setup the leading connection on a port.  Completes on the
2244  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2245  *
2246  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2247  *   Used to setup an additional connection on a port.  Completes on the
2248  *   RCQ of the multi-queue/RSS connection being initialized.
2249  *
2250  * RAMROD_CMD_ID_ETH_STAT_QUERY
2251  *   Used to force the storm processors to update the statistics database
2252  *   in host memory.  This ramrod is send on the leading connection CID and
2253  *   completes as an index increment of the CSTORM on the default status
2254  *   block.
2255  *
2256  * RAMROD_CMD_ID_ETH_UPDATE
2257  *   Used to update the state of the leading connection, usually to udpate
2258  *   the RSS indirection table.  Completes on the RCQ of the leading
2259  *   connection. (Not currently used under FreeBSD until OS support becomes
2260  *   available.)
2261  *
2262  * RAMROD_CMD_ID_ETH_HALT
2263  *   Used when tearing down a connection prior to driver unload.  Completes
2264  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2265  *   use this on the leading connection.
2266  *
2267  * RAMROD_CMD_ID_ETH_SET_MAC
2268  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2269  *   the RCQ of the leading connection.
2270  *
2271  * RAMROD_CMD_ID_ETH_CFC_DEL
2272  *   Used when tearing down a conneciton prior to driver unload.  Completes
2273  *   on the RCQ of the leading connection (since the current connection
2274  *   has been completely removed from controller memory).
2275  *
2276  * RAMROD_CMD_ID_ETH_PORT_DEL
2277  *   Used to tear down the leading connection prior to driver unload,
2278  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2279  *   default status block.
2280  *
2281  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2282  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2283  *   RSS connection that is being offloaded.  (Not currently used under
2284  *   FreeBSD.)
2285  *
2286  * There can only be one command pending per function.
2287  *
2288  * Returns:
2289  *   0 = Success, !0 = Failure.
2290  */
2291
2292 /* must be called under the spq lock */
2293 static inline
2294 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2295 {
2296     struct eth_spe *next_spe = sc->spq_prod_bd;
2297
2298     if (sc->spq_prod_bd == sc->spq_last_bd) {
2299         /* wrap back to the first eth_spq */
2300         sc->spq_prod_bd = sc->spq;
2301         sc->spq_prod_idx = 0;
2302     } else {
2303         sc->spq_prod_bd++;
2304         sc->spq_prod_idx++;
2305     }
2306
2307     return (next_spe);
2308 }
2309
2310 /* must be called under the spq lock */
2311 static inline
2312 void bxe_sp_prod_update(struct bxe_softc *sc)
2313 {
2314     int func = SC_FUNC(sc);
2315
2316     /*
2317      * Make sure that BD data is updated before writing the producer.
2318      * BD data is written to the memory, the producer is read from the
2319      * memory, thus we need a full memory barrier to ensure the ordering.
2320      */
2321     mb();
2322
2323     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2324              sc->spq_prod_idx);
2325
2326     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2327                       BUS_SPACE_BARRIER_WRITE);
2328 }
2329
2330 /**
2331  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2332  *
2333  * @cmd:      command to check
2334  * @cmd_type: command type
2335  */
2336 static inline
2337 int bxe_is_contextless_ramrod(int cmd,
2338                               int cmd_type)
2339 {
2340     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2341         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2342         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2343         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2344         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2345         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2346         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2347         return (TRUE);
2348     } else {
2349         return (FALSE);
2350     }
2351 }
2352
2353 /**
2354  * bxe_sp_post - place a single command on an SP ring
2355  *
2356  * @sc:         driver handle
2357  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2358  * @cid:        SW CID the command is related to
2359  * @data_hi:    command private data address (high 32 bits)
2360  * @data_lo:    command private data address (low 32 bits)
2361  * @cmd_type:   command type (e.g. NONE, ETH)
2362  *
2363  * SP data is handled as if it's always an address pair, thus data fields are
2364  * not swapped to little endian in upper functions. Instead this function swaps
2365  * data as if it's two uint32 fields.
2366  */
2367 int
2368 bxe_sp_post(struct bxe_softc *sc,
2369             int              command,
2370             int              cid,
2371             uint32_t         data_hi,
2372             uint32_t         data_lo,
2373             int              cmd_type)
2374 {
2375     struct eth_spe *spe;
2376     uint16_t type;
2377     int common;
2378
2379     common = bxe_is_contextless_ramrod(command, cmd_type);
2380
2381     BXE_SP_LOCK(sc);
2382
2383     if (common) {
2384         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2385             BLOGE(sc, "EQ ring is full!\n");
2386             BXE_SP_UNLOCK(sc);
2387             return (-1);
2388         }
2389     } else {
2390         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2391             BLOGE(sc, "SPQ ring is full!\n");
2392             BXE_SP_UNLOCK(sc);
2393             return (-1);
2394         }
2395     }
2396
2397     spe = bxe_sp_get_next(sc);
2398
2399     /* CID needs port number to be encoded int it */
2400     spe->hdr.conn_and_cmd_data =
2401         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2402
2403     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2404
2405     /* TBD: Check if it works for VFs */
2406     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2407              SPE_HDR_T_FUNCTION_ID);
2408
2409     spe->hdr.type = htole16(type);
2410
2411     spe->data.update_data_addr.hi = htole32(data_hi);
2412     spe->data.update_data_addr.lo = htole32(data_lo);
2413
2414     /*
2415      * It's ok if the actual decrement is issued towards the memory
2416      * somewhere between the lock and unlock. Thus no more explict
2417      * memory barrier is needed.
2418      */
2419     if (common) {
2420         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2421     } else {
2422         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2423     }
2424
2425     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2426     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2427           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2428     BLOGD(sc, DBG_SP,
2429           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2430           sc->spq_prod_idx,
2431           (uint32_t)U64_HI(sc->spq_dma.paddr),
2432           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2433           command,
2434           common,
2435           HW_CID(sc, cid),
2436           data_hi,
2437           data_lo,
2438           type,
2439           atomic_load_acq_long(&sc->cq_spq_left),
2440           atomic_load_acq_long(&sc->eq_spq_left));
2441
2442     bxe_sp_prod_update(sc);
2443
2444     BXE_SP_UNLOCK(sc);
2445     return (0);
2446 }
2447
2448 /**
2449  * bxe_debug_print_ind_table - prints the indirection table configuration.
2450  *
2451  * @sc: driver hanlde
2452  * @p:  pointer to rss configuration
2453  */
2454
2455 /*
2456  * FreeBSD Device probe function.
2457  *
2458  * Compares the device found to the driver's list of supported devices and
2459  * reports back to the bsd loader whether this is the right driver for the device.
2460  * This is the driver entry function called from the "kldload" command.
2461  *
2462  * Returns:
2463  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2464  */
2465 static int
2466 bxe_probe(device_t dev)
2467 {
2468     struct bxe_softc *sc;
2469     struct bxe_device_type *t;
2470     char *descbuf;
2471     uint16_t did, sdid, svid, vid;
2472
2473     /* Find our device structure */
2474     sc = device_get_softc(dev);
2475     sc->dev = dev;
2476     t = bxe_devs;
2477
2478     /* Get the data for the device to be probed. */
2479     vid  = pci_get_vendor(dev);
2480     did  = pci_get_device(dev);
2481     svid = pci_get_subvendor(dev);
2482     sdid = pci_get_subdevice(dev);
2483
2484     BLOGD(sc, DBG_LOAD,
2485           "%s(); VID = 0x%04X, DID = 0x%04X, SVID = 0x%04X, "
2486           "SDID = 0x%04X\n", __FUNCTION__, vid, did, svid, sdid);
2487
2488     /* Look through the list of known devices for a match. */
2489     while (t->bxe_name != NULL) {
2490         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2491             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2492             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2493             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2494             if (descbuf == NULL)
2495                 return (ENOMEM);
2496
2497             /* Print out the device identity. */
2498             snprintf(descbuf, BXE_DEVDESC_MAX,
2499                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2500                      (((pci_read_config(dev, PCIR_REVID, 4) &
2501                         0xf0) >> 4) + 'A'),
2502                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2503                      BXE_DRIVER_VERSION);
2504
2505             device_set_desc_copy(dev, descbuf);
2506             free(descbuf, M_TEMP);
2507             return (BUS_PROBE_DEFAULT);
2508         }
2509         t++;
2510     }
2511
2512     return (ENXIO);
2513 }
2514
2515 static void
2516 bxe_init_mutexes(struct bxe_softc *sc)
2517 {
2518 #ifdef BXE_CORE_LOCK_SX
2519     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2520              "bxe%d_core_lock", sc->unit);
2521     sx_init(&sc->core_sx, sc->core_sx_name);
2522 #else
2523     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2524              "bxe%d_core_lock", sc->unit);
2525     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2526 #endif
2527
2528     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2529              "bxe%d_sp_lock", sc->unit);
2530     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2531
2532     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2533              "bxe%d_dmae_lock", sc->unit);
2534     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2535
2536     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2537              "bxe%d_phy_lock", sc->unit);
2538     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2539
2540     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2541              "bxe%d_fwmb_lock", sc->unit);
2542     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2543
2544     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2545              "bxe%d_print_lock", sc->unit);
2546     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2547
2548     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2549              "bxe%d_stats_lock", sc->unit);
2550     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2551
2552     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2553              "bxe%d_mcast_lock", sc->unit);
2554     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2555 }
2556
2557 static void
2558 bxe_release_mutexes(struct bxe_softc *sc)
2559 {
2560 #ifdef BXE_CORE_LOCK_SX
2561     sx_destroy(&sc->core_sx);
2562 #else
2563     if (mtx_initialized(&sc->core_mtx)) {
2564         mtx_destroy(&sc->core_mtx);
2565     }
2566 #endif
2567
2568     if (mtx_initialized(&sc->sp_mtx)) {
2569         mtx_destroy(&sc->sp_mtx);
2570     }
2571
2572     if (mtx_initialized(&sc->dmae_mtx)) {
2573         mtx_destroy(&sc->dmae_mtx);
2574     }
2575
2576     if (mtx_initialized(&sc->port.phy_mtx)) {
2577         mtx_destroy(&sc->port.phy_mtx);
2578     }
2579
2580     if (mtx_initialized(&sc->fwmb_mtx)) {
2581         mtx_destroy(&sc->fwmb_mtx);
2582     }
2583
2584     if (mtx_initialized(&sc->print_mtx)) {
2585         mtx_destroy(&sc->print_mtx);
2586     }
2587
2588     if (mtx_initialized(&sc->stats_mtx)) {
2589         mtx_destroy(&sc->stats_mtx);
2590     }
2591
2592     if (mtx_initialized(&sc->mcast_mtx)) {
2593         mtx_destroy(&sc->mcast_mtx);
2594     }
2595 }
2596
2597 static void
2598 bxe_tx_disable(struct bxe_softc* sc)
2599 {
2600     struct ifnet *ifp = sc->ifnet;
2601
2602     /* tell the stack the driver is stopped and TX queue is full */
2603     if (ifp != NULL) {
2604         ifp->if_drv_flags = 0;
2605     }
2606 }
2607
2608 static void
2609 bxe_drv_pulse(struct bxe_softc *sc)
2610 {
2611     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2612              sc->fw_drv_pulse_wr_seq);
2613 }
2614
2615 static inline uint16_t
2616 bxe_tx_avail(struct bxe_softc *sc,
2617              struct bxe_fastpath *fp)
2618 {
2619     int16_t  used;
2620     uint16_t prod;
2621     uint16_t cons;
2622
2623     prod = fp->tx_bd_prod;
2624     cons = fp->tx_bd_cons;
2625
2626     used = SUB_S16(prod, cons);
2627
2628     return (int16_t)(sc->tx_ring_size) - used;
2629 }
2630
2631 static inline int
2632 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2633 {
2634     uint16_t hw_cons;
2635
2636     mb(); /* status block fields can change */
2637     hw_cons = le16toh(*fp->tx_cons_sb);
2638     return (hw_cons != fp->tx_pkt_cons);
2639 }
2640
2641 static inline uint8_t
2642 bxe_has_tx_work(struct bxe_fastpath *fp)
2643 {
2644     /* expand this for multi-cos if ever supported */
2645     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2646 }
2647
2648 static inline int
2649 bxe_has_rx_work(struct bxe_fastpath *fp)
2650 {
2651     uint16_t rx_cq_cons_sb;
2652
2653     mb(); /* status block fields can change */
2654     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2655     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2656         rx_cq_cons_sb++;
2657     return (fp->rx_cq_cons != rx_cq_cons_sb);
2658 }
2659
2660 static void
2661 bxe_sp_event(struct bxe_softc    *sc,
2662              struct bxe_fastpath *fp,
2663              union eth_rx_cqe    *rr_cqe)
2664 {
2665     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2666     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2667     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2668     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2669
2670     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2671           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2672
2673     switch (command) {
2674     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2675         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2676         drv_cmd = ECORE_Q_CMD_UPDATE;
2677         break;
2678
2679     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2680         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2681         drv_cmd = ECORE_Q_CMD_SETUP;
2682         break;
2683
2684     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2685         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2686         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2687         break;
2688
2689     case (RAMROD_CMD_ID_ETH_HALT):
2690         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2691         drv_cmd = ECORE_Q_CMD_HALT;
2692         break;
2693
2694     case (RAMROD_CMD_ID_ETH_TERMINATE):
2695         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2696         drv_cmd = ECORE_Q_CMD_TERMINATE;
2697         break;
2698
2699     case (RAMROD_CMD_ID_ETH_EMPTY):
2700         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2701         drv_cmd = ECORE_Q_CMD_EMPTY;
2702         break;
2703
2704     default:
2705         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2706               command, fp->index);
2707         return;
2708     }
2709
2710     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2711         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2712         /*
2713          * q_obj->complete_cmd() failure means that this was
2714          * an unexpected completion.
2715          *
2716          * In this case we don't want to increase the sc->spq_left
2717          * because apparently we haven't sent this command the first
2718          * place.
2719          */
2720         // bxe_panic(sc, ("Unexpected SP completion\n"));
2721         return;
2722     }
2723
2724     atomic_add_acq_long(&sc->cq_spq_left, 1);
2725
2726     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2727           atomic_load_acq_long(&sc->cq_spq_left));
2728 }
2729
2730 /*
2731  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2732  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2733  * the current aggregation queue as in-progress.
2734  */
2735 static void
2736 bxe_tpa_start(struct bxe_softc            *sc,
2737               struct bxe_fastpath         *fp,
2738               uint16_t                    queue,
2739               uint16_t                    cons,
2740               uint16_t                    prod,
2741               struct eth_fast_path_rx_cqe *cqe)
2742 {
2743     struct bxe_sw_rx_bd tmp_bd;
2744     struct bxe_sw_rx_bd *rx_buf;
2745     struct eth_rx_bd *rx_bd;
2746     int max_agg_queues;
2747     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2748     uint16_t index;
2749
2750     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2751                        "cons=%d prod=%d\n",
2752           fp->index, queue, cons, prod);
2753
2754     max_agg_queues = MAX_AGG_QS(sc);
2755
2756     KASSERT((queue < max_agg_queues),
2757             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2758              fp->index, queue, max_agg_queues));
2759
2760     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2761             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2762              fp->index, queue));
2763
2764     /* copy the existing mbuf and mapping from the TPA pool */
2765     tmp_bd = tpa_info->bd;
2766
2767     if (tmp_bd.m == NULL) {
2768         uint32_t *tmp;
2769
2770         tmp = (uint32_t *)cqe;
2771
2772         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2773               fp->index, queue, cons, prod);
2774         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2775             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2776             
2777         /* XXX Error handling? */
2778         return;
2779     }
2780
2781     /* change the TPA queue to the start state */
2782     tpa_info->state            = BXE_TPA_STATE_START;
2783     tpa_info->placement_offset = cqe->placement_offset;
2784     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2785     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2786     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2787
2788     fp->rx_tpa_queue_used |= (1 << queue);
2789
2790     /*
2791      * If all the buffer descriptors are filled with mbufs then fill in
2792      * the current consumer index with a new BD. Else if a maximum Rx
2793      * buffer limit is imposed then fill in the next producer index.
2794      */
2795     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2796                 prod : cons;
2797
2798     /* move the received mbuf and mapping to TPA pool */
2799     tpa_info->bd = fp->rx_mbuf_chain[cons];
2800
2801     /* release any existing RX BD mbuf mappings */
2802     if (cons != index) {
2803         rx_buf = &fp->rx_mbuf_chain[cons];
2804
2805         if (rx_buf->m_map != NULL) {
2806             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2807                             BUS_DMASYNC_POSTREAD);
2808             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2809         }
2810
2811         /*
2812          * We get here when the maximum number of rx buffers is less than
2813          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2814          * it out here without concern of a memory leak.
2815          */
2816         fp->rx_mbuf_chain[cons].m = NULL;
2817     }
2818
2819     /* update the Rx SW BD with the mbuf info from the TPA pool */
2820     fp->rx_mbuf_chain[index] = tmp_bd;
2821
2822     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2823     rx_bd = &fp->rx_chain[index];
2824     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2825     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2826 }
2827
2828 /*
2829  * When a TPA aggregation is completed, loop through the individual mbufs
2830  * of the aggregation, combining them into a single mbuf which will be sent
2831  * up the stack. Refill all freed SGEs with mbufs as we go along.
2832  */
2833 static int
2834 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2835                    struct bxe_fastpath       *fp,
2836                    struct bxe_sw_tpa_info    *tpa_info,
2837                    uint16_t                  queue,
2838                    uint16_t                  pages,
2839                    struct mbuf               *m,
2840                                struct eth_end_agg_rx_cqe *cqe,
2841                    uint16_t                  cqe_idx)
2842 {
2843     struct mbuf *m_frag;
2844     uint32_t frag_len, frag_size, i;
2845     uint16_t sge_idx;
2846     int rc = 0;
2847     int j;
2848
2849     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2850
2851     BLOGD(sc, DBG_LRO,
2852           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2853           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2854
2855     /* make sure the aggregated frame is not too big to handle */
2856     if (pages > 8 * PAGES_PER_SGE) {
2857
2858         uint32_t *tmp = (uint32_t *)cqe;
2859
2860         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2861                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2862               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2863               tpa_info->len_on_bd, frag_size);
2864
2865         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2866             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2867
2868         bxe_panic(sc, ("sge page count error\n"));
2869         return (EINVAL);
2870     }
2871
2872     /*
2873      * Scan through the scatter gather list pulling individual mbufs into a
2874      * single mbuf for the host stack.
2875      */
2876     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2877         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2878
2879         /*
2880          * Firmware gives the indices of the SGE as if the ring is an array
2881          * (meaning that the "next" element will consume 2 indices).
2882          */
2883         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2884
2885         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2886                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2887               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2888
2889         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2890
2891         /* allocate a new mbuf for the SGE */
2892         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2893         if (rc) {
2894             /* Leave all remaining SGEs in the ring! */
2895             return (rc);
2896         }
2897
2898         /* update the fragment length */
2899         m_frag->m_len = frag_len;
2900
2901         /* concatenate the fragment to the head mbuf */
2902         m_cat(m, m_frag);
2903         fp->eth_q_stats.mbuf_alloc_sge--;
2904
2905         /* update the TPA mbuf size and remaining fragment size */
2906         m->m_pkthdr.len += frag_len;
2907         frag_size -= frag_len;
2908     }
2909
2910     BLOGD(sc, DBG_LRO,
2911           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2912           fp->index, queue, frag_size);
2913
2914     return (rc);
2915 }
2916
2917 static inline void
2918 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2919 {
2920     int i, j;
2921
2922     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2923         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2924
2925         for (j = 0; j < 2; j++) {
2926             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2927             idx--;
2928         }
2929     }
2930 }
2931
2932 static inline void
2933 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2934 {
2935     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2936     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2937
2938     /*
2939      * Clear the two last indices in the page to 1. These are the indices that
2940      * correspond to the "next" element, hence will never be indicated and
2941      * should be removed from the calculations.
2942      */
2943     bxe_clear_sge_mask_next_elems(fp);
2944 }
2945
2946 static inline void
2947 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2948                         uint16_t            idx)
2949 {
2950     uint16_t last_max = fp->last_max_sge;
2951
2952     if (SUB_S16(idx, last_max) > 0) {
2953         fp->last_max_sge = idx;
2954     }
2955 }
2956
2957 static inline void
2958 bxe_update_sge_prod(struct bxe_softc          *sc,
2959                     struct bxe_fastpath       *fp,
2960                     uint16_t                  sge_len,
2961                     union eth_sgl_or_raw_data *cqe)
2962 {
2963     uint16_t last_max, last_elem, first_elem;
2964     uint16_t delta = 0;
2965     uint16_t i;
2966
2967     if (!sge_len) {
2968         return;
2969     }
2970
2971     /* first mark all used pages */
2972     for (i = 0; i < sge_len; i++) {
2973         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
2974                             RX_SGE(le16toh(cqe->sgl[i])));
2975     }
2976
2977     BLOGD(sc, DBG_LRO,
2978           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
2979           fp->index, sge_len - 1,
2980           le16toh(cqe->sgl[sge_len - 1]));
2981
2982     /* assume that the last SGE index is the biggest */
2983     bxe_update_last_max_sge(fp,
2984                             le16toh(cqe->sgl[sge_len - 1]));
2985
2986     last_max = RX_SGE(fp->last_max_sge);
2987     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
2988     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
2989
2990     /* if ring is not full */
2991     if (last_elem + 1 != first_elem) {
2992         last_elem++;
2993     }
2994
2995     /* now update the prod */
2996     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
2997         if (__predict_true(fp->sge_mask[i])) {
2998             break;
2999         }
3000
3001         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3002         delta += BIT_VEC64_ELEM_SZ;
3003     }
3004
3005     if (delta > 0) {
3006         fp->rx_sge_prod += delta;
3007         /* clear page-end entries */
3008         bxe_clear_sge_mask_next_elems(fp);
3009     }
3010
3011     BLOGD(sc, DBG_LRO,
3012           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3013           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3014 }
3015
3016 /*
3017  * The aggregation on the current TPA queue has completed. Pull the individual
3018  * mbuf fragments together into a single mbuf, perform all necessary checksum
3019  * calculations, and send the resuting mbuf to the stack.
3020  */
3021 static void
3022 bxe_tpa_stop(struct bxe_softc          *sc,
3023              struct bxe_fastpath       *fp,
3024              struct bxe_sw_tpa_info    *tpa_info,
3025              uint16_t                  queue,
3026              uint16_t                  pages,
3027                          struct eth_end_agg_rx_cqe *cqe,
3028              uint16_t                  cqe_idx)
3029 {
3030     struct ifnet *ifp = sc->ifnet;
3031     struct mbuf *m;
3032     int rc = 0;
3033
3034     BLOGD(sc, DBG_LRO,
3035           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3036           fp->index, queue, tpa_info->placement_offset,
3037           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3038
3039     m = tpa_info->bd.m;
3040
3041     /* allocate a replacement before modifying existing mbuf */
3042     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3043     if (rc) {
3044         /* drop the frame and log an error */
3045         fp->eth_q_stats.rx_soft_errors++;
3046         goto bxe_tpa_stop_exit;
3047     }
3048
3049     /* we have a replacement, fixup the current mbuf */
3050     m_adj(m, tpa_info->placement_offset);
3051     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3052
3053     /* mark the checksums valid (taken care of by the firmware) */
3054     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3055     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3056     m->m_pkthdr.csum_data = 0xffff;
3057     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3058                                CSUM_IP_VALID   |
3059                                CSUM_DATA_VALID |
3060                                CSUM_PSEUDO_HDR);
3061
3062     /* aggregate all of the SGEs into a single mbuf */
3063     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3064     if (rc) {
3065         /* drop the packet and log an error */
3066         fp->eth_q_stats.rx_soft_errors++;
3067         m_freem(m);
3068     } else {
3069         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3070             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3071             m->m_flags |= M_VLANTAG;
3072         }
3073
3074         /* assign packet to this interface interface */
3075         m->m_pkthdr.rcvif = ifp;
3076
3077 #if __FreeBSD_version >= 800000
3078         /* specify what RSS queue was used for this flow */
3079         m->m_pkthdr.flowid = fp->index;
3080         BXE_SET_FLOWID(m);
3081 #endif
3082
3083         ifp->if_ipackets++;
3084         fp->eth_q_stats.rx_tpa_pkts++;
3085
3086         /* pass the frame to the stack */
3087         (*ifp->if_input)(ifp, m);
3088     }
3089
3090     /* we passed an mbuf up the stack or dropped the frame */
3091     fp->eth_q_stats.mbuf_alloc_tpa--;
3092
3093 bxe_tpa_stop_exit:
3094
3095     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3096     fp->rx_tpa_queue_used &= ~(1 << queue);
3097 }
3098
3099 static uint8_t
3100 bxe_service_rxsgl(
3101                  struct bxe_fastpath *fp,
3102                  uint16_t len,
3103                  uint16_t lenonbd,
3104                  struct mbuf *m,
3105                  struct eth_fast_path_rx_cqe *cqe_fp)
3106 {
3107     struct mbuf *m_frag;
3108     uint16_t frags, frag_len;
3109     uint16_t sge_idx = 0;
3110     uint16_t j;
3111     uint8_t i, rc = 0;
3112     uint32_t frag_size;
3113
3114     /* adjust the mbuf */
3115     m->m_len = lenonbd;
3116
3117     frag_size =  len - lenonbd;
3118     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3119
3120     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3121         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3122
3123         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3124         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3125         m_frag->m_len = frag_len;
3126
3127        /* allocate a new mbuf for the SGE */
3128         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3129         if (rc) {
3130             /* Leave all remaining SGEs in the ring! */
3131             return (rc);
3132         }
3133         fp->eth_q_stats.mbuf_alloc_sge--;
3134
3135         /* concatenate the fragment to the head mbuf */
3136         m_cat(m, m_frag);
3137
3138         frag_size -= frag_len;
3139     }
3140
3141     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3142
3143     return rc;
3144 }
3145
3146 static uint8_t
3147 bxe_rxeof(struct bxe_softc    *sc,
3148           struct bxe_fastpath *fp)
3149 {
3150     struct ifnet *ifp = sc->ifnet;
3151     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3152     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3153     int rx_pkts = 0;
3154     int rc = 0;
3155
3156     BXE_FP_RX_LOCK(fp);
3157
3158     /* CQ "next element" is of the size of the regular element */
3159     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3160     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3161         hw_cq_cons++;
3162     }
3163
3164     bd_cons = fp->rx_bd_cons;
3165     bd_prod = fp->rx_bd_prod;
3166     bd_prod_fw = bd_prod;
3167     sw_cq_cons = fp->rx_cq_cons;
3168     sw_cq_prod = fp->rx_cq_prod;
3169
3170     /*
3171      * Memory barrier necessary as speculative reads of the rx
3172      * buffer can be ahead of the index in the status block
3173      */
3174     rmb();
3175
3176     BLOGD(sc, DBG_RX,
3177           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3178           fp->index, hw_cq_cons, sw_cq_cons);
3179
3180     while (sw_cq_cons != hw_cq_cons) {
3181         struct bxe_sw_rx_bd *rx_buf = NULL;
3182         union eth_rx_cqe *cqe;
3183         struct eth_fast_path_rx_cqe *cqe_fp;
3184         uint8_t cqe_fp_flags;
3185         enum eth_rx_cqe_type cqe_fp_type;
3186         uint16_t len, lenonbd,  pad;
3187         struct mbuf *m = NULL;
3188
3189         comp_ring_cons = RCQ(sw_cq_cons);
3190         bd_prod = RX_BD(bd_prod);
3191         bd_cons = RX_BD(bd_cons);
3192
3193         cqe          = &fp->rcq_chain[comp_ring_cons];
3194         cqe_fp       = &cqe->fast_path_cqe;
3195         cqe_fp_flags = cqe_fp->type_error_flags;
3196         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3197
3198         BLOGD(sc, DBG_RX,
3199               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3200               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3201               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3202               fp->index,
3203               hw_cq_cons,
3204               sw_cq_cons,
3205               bd_prod,
3206               bd_cons,
3207               CQE_TYPE(cqe_fp_flags),
3208               cqe_fp_flags,
3209               cqe_fp->status_flags,
3210               le32toh(cqe_fp->rss_hash_result),
3211               le16toh(cqe_fp->vlan_tag),
3212               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3213               le16toh(cqe_fp->len_on_bd));
3214
3215         /* is this a slowpath msg? */
3216         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3217             bxe_sp_event(sc, fp, cqe);
3218             goto next_cqe;
3219         }
3220
3221         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3222
3223         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3224             struct bxe_sw_tpa_info *tpa_info;
3225             uint16_t frag_size, pages;
3226             uint8_t queue;
3227
3228             if (CQE_TYPE_START(cqe_fp_type)) {
3229                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3230                               bd_cons, bd_prod, cqe_fp);
3231                 m = NULL; /* packet not ready yet */
3232                 goto next_rx;
3233             }
3234
3235             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3236                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3237
3238             queue = cqe->end_agg_cqe.queue_index;
3239             tpa_info = &fp->rx_tpa_info[queue];
3240
3241             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3242                   fp->index, queue);
3243
3244             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3245                          tpa_info->len_on_bd);
3246             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3247
3248             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3249                          &cqe->end_agg_cqe, comp_ring_cons);
3250
3251             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3252
3253             goto next_cqe;
3254         }
3255
3256         /* non TPA */
3257
3258         /* is this an error packet? */
3259         if (__predict_false(cqe_fp_flags &
3260                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3261             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3262             fp->eth_q_stats.rx_soft_errors++;
3263             goto next_rx;
3264         }
3265
3266         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3267         lenonbd = le16toh(cqe_fp->len_on_bd);
3268         pad = cqe_fp->placement_offset;
3269
3270         m = rx_buf->m;
3271
3272         if (__predict_false(m == NULL)) {
3273             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3274                   bd_cons, fp->index);
3275             goto next_rx;
3276         }
3277
3278         /* XXX double copy if packet length under a threshold */
3279
3280         /*
3281          * If all the buffer descriptors are filled with mbufs then fill in
3282          * the current consumer index with a new BD. Else if a maximum Rx
3283          * buffer limit is imposed then fill in the next producer index.
3284          */
3285         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3286                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3287                                       bd_prod : bd_cons);
3288         if (rc != 0) {
3289
3290             /* we simply reuse the received mbuf and don't post it to the stack */
3291             m = NULL;
3292
3293             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3294                   fp->index, rc);
3295             fp->eth_q_stats.rx_soft_errors++;
3296
3297             if (sc->max_rx_bufs != RX_BD_USABLE) {
3298                 /* copy this consumer index to the producer index */
3299                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3300                        sizeof(struct bxe_sw_rx_bd));
3301                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3302             }
3303
3304             goto next_rx;
3305         }
3306
3307         /* current mbuf was detached from the bd */
3308         fp->eth_q_stats.mbuf_alloc_rx--;
3309
3310         /* we allocated a replacement mbuf, fixup the current one */
3311         m_adj(m, pad);
3312         m->m_pkthdr.len = m->m_len = len;
3313
3314         if ((len > 60) && (len > lenonbd)) {
3315             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3316             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3317             if (rc)
3318                 break;
3319             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3320         } else if (lenonbd < len) {
3321             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3322         }
3323
3324         /* assign packet to this interface interface */
3325         m->m_pkthdr.rcvif = ifp;
3326
3327         /* assume no hardware checksum has complated */
3328         m->m_pkthdr.csum_flags = 0;
3329
3330         /* validate checksum if offload enabled */
3331         if (ifp->if_capenable & IFCAP_RXCSUM) {
3332             /* check for a valid IP frame */
3333             if (!(cqe->fast_path_cqe.status_flags &
3334                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3335                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3336                 if (__predict_false(cqe_fp_flags &
3337                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3338                     fp->eth_q_stats.rx_hw_csum_errors++;
3339                 } else {
3340                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3341                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3342                 }
3343             }
3344
3345             /* check for a valid TCP/UDP frame */
3346             if (!(cqe->fast_path_cqe.status_flags &
3347                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3348                 if (__predict_false(cqe_fp_flags &
3349                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3350                     fp->eth_q_stats.rx_hw_csum_errors++;
3351                 } else {
3352                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3353                     m->m_pkthdr.csum_data = 0xFFFF;
3354                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3355                                                CSUM_PSEUDO_HDR);
3356                 }
3357             }
3358         }
3359
3360         /* if there is a VLAN tag then flag that info */
3361         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3362             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3363             m->m_flags |= M_VLANTAG;
3364         }
3365
3366 #if __FreeBSD_version >= 800000
3367         /* specify what RSS queue was used for this flow */
3368         m->m_pkthdr.flowid = fp->index;
3369         BXE_SET_FLOWID(m);
3370 #endif
3371
3372 next_rx:
3373
3374         bd_cons    = RX_BD_NEXT(bd_cons);
3375         bd_prod    = RX_BD_NEXT(bd_prod);
3376         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3377
3378         /* pass the frame to the stack */
3379         if (__predict_true(m != NULL)) {
3380             ifp->if_ipackets++;
3381             rx_pkts++;
3382             (*ifp->if_input)(ifp, m);
3383         }
3384
3385 next_cqe:
3386
3387         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3388         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3389
3390         /* limit spinning on the queue */
3391         if (rc != 0)
3392             break;
3393
3394         if (rx_pkts == sc->rx_budget) {
3395             fp->eth_q_stats.rx_budget_reached++;
3396             break;
3397         }
3398     } /* while work to do */
3399
3400     fp->rx_bd_cons = bd_cons;
3401     fp->rx_bd_prod = bd_prod_fw;
3402     fp->rx_cq_cons = sw_cq_cons;
3403     fp->rx_cq_prod = sw_cq_prod;
3404
3405     /* Update producers */
3406     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3407
3408     fp->eth_q_stats.rx_pkts += rx_pkts;
3409     fp->eth_q_stats.rx_calls++;
3410
3411     BXE_FP_RX_UNLOCK(fp);
3412
3413     return (sw_cq_cons != hw_cq_cons);
3414 }
3415
3416 static uint16_t
3417 bxe_free_tx_pkt(struct bxe_softc    *sc,
3418                 struct bxe_fastpath *fp,
3419                 uint16_t            idx)
3420 {
3421     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3422     struct eth_tx_start_bd *tx_start_bd;
3423     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3424     uint16_t new_cons;
3425     int nbd;
3426
3427     /* unmap the mbuf from non-paged memory */
3428     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3429
3430     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3431     nbd = le16toh(tx_start_bd->nbd) - 1;
3432
3433     new_cons = (tx_buf->first_bd + nbd);
3434
3435     /* free the mbuf */
3436     if (__predict_true(tx_buf->m != NULL)) {
3437         m_freem(tx_buf->m);
3438         fp->eth_q_stats.mbuf_alloc_tx--;
3439     } else {
3440         fp->eth_q_stats.tx_chain_lost_mbuf++;
3441     }
3442
3443     tx_buf->m = NULL;
3444     tx_buf->first_bd = 0;
3445
3446     return (new_cons);
3447 }
3448
3449 /* transmit timeout watchdog */
3450 static int
3451 bxe_watchdog(struct bxe_softc    *sc,
3452              struct bxe_fastpath *fp)
3453 {
3454     BXE_FP_TX_LOCK(fp);
3455
3456     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3457         BXE_FP_TX_UNLOCK(fp);
3458         return (0);
3459     }
3460
3461     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3462     if(sc->trigger_grcdump) {
3463          /* taking grcdump */
3464          bxe_grc_dump(sc);
3465     }
3466
3467     BXE_FP_TX_UNLOCK(fp);
3468
3469     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3470     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3471
3472     return (-1);
3473 }
3474
3475 /* processes transmit completions */
3476 static uint8_t
3477 bxe_txeof(struct bxe_softc    *sc,
3478           struct bxe_fastpath *fp)
3479 {
3480     struct ifnet *ifp = sc->ifnet;
3481     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3482     uint16_t tx_bd_avail;
3483
3484     BXE_FP_TX_LOCK_ASSERT(fp);
3485
3486     bd_cons = fp->tx_bd_cons;
3487     hw_cons = le16toh(*fp->tx_cons_sb);
3488     sw_cons = fp->tx_pkt_cons;
3489
3490     while (sw_cons != hw_cons) {
3491         pkt_cons = TX_BD(sw_cons);
3492
3493         BLOGD(sc, DBG_TX,
3494               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3495               fp->index, hw_cons, sw_cons, pkt_cons);
3496
3497         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3498
3499         sw_cons++;
3500     }
3501
3502     fp->tx_pkt_cons = sw_cons;
3503     fp->tx_bd_cons  = bd_cons;
3504
3505     BLOGD(sc, DBG_TX,
3506           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3507           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3508
3509     mb();
3510
3511     tx_bd_avail = bxe_tx_avail(sc, fp);
3512
3513     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3514         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3515     } else {
3516         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3517     }
3518
3519     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3520         /* reset the watchdog timer if there are pending transmits */
3521         fp->watchdog_timer = BXE_TX_TIMEOUT;
3522         return (TRUE);
3523     } else {
3524         /* clear watchdog when there are no pending transmits */
3525         fp->watchdog_timer = 0;
3526         return (FALSE);
3527     }
3528 }
3529
3530 static void
3531 bxe_drain_tx_queues(struct bxe_softc *sc)
3532 {
3533     struct bxe_fastpath *fp;
3534     int i, count;
3535
3536     /* wait until all TX fastpath tasks have completed */
3537     for (i = 0; i < sc->num_queues; i++) {
3538         fp = &sc->fp[i];
3539
3540         count = 1000;
3541
3542         while (bxe_has_tx_work(fp)) {
3543
3544             BXE_FP_TX_LOCK(fp);
3545             bxe_txeof(sc, fp);
3546             BXE_FP_TX_UNLOCK(fp);
3547
3548             if (count == 0) {
3549                 BLOGE(sc, "Timeout waiting for fp[%d] "
3550                           "transmits to complete!\n", i);
3551                 bxe_panic(sc, ("tx drain failure\n"));
3552                 return;
3553             }
3554
3555             count--;
3556             DELAY(1000);
3557             rmb();
3558         }
3559     }
3560
3561     return;
3562 }
3563
3564 static int
3565 bxe_del_all_macs(struct bxe_softc          *sc,
3566                  struct ecore_vlan_mac_obj *mac_obj,
3567                  int                       mac_type,
3568                  uint8_t                   wait_for_comp)
3569 {
3570     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3571     int rc;
3572
3573     /* wait for completion of requested */
3574     if (wait_for_comp) {
3575         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3576     }
3577
3578     /* Set the mac type of addresses we want to clear */
3579     bxe_set_bit(mac_type, &vlan_mac_flags);
3580
3581     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3582     if (rc < 0) {
3583         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3584             rc, mac_type, wait_for_comp);
3585     }
3586
3587     return (rc);
3588 }
3589
3590 static int
3591 bxe_fill_accept_flags(struct bxe_softc *sc,
3592                       uint32_t         rx_mode,
3593                       unsigned long    *rx_accept_flags,
3594                       unsigned long    *tx_accept_flags)
3595 {
3596     /* Clear the flags first */
3597     *rx_accept_flags = 0;
3598     *tx_accept_flags = 0;
3599
3600     switch (rx_mode) {
3601     case BXE_RX_MODE_NONE:
3602         /*
3603          * 'drop all' supersedes any accept flags that may have been
3604          * passed to the function.
3605          */
3606         break;
3607
3608     case BXE_RX_MODE_NORMAL:
3609         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3610         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3611         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3612
3613         /* internal switching mode */
3614         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3615         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3616         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3617
3618         break;
3619
3620     case BXE_RX_MODE_ALLMULTI:
3621         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3622         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3623         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3624
3625         /* internal switching mode */
3626         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3627         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3628         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3629
3630         break;
3631
3632     case BXE_RX_MODE_PROMISC:
3633         /*
3634          * According to deffinition of SI mode, iface in promisc mode
3635          * should receive matched and unmatched (in resolution of port)
3636          * unicast packets.
3637          */
3638         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3639         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3640         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3641         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3642
3643         /* internal switching mode */
3644         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3645         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3646
3647         if (IS_MF_SI(sc)) {
3648             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3649         } else {
3650             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3651         }
3652
3653         break;
3654
3655     default:
3656         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3657         return (-1);
3658     }
3659
3660     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3661     if (rx_mode != BXE_RX_MODE_NONE) {
3662         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3663         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3664     }
3665
3666     return (0);
3667 }
3668
3669 static int
3670 bxe_set_q_rx_mode(struct bxe_softc *sc,
3671                   uint8_t          cl_id,
3672                   unsigned long    rx_mode_flags,
3673                   unsigned long    rx_accept_flags,
3674                   unsigned long    tx_accept_flags,
3675                   unsigned long    ramrod_flags)
3676 {
3677     struct ecore_rx_mode_ramrod_params ramrod_param;
3678     int rc;
3679
3680     memset(&ramrod_param, 0, sizeof(ramrod_param));
3681
3682     /* Prepare ramrod parameters */
3683     ramrod_param.cid = 0;
3684     ramrod_param.cl_id = cl_id;
3685     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3686     ramrod_param.func_id = SC_FUNC(sc);
3687
3688     ramrod_param.pstate = &sc->sp_state;
3689     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3690
3691     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3692     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3693
3694     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3695
3696     ramrod_param.ramrod_flags = ramrod_flags;
3697     ramrod_param.rx_mode_flags = rx_mode_flags;
3698
3699     ramrod_param.rx_accept_flags = rx_accept_flags;
3700     ramrod_param.tx_accept_flags = tx_accept_flags;
3701
3702     rc = ecore_config_rx_mode(sc, &ramrod_param);
3703     if (rc < 0) {
3704         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3705             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3706             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3707             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3708             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3709         return (rc);
3710     }
3711
3712     return (0);
3713 }
3714
3715 static int
3716 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3717 {
3718     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3719     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3720     int rc;
3721
3722     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3723                                &tx_accept_flags);
3724     if (rc) {
3725         return (rc);
3726     }
3727
3728     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3729     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3730
3731     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3732     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3733                               rx_accept_flags, tx_accept_flags,
3734                               ramrod_flags));
3735 }
3736
3737 /* returns the "mcp load_code" according to global load_count array */
3738 static int
3739 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3740 {
3741     int path = SC_PATH(sc);
3742     int port = SC_PORT(sc);
3743
3744     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3745           path, load_count[path][0], load_count[path][1],
3746           load_count[path][2]);
3747     load_count[path][0]++;
3748     load_count[path][1 + port]++;
3749     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3750           path, load_count[path][0], load_count[path][1],
3751           load_count[path][2]);
3752     if (load_count[path][0] == 1) {
3753         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3754     } else if (load_count[path][1 + port] == 1) {
3755         return (FW_MSG_CODE_DRV_LOAD_PORT);
3756     } else {
3757         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3758     }
3759 }
3760
3761 /* returns the "mcp load_code" according to global load_count array */
3762 static int
3763 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3764 {
3765     int port = SC_PORT(sc);
3766     int path = SC_PATH(sc);
3767
3768     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3769           path, load_count[path][0], load_count[path][1],
3770           load_count[path][2]);
3771     load_count[path][0]--;
3772     load_count[path][1 + port]--;
3773     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3774           path, load_count[path][0], load_count[path][1],
3775           load_count[path][2]);
3776     if (load_count[path][0] == 0) {
3777         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3778     } else if (load_count[path][1 + port] == 0) {
3779         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3780     } else {
3781         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3782     }
3783 }
3784
3785 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3786 static uint32_t
3787 bxe_send_unload_req(struct bxe_softc *sc,
3788                     int              unload_mode)
3789 {
3790     uint32_t reset_code = 0;
3791
3792     /* Select the UNLOAD request mode */
3793     if (unload_mode == UNLOAD_NORMAL) {
3794         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3795     } else {
3796         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3797     }
3798
3799     /* Send the request to the MCP */
3800     if (!BXE_NOMCP(sc)) {
3801         reset_code = bxe_fw_command(sc, reset_code, 0);
3802     } else {
3803         reset_code = bxe_nic_unload_no_mcp(sc);
3804     }
3805
3806     return (reset_code);
3807 }
3808
3809 /* send UNLOAD_DONE command to the MCP */
3810 static void
3811 bxe_send_unload_done(struct bxe_softc *sc,
3812                      uint8_t          keep_link)
3813 {
3814     uint32_t reset_param =
3815         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3816
3817     /* Report UNLOAD_DONE to MCP */
3818     if (!BXE_NOMCP(sc)) {
3819         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3820     }
3821 }
3822
3823 static int
3824 bxe_func_wait_started(struct bxe_softc *sc)
3825 {
3826     int tout = 50;
3827
3828     if (!sc->port.pmf) {
3829         return (0);
3830     }
3831
3832     /*
3833      * (assumption: No Attention from MCP at this stage)
3834      * PMF probably in the middle of TX disable/enable transaction
3835      * 1. Sync IRS for default SB
3836      * 2. Sync SP queue - this guarantees us that attention handling started
3837      * 3. Wait, that TX disable/enable transaction completes
3838      *
3839      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3840      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3841      * received completion for the transaction the state is TX_STOPPED.
3842      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3843      * transaction.
3844      */
3845
3846     /* XXX make sure default SB ISR is done */
3847     /* need a way to synchronize an irq (intr_mtx?) */
3848
3849     /* XXX flush any work queues */
3850
3851     while (ecore_func_get_state(sc, &sc->func_obj) !=
3852            ECORE_F_STATE_STARTED && tout--) {
3853         DELAY(20000);
3854     }
3855
3856     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3857         /*
3858          * Failed to complete the transaction in a "good way"
3859          * Force both transactions with CLR bit.
3860          */
3861         struct ecore_func_state_params func_params = { NULL };
3862
3863         BLOGE(sc, "Unexpected function state! "
3864                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3865
3866         func_params.f_obj = &sc->func_obj;
3867         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3868
3869         /* STARTED-->TX_STOPPED */
3870         func_params.cmd = ECORE_F_CMD_TX_STOP;
3871         ecore_func_state_change(sc, &func_params);
3872
3873         /* TX_STOPPED-->STARTED */
3874         func_params.cmd = ECORE_F_CMD_TX_START;
3875         return (ecore_func_state_change(sc, &func_params));
3876     }
3877
3878     return (0);
3879 }
3880
3881 static int
3882 bxe_stop_queue(struct bxe_softc *sc,
3883                int              index)
3884 {
3885     struct bxe_fastpath *fp = &sc->fp[index];
3886     struct ecore_queue_state_params q_params = { NULL };
3887     int rc;
3888
3889     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3890
3891     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3892     /* We want to wait for completion in this context */
3893     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3894
3895     /* Stop the primary connection: */
3896
3897     /* ...halt the connection */
3898     q_params.cmd = ECORE_Q_CMD_HALT;
3899     rc = ecore_queue_state_change(sc, &q_params);
3900     if (rc) {
3901         return (rc);
3902     }
3903
3904     /* ...terminate the connection */
3905     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3906     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3907     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3908     rc = ecore_queue_state_change(sc, &q_params);
3909     if (rc) {
3910         return (rc);
3911     }
3912
3913     /* ...delete cfc entry */
3914     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3915     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3916     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3917     return (ecore_queue_state_change(sc, &q_params));
3918 }
3919
3920 /* wait for the outstanding SP commands */
3921 static inline uint8_t
3922 bxe_wait_sp_comp(struct bxe_softc *sc,
3923                  unsigned long    mask)
3924 {
3925     unsigned long tmp;
3926     int tout = 5000; /* wait for 5 secs tops */
3927
3928     while (tout--) {
3929         mb();
3930         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3931             return (TRUE);
3932         }
3933
3934         DELAY(1000);
3935     }
3936
3937     mb();
3938
3939     tmp = atomic_load_acq_long(&sc->sp_state);
3940     if (tmp & mask) {
3941         BLOGE(sc, "Filtering completion timed out: "
3942                   "sp_state 0x%lx, mask 0x%lx\n",
3943               tmp, mask);
3944         return (FALSE);
3945     }
3946
3947     return (FALSE);
3948 }
3949
3950 static int
3951 bxe_func_stop(struct bxe_softc *sc)
3952 {
3953     struct ecore_func_state_params func_params = { NULL };
3954     int rc;
3955
3956     /* prepare parameters for function state transitions */
3957     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3958     func_params.f_obj = &sc->func_obj;
3959     func_params.cmd = ECORE_F_CMD_STOP;
3960
3961     /*
3962      * Try to stop the function the 'good way'. If it fails (in case
3963      * of a parity error during bxe_chip_cleanup()) and we are
3964      * not in a debug mode, perform a state transaction in order to
3965      * enable further HW_RESET transaction.
3966      */
3967     rc = ecore_func_state_change(sc, &func_params);
3968     if (rc) {
3969         BLOGE(sc, "FUNC_STOP ramrod failed. "
3970                   "Running a dry transaction (%d)\n", rc);
3971         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3972         return (ecore_func_state_change(sc, &func_params));
3973     }
3974
3975     return (0);
3976 }
3977
3978 static int
3979 bxe_reset_hw(struct bxe_softc *sc,
3980              uint32_t         load_code)
3981 {
3982     struct ecore_func_state_params func_params = { NULL };
3983
3984     /* Prepare parameters for function state transitions */
3985     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3986
3987     func_params.f_obj = &sc->func_obj;
3988     func_params.cmd = ECORE_F_CMD_HW_RESET;
3989
3990     func_params.params.hw_init.load_phase = load_code;
3991
3992     return (ecore_func_state_change(sc, &func_params));
3993 }
3994
3995 static void
3996 bxe_int_disable_sync(struct bxe_softc *sc,
3997                      int              disable_hw)
3998 {
3999     if (disable_hw) {
4000         /* prevent the HW from sending interrupts */
4001         bxe_int_disable(sc);
4002     }
4003
4004     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4005     /* make sure all ISRs are done */
4006
4007     /* XXX make sure sp_task is not running */
4008     /* cancel and flush work queues */
4009 }
4010
4011 static void
4012 bxe_chip_cleanup(struct bxe_softc *sc,
4013                  uint32_t         unload_mode,
4014                  uint8_t          keep_link)
4015 {
4016     int port = SC_PORT(sc);
4017     struct ecore_mcast_ramrod_params rparam = { NULL };
4018     uint32_t reset_code;
4019     int i, rc = 0;
4020
4021     bxe_drain_tx_queues(sc);
4022
4023     /* give HW time to discard old tx messages */
4024     DELAY(1000);
4025
4026     /* Clean all ETH MACs */
4027     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4028     if (rc < 0) {
4029         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4030     }
4031
4032     /* Clean up UC list  */
4033     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4034     if (rc < 0) {
4035         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4036     }
4037
4038     /* Disable LLH */
4039     if (!CHIP_IS_E1(sc)) {
4040         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4041     }
4042
4043     /* Set "drop all" to stop Rx */
4044
4045     /*
4046      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4047      * a race between the completion code and this code.
4048      */
4049     BXE_MCAST_LOCK(sc);
4050
4051     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4052         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4053     } else {
4054         bxe_set_storm_rx_mode(sc);
4055     }
4056
4057     /* Clean up multicast configuration */
4058     rparam.mcast_obj = &sc->mcast_obj;
4059     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4060     if (rc < 0) {
4061         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4062     }
4063
4064     BXE_MCAST_UNLOCK(sc);
4065
4066     // XXX bxe_iov_chip_cleanup(sc);
4067
4068     /*
4069      * Send the UNLOAD_REQUEST to the MCP. This will return if
4070      * this function should perform FUNCTION, PORT, or COMMON HW
4071      * reset.
4072      */
4073     reset_code = bxe_send_unload_req(sc, unload_mode);
4074
4075     /*
4076      * (assumption: No Attention from MCP at this stage)
4077      * PMF probably in the middle of TX disable/enable transaction
4078      */
4079     rc = bxe_func_wait_started(sc);
4080     if (rc) {
4081         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4082     }
4083
4084     /*
4085      * Close multi and leading connections
4086      * Completions for ramrods are collected in a synchronous way
4087      */
4088     for (i = 0; i < sc->num_queues; i++) {
4089         if (bxe_stop_queue(sc, i)) {
4090             goto unload_error;
4091         }
4092     }
4093
4094     /*
4095      * If SP settings didn't get completed so far - something
4096      * very wrong has happen.
4097      */
4098     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4099         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4100     }
4101
4102 unload_error:
4103
4104     rc = bxe_func_stop(sc);
4105     if (rc) {
4106         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4107     }
4108
4109     /* disable HW interrupts */
4110     bxe_int_disable_sync(sc, TRUE);
4111
4112     /* detach interrupts */
4113     bxe_interrupt_detach(sc);
4114
4115     /* Reset the chip */
4116     rc = bxe_reset_hw(sc, reset_code);
4117     if (rc) {
4118         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4119     }
4120
4121     /* Report UNLOAD_DONE to MCP */
4122     bxe_send_unload_done(sc, keep_link);
4123 }
4124
4125 static void
4126 bxe_disable_close_the_gate(struct bxe_softc *sc)
4127 {
4128     uint32_t val;
4129     int port = SC_PORT(sc);
4130
4131     BLOGD(sc, DBG_LOAD,
4132           "Disabling 'close the gates'\n");
4133
4134     if (CHIP_IS_E1(sc)) {
4135         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4136                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4137         val = REG_RD(sc, addr);
4138         val &= ~(0x300);
4139         REG_WR(sc, addr, val);
4140     } else {
4141         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4142         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4143                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4144         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4145     }
4146 }
4147
4148 /*
4149  * Cleans the object that have internal lists without sending
4150  * ramrods. Should be run when interrutps are disabled.
4151  */
4152 static void
4153 bxe_squeeze_objects(struct bxe_softc *sc)
4154 {
4155     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4156     struct ecore_mcast_ramrod_params rparam = { NULL };
4157     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4158     int rc;
4159
4160     /* Cleanup MACs' object first... */
4161
4162     /* Wait for completion of requested */
4163     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4164     /* Perform a dry cleanup */
4165     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4166
4167     /* Clean ETH primary MAC */
4168     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4169     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4170                              &ramrod_flags);
4171     if (rc != 0) {
4172         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4173     }
4174
4175     /* Cleanup UC list */
4176     vlan_mac_flags = 0;
4177     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4178     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4179                              &ramrod_flags);
4180     if (rc != 0) {
4181         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4182     }
4183
4184     /* Now clean mcast object... */
4185
4186     rparam.mcast_obj = &sc->mcast_obj;
4187     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4188
4189     /* Add a DEL command... */
4190     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4191     if (rc < 0) {
4192         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4193     }
4194
4195     /* now wait until all pending commands are cleared */
4196
4197     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4198     while (rc != 0) {
4199         if (rc < 0) {
4200             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4201             return;
4202         }
4203
4204         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4205     }
4206 }
4207
4208 /* stop the controller */
4209 static __noinline int
4210 bxe_nic_unload(struct bxe_softc *sc,
4211                uint32_t         unload_mode,
4212                uint8_t          keep_link)
4213 {
4214     uint8_t global = FALSE;
4215     uint32_t val;
4216     int i;
4217
4218     BXE_CORE_LOCK_ASSERT(sc);
4219
4220     sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
4221
4222     for (i = 0; i < sc->num_queues; i++) {
4223         struct bxe_fastpath *fp;
4224
4225         fp = &sc->fp[i];
4226         BXE_FP_TX_LOCK(fp);
4227         BXE_FP_TX_UNLOCK(fp);
4228     }
4229
4230     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4231
4232     /* mark driver as unloaded in shmem2 */
4233     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4234         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4235         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4236                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4237     }
4238
4239     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4240         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4241         /*
4242          * We can get here if the driver has been unloaded
4243          * during parity error recovery and is either waiting for a
4244          * leader to complete or for other functions to unload and
4245          * then ifconfig down has been issued. In this case we want to
4246          * unload and let other functions to complete a recovery
4247          * process.
4248          */
4249         sc->recovery_state = BXE_RECOVERY_DONE;
4250         sc->is_leader = 0;
4251         bxe_release_leader_lock(sc);
4252         mb();
4253
4254         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4255         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4256             " state = 0x%x\n", sc->recovery_state, sc->state);
4257         return (-1);
4258     }
4259
4260     /*
4261      * Nothing to do during unload if previous bxe_nic_load()
4262      * did not completed succesfully - all resourses are released.
4263      */
4264     if ((sc->state == BXE_STATE_CLOSED) ||
4265         (sc->state == BXE_STATE_ERROR)) {
4266         return (0);
4267     }
4268
4269     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4270     mb();
4271
4272     /* stop tx */
4273     bxe_tx_disable(sc);
4274
4275     sc->rx_mode = BXE_RX_MODE_NONE;
4276     /* XXX set rx mode ??? */
4277
4278     if (IS_PF(sc) && !sc->grcdump_done) {
4279         /* set ALWAYS_ALIVE bit in shmem */
4280         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4281
4282         bxe_drv_pulse(sc);
4283
4284         bxe_stats_handle(sc, STATS_EVENT_STOP);
4285         bxe_save_statistics(sc);
4286     }
4287
4288     /* wait till consumers catch up with producers in all queues */
4289     bxe_drain_tx_queues(sc);
4290
4291     /* if VF indicate to PF this function is going down (PF will delete sp
4292      * elements and clear initializations
4293      */
4294     if (IS_VF(sc)) {
4295         ; /* bxe_vfpf_close_vf(sc); */
4296     } else if (unload_mode != UNLOAD_RECOVERY) {
4297         /* if this is a normal/close unload need to clean up chip */
4298         if (!sc->grcdump_done)
4299             bxe_chip_cleanup(sc, unload_mode, keep_link);
4300     } else {
4301         /* Send the UNLOAD_REQUEST to the MCP */
4302         bxe_send_unload_req(sc, unload_mode);
4303
4304         /*
4305          * Prevent transactions to host from the functions on the
4306          * engine that doesn't reset global blocks in case of global
4307          * attention once gloabl blocks are reset and gates are opened
4308          * (the engine which leader will perform the recovery
4309          * last).
4310          */
4311         if (!CHIP_IS_E1x(sc)) {
4312             bxe_pf_disable(sc);
4313         }
4314
4315         /* disable HW interrupts */
4316         bxe_int_disable_sync(sc, TRUE);
4317
4318         /* detach interrupts */
4319         bxe_interrupt_detach(sc);
4320
4321         /* Report UNLOAD_DONE to MCP */
4322         bxe_send_unload_done(sc, FALSE);
4323     }
4324
4325     /*
4326      * At this stage no more interrupts will arrive so we may safely clean
4327      * the queue'able objects here in case they failed to get cleaned so far.
4328      */
4329     if (IS_PF(sc)) {
4330         bxe_squeeze_objects(sc);
4331     }
4332
4333     /* There should be no more pending SP commands at this stage */
4334     sc->sp_state = 0;
4335
4336     sc->port.pmf = 0;
4337
4338     bxe_free_fp_buffers(sc);
4339
4340     if (IS_PF(sc)) {
4341         bxe_free_mem(sc);
4342     }
4343
4344     bxe_free_fw_stats_mem(sc);
4345
4346     sc->state = BXE_STATE_CLOSED;
4347
4348     /*
4349      * Check if there are pending parity attentions. If there are - set
4350      * RECOVERY_IN_PROGRESS.
4351      */
4352     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4353         bxe_set_reset_in_progress(sc);
4354
4355         /* Set RESET_IS_GLOBAL if needed */
4356         if (global) {
4357             bxe_set_reset_global(sc);
4358         }
4359     }
4360
4361     /*
4362      * The last driver must disable a "close the gate" if there is no
4363      * parity attention or "process kill" pending.
4364      */
4365     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4366         bxe_reset_is_done(sc, SC_PATH(sc))) {
4367         bxe_disable_close_the_gate(sc);
4368     }
4369
4370     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4371
4372     return (0);
4373 }
4374
4375 /*
4376  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4377  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4378  */
4379 static int
4380 bxe_ifmedia_update(struct ifnet *ifp)
4381 {
4382     struct bxe_softc *sc = (struct bxe_softc *)ifp->if_softc;
4383     struct ifmedia *ifm;
4384
4385     ifm = &sc->ifmedia;
4386
4387     /* We only support Ethernet media type. */
4388     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4389         return (EINVAL);
4390     }
4391
4392     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4393     case IFM_AUTO:
4394          break;
4395     case IFM_10G_CX4:
4396     case IFM_10G_SR:
4397     case IFM_10G_T:
4398     case IFM_10G_TWINAX:
4399     default:
4400         /* We don't support changing the media type. */
4401         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4402               IFM_SUBTYPE(ifm->ifm_media));
4403         return (EINVAL);
4404     }
4405
4406     return (0);
4407 }
4408
4409 /*
4410  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4411  */
4412 static void
4413 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4414 {
4415     struct bxe_softc *sc = ifp->if_softc;
4416
4417     /* Report link down if the driver isn't running. */
4418     if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4419         ifmr->ifm_active |= IFM_NONE;
4420         return;
4421     }
4422
4423     /* Setup the default interface info. */
4424     ifmr->ifm_status = IFM_AVALID;
4425     ifmr->ifm_active = IFM_ETHER;
4426
4427     if (sc->link_vars.link_up) {
4428         ifmr->ifm_status |= IFM_ACTIVE;
4429     } else {
4430         ifmr->ifm_active |= IFM_NONE;
4431         return;
4432     }
4433
4434     ifmr->ifm_active |= sc->media;
4435
4436     if (sc->link_vars.duplex == DUPLEX_FULL) {
4437         ifmr->ifm_active |= IFM_FDX;
4438     } else {
4439         ifmr->ifm_active |= IFM_HDX;
4440     }
4441 }
4442
4443 static int
4444 bxe_ioctl_nvram(struct bxe_softc *sc,
4445                 uint32_t         priv_op,
4446                 struct ifreq     *ifr)
4447 {
4448     struct bxe_nvram_data nvdata_base;
4449     struct bxe_nvram_data *nvdata;
4450     int len;
4451     int error = 0;
4452
4453     copyin(ifr->ifr_data, &nvdata_base, sizeof(nvdata_base));
4454
4455     len = (sizeof(struct bxe_nvram_data) +
4456            nvdata_base.len -
4457            sizeof(uint32_t));
4458
4459     if (len > sizeof(struct bxe_nvram_data)) {
4460         if ((nvdata = (struct bxe_nvram_data *)
4461                  malloc(len, M_DEVBUF,
4462                         (M_NOWAIT | M_ZERO))) == NULL) {
4463             BLOGE(sc, "BXE_IOC_RD_NVRAM malloc failed priv_op 0x%x "
4464                 " len = 0x%x\n", priv_op, len);
4465             return (1);
4466         }
4467         memcpy(nvdata, &nvdata_base, sizeof(struct bxe_nvram_data));
4468     } else {
4469         nvdata = &nvdata_base;
4470     }
4471
4472     if (priv_op == BXE_IOC_RD_NVRAM) {
4473         BLOGD(sc, DBG_IOCTL, "IOC_RD_NVRAM 0x%x %d\n",
4474               nvdata->offset, nvdata->len);
4475         error = bxe_nvram_read(sc,
4476                                nvdata->offset,
4477                                (uint8_t *)nvdata->value,
4478                                nvdata->len);
4479         copyout(nvdata, ifr->ifr_data, len);
4480     } else { /* BXE_IOC_WR_NVRAM */
4481         BLOGD(sc, DBG_IOCTL, "IOC_WR_NVRAM 0x%x %d\n",
4482               nvdata->offset, nvdata->len);
4483         copyin(ifr->ifr_data, nvdata, len);
4484         error = bxe_nvram_write(sc,
4485                                 nvdata->offset,
4486                                 (uint8_t *)nvdata->value,
4487                                 nvdata->len);
4488     }
4489
4490     if (len > sizeof(struct bxe_nvram_data)) {
4491         free(nvdata, M_DEVBUF);
4492     }
4493
4494     return (error);
4495 }
4496
4497 static int
4498 bxe_ioctl_stats_show(struct bxe_softc *sc,
4499                      uint32_t         priv_op,
4500                      struct ifreq     *ifr)
4501 {
4502     const size_t str_size   = (BXE_NUM_ETH_STATS * STAT_NAME_LEN);
4503     const size_t stats_size = (BXE_NUM_ETH_STATS * sizeof(uint64_t));
4504     caddr_t p_tmp;
4505     uint32_t *offset;
4506     int i;
4507
4508     switch (priv_op)
4509     {
4510     case BXE_IOC_STATS_SHOW_NUM:
4511         memset(ifr->ifr_data, 0, sizeof(union bxe_stats_show_data));
4512         ((union bxe_stats_show_data *)ifr->ifr_data)->desc.num =
4513             BXE_NUM_ETH_STATS;
4514         ((union bxe_stats_show_data *)ifr->ifr_data)->desc.len =
4515             STAT_NAME_LEN;
4516         return (0);
4517
4518     case BXE_IOC_STATS_SHOW_STR:
4519         memset(ifr->ifr_data, 0, str_size);
4520         p_tmp = ifr->ifr_data;
4521         for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4522             strcpy(p_tmp, bxe_eth_stats_arr[i].string);
4523             p_tmp += STAT_NAME_LEN;
4524         }
4525         return (0);
4526
4527     case BXE_IOC_STATS_SHOW_CNT:
4528         memset(ifr->ifr_data, 0, stats_size);
4529         p_tmp = ifr->ifr_data;
4530         for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4531             offset = ((uint32_t *)&sc->eth_stats +
4532                       bxe_eth_stats_arr[i].offset);
4533             switch (bxe_eth_stats_arr[i].size) {
4534             case 4:
4535                 *((uint64_t *)p_tmp) = (uint64_t)*offset;
4536                 break;
4537             case 8:
4538                 *((uint64_t *)p_tmp) = HILO_U64(*offset, *(offset + 1));
4539                 break;
4540             default:
4541                 *((uint64_t *)p_tmp) = 0;
4542             }
4543             p_tmp += sizeof(uint64_t);
4544         }
4545         return (0);
4546
4547     default:
4548         return (-1);
4549     }
4550 }
4551
4552 static void
4553 bxe_handle_chip_tq(void *context,
4554                    int  pending)
4555 {
4556     struct bxe_softc *sc = (struct bxe_softc *)context;
4557     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4558
4559     switch (work)
4560     {
4561     case CHIP_TQ_REINIT:
4562         if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
4563             /* restart the interface */
4564             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4565             bxe_periodic_stop(sc);
4566             BXE_CORE_LOCK(sc);
4567             bxe_stop_locked(sc);
4568             bxe_init_locked(sc);
4569             BXE_CORE_UNLOCK(sc);
4570         }
4571         break;
4572
4573     default:
4574         break;
4575     }
4576 }
4577
4578 /*
4579  * Handles any IOCTL calls from the operating system.
4580  *
4581  * Returns:
4582  *   0 = Success, >0 Failure
4583  */
4584 static int
4585 bxe_ioctl(struct ifnet *ifp,
4586           u_long       command,
4587           caddr_t      data)
4588 {
4589     struct bxe_softc *sc = ifp->if_softc;
4590     struct ifreq *ifr = (struct ifreq *)data;
4591     struct bxe_nvram_data *nvdata;
4592     uint32_t priv_op;
4593     int mask = 0;
4594     int reinit = 0;
4595     int error = 0;
4596
4597     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4598     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4599
4600     switch (command)
4601     {
4602     case SIOCSIFMTU:
4603         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4604               ifr->ifr_mtu);
4605
4606         if (sc->mtu == ifr->ifr_mtu) {
4607             /* nothing to change */
4608             break;
4609         }
4610
4611         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4612             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4613                   ifr->ifr_mtu, mtu_min, mtu_max);
4614             error = EINVAL;
4615             break;
4616         }
4617
4618         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4619                              (unsigned long)ifr->ifr_mtu);
4620         atomic_store_rel_long((volatile unsigned long *)&ifp->if_mtu,
4621                               (unsigned long)ifr->ifr_mtu);
4622
4623         reinit = 1;
4624         break;
4625
4626     case SIOCSIFFLAGS:
4627         /* toggle the interface state up or down */
4628         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4629
4630         BXE_CORE_LOCK(sc);
4631         /* check if the interface is up */
4632         if (ifp->if_flags & IFF_UP) {
4633             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4634                 /* set the receive mode flags */
4635                 bxe_set_rx_mode(sc);
4636             } else if(sc->state != BXE_STATE_DISABLED) {
4637                 bxe_init_locked(sc);
4638             }
4639         } else {
4640             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4641                 bxe_periodic_stop(sc);
4642                 bxe_stop_locked(sc);
4643             }
4644         }
4645         BXE_CORE_UNLOCK(sc);
4646
4647         break;
4648
4649     case SIOCADDMULTI:
4650     case SIOCDELMULTI:
4651         /* add/delete multicast addresses */
4652         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4653
4654         /* check if the interface is up */
4655         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4656             /* set the receive mode flags */
4657             BXE_CORE_LOCK(sc);
4658             bxe_set_rx_mode(sc);
4659             BXE_CORE_UNLOCK(sc); 
4660         }
4661
4662         break;
4663
4664     case SIOCSIFCAP:
4665         /* find out which capabilities have changed */
4666         mask = (ifr->ifr_reqcap ^ ifp->if_capenable);
4667
4668         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4669               mask);
4670
4671         /* toggle the LRO capabilites enable flag */
4672         if (mask & IFCAP_LRO) {
4673             ifp->if_capenable ^= IFCAP_LRO;
4674             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4675                   (ifp->if_capenable & IFCAP_LRO) ? "ON" : "OFF");
4676             reinit = 1;
4677         }
4678
4679         /* toggle the TXCSUM checksum capabilites enable flag */
4680         if (mask & IFCAP_TXCSUM) {
4681             ifp->if_capenable ^= IFCAP_TXCSUM;
4682             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4683                   (ifp->if_capenable & IFCAP_TXCSUM) ? "ON" : "OFF");
4684             if (ifp->if_capenable & IFCAP_TXCSUM) {
4685                 ifp->if_hwassist = (CSUM_IP       |
4686                                     CSUM_TCP      |
4687                                     CSUM_UDP      |
4688                                     CSUM_TSO      |
4689                                     CSUM_TCP_IPV6 |
4690                                     CSUM_UDP_IPV6);
4691             } else {
4692                 ifp->if_hwassist = 0;
4693             }
4694         }
4695
4696         /* toggle the RXCSUM checksum capabilities enable flag */
4697         if (mask & IFCAP_RXCSUM) {
4698             ifp->if_capenable ^= IFCAP_RXCSUM;
4699             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4700                   (ifp->if_capenable & IFCAP_RXCSUM) ? "ON" : "OFF");
4701             if (ifp->if_capenable & IFCAP_RXCSUM) {
4702                 ifp->if_hwassist = (CSUM_IP       |
4703                                     CSUM_TCP      |
4704                                     CSUM_UDP      |
4705                                     CSUM_TSO      |
4706                                     CSUM_TCP_IPV6 |
4707                                     CSUM_UDP_IPV6);
4708             } else {
4709                 ifp->if_hwassist = 0;
4710             }
4711         }
4712
4713         /* toggle TSO4 capabilities enabled flag */
4714         if (mask & IFCAP_TSO4) {
4715             ifp->if_capenable ^= IFCAP_TSO4;
4716             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4717                   (ifp->if_capenable & IFCAP_TSO4) ? "ON" : "OFF");
4718         }
4719
4720         /* toggle TSO6 capabilities enabled flag */
4721         if (mask & IFCAP_TSO6) {
4722             ifp->if_capenable ^= IFCAP_TSO6;
4723             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4724                   (ifp->if_capenable & IFCAP_TSO6) ? "ON" : "OFF");
4725         }
4726
4727         /* toggle VLAN_HWTSO capabilities enabled flag */
4728         if (mask & IFCAP_VLAN_HWTSO) {
4729             ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
4730             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4731                   (ifp->if_capenable & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4732         }
4733
4734         /* toggle VLAN_HWCSUM capabilities enabled flag */
4735         if (mask & IFCAP_VLAN_HWCSUM) {
4736             /* XXX investigate this... */
4737             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4738             error = EINVAL;
4739         }
4740
4741         /* toggle VLAN_MTU capabilities enable flag */
4742         if (mask & IFCAP_VLAN_MTU) {
4743             /* XXX investigate this... */
4744             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4745             error = EINVAL;
4746         }
4747
4748         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4749         if (mask & IFCAP_VLAN_HWTAGGING) {
4750             /* XXX investigate this... */
4751             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4752             error = EINVAL;
4753         }
4754
4755         /* toggle VLAN_HWFILTER capabilities enabled flag */
4756         if (mask & IFCAP_VLAN_HWFILTER) {
4757             /* XXX investigate this... */
4758             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4759             error = EINVAL;
4760         }
4761
4762         /* XXX not yet...
4763          * IFCAP_WOL_MAGIC
4764          */
4765
4766         break;
4767
4768     case SIOCSIFMEDIA:
4769     case SIOCGIFMEDIA:
4770         /* set/get interface media */
4771         BLOGD(sc, DBG_IOCTL,
4772               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4773               (command & 0xff));
4774         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4775         break;
4776
4777     case SIOCGPRIVATE_0:
4778         copyin(ifr->ifr_data, &priv_op, sizeof(priv_op));
4779
4780         switch (priv_op)
4781         {
4782         case BXE_IOC_RD_NVRAM:
4783         case BXE_IOC_WR_NVRAM:
4784             nvdata = (struct bxe_nvram_data *)ifr->ifr_data;
4785             BLOGD(sc, DBG_IOCTL,
4786                   "Received Private NVRAM ioctl addr=0x%x size=%u\n",
4787                   nvdata->offset, nvdata->len);
4788             error = bxe_ioctl_nvram(sc, priv_op, ifr);
4789             break;
4790
4791         case BXE_IOC_STATS_SHOW_NUM:
4792         case BXE_IOC_STATS_SHOW_STR:
4793         case BXE_IOC_STATS_SHOW_CNT:
4794             BLOGD(sc, DBG_IOCTL, "Received Private Stats ioctl (%d)\n",
4795                   priv_op);
4796             error = bxe_ioctl_stats_show(sc, priv_op, ifr);
4797             break;
4798
4799         default:
4800             BLOGW(sc, "Received Private Unknown ioctl (%d)\n", priv_op);
4801             error = EINVAL;
4802             break;
4803         }
4804
4805         break;
4806
4807     default:
4808         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4809               (command & 0xff));
4810         error = ether_ioctl(ifp, command, data);
4811         break;
4812     }
4813
4814     if (reinit && (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
4815         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4816               "Re-initializing hardware from IOCTL change\n");
4817         bxe_periodic_stop(sc);
4818         BXE_CORE_LOCK(sc);
4819         bxe_stop_locked(sc);
4820         bxe_init_locked(sc);
4821         BXE_CORE_UNLOCK(sc);
4822     }
4823
4824     return (error);
4825 }
4826
4827 static __noinline void
4828 bxe_dump_mbuf(struct bxe_softc *sc,
4829               struct mbuf      *m,
4830               uint8_t          contents)
4831 {
4832     char * type;
4833     int i = 0;
4834
4835     if (!(sc->debug & DBG_MBUF)) {
4836         return;
4837     }
4838
4839     if (m == NULL) {
4840         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4841         return;
4842     }
4843
4844     while (m) {
4845
4846 #if __FreeBSD_version >= 1000000
4847         BLOGD(sc, DBG_MBUF,
4848               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4849               i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4850
4851         if (m->m_flags & M_PKTHDR) {
4852              BLOGD(sc, DBG_MBUF,
4853                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4854                    i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4855                    (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4856         }
4857 #else
4858         BLOGD(sc, DBG_MBUF,
4859               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4860               i, m, m->m_len, m->m_flags,
4861               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4862
4863         if (m->m_flags & M_PKTHDR) {
4864              BLOGD(sc, DBG_MBUF,
4865                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4866                    i, m->m_pkthdr.len, m->m_flags,
4867                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4868                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4869                    "\22M_PROMISC\23M_NOFREE",
4870                    (int)m->m_pkthdr.csum_flags,
4871                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4872                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4873                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4874                    "\14CSUM_PSEUDO_HDR");
4875         }
4876 #endif /* #if __FreeBSD_version >= 1000000 */
4877
4878         if (m->m_flags & M_EXT) {
4879             switch (m->m_ext.ext_type) {
4880             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4881             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4882             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4883             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4884             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4885             case EXT_PACKET:     type = "EXT_PACKET";     break;
4886             case EXT_MBUF:       type = "EXT_MBUF";       break;
4887             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4888             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4889             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4890             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4891             default:             type = "UNKNOWN";        break;
4892             }
4893
4894             BLOGD(sc, DBG_MBUF,
4895                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4896                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4897         }
4898
4899         if (contents) {
4900             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4901         }
4902
4903         m = m->m_next;
4904         i++;
4905     }
4906 }
4907
4908 /*
4909  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4910  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4911  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4912  * The headers comes in a seperate bd in FreeBSD so 13-3=10.
4913  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4914  */
4915 static int
4916 bxe_chktso_window(struct bxe_softc  *sc,
4917                   int               nsegs,
4918                   bus_dma_segment_t *segs,
4919                   struct mbuf       *m)
4920 {
4921     uint32_t num_wnds, wnd_size, wnd_sum;
4922     int32_t frag_idx, wnd_idx;
4923     unsigned short lso_mss;
4924     int defrag;
4925
4926     defrag = 0;
4927     wnd_sum = 0;
4928     wnd_size = 10;
4929     num_wnds = nsegs - wnd_size;
4930     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4931
4932     /*
4933      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4934      * first window sum of data while skipping the first assuming it is the
4935      * header in FreeBSD.
4936      */
4937     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4938         wnd_sum += htole16(segs[frag_idx].ds_len);
4939     }
4940
4941     /* check the first 10 bd window size */
4942     if (wnd_sum < lso_mss) {
4943         return (1);
4944     }
4945
4946     /* run through the windows */
4947     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4948         /* subtract the first mbuf->m_len of the last wndw(-header) */
4949         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4950         /* add the next mbuf len to the len of our new window */
4951         wnd_sum += htole16(segs[frag_idx].ds_len);
4952         if (wnd_sum < lso_mss) {
4953             return (1);
4954         }
4955     }
4956
4957     return (0);
4958 }
4959
4960 static uint8_t
4961 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4962                     struct mbuf         *m,
4963                     uint32_t            *parsing_data)
4964 {
4965     struct ether_vlan_header *eh = NULL;
4966     struct ip *ip4 = NULL;
4967     struct ip6_hdr *ip6 = NULL;
4968     caddr_t ip = NULL;
4969     struct tcphdr *th = NULL;
4970     int e_hlen, ip_hlen, l4_off;
4971     uint16_t proto;
4972
4973     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4974         /* no L4 checksum offload needed */
4975         return (0);
4976     }
4977
4978     /* get the Ethernet header */
4979     eh = mtod(m, struct ether_vlan_header *);
4980
4981     /* handle VLAN encapsulation if present */
4982     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4983         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4984         proto  = ntohs(eh->evl_proto);
4985     } else {
4986         e_hlen = ETHER_HDR_LEN;
4987         proto  = ntohs(eh->evl_encap_proto);
4988     }
4989
4990     switch (proto) {
4991     case ETHERTYPE_IP:
4992         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4993         ip4 = (m->m_len < sizeof(struct ip)) ?
4994                   (struct ip *)m->m_next->m_data :
4995                   (struct ip *)(m->m_data + e_hlen);
4996         /* ip_hl is number of 32-bit words */
4997         ip_hlen = (ip4->ip_hl << 2);
4998         ip = (caddr_t)ip4;
4999         break;
5000     case ETHERTYPE_IPV6:
5001         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
5002         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
5003                   (struct ip6_hdr *)m->m_next->m_data :
5004                   (struct ip6_hdr *)(m->m_data + e_hlen);
5005         /* XXX cannot support offload with IPv6 extensions */
5006         ip_hlen = sizeof(struct ip6_hdr);
5007         ip = (caddr_t)ip6;
5008         break;
5009     default:
5010         /* We can't offload in this case... */
5011         /* XXX error stat ??? */
5012         return (0);
5013     }
5014
5015     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5016     l4_off = (e_hlen + ip_hlen);
5017
5018     *parsing_data |=
5019         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
5020          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
5021
5022     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5023                                   CSUM_TSO |
5024                                   CSUM_TCP_IPV6)) {
5025         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5026         th = (struct tcphdr *)(ip + ip_hlen);
5027         /* th_off is number of 32-bit words */
5028         *parsing_data |= ((th->th_off <<
5029                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
5030                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
5031         return (l4_off + (th->th_off << 2)); /* entire header length */
5032     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5033                                          CSUM_UDP_IPV6)) {
5034         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5035         return (l4_off + sizeof(struct udphdr)); /* entire header length */
5036     } else {
5037         /* XXX error stat ??? */
5038         return (0);
5039     }
5040 }
5041
5042 static uint8_t
5043 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
5044                  struct mbuf                *m,
5045                  struct eth_tx_parse_bd_e1x *pbd)
5046 {
5047     struct ether_vlan_header *eh = NULL;
5048     struct ip *ip4 = NULL;
5049     struct ip6_hdr *ip6 = NULL;
5050     caddr_t ip = NULL;
5051     struct tcphdr *th = NULL;
5052     struct udphdr *uh = NULL;
5053     int e_hlen, ip_hlen;
5054     uint16_t proto;
5055     uint8_t hlen;
5056     uint16_t tmp_csum;
5057     uint32_t *tmp_uh;
5058
5059     /* get the Ethernet header */
5060     eh = mtod(m, struct ether_vlan_header *);
5061
5062     /* handle VLAN encapsulation if present */
5063     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
5064         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
5065         proto  = ntohs(eh->evl_proto);
5066     } else {
5067         e_hlen = ETHER_HDR_LEN;
5068         proto  = ntohs(eh->evl_encap_proto);
5069     }
5070
5071     switch (proto) {
5072     case ETHERTYPE_IP:
5073         /* get the IP header, if mbuf len < 20 then header in next mbuf */
5074         ip4 = (m->m_len < sizeof(struct ip)) ?
5075                   (struct ip *)m->m_next->m_data :
5076                   (struct ip *)(m->m_data + e_hlen);
5077         /* ip_hl is number of 32-bit words */
5078         ip_hlen = (ip4->ip_hl << 1);
5079         ip = (caddr_t)ip4;
5080         break;
5081     case ETHERTYPE_IPV6:
5082         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
5083         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
5084                   (struct ip6_hdr *)m->m_next->m_data :
5085                   (struct ip6_hdr *)(m->m_data + e_hlen);
5086         /* XXX cannot support offload with IPv6 extensions */
5087         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
5088         ip = (caddr_t)ip6;
5089         break;
5090     default:
5091         /* We can't offload in this case... */
5092         /* XXX error stat ??? */
5093         return (0);
5094     }
5095
5096     hlen = (e_hlen >> 1);
5097
5098     /* note that rest of global_data is indirectly zeroed here */
5099     if (m->m_flags & M_VLANTAG) {
5100         pbd->global_data =
5101             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
5102     } else {
5103         pbd->global_data = htole16(hlen);
5104     }
5105
5106     pbd->ip_hlen_w = ip_hlen;
5107
5108     hlen += pbd->ip_hlen_w;
5109
5110     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5111
5112     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5113                                   CSUM_TSO |
5114                                   CSUM_TCP_IPV6)) {
5115         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5116         /* th_off is number of 32-bit words */
5117         hlen += (uint16_t)(th->th_off << 1);
5118     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5119                                          CSUM_UDP_IPV6)) {
5120         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5121         hlen += (sizeof(struct udphdr) / 2);
5122     } else {
5123         /* valid case as only CSUM_IP was set */
5124         return (0);
5125     }
5126
5127     pbd->total_hlen_w = htole16(hlen);
5128
5129     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5130                                   CSUM_TSO |
5131                                   CSUM_TCP_IPV6)) {
5132         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5133         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5134     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5135                                          CSUM_UDP_IPV6)) {
5136         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5137
5138         /*
5139          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5140          * checksums and does not know anything about the UDP header and where
5141          * the checksum field is located. It only knows about TCP. Therefore
5142          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5143          * offload. Since the checksum field offset for TCP is 16 bytes and
5144          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5145          * bytes less than the start of the UDP header. This allows the
5146          * hardware to write the checksum in the correct spot. But the
5147          * hardware will compute a checksum which includes the last 10 bytes
5148          * of the IP header. To correct this we tweak the stack computed
5149          * pseudo checksum by folding in the calculation of the inverse
5150          * checksum for those final 10 bytes of the IP header. This allows
5151          * the correct checksum to be computed by the hardware.
5152          */
5153
5154         /* set pointer 10 bytes before UDP header */
5155         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5156
5157         /* calculate a pseudo header checksum over the first 10 bytes */
5158         tmp_csum = in_pseudo(*tmp_uh,
5159                              *(tmp_uh + 1),
5160                              *(uint16_t *)(tmp_uh + 2));
5161
5162         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5163     }
5164
5165     return (hlen * 2); /* entire header length, number of bytes */
5166 }
5167
5168 static void
5169 bxe_set_pbd_lso_e2(struct mbuf *m,
5170                    uint32_t    *parsing_data)
5171 {
5172     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5173                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5174                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5175
5176     /* XXX test for IPv6 with extension header... */
5177 }
5178
5179 static void
5180 bxe_set_pbd_lso(struct mbuf                *m,
5181                 struct eth_tx_parse_bd_e1x *pbd)
5182 {
5183     struct ether_vlan_header *eh = NULL;
5184     struct ip *ip = NULL;
5185     struct tcphdr *th = NULL;
5186     int e_hlen;
5187
5188     /* get the Ethernet header */
5189     eh = mtod(m, struct ether_vlan_header *);
5190
5191     /* handle VLAN encapsulation if present */
5192     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5193                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5194
5195     /* get the IP and TCP header, with LSO entire header in first mbuf */
5196     /* XXX assuming IPv4 */
5197     ip = (struct ip *)(m->m_data + e_hlen);
5198     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5199
5200     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5201     pbd->tcp_send_seq = ntohl(th->th_seq);
5202     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5203
5204 #if 1
5205         /* XXX IPv4 */
5206         pbd->ip_id = ntohs(ip->ip_id);
5207         pbd->tcp_pseudo_csum =
5208             ntohs(in_pseudo(ip->ip_src.s_addr,
5209                             ip->ip_dst.s_addr,
5210                             htons(IPPROTO_TCP)));
5211 #else
5212         /* XXX IPv6 */
5213         pbd->tcp_pseudo_csum =
5214             ntohs(in_pseudo(&ip6->ip6_src,
5215                             &ip6->ip6_dst,
5216                             htons(IPPROTO_TCP)));
5217 #endif
5218
5219     pbd->global_data |=
5220         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5221 }
5222
5223 /*
5224  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5225  * visible to the controller.
5226  *
5227  * If an mbuf is submitted to this routine and cannot be given to the
5228  * controller (e.g. it has too many fragments) then the function may free
5229  * the mbuf and return to the caller.
5230  *
5231  * Returns:
5232  *   0 = Success, !0 = Failure
5233  *   Note the side effect that an mbuf may be freed if it causes a problem.
5234  */
5235 static int
5236 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5237 {
5238     bus_dma_segment_t segs[32];
5239     struct mbuf *m0;
5240     struct bxe_sw_tx_bd *tx_buf;
5241     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5242     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5243     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5244     struct eth_tx_bd *tx_data_bd;
5245     struct eth_tx_bd *tx_total_pkt_size_bd;
5246     struct eth_tx_start_bd *tx_start_bd;
5247     uint16_t bd_prod, pkt_prod, total_pkt_size;
5248     uint8_t mac_type;
5249     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5250     struct bxe_softc *sc;
5251     uint16_t tx_bd_avail;
5252     struct ether_vlan_header *eh;
5253     uint32_t pbd_e2_parsing_data = 0;
5254     uint8_t hlen = 0;
5255     int tmp_bd;
5256     int i;
5257
5258     sc = fp->sc;
5259
5260 #if __FreeBSD_version >= 800000
5261     M_ASSERTPKTHDR(*m_head);
5262 #endif /* #if __FreeBSD_version >= 800000 */
5263
5264     m0 = *m_head;
5265     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5266     tx_start_bd = NULL;
5267     tx_data_bd = NULL;
5268     tx_total_pkt_size_bd = NULL;
5269
5270     /* get the H/W pointer for packets and BDs */
5271     pkt_prod = fp->tx_pkt_prod;
5272     bd_prod = fp->tx_bd_prod;
5273
5274     mac_type = UNICAST_ADDRESS;
5275
5276     /* map the mbuf into the next open DMAable memory */
5277     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5278     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5279                                     tx_buf->m_map, m0,
5280                                     segs, &nsegs, BUS_DMA_NOWAIT);
5281
5282     /* mapping errors */
5283     if(__predict_false(error != 0)) {
5284         fp->eth_q_stats.tx_dma_mapping_failure++;
5285         if (error == ENOMEM) {
5286             /* resource issue, try again later */
5287             rc = ENOMEM;
5288         } else if (error == EFBIG) {
5289             /* possibly recoverable with defragmentation */
5290             fp->eth_q_stats.mbuf_defrag_attempts++;
5291             m0 = m_defrag(*m_head, M_DONTWAIT);
5292             if (m0 == NULL) {
5293                 fp->eth_q_stats.mbuf_defrag_failures++;
5294                 rc = ENOBUFS;
5295             } else {
5296                 /* defrag successful, try mapping again */
5297                 *m_head = m0;
5298                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5299                                                 tx_buf->m_map, m0,
5300                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5301                 if (error) {
5302                     fp->eth_q_stats.tx_dma_mapping_failure++;
5303                     rc = error;
5304                 }
5305             }
5306         } else {
5307             /* unknown, unrecoverable mapping error */
5308             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5309             bxe_dump_mbuf(sc, m0, FALSE);
5310             rc = error;
5311         }
5312
5313         goto bxe_tx_encap_continue;
5314     }
5315
5316     tx_bd_avail = bxe_tx_avail(sc, fp);
5317
5318     /* make sure there is enough room in the send queue */
5319     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5320         /* Recoverable, try again later. */
5321         fp->eth_q_stats.tx_hw_queue_full++;
5322         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5323         rc = ENOMEM;
5324         goto bxe_tx_encap_continue;
5325     }
5326
5327     /* capture the current H/W TX chain high watermark */
5328     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5329                         (TX_BD_USABLE - tx_bd_avail))) {
5330         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5331     }
5332
5333     /* make sure it fits in the packet window */
5334     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5335         /*
5336          * The mbuf may be to big for the controller to handle. If the frame
5337          * is a TSO frame we'll need to do an additional check.
5338          */
5339         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5340             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5341                 goto bxe_tx_encap_continue; /* OK to send */
5342             } else {
5343                 fp->eth_q_stats.tx_window_violation_tso++;
5344             }
5345         } else {
5346             fp->eth_q_stats.tx_window_violation_std++;
5347         }
5348
5349         /* lets try to defragment this mbuf and remap it */
5350         fp->eth_q_stats.mbuf_defrag_attempts++;
5351         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5352
5353         m0 = m_defrag(*m_head, M_DONTWAIT);
5354         if (m0 == NULL) {
5355             fp->eth_q_stats.mbuf_defrag_failures++;
5356             /* Ugh, just drop the frame... :( */
5357             rc = ENOBUFS;
5358         } else {
5359             /* defrag successful, try mapping again */
5360             *m_head = m0;
5361             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5362                                             tx_buf->m_map, m0,
5363                                             segs, &nsegs, BUS_DMA_NOWAIT);
5364             if (error) {
5365                 fp->eth_q_stats.tx_dma_mapping_failure++;
5366                 /* No sense in trying to defrag/copy chain, drop it. :( */
5367                 rc = error;
5368             }
5369             else {
5370                 /* if the chain is still too long then drop it */
5371                 if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5372                     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5373                     rc = ENODEV;
5374                 }
5375             }
5376         }
5377     }
5378
5379 bxe_tx_encap_continue:
5380
5381     /* Check for errors */
5382     if (rc) {
5383         if (rc == ENOMEM) {
5384             /* recoverable try again later  */
5385         } else {
5386             fp->eth_q_stats.tx_soft_errors++;
5387             fp->eth_q_stats.mbuf_alloc_tx--;
5388             m_freem(*m_head);
5389             *m_head = NULL;
5390         }
5391
5392         return (rc);
5393     }
5394
5395     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5396     if (m0->m_flags & M_BCAST) {
5397         mac_type = BROADCAST_ADDRESS;
5398     } else if (m0->m_flags & M_MCAST) {
5399         mac_type = MULTICAST_ADDRESS;
5400     }
5401
5402     /* store the mbuf into the mbuf ring */
5403     tx_buf->m        = m0;
5404     tx_buf->first_bd = fp->tx_bd_prod;
5405     tx_buf->flags    = 0;
5406
5407     /* prepare the first transmit (start) BD for the mbuf */
5408     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5409
5410     BLOGD(sc, DBG_TX,
5411           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5412           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5413
5414     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5415     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5416     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5417     total_pkt_size += tx_start_bd->nbytes;
5418     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5419
5420     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5421
5422     /* all frames have at least Start BD + Parsing BD */
5423     nbds = nsegs + 1;
5424     tx_start_bd->nbd = htole16(nbds);
5425
5426     if (m0->m_flags & M_VLANTAG) {
5427         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5428         tx_start_bd->bd_flags.as_bitfield |=
5429             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5430     } else {
5431         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5432         if (IS_VF(sc)) {
5433             /* map ethernet header to find type and header length */
5434             eh = mtod(m0, struct ether_vlan_header *);
5435             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5436         } else {
5437             /* used by FW for packet accounting */
5438             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5439         }
5440     }
5441
5442     /*
5443      * add a parsing BD from the chain. The parsing BD is always added
5444      * though it is only used for TSO and chksum
5445      */
5446     bd_prod = TX_BD_NEXT(bd_prod);
5447
5448     if (m0->m_pkthdr.csum_flags) {
5449         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5450             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5451             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5452         }
5453
5454         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5455             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5456                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5457         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5458             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5459                                                   ETH_TX_BD_FLAGS_IS_UDP |
5460                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5461         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5462                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5463             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5464         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5465             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5466                                                   ETH_TX_BD_FLAGS_IS_UDP);
5467         }
5468     }
5469
5470     if (!CHIP_IS_E1x(sc)) {
5471         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5472         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5473
5474         if (m0->m_pkthdr.csum_flags) {
5475             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5476         }
5477
5478         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5479                  mac_type);
5480     } else {
5481         uint16_t global_data = 0;
5482
5483         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5484         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5485
5486         if (m0->m_pkthdr.csum_flags) {
5487             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5488         }
5489
5490         SET_FLAG(global_data,
5491                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5492         pbd_e1x->global_data |= htole16(global_data);
5493     }
5494
5495     /* setup the parsing BD with TSO specific info */
5496     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5497         fp->eth_q_stats.tx_ofld_frames_lso++;
5498         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5499
5500         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5501             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5502
5503             /* split the first BD into header/data making the fw job easy */
5504             nbds++;
5505             tx_start_bd->nbd = htole16(nbds);
5506             tx_start_bd->nbytes = htole16(hlen);
5507
5508             bd_prod = TX_BD_NEXT(bd_prod);
5509
5510             /* new transmit BD after the tx_parse_bd */
5511             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5512             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5513             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5514             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5515             if (tx_total_pkt_size_bd == NULL) {
5516                 tx_total_pkt_size_bd = tx_data_bd;
5517             }
5518
5519             BLOGD(sc, DBG_TX,
5520                   "TSO split header size is %d (%x:%x) nbds %d\n",
5521                   le16toh(tx_start_bd->nbytes),
5522                   le32toh(tx_start_bd->addr_hi),
5523                   le32toh(tx_start_bd->addr_lo),
5524                   nbds);
5525         }
5526
5527         if (!CHIP_IS_E1x(sc)) {
5528             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5529         } else {
5530             bxe_set_pbd_lso(m0, pbd_e1x);
5531         }
5532     }
5533
5534     if (pbd_e2_parsing_data) {
5535         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5536     }
5537
5538     /* prepare remaining BDs, start tx bd contains first seg/frag */
5539     for (i = 1; i < nsegs ; i++) {
5540         bd_prod = TX_BD_NEXT(bd_prod);
5541         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5542         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5543         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5544         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5545         if (tx_total_pkt_size_bd == NULL) {
5546             tx_total_pkt_size_bd = tx_data_bd;
5547         }
5548         total_pkt_size += tx_data_bd->nbytes;
5549     }
5550
5551     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5552
5553     if (tx_total_pkt_size_bd != NULL) {
5554         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5555     }
5556
5557     if (__predict_false(sc->debug & DBG_TX)) {
5558         tmp_bd = tx_buf->first_bd;
5559         for (i = 0; i < nbds; i++)
5560         {
5561             if (i == 0) {
5562                 BLOGD(sc, DBG_TX,
5563                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5564                       "bd_flags=0x%x hdr_nbds=%d\n",
5565                       tx_start_bd,
5566                       tmp_bd,
5567                       le16toh(tx_start_bd->nbd),
5568                       le16toh(tx_start_bd->vlan_or_ethertype),
5569                       tx_start_bd->bd_flags.as_bitfield,
5570                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5571             } else if (i == 1) {
5572                 if (pbd_e1x) {
5573                     BLOGD(sc, DBG_TX,
5574                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5575                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5576                           "tcp_seq=%u total_hlen_w=%u\n",
5577                           pbd_e1x,
5578                           tmp_bd,
5579                           pbd_e1x->global_data,
5580                           pbd_e1x->ip_hlen_w,
5581                           pbd_e1x->ip_id,
5582                           pbd_e1x->lso_mss,
5583                           pbd_e1x->tcp_flags,
5584                           pbd_e1x->tcp_pseudo_csum,
5585                           pbd_e1x->tcp_send_seq,
5586                           le16toh(pbd_e1x->total_hlen_w));
5587                 } else { /* if (pbd_e2) */
5588                     BLOGD(sc, DBG_TX,
5589                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5590                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5591                           pbd_e2,
5592                           tmp_bd,
5593                           pbd_e2->data.mac_addr.dst_hi,
5594                           pbd_e2->data.mac_addr.dst_mid,
5595                           pbd_e2->data.mac_addr.dst_lo,
5596                           pbd_e2->data.mac_addr.src_hi,
5597                           pbd_e2->data.mac_addr.src_mid,
5598                           pbd_e2->data.mac_addr.src_lo,
5599                           pbd_e2->parsing_data);
5600                 }
5601             }
5602
5603             if (i != 1) { /* skip parse db as it doesn't hold data */
5604                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5605                 BLOGD(sc, DBG_TX,
5606                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5607                       tx_data_bd,
5608                       tmp_bd,
5609                       le16toh(tx_data_bd->nbytes),
5610                       le32toh(tx_data_bd->addr_hi),
5611                       le32toh(tx_data_bd->addr_lo));
5612             }
5613
5614             tmp_bd = TX_BD_NEXT(tmp_bd);
5615         }
5616     }
5617
5618     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5619
5620     /* update TX BD producer index value for next TX */
5621     bd_prod = TX_BD_NEXT(bd_prod);
5622
5623     /*
5624      * If the chain of tx_bd's describing this frame is adjacent to or spans
5625      * an eth_tx_next_bd element then we need to increment the nbds value.
5626      */
5627     if (TX_BD_IDX(bd_prod) < nbds) {
5628         nbds++;
5629     }
5630
5631     /* don't allow reordering of writes for nbd and packets */
5632     mb();
5633
5634     fp->tx_db.data.prod += nbds;
5635
5636     /* producer points to the next free tx_bd at this point */
5637     fp->tx_pkt_prod++;
5638     fp->tx_bd_prod = bd_prod;
5639
5640     DOORBELL(sc, fp->index, fp->tx_db.raw);
5641
5642     fp->eth_q_stats.tx_pkts++;
5643
5644     /* Prevent speculative reads from getting ahead of the status block. */
5645     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5646                       0, 0, BUS_SPACE_BARRIER_READ);
5647
5648     /* Prevent speculative reads from getting ahead of the doorbell. */
5649     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5650                       0, 0, BUS_SPACE_BARRIER_READ);
5651
5652     return (0);
5653 }
5654
5655 static void
5656 bxe_tx_start_locked(struct bxe_softc    *sc,
5657                     struct ifnet        *ifp,
5658                     struct bxe_fastpath *fp)
5659 {
5660     struct mbuf *m = NULL;
5661     int tx_count = 0;
5662     uint16_t tx_bd_avail;
5663
5664     BXE_FP_TX_LOCK_ASSERT(fp);
5665
5666     /* keep adding entries while there are frames to send */
5667     while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
5668
5669         /*
5670          * check for any frames to send
5671          * dequeue can still be NULL even if queue is not empty
5672          */
5673         IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
5674         if (__predict_false(m == NULL)) {
5675             break;
5676         }
5677
5678         /* the mbuf now belongs to us */
5679         fp->eth_q_stats.mbuf_alloc_tx++;
5680
5681         /*
5682          * Put the frame into the transmit ring. If we don't have room,
5683          * place the mbuf back at the head of the TX queue, set the
5684          * OACTIVE flag, and wait for the NIC to drain the chain.
5685          */
5686         if (__predict_false(bxe_tx_encap(fp, &m))) {
5687             fp->eth_q_stats.tx_encap_failures++;
5688             if (m != NULL) {
5689                 /* mark the TX queue as full and return the frame */
5690                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5691                 IFQ_DRV_PREPEND(&ifp->if_snd, m);
5692                 fp->eth_q_stats.mbuf_alloc_tx--;
5693                 fp->eth_q_stats.tx_queue_xoff++;
5694             }
5695
5696             /* stop looking for more work */
5697             break;
5698         }
5699
5700         /* the frame was enqueued successfully */
5701         tx_count++;
5702
5703         /* send a copy of the frame to any BPF listeners. */
5704         BPF_MTAP(ifp, m);
5705
5706         tx_bd_avail = bxe_tx_avail(sc, fp);
5707
5708         /* handle any completions if we're running low */
5709         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5710             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5711             bxe_txeof(sc, fp);
5712             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5713                 break;
5714             }
5715         }
5716     }
5717
5718     /* all TX packets were dequeued and/or the tx ring is full */
5719     if (tx_count > 0) {
5720         /* reset the TX watchdog timeout timer */
5721         fp->watchdog_timer = BXE_TX_TIMEOUT;
5722     }
5723 }
5724
5725 /* Legacy (non-RSS) dispatch routine */
5726 static void
5727 bxe_tx_start(struct ifnet *ifp)
5728 {
5729     struct bxe_softc *sc;
5730     struct bxe_fastpath *fp;
5731
5732     sc = ifp->if_softc;
5733
5734     if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5735         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5736         return;
5737     }
5738
5739     if (!sc->link_vars.link_up) {
5740         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5741         return;
5742     }
5743
5744     fp = &sc->fp[0];
5745
5746     if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5747         fp->eth_q_stats.tx_queue_full_return++;
5748         return;
5749     }
5750
5751     BXE_FP_TX_LOCK(fp);
5752     bxe_tx_start_locked(sc, ifp, fp);
5753     BXE_FP_TX_UNLOCK(fp);
5754 }
5755
5756 #if __FreeBSD_version >= 800000
5757
5758 static int
5759 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5760                        struct ifnet        *ifp,
5761                        struct bxe_fastpath *fp,
5762                        struct mbuf         *m)
5763 {
5764     struct buf_ring *tx_br = fp->tx_br;
5765     struct mbuf *next;
5766     int depth, rc, tx_count;
5767     uint16_t tx_bd_avail;
5768
5769     rc = tx_count = 0;
5770
5771     BXE_FP_TX_LOCK_ASSERT(fp);
5772
5773     if (!tx_br) {
5774         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5775         return (EINVAL);
5776     }
5777
5778     if (!sc->link_vars.link_up ||
5779         (ifp->if_drv_flags &
5780         (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) != IFF_DRV_RUNNING) {
5781         rc = drbr_enqueue(ifp, tx_br, m);
5782         goto bxe_tx_mq_start_locked_exit;
5783     }
5784
5785     /* fetch the depth of the driver queue */
5786     depth = drbr_inuse(ifp, tx_br);
5787     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5788         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5789     }
5790
5791     if (m == NULL) {
5792         /* no new work, check for pending frames */
5793         next = drbr_dequeue(ifp, tx_br);
5794     } else if (drbr_needs_enqueue(ifp, tx_br)) {
5795         /* have both new and pending work, maintain packet order */
5796         rc = drbr_enqueue(ifp, tx_br, m);
5797         if (rc != 0) {
5798             fp->eth_q_stats.tx_soft_errors++;
5799             goto bxe_tx_mq_start_locked_exit;
5800         }
5801         next = drbr_dequeue(ifp, tx_br);
5802     } else {
5803         /* new work only and nothing pending */
5804         next = m;
5805     }
5806
5807     /* keep adding entries while there are frames to send */
5808     while (next != NULL) {
5809
5810         /* the mbuf now belongs to us */
5811         fp->eth_q_stats.mbuf_alloc_tx++;
5812
5813         /*
5814          * Put the frame into the transmit ring. If we don't have room,
5815          * place the mbuf back at the head of the TX queue, set the
5816          * OACTIVE flag, and wait for the NIC to drain the chain.
5817          */
5818         rc = bxe_tx_encap(fp, &next);
5819         if (__predict_false(rc != 0)) {
5820             fp->eth_q_stats.tx_encap_failures++;
5821             if (next != NULL) {
5822                 /* mark the TX queue as full and save the frame */
5823                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5824                 /* XXX this may reorder the frame */
5825                 rc = drbr_enqueue(ifp, tx_br, next);
5826                 fp->eth_q_stats.mbuf_alloc_tx--;
5827                 fp->eth_q_stats.tx_frames_deferred++;
5828             }
5829
5830             /* stop looking for more work */
5831             break;
5832         }
5833
5834         /* the transmit frame was enqueued successfully */
5835         tx_count++;
5836
5837         /* send a copy of the frame to any BPF listeners */
5838         BPF_MTAP(ifp, next);
5839
5840         tx_bd_avail = bxe_tx_avail(sc, fp);
5841
5842         /* handle any completions if we're running low */
5843         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5844             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5845             bxe_txeof(sc, fp);
5846             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5847                 break;
5848             }
5849         }
5850
5851         next = drbr_dequeue(ifp, tx_br);
5852     }
5853
5854     /* all TX packets were dequeued and/or the tx ring is full */
5855     if (tx_count > 0) {
5856         /* reset the TX watchdog timeout timer */
5857         fp->watchdog_timer = BXE_TX_TIMEOUT;
5858     }
5859
5860 bxe_tx_mq_start_locked_exit:
5861
5862     return (rc);
5863 }
5864
5865 /* Multiqueue (TSS) dispatch routine. */
5866 static int
5867 bxe_tx_mq_start(struct ifnet *ifp,
5868                 struct mbuf  *m)
5869 {
5870     struct bxe_softc *sc = ifp->if_softc;
5871     struct bxe_fastpath *fp;
5872     int fp_index, rc;
5873
5874     fp_index = 0; /* default is the first queue */
5875
5876     /* check if flowid is set */
5877
5878     if (BXE_VALID_FLOWID(m))
5879         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5880
5881     fp = &sc->fp[fp_index];
5882
5883     if (BXE_FP_TX_TRYLOCK(fp)) {
5884         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5885         BXE_FP_TX_UNLOCK(fp);
5886     } else
5887         rc = drbr_enqueue(ifp, fp->tx_br, m);
5888
5889     return (rc);
5890 }
5891
5892 static void
5893 bxe_mq_flush(struct ifnet *ifp)
5894 {
5895     struct bxe_softc *sc = ifp->if_softc;
5896     struct bxe_fastpath *fp;
5897     struct mbuf *m;
5898     int i;
5899
5900     for (i = 0; i < sc->num_queues; i++) {
5901         fp = &sc->fp[i];
5902
5903         if (fp->state != BXE_FP_STATE_OPEN) {
5904             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5905                   fp->index, fp->state);
5906             continue;
5907         }
5908
5909         if (fp->tx_br != NULL) {
5910             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5911             BXE_FP_TX_LOCK(fp);
5912             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5913                 m_freem(m);
5914             }
5915             BXE_FP_TX_UNLOCK(fp);
5916         }
5917     }
5918
5919     if_qflush(ifp);
5920 }
5921
5922 #endif /* FreeBSD_version >= 800000 */
5923
5924 static uint16_t
5925 bxe_cid_ilt_lines(struct bxe_softc *sc)
5926 {
5927     if (IS_SRIOV(sc)) {
5928         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5929     }
5930     return (L2_ILT_LINES(sc));
5931 }
5932
5933 static void
5934 bxe_ilt_set_info(struct bxe_softc *sc)
5935 {
5936     struct ilt_client_info *ilt_client;
5937     struct ecore_ilt *ilt = sc->ilt;
5938     uint16_t line = 0;
5939
5940     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5941     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5942
5943     /* CDU */
5944     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5945     ilt_client->client_num = ILT_CLIENT_CDU;
5946     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5947     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5948     ilt_client->start = line;
5949     line += bxe_cid_ilt_lines(sc);
5950
5951     if (CNIC_SUPPORT(sc)) {
5952         line += CNIC_ILT_LINES;
5953     }
5954
5955     ilt_client->end = (line - 1);
5956
5957     BLOGD(sc, DBG_LOAD,
5958           "ilt client[CDU]: start %d, end %d, "
5959           "psz 0x%x, flags 0x%x, hw psz %d\n",
5960           ilt_client->start, ilt_client->end,
5961           ilt_client->page_size,
5962           ilt_client->flags,
5963           ilog2(ilt_client->page_size >> 12));
5964
5965     /* QM */
5966     if (QM_INIT(sc->qm_cid_count)) {
5967         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5968         ilt_client->client_num = ILT_CLIENT_QM;
5969         ilt_client->page_size = QM_ILT_PAGE_SZ;
5970         ilt_client->flags = 0;
5971         ilt_client->start = line;
5972
5973         /* 4 bytes for each cid */
5974         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5975                              QM_ILT_PAGE_SZ);
5976
5977         ilt_client->end = (line - 1);
5978
5979         BLOGD(sc, DBG_LOAD,
5980               "ilt client[QM]: start %d, end %d, "
5981               "psz 0x%x, flags 0x%x, hw psz %d\n",
5982               ilt_client->start, ilt_client->end,
5983               ilt_client->page_size, ilt_client->flags,
5984               ilog2(ilt_client->page_size >> 12));
5985     }
5986
5987     if (CNIC_SUPPORT(sc)) {
5988         /* SRC */
5989         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5990         ilt_client->client_num = ILT_CLIENT_SRC;
5991         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5992         ilt_client->flags = 0;
5993         ilt_client->start = line;
5994         line += SRC_ILT_LINES;
5995         ilt_client->end = (line - 1);
5996
5997         BLOGD(sc, DBG_LOAD,
5998               "ilt client[SRC]: start %d, end %d, "
5999               "psz 0x%x, flags 0x%x, hw psz %d\n",
6000               ilt_client->start, ilt_client->end,
6001               ilt_client->page_size, ilt_client->flags,
6002               ilog2(ilt_client->page_size >> 12));
6003
6004         /* TM */
6005         ilt_client = &ilt->clients[ILT_CLIENT_TM];
6006         ilt_client->client_num = ILT_CLIENT_TM;
6007         ilt_client->page_size = TM_ILT_PAGE_SZ;
6008         ilt_client->flags = 0;
6009         ilt_client->start = line;
6010         line += TM_ILT_LINES;
6011         ilt_client->end = (line - 1);
6012
6013         BLOGD(sc, DBG_LOAD,
6014               "ilt client[TM]: start %d, end %d, "
6015               "psz 0x%x, flags 0x%x, hw psz %d\n",
6016               ilt_client->start, ilt_client->end,
6017               ilt_client->page_size, ilt_client->flags,
6018               ilog2(ilt_client->page_size >> 12));
6019     }
6020
6021     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
6022 }
6023
6024 static void
6025 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
6026 {
6027     int i;
6028     uint32_t rx_buf_size;
6029
6030     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
6031
6032     for (i = 0; i < sc->num_queues; i++) {
6033         if(rx_buf_size <= MCLBYTES){
6034             sc->fp[i].rx_buf_size = rx_buf_size;
6035             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6036         }else if (rx_buf_size <= MJUMPAGESIZE){
6037             sc->fp[i].rx_buf_size = rx_buf_size;
6038             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
6039         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
6040             sc->fp[i].rx_buf_size = MCLBYTES;
6041             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6042         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
6043             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
6044             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
6045         }else {
6046             sc->fp[i].rx_buf_size = MCLBYTES;
6047             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6048         }
6049     }
6050 }
6051
6052 static int
6053 bxe_alloc_ilt_mem(struct bxe_softc *sc)
6054 {
6055     int rc = 0;
6056
6057     if ((sc->ilt =
6058          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
6059                                     M_BXE_ILT,
6060                                     (M_NOWAIT | M_ZERO))) == NULL) {
6061         rc = 1;
6062     }
6063
6064     return (rc);
6065 }
6066
6067 static int
6068 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
6069 {
6070     int rc = 0;
6071
6072     if ((sc->ilt->lines =
6073          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6074                                     M_BXE_ILT,
6075                                     (M_NOWAIT | M_ZERO))) == NULL) {
6076         rc = 1;
6077     }
6078
6079     return (rc);
6080 }
6081
6082 static void
6083 bxe_free_ilt_mem(struct bxe_softc *sc)
6084 {
6085     if (sc->ilt != NULL) {
6086         free(sc->ilt, M_BXE_ILT);
6087         sc->ilt = NULL;
6088     }
6089 }
6090
6091 static void
6092 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6093 {
6094     if (sc->ilt->lines != NULL) {
6095         free(sc->ilt->lines, M_BXE_ILT);
6096         sc->ilt->lines = NULL;
6097     }
6098 }
6099
6100 static void
6101 bxe_free_mem(struct bxe_softc *sc)
6102 {
6103     int i;
6104
6105     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6106         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6107         sc->context[i].vcxt = NULL;
6108         sc->context[i].size = 0;
6109     }
6110
6111     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6112
6113     bxe_free_ilt_lines_mem(sc);
6114
6115 }
6116
6117 static int
6118 bxe_alloc_mem(struct bxe_softc *sc)
6119 {
6120     int context_size;
6121     int allocated;
6122     int i;
6123
6124     /*
6125      * Allocate memory for CDU context:
6126      * This memory is allocated separately and not in the generic ILT
6127      * functions because CDU differs in few aspects:
6128      * 1. There can be multiple entities allocating memory for context -
6129      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6130      * its own ILT lines.
6131      * 2. Since CDU page-size is not a single 4KB page (which is the case
6132      * for the other ILT clients), to be efficient we want to support
6133      * allocation of sub-page-size in the last entry.
6134      * 3. Context pointers are used by the driver to pass to FW / update
6135      * the context (for the other ILT clients the pointers are used just to
6136      * free the memory during unload).
6137      */
6138     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6139     for (i = 0, allocated = 0; allocated < context_size; i++) {
6140         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6141                                   (context_size - allocated));
6142
6143         if (bxe_dma_alloc(sc, sc->context[i].size,
6144                           &sc->context[i].vcxt_dma,
6145                           "cdu context") != 0) {
6146             bxe_free_mem(sc);
6147             return (-1);
6148         }
6149
6150         sc->context[i].vcxt =
6151             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6152
6153         allocated += sc->context[i].size;
6154     }
6155
6156     bxe_alloc_ilt_lines_mem(sc);
6157
6158     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6159           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6160     {
6161         for (i = 0; i < 4; i++) {
6162             BLOGD(sc, DBG_LOAD,
6163                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6164                   i,
6165                   sc->ilt->clients[i].page_size,
6166                   sc->ilt->clients[i].start,
6167                   sc->ilt->clients[i].end,
6168                   sc->ilt->clients[i].client_num,
6169                   sc->ilt->clients[i].flags);
6170         }
6171     }
6172     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6173         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6174         bxe_free_mem(sc);
6175         return (-1);
6176     }
6177
6178     return (0);
6179 }
6180
6181 static void
6182 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6183 {
6184     struct bxe_softc *sc;
6185     int i;
6186
6187     sc = fp->sc;
6188
6189     if (fp->rx_mbuf_tag == NULL) {
6190         return;
6191     }
6192
6193     /* free all mbufs and unload all maps */
6194     for (i = 0; i < RX_BD_TOTAL; i++) {
6195         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6196             bus_dmamap_sync(fp->rx_mbuf_tag,
6197                             fp->rx_mbuf_chain[i].m_map,
6198                             BUS_DMASYNC_POSTREAD);
6199             bus_dmamap_unload(fp->rx_mbuf_tag,
6200                               fp->rx_mbuf_chain[i].m_map);
6201         }
6202
6203         if (fp->rx_mbuf_chain[i].m != NULL) {
6204             m_freem(fp->rx_mbuf_chain[i].m);
6205             fp->rx_mbuf_chain[i].m = NULL;
6206             fp->eth_q_stats.mbuf_alloc_rx--;
6207         }
6208     }
6209 }
6210
6211 static void
6212 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6213 {
6214     struct bxe_softc *sc;
6215     int i, max_agg_queues;
6216
6217     sc = fp->sc;
6218
6219     if (fp->rx_mbuf_tag == NULL) {
6220         return;
6221     }
6222
6223     max_agg_queues = MAX_AGG_QS(sc);
6224
6225     /* release all mbufs and unload all DMA maps in the TPA pool */
6226     for (i = 0; i < max_agg_queues; i++) {
6227         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6228             bus_dmamap_sync(fp->rx_mbuf_tag,
6229                             fp->rx_tpa_info[i].bd.m_map,
6230                             BUS_DMASYNC_POSTREAD);
6231             bus_dmamap_unload(fp->rx_mbuf_tag,
6232                               fp->rx_tpa_info[i].bd.m_map);
6233         }
6234
6235         if (fp->rx_tpa_info[i].bd.m != NULL) {
6236             m_freem(fp->rx_tpa_info[i].bd.m);
6237             fp->rx_tpa_info[i].bd.m = NULL;
6238             fp->eth_q_stats.mbuf_alloc_tpa--;
6239         }
6240     }
6241 }
6242
6243 static void
6244 bxe_free_sge_chain(struct bxe_fastpath *fp)
6245 {
6246     struct bxe_softc *sc;
6247     int i;
6248
6249     sc = fp->sc;
6250
6251     if (fp->rx_sge_mbuf_tag == NULL) {
6252         return;
6253     }
6254
6255     /* rree all mbufs and unload all maps */
6256     for (i = 0; i < RX_SGE_TOTAL; i++) {
6257         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6258             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6259                             fp->rx_sge_mbuf_chain[i].m_map,
6260                             BUS_DMASYNC_POSTREAD);
6261             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6262                               fp->rx_sge_mbuf_chain[i].m_map);
6263         }
6264
6265         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6266             m_freem(fp->rx_sge_mbuf_chain[i].m);
6267             fp->rx_sge_mbuf_chain[i].m = NULL;
6268             fp->eth_q_stats.mbuf_alloc_sge--;
6269         }
6270     }
6271 }
6272
6273 static void
6274 bxe_free_fp_buffers(struct bxe_softc *sc)
6275 {
6276     struct bxe_fastpath *fp;
6277     int i;
6278
6279     for (i = 0; i < sc->num_queues; i++) {
6280         fp = &sc->fp[i];
6281
6282 #if __FreeBSD_version >= 800000
6283         if (fp->tx_br != NULL) {
6284             /* just in case bxe_mq_flush() wasn't called */
6285             if (mtx_initialized(&fp->tx_mtx)) {
6286                 struct mbuf *m;
6287
6288                 BXE_FP_TX_LOCK(fp);
6289                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6290                     m_freem(m);
6291                 BXE_FP_TX_UNLOCK(fp);
6292             }
6293         }
6294 #endif
6295
6296         /* free all RX buffers */
6297         bxe_free_rx_bd_chain(fp);
6298         bxe_free_tpa_pool(fp);
6299         bxe_free_sge_chain(fp);
6300
6301         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6302             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6303                   fp->eth_q_stats.mbuf_alloc_rx);
6304         }
6305
6306         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6307             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6308                   fp->eth_q_stats.mbuf_alloc_sge);
6309         }
6310
6311         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6312             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6313                   fp->eth_q_stats.mbuf_alloc_tpa);
6314         }
6315
6316         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6317             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6318                   fp->eth_q_stats.mbuf_alloc_tx);
6319         }
6320
6321         /* XXX verify all mbufs were reclaimed */
6322     }
6323 }
6324
6325 static int
6326 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6327                      uint16_t            prev_index,
6328                      uint16_t            index)
6329 {
6330     struct bxe_sw_rx_bd *rx_buf;
6331     struct eth_rx_bd *rx_bd;
6332     bus_dma_segment_t segs[1];
6333     bus_dmamap_t map;
6334     struct mbuf *m;
6335     int nsegs, rc;
6336
6337     rc = 0;
6338
6339     /* allocate the new RX BD mbuf */
6340     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6341     if (__predict_false(m == NULL)) {
6342         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6343         return (ENOBUFS);
6344     }
6345
6346     fp->eth_q_stats.mbuf_alloc_rx++;
6347
6348     /* initialize the mbuf buffer length */
6349     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6350
6351     /* map the mbuf into non-paged pool */
6352     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6353                                  fp->rx_mbuf_spare_map,
6354                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6355     if (__predict_false(rc != 0)) {
6356         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6357         m_freem(m);
6358         fp->eth_q_stats.mbuf_alloc_rx--;
6359         return (rc);
6360     }
6361
6362     /* all mbufs must map to a single segment */
6363     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6364
6365     /* release any existing RX BD mbuf mappings */
6366
6367     if (prev_index != index) {
6368         rx_buf = &fp->rx_mbuf_chain[prev_index];
6369
6370         if (rx_buf->m_map != NULL) {
6371             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6372                             BUS_DMASYNC_POSTREAD);
6373             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6374         }
6375
6376         /*
6377          * We only get here from bxe_rxeof() when the maximum number
6378          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6379          * holds the mbuf in the prev_index so it's OK to NULL it out
6380          * here without concern of a memory leak.
6381          */
6382         fp->rx_mbuf_chain[prev_index].m = NULL;
6383     }
6384
6385     rx_buf = &fp->rx_mbuf_chain[index];
6386
6387     if (rx_buf->m_map != NULL) {
6388         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6389                         BUS_DMASYNC_POSTREAD);
6390         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6391     }
6392
6393     /* save the mbuf and mapping info for a future packet */
6394     map = (prev_index != index) ?
6395               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6396     rx_buf->m_map = fp->rx_mbuf_spare_map;
6397     fp->rx_mbuf_spare_map = map;
6398     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6399                     BUS_DMASYNC_PREREAD);
6400     rx_buf->m = m;
6401
6402     rx_bd = &fp->rx_chain[index];
6403     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6404     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6405
6406     return (rc);
6407 }
6408
6409 static int
6410 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6411                       int                 queue)
6412 {
6413     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6414     bus_dma_segment_t segs[1];
6415     bus_dmamap_t map;
6416     struct mbuf *m;
6417     int nsegs;
6418     int rc = 0;
6419
6420     /* allocate the new TPA mbuf */
6421     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6422     if (__predict_false(m == NULL)) {
6423         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6424         return (ENOBUFS);
6425     }
6426
6427     fp->eth_q_stats.mbuf_alloc_tpa++;
6428
6429     /* initialize the mbuf buffer length */
6430     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6431
6432     /* map the mbuf into non-paged pool */
6433     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6434                                  fp->rx_tpa_info_mbuf_spare_map,
6435                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6436     if (__predict_false(rc != 0)) {
6437         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6438         m_free(m);
6439         fp->eth_q_stats.mbuf_alloc_tpa--;
6440         return (rc);
6441     }
6442
6443     /* all mbufs must map to a single segment */
6444     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6445
6446     /* release any existing TPA mbuf mapping */
6447     if (tpa_info->bd.m_map != NULL) {
6448         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6449                         BUS_DMASYNC_POSTREAD);
6450         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6451     }
6452
6453     /* save the mbuf and mapping info for the TPA mbuf */
6454     map = tpa_info->bd.m_map;
6455     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6456     fp->rx_tpa_info_mbuf_spare_map = map;
6457     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6458                     BUS_DMASYNC_PREREAD);
6459     tpa_info->bd.m = m;
6460     tpa_info->seg = segs[0];
6461
6462     return (rc);
6463 }
6464
6465 /*
6466  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6467  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6468  * chain.
6469  */
6470 static int
6471 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6472                       uint16_t            index)
6473 {
6474     struct bxe_sw_rx_bd *sge_buf;
6475     struct eth_rx_sge *sge;
6476     bus_dma_segment_t segs[1];
6477     bus_dmamap_t map;
6478     struct mbuf *m;
6479     int nsegs;
6480     int rc = 0;
6481
6482     /* allocate a new SGE mbuf */
6483     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6484     if (__predict_false(m == NULL)) {
6485         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6486         return (ENOMEM);
6487     }
6488
6489     fp->eth_q_stats.mbuf_alloc_sge++;
6490
6491     /* initialize the mbuf buffer length */
6492     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6493
6494     /* map the SGE mbuf into non-paged pool */
6495     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6496                                  fp->rx_sge_mbuf_spare_map,
6497                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6498     if (__predict_false(rc != 0)) {
6499         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6500         m_freem(m);
6501         fp->eth_q_stats.mbuf_alloc_sge--;
6502         return (rc);
6503     }
6504
6505     /* all mbufs must map to a single segment */
6506     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6507
6508     sge_buf = &fp->rx_sge_mbuf_chain[index];
6509
6510     /* release any existing SGE mbuf mapping */
6511     if (sge_buf->m_map != NULL) {
6512         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6513                         BUS_DMASYNC_POSTREAD);
6514         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6515     }
6516
6517     /* save the mbuf and mapping info for a future packet */
6518     map = sge_buf->m_map;
6519     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6520     fp->rx_sge_mbuf_spare_map = map;
6521     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6522                     BUS_DMASYNC_PREREAD);
6523     sge_buf->m = m;
6524
6525     sge = &fp->rx_sge_chain[index];
6526     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6527     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6528
6529     return (rc);
6530 }
6531
6532 static __noinline int
6533 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6534 {
6535     struct bxe_fastpath *fp;
6536     int i, j, rc = 0;
6537     int ring_prod, cqe_ring_prod;
6538     int max_agg_queues;
6539
6540     for (i = 0; i < sc->num_queues; i++) {
6541         fp = &sc->fp[i];
6542
6543         ring_prod = cqe_ring_prod = 0;
6544         fp->rx_bd_cons = 0;
6545         fp->rx_cq_cons = 0;
6546
6547         /* allocate buffers for the RX BDs in RX BD chain */
6548         for (j = 0; j < sc->max_rx_bufs; j++) {
6549             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6550             if (rc != 0) {
6551                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6552                       i, rc);
6553                 goto bxe_alloc_fp_buffers_error;
6554             }
6555
6556             ring_prod     = RX_BD_NEXT(ring_prod);
6557             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6558         }
6559
6560         fp->rx_bd_prod = ring_prod;
6561         fp->rx_cq_prod = cqe_ring_prod;
6562         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6563
6564         max_agg_queues = MAX_AGG_QS(sc);
6565
6566         fp->tpa_enable = TRUE;
6567
6568         /* fill the TPA pool */
6569         for (j = 0; j < max_agg_queues; j++) {
6570             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6571             if (rc != 0) {
6572                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6573                           i, j);
6574                 fp->tpa_enable = FALSE;
6575                 goto bxe_alloc_fp_buffers_error;
6576             }
6577
6578             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6579         }
6580
6581         if (fp->tpa_enable) {
6582             /* fill the RX SGE chain */
6583             ring_prod = 0;
6584             for (j = 0; j < RX_SGE_USABLE; j++) {
6585                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6586                 if (rc != 0) {
6587                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6588                               i, ring_prod);
6589                     fp->tpa_enable = FALSE;
6590                     ring_prod = 0;
6591                     goto bxe_alloc_fp_buffers_error;
6592                 }
6593
6594                 ring_prod = RX_SGE_NEXT(ring_prod);
6595             }
6596
6597             fp->rx_sge_prod = ring_prod;
6598         }
6599     }
6600
6601     return (0);
6602
6603 bxe_alloc_fp_buffers_error:
6604
6605     /* unwind what was already allocated */
6606     bxe_free_rx_bd_chain(fp);
6607     bxe_free_tpa_pool(fp);
6608     bxe_free_sge_chain(fp);
6609
6610     return (ENOBUFS);
6611 }
6612
6613 static void
6614 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6615 {
6616     bxe_dma_free(sc, &sc->fw_stats_dma);
6617
6618     sc->fw_stats_num = 0;
6619
6620     sc->fw_stats_req_size = 0;
6621     sc->fw_stats_req = NULL;
6622     sc->fw_stats_req_mapping = 0;
6623
6624     sc->fw_stats_data_size = 0;
6625     sc->fw_stats_data = NULL;
6626     sc->fw_stats_data_mapping = 0;
6627 }
6628
6629 static int
6630 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6631 {
6632     uint8_t num_queue_stats;
6633     int num_groups;
6634
6635     /* number of queues for statistics is number of eth queues */
6636     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6637
6638     /*
6639      * Total number of FW statistics requests =
6640      *   1 for port stats + 1 for PF stats + num of queues
6641      */
6642     sc->fw_stats_num = (2 + num_queue_stats);
6643
6644     /*
6645      * Request is built from stats_query_header and an array of
6646      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6647      * rules. The real number or requests is configured in the
6648      * stats_query_header.
6649      */
6650     num_groups =
6651         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6652          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6653
6654     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6655           sc->fw_stats_num, num_groups);
6656
6657     sc->fw_stats_req_size =
6658         (sizeof(struct stats_query_header) +
6659          (num_groups * sizeof(struct stats_query_cmd_group)));
6660
6661     /*
6662      * Data for statistics requests + stats_counter.
6663      * stats_counter holds per-STORM counters that are incremented when
6664      * STORM has finished with the current request. Memory for FCoE
6665      * offloaded statistics are counted anyway, even if they will not be sent.
6666      * VF stats are not accounted for here as the data of VF stats is stored
6667      * in memory allocated by the VF, not here.
6668      */
6669     sc->fw_stats_data_size =
6670         (sizeof(struct stats_counter) +
6671          sizeof(struct per_port_stats) +
6672          sizeof(struct per_pf_stats) +
6673          /* sizeof(struct fcoe_statistics_params) + */
6674          (sizeof(struct per_queue_stats) * num_queue_stats));
6675
6676     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6677                       &sc->fw_stats_dma, "fw stats") != 0) {
6678         bxe_free_fw_stats_mem(sc);
6679         return (-1);
6680     }
6681
6682     /* set up the shortcuts */
6683
6684     sc->fw_stats_req =
6685         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6686     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6687
6688     sc->fw_stats_data =
6689         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6690                                      sc->fw_stats_req_size);
6691     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6692                                  sc->fw_stats_req_size);
6693
6694     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6695           (uintmax_t)sc->fw_stats_req_mapping);
6696
6697     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6698           (uintmax_t)sc->fw_stats_data_mapping);
6699
6700     return (0);
6701 }
6702
6703 /*
6704  * Bits map:
6705  * 0-7  - Engine0 load counter.
6706  * 8-15 - Engine1 load counter.
6707  * 16   - Engine0 RESET_IN_PROGRESS bit.
6708  * 17   - Engine1 RESET_IN_PROGRESS bit.
6709  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6710  *        function on the engine
6711  * 19   - Engine1 ONE_IS_LOADED.
6712  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6713  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6714  *        for just the one belonging to its engine).
6715  */
6716 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6717 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6718 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6719 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6720 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6721 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6722 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6723 #define BXE_GLOBAL_RESET_BIT      0x00040000
6724
6725 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6726 static void
6727 bxe_set_reset_global(struct bxe_softc *sc)
6728 {
6729     uint32_t val;
6730     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6731     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6732     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6733     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6734 }
6735
6736 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6737 static void
6738 bxe_clear_reset_global(struct bxe_softc *sc)
6739 {
6740     uint32_t val;
6741     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6742     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6743     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6744     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6745 }
6746
6747 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6748 static uint8_t
6749 bxe_reset_is_global(struct bxe_softc *sc)
6750 {
6751     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6752     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6753     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6754 }
6755
6756 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6757 static void
6758 bxe_set_reset_done(struct bxe_softc *sc)
6759 {
6760     uint32_t val;
6761     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6762                                  BXE_PATH0_RST_IN_PROG_BIT;
6763
6764     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6765
6766     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6767     /* Clear the bit */
6768     val &= ~bit;
6769     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6770
6771     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6772 }
6773
6774 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6775 static void
6776 bxe_set_reset_in_progress(struct bxe_softc *sc)
6777 {
6778     uint32_t val;
6779     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6780                                  BXE_PATH0_RST_IN_PROG_BIT;
6781
6782     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6783
6784     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6785     /* Set the bit */
6786     val |= bit;
6787     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6788
6789     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6790 }
6791
6792 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6793 static uint8_t
6794 bxe_reset_is_done(struct bxe_softc *sc,
6795                   int              engine)
6796 {
6797     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6798     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6799                             BXE_PATH0_RST_IN_PROG_BIT;
6800
6801     /* return false if bit is set */
6802     return (val & bit) ? FALSE : TRUE;
6803 }
6804
6805 /* get the load status for an engine, should be run under rtnl lock */
6806 static uint8_t
6807 bxe_get_load_status(struct bxe_softc *sc,
6808                     int              engine)
6809 {
6810     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6811                              BXE_PATH0_LOAD_CNT_MASK;
6812     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6813                               BXE_PATH0_LOAD_CNT_SHIFT;
6814     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6815
6816     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6817
6818     val = ((val & mask) >> shift);
6819
6820     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6821
6822     return (val != 0);
6823 }
6824
6825 /* set pf load mark */
6826 /* XXX needs to be under rtnl lock */
6827 static void
6828 bxe_set_pf_load(struct bxe_softc *sc)
6829 {
6830     uint32_t val;
6831     uint32_t val1;
6832     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6833                                   BXE_PATH0_LOAD_CNT_MASK;
6834     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6835                                    BXE_PATH0_LOAD_CNT_SHIFT;
6836
6837     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6838
6839     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6840     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6841
6842     /* get the current counter value */
6843     val1 = ((val & mask) >> shift);
6844
6845     /* set bit of this PF */
6846     val1 |= (1 << SC_ABS_FUNC(sc));
6847
6848     /* clear the old value */
6849     val &= ~mask;
6850
6851     /* set the new one */
6852     val |= ((val1 << shift) & mask);
6853
6854     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6855
6856     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6857 }
6858
6859 /* clear pf load mark */
6860 /* XXX needs to be under rtnl lock */
6861 static uint8_t
6862 bxe_clear_pf_load(struct bxe_softc *sc)
6863 {
6864     uint32_t val1, val;
6865     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6866                                   BXE_PATH0_LOAD_CNT_MASK;
6867     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6868                                    BXE_PATH0_LOAD_CNT_SHIFT;
6869
6870     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6871     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6872     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6873
6874     /* get the current counter value */
6875     val1 = (val & mask) >> shift;
6876
6877     /* clear bit of that PF */
6878     val1 &= ~(1 << SC_ABS_FUNC(sc));
6879
6880     /* clear the old value */
6881     val &= ~mask;
6882
6883     /* set the new one */
6884     val |= ((val1 << shift) & mask);
6885
6886     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6887     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6888     return (val1 != 0);
6889 }
6890
6891 /* send load requrest to mcp and analyze response */
6892 static int
6893 bxe_nic_load_request(struct bxe_softc *sc,
6894                      uint32_t         *load_code)
6895 {
6896     /* init fw_seq */
6897     sc->fw_seq =
6898         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6899          DRV_MSG_SEQ_NUMBER_MASK);
6900
6901     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6902
6903     /* get the current FW pulse sequence */
6904     sc->fw_drv_pulse_wr_seq =
6905         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6906          DRV_PULSE_SEQ_MASK);
6907
6908     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6909           sc->fw_drv_pulse_wr_seq);
6910
6911     /* load request */
6912     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6913                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6914
6915     /* if the MCP fails to respond we must abort */
6916     if (!(*load_code)) {
6917         BLOGE(sc, "MCP response failure!\n");
6918         return (-1);
6919     }
6920
6921     /* if MCP refused then must abort */
6922     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6923         BLOGE(sc, "MCP refused load request\n");
6924         return (-1);
6925     }
6926
6927     return (0);
6928 }
6929
6930 /*
6931  * Check whether another PF has already loaded FW to chip. In virtualized
6932  * environments a pf from anoth VM may have already initialized the device
6933  * including loading FW.
6934  */
6935 static int
6936 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6937                          uint32_t         load_code)
6938 {
6939     uint32_t my_fw, loaded_fw;
6940
6941     /* is another pf loaded on this engine? */
6942     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6943         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6944         /* build my FW version dword */
6945         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6946                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6947                  (BCM_5710_FW_REVISION_VERSION << 16) +
6948                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6949
6950         /* read loaded FW from chip */
6951         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6952         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6953               loaded_fw, my_fw);
6954
6955         /* abort nic load if version mismatch */
6956         if (my_fw != loaded_fw) {
6957             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6958                   loaded_fw, my_fw);
6959             return (-1);
6960         }
6961     }
6962
6963     return (0);
6964 }
6965
6966 /* mark PMF if applicable */
6967 static void
6968 bxe_nic_load_pmf(struct bxe_softc *sc,
6969                  uint32_t         load_code)
6970 {
6971     uint32_t ncsi_oem_data_addr;
6972
6973     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6974         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6975         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6976         /*
6977          * Barrier here for ordering between the writing to sc->port.pmf here
6978          * and reading it from the periodic task.
6979          */
6980         sc->port.pmf = 1;
6981         mb();
6982     } else {
6983         sc->port.pmf = 0;
6984     }
6985
6986     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6987
6988     /* XXX needed? */
6989     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6990         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6991             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6992             if (ncsi_oem_data_addr) {
6993                 REG_WR(sc,
6994                        (ncsi_oem_data_addr +
6995                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6996                        0);
6997             }
6998         }
6999     }
7000 }
7001
7002 static void
7003 bxe_read_mf_cfg(struct bxe_softc *sc)
7004 {
7005     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
7006     int abs_func;
7007     int vn;
7008
7009     if (BXE_NOMCP(sc)) {
7010         return; /* what should be the default bvalue in this case */
7011     }
7012
7013     /*
7014      * The formula for computing the absolute function number is...
7015      * For 2 port configuration (4 functions per port):
7016      *   abs_func = 2 * vn + SC_PORT + SC_PATH
7017      * For 4 port configuration (2 functions per port):
7018      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
7019      */
7020     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
7021         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
7022         if (abs_func >= E1H_FUNC_MAX) {
7023             break;
7024         }
7025         sc->devinfo.mf_info.mf_config[vn] =
7026             MFCFG_RD(sc, func_mf_config[abs_func].config);
7027     }
7028
7029     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
7030         FUNC_MF_CFG_FUNC_DISABLED) {
7031         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
7032         sc->flags |= BXE_MF_FUNC_DIS;
7033     } else {
7034         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
7035         sc->flags &= ~BXE_MF_FUNC_DIS;
7036     }
7037 }
7038
7039 /* acquire split MCP access lock register */
7040 static int bxe_acquire_alr(struct bxe_softc *sc)
7041 {
7042     uint32_t j, val;
7043
7044     for (j = 0; j < 1000; j++) {
7045         val = (1UL << 31);
7046         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
7047         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
7048         if (val & (1L << 31))
7049             break;
7050
7051         DELAY(5000);
7052     }
7053
7054     if (!(val & (1L << 31))) {
7055         BLOGE(sc, "Cannot acquire MCP access lock register\n");
7056         return (-1);
7057     }
7058
7059     return (0);
7060 }
7061
7062 /* release split MCP access lock register */
7063 static void bxe_release_alr(struct bxe_softc *sc)
7064 {
7065     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
7066 }
7067
7068 static void
7069 bxe_fan_failure(struct bxe_softc *sc)
7070 {
7071     int port = SC_PORT(sc);
7072     uint32_t ext_phy_config;
7073
7074     /* mark the failure */
7075     ext_phy_config =
7076         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7077
7078     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7079     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7080     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7081              ext_phy_config);
7082
7083     /* log the failure */
7084     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7085               "the card to prevent permanent damage. "
7086               "Please contact OEM Support for assistance\n");
7087
7088     /* XXX */
7089 #if 1
7090     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7091 #else
7092     /*
7093      * Schedule device reset (unload)
7094      * This is due to some boards consuming sufficient power when driver is
7095      * up to overheat if fan fails.
7096      */
7097     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7098     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7099 #endif
7100 }
7101
7102 /* this function is called upon a link interrupt */
7103 static void
7104 bxe_link_attn(struct bxe_softc *sc)
7105 {
7106     uint32_t pause_enabled = 0;
7107     struct host_port_stats *pstats;
7108     int cmng_fns;
7109
7110     /* Make sure that we are synced with the current statistics */
7111     bxe_stats_handle(sc, STATS_EVENT_STOP);
7112
7113     elink_link_update(&sc->link_params, &sc->link_vars);
7114
7115     if (sc->link_vars.link_up) {
7116
7117         /* dropless flow control */
7118         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7119             pause_enabled = 0;
7120
7121             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7122                 pause_enabled = 1;
7123             }
7124
7125             REG_WR(sc,
7126                    (BAR_USTRORM_INTMEM +
7127                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7128                    pause_enabled);
7129         }
7130
7131         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7132             pstats = BXE_SP(sc, port_stats);
7133             /* reset old mac stats */
7134             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7135         }
7136
7137         if (sc->state == BXE_STATE_OPEN) {
7138             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7139         }
7140     }
7141
7142     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7143         cmng_fns = bxe_get_cmng_fns_mode(sc);
7144
7145         if (cmng_fns != CMNG_FNS_NONE) {
7146             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7147             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7148         } else {
7149             /* rate shaping and fairness are disabled */
7150             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7151         }
7152     }
7153
7154     bxe_link_report_locked(sc);
7155
7156     if (IS_MF(sc)) {
7157         ; // XXX bxe_link_sync_notify(sc);
7158     }
7159 }
7160
7161 static void
7162 bxe_attn_int_asserted(struct bxe_softc *sc,
7163                       uint32_t         asserted)
7164 {
7165     int port = SC_PORT(sc);
7166     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7167                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7168     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7169                                         NIG_REG_MASK_INTERRUPT_PORT0;
7170     uint32_t aeu_mask;
7171     uint32_t nig_mask = 0;
7172     uint32_t reg_addr;
7173     uint32_t igu_acked;
7174     uint32_t cnt;
7175
7176     if (sc->attn_state & asserted) {
7177         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7178     }
7179
7180     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7181
7182     aeu_mask = REG_RD(sc, aeu_addr);
7183
7184     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7185           aeu_mask, asserted);
7186
7187     aeu_mask &= ~(asserted & 0x3ff);
7188
7189     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7190
7191     REG_WR(sc, aeu_addr, aeu_mask);
7192
7193     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7194
7195     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7196     sc->attn_state |= asserted;
7197     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7198
7199     if (asserted & ATTN_HARD_WIRED_MASK) {
7200         if (asserted & ATTN_NIG_FOR_FUNC) {
7201
7202             bxe_acquire_phy_lock(sc);
7203             /* save nig interrupt mask */
7204             nig_mask = REG_RD(sc, nig_int_mask_addr);
7205
7206             /* If nig_mask is not set, no need to call the update function */
7207             if (nig_mask) {
7208                 REG_WR(sc, nig_int_mask_addr, 0);
7209
7210                 bxe_link_attn(sc);
7211             }
7212
7213             /* handle unicore attn? */
7214         }
7215
7216         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7217             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7218         }
7219
7220         if (asserted & GPIO_2_FUNC) {
7221             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7222         }
7223
7224         if (asserted & GPIO_3_FUNC) {
7225             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7226         }
7227
7228         if (asserted & GPIO_4_FUNC) {
7229             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7230         }
7231
7232         if (port == 0) {
7233             if (asserted & ATTN_GENERAL_ATTN_1) {
7234                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7235                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7236             }
7237             if (asserted & ATTN_GENERAL_ATTN_2) {
7238                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7239                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7240             }
7241             if (asserted & ATTN_GENERAL_ATTN_3) {
7242                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7243                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7244             }
7245         } else {
7246             if (asserted & ATTN_GENERAL_ATTN_4) {
7247                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7248                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7249             }
7250             if (asserted & ATTN_GENERAL_ATTN_5) {
7251                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7252                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7253             }
7254             if (asserted & ATTN_GENERAL_ATTN_6) {
7255                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7256                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7257             }
7258         }
7259     } /* hardwired */
7260
7261     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7262         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7263     } else {
7264         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7265     }
7266
7267     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7268           asserted,
7269           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7270     REG_WR(sc, reg_addr, asserted);
7271
7272     /* now set back the mask */
7273     if (asserted & ATTN_NIG_FOR_FUNC) {
7274         /*
7275          * Verify that IGU ack through BAR was written before restoring
7276          * NIG mask. This loop should exit after 2-3 iterations max.
7277          */
7278         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7279             cnt = 0;
7280
7281             do {
7282                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7283             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7284                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7285
7286             if (!igu_acked) {
7287                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7288             }
7289
7290             mb();
7291         }
7292
7293         REG_WR(sc, nig_int_mask_addr, nig_mask);
7294
7295         bxe_release_phy_lock(sc);
7296     }
7297 }
7298
7299 static void
7300 bxe_print_next_block(struct bxe_softc *sc,
7301                      int              idx,
7302                      const char       *blk)
7303 {
7304     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7305 }
7306
7307 static int
7308 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7309                               uint32_t         sig,
7310                               int              par_num,
7311                               uint8_t          print)
7312 {
7313     uint32_t cur_bit = 0;
7314     int i = 0;
7315
7316     for (i = 0; sig; i++) {
7317         cur_bit = ((uint32_t)0x1 << i);
7318         if (sig & cur_bit) {
7319             switch (cur_bit) {
7320             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7321                 if (print)
7322                     bxe_print_next_block(sc, par_num++, "BRB");
7323                 break;
7324             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7325                 if (print)
7326                     bxe_print_next_block(sc, par_num++, "PARSER");
7327                 break;
7328             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7329                 if (print)
7330                     bxe_print_next_block(sc, par_num++, "TSDM");
7331                 break;
7332             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7333                 if (print)
7334                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7335                 break;
7336             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7337                 if (print)
7338                     bxe_print_next_block(sc, par_num++, "TCM");
7339                 break;
7340             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7341                 if (print)
7342                     bxe_print_next_block(sc, par_num++, "TSEMI");
7343                 break;
7344             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7345                 if (print)
7346                     bxe_print_next_block(sc, par_num++, "XPB");
7347                 break;
7348             }
7349
7350             /* Clear the bit */
7351             sig &= ~cur_bit;
7352         }
7353     }
7354
7355     return (par_num);
7356 }
7357
7358 static int
7359 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7360                               uint32_t         sig,
7361                               int              par_num,
7362                               uint8_t          *global,
7363                               uint8_t          print)
7364 {
7365     int i = 0;
7366     uint32_t cur_bit = 0;
7367     for (i = 0; sig; i++) {
7368         cur_bit = ((uint32_t)0x1 << i);
7369         if (sig & cur_bit) {
7370             switch (cur_bit) {
7371             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7372                 if (print)
7373                     bxe_print_next_block(sc, par_num++, "PBF");
7374                 break;
7375             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7376                 if (print)
7377                     bxe_print_next_block(sc, par_num++, "QM");
7378                 break;
7379             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7380                 if (print)
7381                     bxe_print_next_block(sc, par_num++, "TM");
7382                 break;
7383             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7384                 if (print)
7385                     bxe_print_next_block(sc, par_num++, "XSDM");
7386                 break;
7387             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7388                 if (print)
7389                     bxe_print_next_block(sc, par_num++, "XCM");
7390                 break;
7391             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7392                 if (print)
7393                     bxe_print_next_block(sc, par_num++, "XSEMI");
7394                 break;
7395             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7396                 if (print)
7397                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7398                 break;
7399             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7400                 if (print)
7401                     bxe_print_next_block(sc, par_num++, "NIG");
7402                 break;
7403             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7404                 if (print)
7405                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7406                 *global = TRUE;
7407                 break;
7408             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7409                 if (print)
7410                     bxe_print_next_block(sc, par_num++, "DEBUG");
7411                 break;
7412             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7413                 if (print)
7414                     bxe_print_next_block(sc, par_num++, "USDM");
7415                 break;
7416             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7417                 if (print)
7418                     bxe_print_next_block(sc, par_num++, "UCM");
7419                 break;
7420             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7421                 if (print)
7422                     bxe_print_next_block(sc, par_num++, "USEMI");
7423                 break;
7424             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7425                 if (print)
7426                     bxe_print_next_block(sc, par_num++, "UPB");
7427                 break;
7428             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7429                 if (print)
7430                     bxe_print_next_block(sc, par_num++, "CSDM");
7431                 break;
7432             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7433                 if (print)
7434                     bxe_print_next_block(sc, par_num++, "CCM");
7435                 break;
7436             }
7437
7438             /* Clear the bit */
7439             sig &= ~cur_bit;
7440         }
7441     }
7442
7443     return (par_num);
7444 }
7445
7446 static int
7447 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7448                               uint32_t         sig,
7449                               int              par_num,
7450                               uint8_t          print)
7451 {
7452     uint32_t cur_bit = 0;
7453     int i = 0;
7454
7455     for (i = 0; sig; i++) {
7456         cur_bit = ((uint32_t)0x1 << i);
7457         if (sig & cur_bit) {
7458             switch (cur_bit) {
7459             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7460                 if (print)
7461                     bxe_print_next_block(sc, par_num++, "CSEMI");
7462                 break;
7463             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7464                 if (print)
7465                     bxe_print_next_block(sc, par_num++, "PXP");
7466                 break;
7467             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7468                 if (print)
7469                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7470                 break;
7471             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7472                 if (print)
7473                     bxe_print_next_block(sc, par_num++, "CFC");
7474                 break;
7475             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7476                 if (print)
7477                     bxe_print_next_block(sc, par_num++, "CDU");
7478                 break;
7479             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7480                 if (print)
7481                     bxe_print_next_block(sc, par_num++, "DMAE");
7482                 break;
7483             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7484                 if (print)
7485                     bxe_print_next_block(sc, par_num++, "IGU");
7486                 break;
7487             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7488                 if (print)
7489                     bxe_print_next_block(sc, par_num++, "MISC");
7490                 break;
7491             }
7492
7493             /* Clear the bit */
7494             sig &= ~cur_bit;
7495         }
7496     }
7497
7498     return (par_num);
7499 }
7500
7501 static int
7502 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7503                               uint32_t         sig,
7504                               int              par_num,
7505                               uint8_t          *global,
7506                               uint8_t          print)
7507 {
7508     uint32_t cur_bit = 0;
7509     int i = 0;
7510
7511     for (i = 0; sig; i++) {
7512         cur_bit = ((uint32_t)0x1 << i);
7513         if (sig & cur_bit) {
7514             switch (cur_bit) {
7515             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7516                 if (print)
7517                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7518                 *global = TRUE;
7519                 break;
7520             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7521                 if (print)
7522                     bxe_print_next_block(sc, par_num++,
7523                               "MCP UMP RX");
7524                 *global = TRUE;
7525                 break;
7526             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7527                 if (print)
7528                     bxe_print_next_block(sc, par_num++,
7529                               "MCP UMP TX");
7530                 *global = TRUE;
7531                 break;
7532             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7533                 if (print)
7534                     bxe_print_next_block(sc, par_num++,
7535                               "MCP SCPAD");
7536                 *global = TRUE;
7537                 break;
7538             }
7539
7540             /* Clear the bit */
7541             sig &= ~cur_bit;
7542         }
7543     }
7544
7545     return (par_num);
7546 }
7547
7548 static int
7549 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7550                               uint32_t         sig,
7551                               int              par_num,
7552                               uint8_t          print)
7553 {
7554     uint32_t cur_bit = 0;
7555     int i = 0;
7556
7557     for (i = 0; sig; i++) {
7558         cur_bit = ((uint32_t)0x1 << i);
7559         if (sig & cur_bit) {
7560             switch (cur_bit) {
7561             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7562                 if (print)
7563                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7564                 break;
7565             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7566                 if (print)
7567                     bxe_print_next_block(sc, par_num++, "ATC");
7568                 break;
7569             }
7570
7571             /* Clear the bit */
7572             sig &= ~cur_bit;
7573         }
7574     }
7575
7576     return (par_num);
7577 }
7578
7579 static uint8_t
7580 bxe_parity_attn(struct bxe_softc *sc,
7581                 uint8_t          *global,
7582                 uint8_t          print,
7583                 uint32_t         *sig)
7584 {
7585     int par_num = 0;
7586
7587     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7588         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7589         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7590         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7591         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7592         BLOGE(sc, "Parity error: HW block parity attention:\n"
7593                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7594               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7595               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7596               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7597               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7598               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7599
7600         if (print)
7601             BLOGI(sc, "Parity errors detected in blocks: ");
7602
7603         par_num =
7604             bxe_check_blocks_with_parity0(sc, sig[0] &
7605                                           HW_PRTY_ASSERT_SET_0,
7606                                           par_num, print);
7607         par_num =
7608             bxe_check_blocks_with_parity1(sc, sig[1] &
7609                                           HW_PRTY_ASSERT_SET_1,
7610                                           par_num, global, print);
7611         par_num =
7612             bxe_check_blocks_with_parity2(sc, sig[2] &
7613                                           HW_PRTY_ASSERT_SET_2,
7614                                           par_num, print);
7615         par_num =
7616             bxe_check_blocks_with_parity3(sc, sig[3] &
7617                                           HW_PRTY_ASSERT_SET_3,
7618                                           par_num, global, print);
7619         par_num =
7620             bxe_check_blocks_with_parity4(sc, sig[4] &
7621                                           HW_PRTY_ASSERT_SET_4,
7622                                           par_num, print);
7623
7624         if (print)
7625             BLOGI(sc, "\n");
7626
7627         return (TRUE);
7628     }
7629
7630     return (FALSE);
7631 }
7632
7633 static uint8_t
7634 bxe_chk_parity_attn(struct bxe_softc *sc,
7635                     uint8_t          *global,
7636                     uint8_t          print)
7637 {
7638     struct attn_route attn = { {0} };
7639     int port = SC_PORT(sc);
7640
7641     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7642     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7643     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7644     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7645
7646     /*
7647      * Since MCP attentions can't be disabled inside the block, we need to
7648      * read AEU registers to see whether they're currently disabled
7649      */
7650     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7651                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7652                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7653                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7654
7655
7656     if (!CHIP_IS_E1x(sc))
7657         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7658
7659     return (bxe_parity_attn(sc, global, print, attn.sig));
7660 }
7661
7662 static void
7663 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7664                          uint32_t         attn)
7665 {
7666     uint32_t val;
7667
7668     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7669         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7670         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7671         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7672             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7673         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7674             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7675         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7676             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7677         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7678             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7679         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7680             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7681         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7682             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7683         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7684             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7685         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7686             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7687         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7688             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7689     }
7690
7691     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7692         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7693         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7694         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7695             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7696         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7697             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7698         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7699             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7700         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7701             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7702         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7703             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7704         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7705             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7706     }
7707
7708     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7709                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7710         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7711               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7712                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7713     }
7714 }
7715
7716 static void
7717 bxe_e1h_disable(struct bxe_softc *sc)
7718 {
7719     int port = SC_PORT(sc);
7720
7721     bxe_tx_disable(sc);
7722
7723     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7724 }
7725
7726 static void
7727 bxe_e1h_enable(struct bxe_softc *sc)
7728 {
7729     int port = SC_PORT(sc);
7730
7731     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7732
7733     // XXX bxe_tx_enable(sc);
7734 }
7735
7736 /*
7737  * called due to MCP event (on pmf):
7738  *   reread new bandwidth configuration
7739  *   configure FW
7740  *   notify others function about the change
7741  */
7742 static void
7743 bxe_config_mf_bw(struct bxe_softc *sc)
7744 {
7745     if (sc->link_vars.link_up) {
7746         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7747         // XXX bxe_link_sync_notify(sc);
7748     }
7749
7750     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7751 }
7752
7753 static void
7754 bxe_set_mf_bw(struct bxe_softc *sc)
7755 {
7756     bxe_config_mf_bw(sc);
7757     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7758 }
7759
7760 static void
7761 bxe_handle_eee_event(struct bxe_softc *sc)
7762 {
7763     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7764     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7765 }
7766
7767 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7768
7769 static void
7770 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7771 {
7772     struct eth_stats_info *ether_stat =
7773         &sc->sp->drv_info_to_mcp.ether_stat;
7774
7775     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7776             ETH_STAT_INFO_VERSION_LEN);
7777
7778     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7779     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7780                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7781                                           ether_stat->mac_local + MAC_PAD,
7782                                           MAC_PAD, ETH_ALEN);
7783
7784     ether_stat->mtu_size = sc->mtu;
7785
7786     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7787     if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
7788         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7789     }
7790
7791     // XXX ether_stat->feature_flags |= ???;
7792
7793     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7794
7795     ether_stat->txq_size = sc->tx_ring_size;
7796     ether_stat->rxq_size = sc->rx_ring_size;
7797 }
7798
7799 static void
7800 bxe_handle_drv_info_req(struct bxe_softc *sc)
7801 {
7802     enum drv_info_opcode op_code;
7803     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7804
7805     /* if drv_info version supported by MFW doesn't match - send NACK */
7806     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7807         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7808         return;
7809     }
7810
7811     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7812                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7813
7814     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7815
7816     switch (op_code) {
7817     case ETH_STATS_OPCODE:
7818         bxe_drv_info_ether_stat(sc);
7819         break;
7820     case FCOE_STATS_OPCODE:
7821     case ISCSI_STATS_OPCODE:
7822     default:
7823         /* if op code isn't supported - send NACK */
7824         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7825         return;
7826     }
7827
7828     /*
7829      * If we got drv_info attn from MFW then these fields are defined in
7830      * shmem2 for sure
7831      */
7832     SHMEM2_WR(sc, drv_info_host_addr_lo,
7833               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7834     SHMEM2_WR(sc, drv_info_host_addr_hi,
7835               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7836
7837     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7838 }
7839
7840 static void
7841 bxe_dcc_event(struct bxe_softc *sc,
7842               uint32_t         dcc_event)
7843 {
7844     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7845
7846     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7847         /*
7848          * This is the only place besides the function initialization
7849          * where the sc->flags can change so it is done without any
7850          * locks
7851          */
7852         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7853             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7854             sc->flags |= BXE_MF_FUNC_DIS;
7855             bxe_e1h_disable(sc);
7856         } else {
7857             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7858             sc->flags &= ~BXE_MF_FUNC_DIS;
7859             bxe_e1h_enable(sc);
7860         }
7861         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7862     }
7863
7864     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7865         bxe_config_mf_bw(sc);
7866         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7867     }
7868
7869     /* Report results to MCP */
7870     if (dcc_event)
7871         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7872     else
7873         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7874 }
7875
7876 static void
7877 bxe_pmf_update(struct bxe_softc *sc)
7878 {
7879     int port = SC_PORT(sc);
7880     uint32_t val;
7881
7882     sc->port.pmf = 1;
7883     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7884
7885     /*
7886      * We need the mb() to ensure the ordering between the writing to
7887      * sc->port.pmf here and reading it from the bxe_periodic_task().
7888      */
7889     mb();
7890
7891     /* queue a periodic task */
7892     // XXX schedule task...
7893
7894     // XXX bxe_dcbx_pmf_update(sc);
7895
7896     /* enable nig attention */
7897     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7898     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7899         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7900         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7901     } else if (!CHIP_IS_E1x(sc)) {
7902         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7903         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7904     }
7905
7906     bxe_stats_handle(sc, STATS_EVENT_PMF);
7907 }
7908
7909 static int
7910 bxe_mc_assert(struct bxe_softc *sc)
7911 {
7912     char last_idx;
7913     int i, rc = 0;
7914     uint32_t row0, row1, row2, row3;
7915
7916     /* XSTORM */
7917     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7918     if (last_idx)
7919         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7920
7921     /* print the asserts */
7922     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7923
7924         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7925         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7926         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7927         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7928
7929         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7930             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7931                   i, row3, row2, row1, row0);
7932             rc++;
7933         } else {
7934             break;
7935         }
7936     }
7937
7938     /* TSTORM */
7939     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7940     if (last_idx) {
7941         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7942     }
7943
7944     /* print the asserts */
7945     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7946
7947         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7948         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7949         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7950         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7951
7952         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7953             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7954                   i, row3, row2, row1, row0);
7955             rc++;
7956         } else {
7957             break;
7958         }
7959     }
7960
7961     /* CSTORM */
7962     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7963     if (last_idx) {
7964         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7965     }
7966
7967     /* print the asserts */
7968     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7969
7970         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7971         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7972         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7973         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7974
7975         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7976             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7977                   i, row3, row2, row1, row0);
7978             rc++;
7979         } else {
7980             break;
7981         }
7982     }
7983
7984     /* USTORM */
7985     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7986     if (last_idx) {
7987         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7988     }
7989
7990     /* print the asserts */
7991     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7992
7993         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7994         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7995         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7996         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7997
7998         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7999             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
8000                   i, row3, row2, row1, row0);
8001             rc++;
8002         } else {
8003             break;
8004         }
8005     }
8006
8007     return (rc);
8008 }
8009
8010 static void
8011 bxe_attn_int_deasserted3(struct bxe_softc *sc,
8012                          uint32_t         attn)
8013 {
8014     int func = SC_FUNC(sc);
8015     uint32_t val;
8016
8017     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
8018
8019         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
8020
8021             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
8022             bxe_read_mf_cfg(sc);
8023             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
8024                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
8025             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
8026
8027             if (val & DRV_STATUS_DCC_EVENT_MASK)
8028                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
8029
8030             if (val & DRV_STATUS_SET_MF_BW)
8031                 bxe_set_mf_bw(sc);
8032
8033             if (val & DRV_STATUS_DRV_INFO_REQ)
8034                 bxe_handle_drv_info_req(sc);
8035
8036             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
8037                 bxe_pmf_update(sc);
8038
8039             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
8040                 bxe_handle_eee_event(sc);
8041
8042             if (sc->link_vars.periodic_flags &
8043                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
8044                 /* sync with link */
8045                 bxe_acquire_phy_lock(sc);
8046                 sc->link_vars.periodic_flags &=
8047                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
8048                 bxe_release_phy_lock(sc);
8049                 if (IS_MF(sc))
8050                     ; // XXX bxe_link_sync_notify(sc);
8051                 bxe_link_report(sc);
8052             }
8053
8054             /*
8055              * Always call it here: bxe_link_report() will
8056              * prevent the link indication duplication.
8057              */
8058             bxe_link_status_update(sc);
8059
8060         } else if (attn & BXE_MC_ASSERT_BITS) {
8061
8062             BLOGE(sc, "MC assert!\n");
8063             bxe_mc_assert(sc);
8064             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8065             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8066             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8067             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8068             bxe_panic(sc, ("MC assert!\n"));
8069
8070         } else if (attn & BXE_MCP_ASSERT) {
8071
8072             BLOGE(sc, "MCP assert!\n");
8073             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8074             // XXX bxe_fw_dump(sc);
8075
8076         } else {
8077             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8078         }
8079     }
8080
8081     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8082         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8083         if (attn & BXE_GRC_TIMEOUT) {
8084             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8085             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8086         }
8087         if (attn & BXE_GRC_RSV) {
8088             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8089             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8090         }
8091         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8092     }
8093 }
8094
8095 static void
8096 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8097                          uint32_t         attn)
8098 {
8099     int port = SC_PORT(sc);
8100     int reg_offset;
8101     uint32_t val0, mask0, val1, mask1;
8102     uint32_t val;
8103
8104     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8105         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8106         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8107         /* CFC error attention */
8108         if (val & 0x2) {
8109             BLOGE(sc, "FATAL error from CFC\n");
8110         }
8111     }
8112
8113     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8114         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8115         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8116         /* RQ_USDMDP_FIFO_OVERFLOW */
8117         if (val & 0x18000) {
8118             BLOGE(sc, "FATAL error from PXP\n");
8119         }
8120
8121         if (!CHIP_IS_E1x(sc)) {
8122             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8123             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8124         }
8125     }
8126
8127 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8128 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8129
8130     if (attn & AEU_PXP2_HW_INT_BIT) {
8131         /*  CQ47854 workaround do not panic on
8132          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8133          */
8134         if (!CHIP_IS_E1x(sc)) {
8135             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8136             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8137             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8138             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8139             /*
8140              * If the olny PXP2_EOP_ERROR_BIT is set in
8141              * STS0 and STS1 - clear it
8142              *
8143              * probably we lose additional attentions between
8144              * STS0 and STS_CLR0, in this case user will not
8145              * be notified about them
8146              */
8147             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8148                 !(val1 & mask1))
8149                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8150
8151             /* print the register, since no one can restore it */
8152             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8153
8154             /*
8155              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8156              * then notify
8157              */
8158             if (val0 & PXP2_EOP_ERROR_BIT) {
8159                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8160
8161                 /*
8162                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8163                  * set then clear attention from PXP2 block without panic
8164                  */
8165                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8166                     ((val1 & mask1) == 0))
8167                     attn &= ~AEU_PXP2_HW_INT_BIT;
8168             }
8169         }
8170     }
8171
8172     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8173         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8174                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8175
8176         val = REG_RD(sc, reg_offset);
8177         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8178         REG_WR(sc, reg_offset, val);
8179
8180         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8181               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8182         bxe_panic(sc, ("HW block attention set2\n"));
8183     }
8184 }
8185
8186 static void
8187 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8188                          uint32_t         attn)
8189 {
8190     int port = SC_PORT(sc);
8191     int reg_offset;
8192     uint32_t val;
8193
8194     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8195         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8196         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8197         /* DORQ discard attention */
8198         if (val & 0x2) {
8199             BLOGE(sc, "FATAL error from DORQ\n");
8200         }
8201     }
8202
8203     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8204         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8205                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8206
8207         val = REG_RD(sc, reg_offset);
8208         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8209         REG_WR(sc, reg_offset, val);
8210
8211         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8212               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8213         bxe_panic(sc, ("HW block attention set1\n"));
8214     }
8215 }
8216
8217 static void
8218 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8219                          uint32_t         attn)
8220 {
8221     int port = SC_PORT(sc);
8222     int reg_offset;
8223     uint32_t val;
8224
8225     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8226                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8227
8228     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8229         val = REG_RD(sc, reg_offset);
8230         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8231         REG_WR(sc, reg_offset, val);
8232
8233         BLOGW(sc, "SPIO5 hw attention\n");
8234
8235         /* Fan failure attention */
8236         elink_hw_reset_phy(&sc->link_params);
8237         bxe_fan_failure(sc);
8238     }
8239
8240     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8241         bxe_acquire_phy_lock(sc);
8242         elink_handle_module_detect_int(&sc->link_params);
8243         bxe_release_phy_lock(sc);
8244     }
8245
8246     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8247         val = REG_RD(sc, reg_offset);
8248         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8249         REG_WR(sc, reg_offset, val);
8250
8251         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8252                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8253     }
8254 }
8255
8256 static void
8257 bxe_attn_int_deasserted(struct bxe_softc *sc,
8258                         uint32_t         deasserted)
8259 {
8260     struct attn_route attn;
8261     struct attn_route *group_mask;
8262     int port = SC_PORT(sc);
8263     int index;
8264     uint32_t reg_addr;
8265     uint32_t val;
8266     uint32_t aeu_mask;
8267     uint8_t global = FALSE;
8268
8269     /*
8270      * Need to take HW lock because MCP or other port might also
8271      * try to handle this event.
8272      */
8273     bxe_acquire_alr(sc);
8274
8275     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8276         /* XXX
8277          * In case of parity errors don't handle attentions so that
8278          * other function would "see" parity errors.
8279          */
8280         sc->recovery_state = BXE_RECOVERY_INIT;
8281         // XXX schedule a recovery task...
8282         /* disable HW interrupts */
8283         bxe_int_disable(sc);
8284         bxe_release_alr(sc);
8285         return;
8286     }
8287
8288     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8289     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8290     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8291     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8292     if (!CHIP_IS_E1x(sc)) {
8293         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8294     } else {
8295         attn.sig[4] = 0;
8296     }
8297
8298     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8299           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8300
8301     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8302         if (deasserted & (1 << index)) {
8303             group_mask = &sc->attn_group[index];
8304
8305             BLOGD(sc, DBG_INTR,
8306                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8307                   group_mask->sig[0], group_mask->sig[1],
8308                   group_mask->sig[2], group_mask->sig[3],
8309                   group_mask->sig[4]);
8310
8311             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8312             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8313             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8314             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8315             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8316         }
8317     }
8318
8319     bxe_release_alr(sc);
8320
8321     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8322         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8323                     COMMAND_REG_ATTN_BITS_CLR);
8324     } else {
8325         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8326     }
8327
8328     val = ~deasserted;
8329     BLOGD(sc, DBG_INTR,
8330           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8331           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8332     REG_WR(sc, reg_addr, val);
8333
8334     if (~sc->attn_state & deasserted) {
8335         BLOGE(sc, "IGU error\n");
8336     }
8337
8338     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8339                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8340
8341     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8342
8343     aeu_mask = REG_RD(sc, reg_addr);
8344
8345     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8346           aeu_mask, deasserted);
8347     aeu_mask |= (deasserted & 0x3ff);
8348     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8349
8350     REG_WR(sc, reg_addr, aeu_mask);
8351     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8352
8353     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8354     sc->attn_state &= ~deasserted;
8355     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8356 }
8357
8358 static void
8359 bxe_attn_int(struct bxe_softc *sc)
8360 {
8361     /* read local copy of bits */
8362     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8363     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8364     uint32_t attn_state = sc->attn_state;
8365
8366     /* look for changed bits */
8367     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8368     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8369
8370     BLOGD(sc, DBG_INTR,
8371           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8372           attn_bits, attn_ack, asserted, deasserted);
8373
8374     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8375         BLOGE(sc, "BAD attention state\n");
8376     }
8377
8378     /* handle bits that were raised */
8379     if (asserted) {
8380         bxe_attn_int_asserted(sc, asserted);
8381     }
8382
8383     if (deasserted) {
8384         bxe_attn_int_deasserted(sc, deasserted);
8385     }
8386 }
8387
8388 static uint16_t
8389 bxe_update_dsb_idx(struct bxe_softc *sc)
8390 {
8391     struct host_sp_status_block *def_sb = sc->def_sb;
8392     uint16_t rc = 0;
8393
8394     mb(); /* status block is written to by the chip */
8395
8396     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8397         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8398         rc |= BXE_DEF_SB_ATT_IDX;
8399     }
8400
8401     if (sc->def_idx != def_sb->sp_sb.running_index) {
8402         sc->def_idx = def_sb->sp_sb.running_index;
8403         rc |= BXE_DEF_SB_IDX;
8404     }
8405
8406     mb();
8407
8408     return (rc);
8409 }
8410
8411 static inline struct ecore_queue_sp_obj *
8412 bxe_cid_to_q_obj(struct bxe_softc *sc,
8413                  uint32_t         cid)
8414 {
8415     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8416     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8417 }
8418
8419 static void
8420 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8421 {
8422     struct ecore_mcast_ramrod_params rparam;
8423     int rc;
8424
8425     memset(&rparam, 0, sizeof(rparam));
8426
8427     rparam.mcast_obj = &sc->mcast_obj;
8428
8429     BXE_MCAST_LOCK(sc);
8430
8431     /* clear pending state for the last command */
8432     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8433
8434     /* if there are pending mcast commands - send them */
8435     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8436         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8437         if (rc < 0) {
8438             BLOGD(sc, DBG_SP,
8439                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8440         }
8441     }
8442
8443     BXE_MCAST_UNLOCK(sc);
8444 }
8445
8446 static void
8447 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8448                               union event_ring_elem *elem)
8449 {
8450     unsigned long ramrod_flags = 0;
8451     int rc = 0;
8452     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8453     struct ecore_vlan_mac_obj *vlan_mac_obj;
8454
8455     /* always push next commands out, don't wait here */
8456     bit_set(&ramrod_flags, RAMROD_CONT);
8457
8458     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8459     case ECORE_FILTER_MAC_PENDING:
8460         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8461         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8462         break;
8463
8464     case ECORE_FILTER_MCAST_PENDING:
8465         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8466         /*
8467          * This is only relevant for 57710 where multicast MACs are
8468          * configured as unicast MACs using the same ramrod.
8469          */
8470         bxe_handle_mcast_eqe(sc);
8471         return;
8472
8473     default:
8474         BLOGE(sc, "Unsupported classification command: %d\n",
8475               elem->message.data.eth_event.echo);
8476         return;
8477     }
8478
8479     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8480
8481     if (rc < 0) {
8482         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8483     } else if (rc > 0) {
8484         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8485     }
8486 }
8487
8488 static void
8489 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8490                        union event_ring_elem *elem)
8491 {
8492     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8493
8494     /* send rx_mode command again if was requested */
8495     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8496                                &sc->sp_state)) {
8497         bxe_set_storm_rx_mode(sc);
8498     }
8499 }
8500
8501 static void
8502 bxe_update_eq_prod(struct bxe_softc *sc,
8503                    uint16_t         prod)
8504 {
8505     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8506     wmb(); /* keep prod updates ordered */
8507 }
8508
8509 static void
8510 bxe_eq_int(struct bxe_softc *sc)
8511 {
8512     uint16_t hw_cons, sw_cons, sw_prod;
8513     union event_ring_elem *elem;
8514     uint8_t echo;
8515     uint32_t cid;
8516     uint8_t opcode;
8517     int spqe_cnt = 0;
8518     struct ecore_queue_sp_obj *q_obj;
8519     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8520     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8521
8522     hw_cons = le16toh(*sc->eq_cons_sb);
8523
8524     /*
8525      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8526      * when we get to the next-page we need to adjust so the loop
8527      * condition below will be met. The next element is the size of a
8528      * regular element and hence incrementing by 1
8529      */
8530     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8531         hw_cons++;
8532     }
8533
8534     /*
8535      * This function may never run in parallel with itself for a
8536      * specific sc and no need for a read memory barrier here.
8537      */
8538     sw_cons = sc->eq_cons;
8539     sw_prod = sc->eq_prod;
8540
8541     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8542           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8543
8544     for (;
8545          sw_cons != hw_cons;
8546          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8547
8548         elem = &sc->eq[EQ_DESC(sw_cons)];
8549
8550         /* elem CID originates from FW, actually LE */
8551         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8552         opcode = elem->message.opcode;
8553
8554         /* handle eq element */
8555         switch (opcode) {
8556
8557         case EVENT_RING_OPCODE_STAT_QUERY:
8558             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8559                   sc->stats_comp++);
8560             /* nothing to do with stats comp */
8561             goto next_spqe;
8562
8563         case EVENT_RING_OPCODE_CFC_DEL:
8564             /* handle according to cid range */
8565             /* we may want to verify here that the sc state is HALTING */
8566             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8567             q_obj = bxe_cid_to_q_obj(sc, cid);
8568             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8569                 break;
8570             }
8571             goto next_spqe;
8572
8573         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8574             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8575             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8576                 break;
8577             }
8578             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8579             goto next_spqe;
8580
8581         case EVENT_RING_OPCODE_START_TRAFFIC:
8582             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8583             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8584                 break;
8585             }
8586             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8587             goto next_spqe;
8588
8589         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8590             echo = elem->message.data.function_update_event.echo;
8591             if (echo == SWITCH_UPDATE) {
8592                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8593                 if (f_obj->complete_cmd(sc, f_obj,
8594                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8595                     break;
8596                 }
8597             }
8598             else {
8599                 BLOGD(sc, DBG_SP,
8600                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8601             }
8602             goto next_spqe;
8603
8604         case EVENT_RING_OPCODE_FORWARD_SETUP:
8605             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8606             if (q_obj->complete_cmd(sc, q_obj,
8607                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8608                 break;
8609             }
8610             goto next_spqe;
8611
8612         case EVENT_RING_OPCODE_FUNCTION_START:
8613             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8614             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8615                 break;
8616             }
8617             goto next_spqe;
8618
8619         case EVENT_RING_OPCODE_FUNCTION_STOP:
8620             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8621             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8622                 break;
8623             }
8624             goto next_spqe;
8625         }
8626
8627         switch (opcode | sc->state) {
8628         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8629         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8630             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8631             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8632             rss_raw->clear_pending(rss_raw);
8633             break;
8634
8635         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8636         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8637         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8638         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8639         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8640         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8641             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8642             bxe_handle_classification_eqe(sc, elem);
8643             break;
8644
8645         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8646         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8647         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8648             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8649             bxe_handle_mcast_eqe(sc);
8650             break;
8651
8652         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8653         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8654         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8655             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8656             bxe_handle_rx_mode_eqe(sc, elem);
8657             break;
8658
8659         default:
8660             /* unknown event log error and continue */
8661             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8662                   elem->message.opcode, sc->state);
8663         }
8664
8665 next_spqe:
8666         spqe_cnt++;
8667     } /* for */
8668
8669     mb();
8670     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8671
8672     sc->eq_cons = sw_cons;
8673     sc->eq_prod = sw_prod;
8674
8675     /* make sure that above mem writes were issued towards the memory */
8676     wmb();
8677
8678     /* update producer */
8679     bxe_update_eq_prod(sc, sc->eq_prod);
8680 }
8681
8682 static void
8683 bxe_handle_sp_tq(void *context,
8684                  int  pending)
8685 {
8686     struct bxe_softc *sc = (struct bxe_softc *)context;
8687     uint16_t status;
8688
8689     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8690
8691     /* what work needs to be performed? */
8692     status = bxe_update_dsb_idx(sc);
8693
8694     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8695
8696     /* HW attentions */
8697     if (status & BXE_DEF_SB_ATT_IDX) {
8698         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8699         bxe_attn_int(sc);
8700         status &= ~BXE_DEF_SB_ATT_IDX;
8701     }
8702
8703     /* SP events: STAT_QUERY and others */
8704     if (status & BXE_DEF_SB_IDX) {
8705         /* handle EQ completions */
8706         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8707         bxe_eq_int(sc);
8708         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8709                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8710         status &= ~BXE_DEF_SB_IDX;
8711     }
8712
8713     /* if status is non zero then something went wrong */
8714     if (__predict_false(status)) {
8715         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8716     }
8717
8718     /* ack status block only if something was actually handled */
8719     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8720                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8721
8722     /*
8723      * Must be called after the EQ processing (since eq leads to sriov
8724      * ramrod completion flows).
8725      * This flow may have been scheduled by the arrival of a ramrod
8726      * completion, or by the sriov code rescheduling itself.
8727      */
8728     // XXX bxe_iov_sp_task(sc);
8729
8730 }
8731
8732 static void
8733 bxe_handle_fp_tq(void *context,
8734                  int  pending)
8735 {
8736     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8737     struct bxe_softc *sc = fp->sc;
8738     uint8_t more_tx = FALSE;
8739     uint8_t more_rx = FALSE;
8740
8741     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8742
8743     /* XXX
8744      * IFF_DRV_RUNNING state can't be checked here since we process
8745      * slowpath events on a client queue during setup. Instead
8746      * we need to add a "process/continue" flag here that the driver
8747      * can use to tell the task here not to do anything.
8748      */
8749 #if 0
8750     if (!(sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
8751         return;
8752     }
8753 #endif
8754
8755     /* update the fastpath index */
8756     bxe_update_fp_sb_idx(fp);
8757
8758     /* XXX add loop here if ever support multiple tx CoS */
8759     /* fp->txdata[cos] */
8760     if (bxe_has_tx_work(fp)) {
8761         BXE_FP_TX_LOCK(fp);
8762         more_tx = bxe_txeof(sc, fp);
8763         BXE_FP_TX_UNLOCK(fp);
8764     }
8765
8766     if (bxe_has_rx_work(fp)) {
8767         more_rx = bxe_rxeof(sc, fp);
8768     }
8769
8770     if (more_rx /*|| more_tx*/) {
8771         /* still more work to do */
8772         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8773         return;
8774     }
8775
8776     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8777                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8778 }
8779
8780 static void
8781 bxe_task_fp(struct bxe_fastpath *fp)
8782 {
8783     struct bxe_softc *sc = fp->sc;
8784     uint8_t more_tx = FALSE;
8785     uint8_t more_rx = FALSE;
8786
8787     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8788
8789     /* update the fastpath index */
8790     bxe_update_fp_sb_idx(fp);
8791
8792     /* XXX add loop here if ever support multiple tx CoS */
8793     /* fp->txdata[cos] */
8794     if (bxe_has_tx_work(fp)) {
8795         BXE_FP_TX_LOCK(fp);
8796         more_tx = bxe_txeof(sc, fp);
8797         BXE_FP_TX_UNLOCK(fp);
8798     }
8799
8800     if (bxe_has_rx_work(fp)) {
8801         more_rx = bxe_rxeof(sc, fp);
8802     }
8803
8804     if (more_rx /*|| more_tx*/) {
8805         /* still more work to do, bail out if this ISR and process later */
8806         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8807         return;
8808     }
8809
8810     /*
8811      * Here we write the fastpath index taken before doing any tx or rx work.
8812      * It is very well possible other hw events occurred up to this point and
8813      * they were actually processed accordingly above. Since we're going to
8814      * write an older fastpath index, an interrupt is coming which we might
8815      * not do any work in.
8816      */
8817     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8818                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8819 }
8820
8821 /*
8822  * Legacy interrupt entry point.
8823  *
8824  * Verifies that the controller generated the interrupt and
8825  * then calls a separate routine to handle the various
8826  * interrupt causes: link, RX, and TX.
8827  */
8828 static void
8829 bxe_intr_legacy(void *xsc)
8830 {
8831     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8832     struct bxe_fastpath *fp;
8833     uint16_t status, mask;
8834     int i;
8835
8836     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8837
8838     /*
8839      * 0 for ustorm, 1 for cstorm
8840      * the bits returned from ack_int() are 0-15
8841      * bit 0 = attention status block
8842      * bit 1 = fast path status block
8843      * a mask of 0x2 or more = tx/rx event
8844      * a mask of 1 = slow path event
8845      */
8846
8847     status = bxe_ack_int(sc);
8848
8849     /* the interrupt is not for us */
8850     if (__predict_false(status == 0)) {
8851         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8852         return;
8853     }
8854
8855     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8856
8857     FOR_EACH_ETH_QUEUE(sc, i) {
8858         fp = &sc->fp[i];
8859         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8860         if (status & mask) {
8861             /* acknowledge and disable further fastpath interrupts */
8862             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8863             bxe_task_fp(fp);
8864             status &= ~mask;
8865         }
8866     }
8867
8868     if (__predict_false(status & 0x1)) {
8869         /* acknowledge and disable further slowpath interrupts */
8870         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8871
8872         /* schedule slowpath handler */
8873         taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8874
8875         status &= ~0x1;
8876     }
8877
8878     if (__predict_false(status)) {
8879         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8880     }
8881 }
8882
8883 /* slowpath interrupt entry point */
8884 static void
8885 bxe_intr_sp(void *xsc)
8886 {
8887     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8888
8889     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8890
8891     /* acknowledge and disable further slowpath interrupts */
8892     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8893
8894     /* schedule slowpath handler */
8895     taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8896 }
8897
8898 /* fastpath interrupt entry point */
8899 static void
8900 bxe_intr_fp(void *xfp)
8901 {
8902     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8903     struct bxe_softc *sc = fp->sc;
8904
8905     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8906
8907     BLOGD(sc, DBG_INTR,
8908           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8909           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8910
8911     /* acknowledge and disable further fastpath interrupts */
8912     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8913
8914     bxe_task_fp(fp);
8915 }
8916
8917 /* Release all interrupts allocated by the driver. */
8918 static void
8919 bxe_interrupt_free(struct bxe_softc *sc)
8920 {
8921     int i;
8922
8923     switch (sc->interrupt_mode) {
8924     case INTR_MODE_INTX:
8925         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8926         if (sc->intr[0].resource != NULL) {
8927             bus_release_resource(sc->dev,
8928                                  SYS_RES_IRQ,
8929                                  sc->intr[0].rid,
8930                                  sc->intr[0].resource);
8931         }
8932         break;
8933     case INTR_MODE_MSI:
8934         for (i = 0; i < sc->intr_count; i++) {
8935             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8936             if (sc->intr[i].resource && sc->intr[i].rid) {
8937                 bus_release_resource(sc->dev,
8938                                      SYS_RES_IRQ,
8939                                      sc->intr[i].rid,
8940                                      sc->intr[i].resource);
8941             }
8942         }
8943         pci_release_msi(sc->dev);
8944         break;
8945     case INTR_MODE_MSIX:
8946         for (i = 0; i < sc->intr_count; i++) {
8947             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8948             if (sc->intr[i].resource && sc->intr[i].rid) {
8949                 bus_release_resource(sc->dev,
8950                                      SYS_RES_IRQ,
8951                                      sc->intr[i].rid,
8952                                      sc->intr[i].resource);
8953             }
8954         }
8955         pci_release_msi(sc->dev);
8956         break;
8957     default:
8958         /* nothing to do as initial allocation failed */
8959         break;
8960     }
8961 }
8962
8963 /*
8964  * This function determines and allocates the appropriate
8965  * interrupt based on system capabilites and user request.
8966  *
8967  * The user may force a particular interrupt mode, specify
8968  * the number of receive queues, specify the method for
8969  * distribuitng received frames to receive queues, or use
8970  * the default settings which will automatically select the
8971  * best supported combination.  In addition, the OS may or
8972  * may not support certain combinations of these settings.
8973  * This routine attempts to reconcile the settings requested
8974  * by the user with the capabilites available from the system
8975  * to select the optimal combination of features.
8976  *
8977  * Returns:
8978  *   0 = Success, !0 = Failure.
8979  */
8980 static int
8981 bxe_interrupt_alloc(struct bxe_softc *sc)
8982 {
8983     int msix_count = 0;
8984     int msi_count = 0;
8985     int num_requested = 0;
8986     int num_allocated = 0;
8987     int rid, i, j;
8988     int rc;
8989
8990     /* get the number of available MSI/MSI-X interrupts from the OS */
8991     if (sc->interrupt_mode > 0) {
8992         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8993             msix_count = pci_msix_count(sc->dev);
8994         }
8995
8996         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8997             msi_count = pci_msi_count(sc->dev);
8998         }
8999
9000         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
9001               msi_count, msix_count);
9002     }
9003
9004     do { /* try allocating MSI-X interrupt resources (at least 2) */
9005         if (sc->interrupt_mode != INTR_MODE_MSIX) {
9006             break;
9007         }
9008
9009         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
9010             (msix_count < 2)) {
9011             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9012             break;
9013         }
9014
9015         /* ask for the necessary number of MSI-X vectors */
9016         num_requested = min((sc->num_queues + 1), msix_count);
9017
9018         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
9019
9020         num_allocated = num_requested;
9021         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
9022             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
9023             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9024             break;
9025         }
9026
9027         if (num_allocated < 2) { /* possible? */
9028             BLOGE(sc, "MSI-X allocation less than 2!\n");
9029             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9030             pci_release_msi(sc->dev);
9031             break;
9032         }
9033
9034         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
9035               num_requested, num_allocated);
9036
9037         /* best effort so use the number of vectors allocated to us */
9038         sc->intr_count = num_allocated;
9039         sc->num_queues = num_allocated - 1;
9040
9041         rid = 1; /* initial resource identifier */
9042
9043         /* allocate the MSI-X vectors */
9044         for (i = 0; i < num_allocated; i++) {
9045             sc->intr[i].rid = (rid + i);
9046
9047             if ((sc->intr[i].resource =
9048                  bus_alloc_resource_any(sc->dev,
9049                                         SYS_RES_IRQ,
9050                                         &sc->intr[i].rid,
9051                                         RF_ACTIVE)) == NULL) {
9052                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
9053                       i, (rid + i));
9054
9055                 for (j = (i - 1); j >= 0; j--) {
9056                     bus_release_resource(sc->dev,
9057                                          SYS_RES_IRQ,
9058                                          sc->intr[j].rid,
9059                                          sc->intr[j].resource);
9060                 }
9061
9062                 sc->intr_count = 0;
9063                 sc->num_queues = 0;
9064                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9065                 pci_release_msi(sc->dev);
9066                 break;
9067             }
9068
9069             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9070         }
9071     } while (0);
9072
9073     do { /* try allocating MSI vector resources (at least 2) */
9074         if (sc->interrupt_mode != INTR_MODE_MSI) {
9075             break;
9076         }
9077
9078         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9079             (msi_count < 1)) {
9080             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9081             break;
9082         }
9083
9084         /* ask for a single MSI vector */
9085         num_requested = 1;
9086
9087         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9088
9089         num_allocated = num_requested;
9090         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9091             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9092             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9093             break;
9094         }
9095
9096         if (num_allocated != 1) { /* possible? */
9097             BLOGE(sc, "MSI allocation is not 1!\n");
9098             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9099             pci_release_msi(sc->dev);
9100             break;
9101         }
9102
9103         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9104               num_requested, num_allocated);
9105
9106         /* best effort so use the number of vectors allocated to us */
9107         sc->intr_count = num_allocated;
9108         sc->num_queues = num_allocated;
9109
9110         rid = 1; /* initial resource identifier */
9111
9112         sc->intr[0].rid = rid;
9113
9114         if ((sc->intr[0].resource =
9115              bus_alloc_resource_any(sc->dev,
9116                                     SYS_RES_IRQ,
9117                                     &sc->intr[0].rid,
9118                                     RF_ACTIVE)) == NULL) {
9119             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9120             sc->intr_count = 0;
9121             sc->num_queues = 0;
9122             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9123             pci_release_msi(sc->dev);
9124             break;
9125         }
9126
9127         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9128     } while (0);
9129
9130     do { /* try allocating INTx vector resources */
9131         if (sc->interrupt_mode != INTR_MODE_INTX) {
9132             break;
9133         }
9134
9135         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9136
9137         /* only one vector for INTx */
9138         sc->intr_count = 1;
9139         sc->num_queues = 1;
9140
9141         rid = 0; /* initial resource identifier */
9142
9143         sc->intr[0].rid = rid;
9144
9145         if ((sc->intr[0].resource =
9146              bus_alloc_resource_any(sc->dev,
9147                                     SYS_RES_IRQ,
9148                                     &sc->intr[0].rid,
9149                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9150             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9151             sc->intr_count = 0;
9152             sc->num_queues = 0;
9153             sc->interrupt_mode = -1; /* Failed! */
9154             break;
9155         }
9156
9157         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9158     } while (0);
9159
9160     if (sc->interrupt_mode == -1) {
9161         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9162         rc = 1;
9163     } else {
9164         BLOGD(sc, DBG_LOAD,
9165               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9166               sc->interrupt_mode, sc->num_queues);
9167         rc = 0;
9168     }
9169
9170     return (rc);
9171 }
9172
9173 static void
9174 bxe_interrupt_detach(struct bxe_softc *sc)
9175 {
9176     struct bxe_fastpath *fp;
9177     int i;
9178
9179     /* release interrupt resources */
9180     for (i = 0; i < sc->intr_count; i++) {
9181         if (sc->intr[i].resource && sc->intr[i].tag) {
9182             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9183             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9184         }
9185     }
9186
9187     for (i = 0; i < sc->num_queues; i++) {
9188         fp = &sc->fp[i];
9189         if (fp->tq) {
9190             taskqueue_drain(fp->tq, &fp->tq_task);
9191             taskqueue_free(fp->tq);
9192             fp->tq = NULL;
9193         }
9194     }
9195
9196
9197     if (sc->sp_tq) {
9198         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9199         taskqueue_free(sc->sp_tq);
9200         sc->sp_tq = NULL;
9201     }
9202 }
9203
9204 /*
9205  * Enables interrupts and attach to the ISR.
9206  *
9207  * When using multiple MSI/MSI-X vectors the first vector
9208  * is used for slowpath operations while all remaining
9209  * vectors are used for fastpath operations.  If only a
9210  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9211  * ISR must look for both slowpath and fastpath completions.
9212  */
9213 static int
9214 bxe_interrupt_attach(struct bxe_softc *sc)
9215 {
9216     struct bxe_fastpath *fp;
9217     int rc = 0;
9218     int i;
9219
9220     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9221              "bxe%d_sp_tq", sc->unit);
9222     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9223     sc->sp_tq = taskqueue_create_fast(sc->sp_tq_name, M_NOWAIT,
9224                                       taskqueue_thread_enqueue,
9225                                       &sc->sp_tq);
9226     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9227                             "%s", sc->sp_tq_name);
9228
9229
9230     for (i = 0; i < sc->num_queues; i++) {
9231         fp = &sc->fp[i];
9232         snprintf(fp->tq_name, sizeof(fp->tq_name),
9233                  "bxe%d_fp%d_tq", sc->unit, i);
9234         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9235         fp->tq = taskqueue_create_fast(fp->tq_name, M_NOWAIT,
9236                                        taskqueue_thread_enqueue,
9237                                        &fp->tq);
9238         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9239                                 "%s", fp->tq_name);
9240     }
9241
9242     /* setup interrupt handlers */
9243     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9244         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9245
9246         /*
9247          * Setup the interrupt handler. Note that we pass the driver instance
9248          * to the interrupt handler for the slowpath.
9249          */
9250         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9251                                  (INTR_TYPE_NET | INTR_MPSAFE),
9252                                  NULL, bxe_intr_sp, sc,
9253                                  &sc->intr[0].tag)) != 0) {
9254             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9255             goto bxe_interrupt_attach_exit;
9256         }
9257
9258         bus_describe_intr(sc->dev, sc->intr[0].resource,
9259                           sc->intr[0].tag, "sp");
9260
9261         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9262
9263         /* initialize the fastpath vectors (note the first was used for sp) */
9264         for (i = 0; i < sc->num_queues; i++) {
9265             fp = &sc->fp[i];
9266             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9267
9268             /*
9269              * Setup the interrupt handler. Note that we pass the
9270              * fastpath context to the interrupt handler in this
9271              * case.
9272              */
9273             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9274                                      (INTR_TYPE_NET | INTR_MPSAFE),
9275                                      NULL, bxe_intr_fp, fp,
9276                                      &sc->intr[i + 1].tag)) != 0) {
9277                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9278                       (i + 1), rc);
9279                 goto bxe_interrupt_attach_exit;
9280             }
9281
9282             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9283                               sc->intr[i + 1].tag, "fp%02d", i);
9284
9285             /* bind the fastpath instance to a cpu */
9286             if (sc->num_queues > 1) {
9287                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9288             }
9289
9290             fp->state = BXE_FP_STATE_IRQ;
9291         }
9292     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9293         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9294
9295         /*
9296          * Setup the interrupt handler. Note that we pass the
9297          * driver instance to the interrupt handler which
9298          * will handle both the slowpath and fastpath.
9299          */
9300         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9301                                  (INTR_TYPE_NET | INTR_MPSAFE),
9302                                  NULL, bxe_intr_legacy, sc,
9303                                  &sc->intr[0].tag)) != 0) {
9304             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9305             goto bxe_interrupt_attach_exit;
9306         }
9307
9308     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9309         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9310
9311         /*
9312          * Setup the interrupt handler. Note that we pass the
9313          * driver instance to the interrupt handler which
9314          * will handle both the slowpath and fastpath.
9315          */
9316         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9317                                  (INTR_TYPE_NET | INTR_MPSAFE),
9318                                  NULL, bxe_intr_legacy, sc,
9319                                  &sc->intr[0].tag)) != 0) {
9320             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9321             goto bxe_interrupt_attach_exit;
9322         }
9323     }
9324
9325 bxe_interrupt_attach_exit:
9326
9327     return (rc);
9328 }
9329
9330 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9331 static int  bxe_init_hw_common(struct bxe_softc *sc);
9332 static int  bxe_init_hw_port(struct bxe_softc *sc);
9333 static int  bxe_init_hw_func(struct bxe_softc *sc);
9334 static void bxe_reset_common(struct bxe_softc *sc);
9335 static void bxe_reset_port(struct bxe_softc *sc);
9336 static void bxe_reset_func(struct bxe_softc *sc);
9337 static int  bxe_gunzip_init(struct bxe_softc *sc);
9338 static void bxe_gunzip_end(struct bxe_softc *sc);
9339 static int  bxe_init_firmware(struct bxe_softc *sc);
9340 static void bxe_release_firmware(struct bxe_softc *sc);
9341
9342 static struct
9343 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9344     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9345     .init_hw_cmn      = bxe_init_hw_common,
9346     .init_hw_port     = bxe_init_hw_port,
9347     .init_hw_func     = bxe_init_hw_func,
9348
9349     .reset_hw_cmn     = bxe_reset_common,
9350     .reset_hw_port    = bxe_reset_port,
9351     .reset_hw_func    = bxe_reset_func,
9352
9353     .gunzip_init      = bxe_gunzip_init,
9354     .gunzip_end       = bxe_gunzip_end,
9355
9356     .init_fw          = bxe_init_firmware,
9357     .release_fw       = bxe_release_firmware,
9358 };
9359
9360 static void
9361 bxe_init_func_obj(struct bxe_softc *sc)
9362 {
9363     sc->dmae_ready = 0;
9364
9365     ecore_init_func_obj(sc,
9366                         &sc->func_obj,
9367                         BXE_SP(sc, func_rdata),
9368                         BXE_SP_MAPPING(sc, func_rdata),
9369                         BXE_SP(sc, func_afex_rdata),
9370                         BXE_SP_MAPPING(sc, func_afex_rdata),
9371                         &bxe_func_sp_drv);
9372 }
9373
9374 static int
9375 bxe_init_hw(struct bxe_softc *sc,
9376             uint32_t         load_code)
9377 {
9378     struct ecore_func_state_params func_params = { NULL };
9379     int rc;
9380
9381     /* prepare the parameters for function state transitions */
9382     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9383
9384     func_params.f_obj = &sc->func_obj;
9385     func_params.cmd = ECORE_F_CMD_HW_INIT;
9386
9387     func_params.params.hw_init.load_phase = load_code;
9388
9389     /*
9390      * Via a plethora of function pointers, we will eventually reach
9391      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9392      */
9393     rc = ecore_func_state_change(sc, &func_params);
9394
9395     return (rc);
9396 }
9397
9398 static void
9399 bxe_fill(struct bxe_softc *sc,
9400          uint32_t         addr,
9401          int              fill,
9402          uint32_t         len)
9403 {
9404     uint32_t i;
9405
9406     if (!(len % 4) && !(addr % 4)) {
9407         for (i = 0; i < len; i += 4) {
9408             REG_WR(sc, (addr + i), fill);
9409         }
9410     } else {
9411         for (i = 0; i < len; i++) {
9412             REG_WR8(sc, (addr + i), fill);
9413         }
9414     }
9415 }
9416
9417 /* writes FP SP data to FW - data_size in dwords */
9418 static void
9419 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9420                   int              fw_sb_id,
9421                   uint32_t         *sb_data_p,
9422                   uint32_t         data_size)
9423 {
9424     int index;
9425
9426     for (index = 0; index < data_size; index++) {
9427         REG_WR(sc,
9428                (BAR_CSTRORM_INTMEM +
9429                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9430                 (sizeof(uint32_t) * index)),
9431                *(sb_data_p + index));
9432     }
9433 }
9434
9435 static void
9436 bxe_zero_fp_sb(struct bxe_softc *sc,
9437                int              fw_sb_id)
9438 {
9439     struct hc_status_block_data_e2 sb_data_e2;
9440     struct hc_status_block_data_e1x sb_data_e1x;
9441     uint32_t *sb_data_p;
9442     uint32_t data_size = 0;
9443
9444     if (!CHIP_IS_E1x(sc)) {
9445         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9446         sb_data_e2.common.state = SB_DISABLED;
9447         sb_data_e2.common.p_func.vf_valid = FALSE;
9448         sb_data_p = (uint32_t *)&sb_data_e2;
9449         data_size = (sizeof(struct hc_status_block_data_e2) /
9450                      sizeof(uint32_t));
9451     } else {
9452         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9453         sb_data_e1x.common.state = SB_DISABLED;
9454         sb_data_e1x.common.p_func.vf_valid = FALSE;
9455         sb_data_p = (uint32_t *)&sb_data_e1x;
9456         data_size = (sizeof(struct hc_status_block_data_e1x) /
9457                      sizeof(uint32_t));
9458     }
9459
9460     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9461
9462     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9463              0, CSTORM_STATUS_BLOCK_SIZE);
9464     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9465              0, CSTORM_SYNC_BLOCK_SIZE);
9466 }
9467
9468 static void
9469 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9470                   struct hc_sp_status_block_data *sp_sb_data)
9471 {
9472     int i;
9473
9474     for (i = 0;
9475          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9476          i++) {
9477         REG_WR(sc,
9478                (BAR_CSTRORM_INTMEM +
9479                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9480                 (i * sizeof(uint32_t))),
9481                *((uint32_t *)sp_sb_data + i));
9482     }
9483 }
9484
9485 static void
9486 bxe_zero_sp_sb(struct bxe_softc *sc)
9487 {
9488     struct hc_sp_status_block_data sp_sb_data;
9489
9490     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9491
9492     sp_sb_data.state           = SB_DISABLED;
9493     sp_sb_data.p_func.vf_valid = FALSE;
9494
9495     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9496
9497     bxe_fill(sc,
9498              (BAR_CSTRORM_INTMEM +
9499               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9500               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9501     bxe_fill(sc,
9502              (BAR_CSTRORM_INTMEM +
9503               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9504               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9505 }
9506
9507 static void
9508 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9509                              int                       igu_sb_id,
9510                              int                       igu_seg_id)
9511 {
9512     hc_sm->igu_sb_id      = igu_sb_id;
9513     hc_sm->igu_seg_id     = igu_seg_id;
9514     hc_sm->timer_value    = 0xFF;
9515     hc_sm->time_to_expire = 0xFFFFFFFF;
9516 }
9517
9518 static void
9519 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9520 {
9521     /* zero out state machine indices */
9522
9523     /* rx indices */
9524     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9525
9526     /* tx indices */
9527     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9528     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9529     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9530     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9531
9532     /* map indices */
9533
9534     /* rx indices */
9535     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9536         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9537
9538     /* tx indices */
9539     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9540         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9541     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9542         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9543     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9544         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9545     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9546         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9547 }
9548
9549 static void
9550 bxe_init_sb(struct bxe_softc *sc,
9551             bus_addr_t       busaddr,
9552             int              vfid,
9553             uint8_t          vf_valid,
9554             int              fw_sb_id,
9555             int              igu_sb_id)
9556 {
9557     struct hc_status_block_data_e2  sb_data_e2;
9558     struct hc_status_block_data_e1x sb_data_e1x;
9559     struct hc_status_block_sm       *hc_sm_p;
9560     uint32_t *sb_data_p;
9561     int igu_seg_id;
9562     int data_size;
9563
9564     if (CHIP_INT_MODE_IS_BC(sc)) {
9565         igu_seg_id = HC_SEG_ACCESS_NORM;
9566     } else {
9567         igu_seg_id = IGU_SEG_ACCESS_NORM;
9568     }
9569
9570     bxe_zero_fp_sb(sc, fw_sb_id);
9571
9572     if (!CHIP_IS_E1x(sc)) {
9573         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9574         sb_data_e2.common.state = SB_ENABLED;
9575         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9576         sb_data_e2.common.p_func.vf_id = vfid;
9577         sb_data_e2.common.p_func.vf_valid = vf_valid;
9578         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9579         sb_data_e2.common.same_igu_sb_1b = TRUE;
9580         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9581         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9582         hc_sm_p = sb_data_e2.common.state_machine;
9583         sb_data_p = (uint32_t *)&sb_data_e2;
9584         data_size = (sizeof(struct hc_status_block_data_e2) /
9585                      sizeof(uint32_t));
9586         bxe_map_sb_state_machines(sb_data_e2.index_data);
9587     } else {
9588         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9589         sb_data_e1x.common.state = SB_ENABLED;
9590         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9591         sb_data_e1x.common.p_func.vf_id = 0xff;
9592         sb_data_e1x.common.p_func.vf_valid = FALSE;
9593         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9594         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9595         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9596         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9597         hc_sm_p = sb_data_e1x.common.state_machine;
9598         sb_data_p = (uint32_t *)&sb_data_e1x;
9599         data_size = (sizeof(struct hc_status_block_data_e1x) /
9600                      sizeof(uint32_t));
9601         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9602     }
9603
9604     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9605     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9606
9607     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9608
9609     /* write indices to HW - PCI guarantees endianity of regpairs */
9610     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9611 }
9612
9613 static inline uint8_t
9614 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9615 {
9616     if (CHIP_IS_E1x(fp->sc)) {
9617         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9618     } else {
9619         return (fp->cl_id);
9620     }
9621 }
9622
9623 static inline uint32_t
9624 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9625                            struct bxe_fastpath *fp)
9626 {
9627     uint32_t offset = BAR_USTRORM_INTMEM;
9628
9629     if (!CHIP_IS_E1x(sc)) {
9630         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9631     } else {
9632         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9633     }
9634
9635     return (offset);
9636 }
9637
9638 static void
9639 bxe_init_eth_fp(struct bxe_softc *sc,
9640                 int              idx)
9641 {
9642     struct bxe_fastpath *fp = &sc->fp[idx];
9643     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9644     unsigned long q_type = 0;
9645     int cos;
9646
9647     fp->sc    = sc;
9648     fp->index = idx;
9649
9650     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9651     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9652
9653     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9654                     (SC_L_ID(sc) + idx) :
9655                     /* want client ID same as IGU SB ID for non-E1 */
9656                     fp->igu_sb_id;
9657     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9658
9659     /* setup sb indices */
9660     if (!CHIP_IS_E1x(sc)) {
9661         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9662         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9663     } else {
9664         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9665         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9666     }
9667
9668     /* init shortcut */
9669     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9670
9671     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9672
9673     /*
9674      * XXX If multiple CoS is ever supported then each fastpath structure
9675      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9676      */
9677     for (cos = 0; cos < sc->max_cos; cos++) {
9678         cids[cos] = idx;
9679     }
9680     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9681
9682     /* nothing more for a VF to do */
9683     if (IS_VF(sc)) {
9684         return;
9685     }
9686
9687     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9688                 fp->fw_sb_id, fp->igu_sb_id);
9689
9690     bxe_update_fp_sb_idx(fp);
9691
9692     /* Configure Queue State object */
9693     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9694     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9695
9696     ecore_init_queue_obj(sc,
9697                          &sc->sp_objs[idx].q_obj,
9698                          fp->cl_id,
9699                          cids,
9700                          sc->max_cos,
9701                          SC_FUNC(sc),
9702                          BXE_SP(sc, q_rdata),
9703                          BXE_SP_MAPPING(sc, q_rdata),
9704                          q_type);
9705
9706     /* configure classification DBs */
9707     ecore_init_mac_obj(sc,
9708                        &sc->sp_objs[idx].mac_obj,
9709                        fp->cl_id,
9710                        idx,
9711                        SC_FUNC(sc),
9712                        BXE_SP(sc, mac_rdata),
9713                        BXE_SP_MAPPING(sc, mac_rdata),
9714                        ECORE_FILTER_MAC_PENDING,
9715                        &sc->sp_state,
9716                        ECORE_OBJ_TYPE_RX_TX,
9717                        &sc->macs_pool);
9718
9719     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9720           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9721 }
9722
9723 static inline void
9724 bxe_update_rx_prod(struct bxe_softc    *sc,
9725                    struct bxe_fastpath *fp,
9726                    uint16_t            rx_bd_prod,
9727                    uint16_t            rx_cq_prod,
9728                    uint16_t            rx_sge_prod)
9729 {
9730     struct ustorm_eth_rx_producers rx_prods = { 0 };
9731     uint32_t i;
9732
9733     /* update producers */
9734     rx_prods.bd_prod  = rx_bd_prod;
9735     rx_prods.cqe_prod = rx_cq_prod;
9736     rx_prods.sge_prod = rx_sge_prod;
9737
9738     /*
9739      * Make sure that the BD and SGE data is updated before updating the
9740      * producers since FW might read the BD/SGE right after the producer
9741      * is updated.
9742      * This is only applicable for weak-ordered memory model archs such
9743      * as IA-64. The following barrier is also mandatory since FW will
9744      * assumes BDs must have buffers.
9745      */
9746     wmb();
9747
9748     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9749         REG_WR(sc,
9750                (fp->ustorm_rx_prods_offset + (i * 4)),
9751                ((uint32_t *)&rx_prods)[i]);
9752     }
9753
9754     wmb(); /* keep prod updates ordered */
9755
9756     BLOGD(sc, DBG_RX,
9757           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9758           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9759 }
9760
9761 static void
9762 bxe_init_rx_rings(struct bxe_softc *sc)
9763 {
9764     struct bxe_fastpath *fp;
9765     int i;
9766
9767     for (i = 0; i < sc->num_queues; i++) {
9768         fp = &sc->fp[i];
9769
9770         fp->rx_bd_cons = 0;
9771
9772         /*
9773          * Activate the BD ring...
9774          * Warning, this will generate an interrupt (to the TSTORM)
9775          * so this can only be done after the chip is initialized
9776          */
9777         bxe_update_rx_prod(sc, fp,
9778                            fp->rx_bd_prod,
9779                            fp->rx_cq_prod,
9780                            fp->rx_sge_prod);
9781
9782         if (i != 0) {
9783             continue;
9784         }
9785
9786         if (CHIP_IS_E1(sc)) {
9787             REG_WR(sc,
9788                    (BAR_USTRORM_INTMEM +
9789                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9790                    U64_LO(fp->rcq_dma.paddr));
9791             REG_WR(sc,
9792                    (BAR_USTRORM_INTMEM +
9793                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9794                    U64_HI(fp->rcq_dma.paddr));
9795         }
9796     }
9797 }
9798
9799 static void
9800 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9801 {
9802     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9803     fp->tx_db.data.zero_fill1 = 0;
9804     fp->tx_db.data.prod = 0;
9805
9806     fp->tx_pkt_prod = 0;
9807     fp->tx_pkt_cons = 0;
9808     fp->tx_bd_prod = 0;
9809     fp->tx_bd_cons = 0;
9810     fp->eth_q_stats.tx_pkts = 0;
9811 }
9812
9813 static inline void
9814 bxe_init_tx_rings(struct bxe_softc *sc)
9815 {
9816     int i;
9817
9818     for (i = 0; i < sc->num_queues; i++) {
9819         bxe_init_tx_ring_one(&sc->fp[i]);
9820     }
9821 }
9822
9823 static void
9824 bxe_init_def_sb(struct bxe_softc *sc)
9825 {
9826     struct host_sp_status_block *def_sb = sc->def_sb;
9827     bus_addr_t mapping = sc->def_sb_dma.paddr;
9828     int igu_sp_sb_index;
9829     int igu_seg_id;
9830     int port = SC_PORT(sc);
9831     int func = SC_FUNC(sc);
9832     int reg_offset, reg_offset_en5;
9833     uint64_t section;
9834     int index, sindex;
9835     struct hc_sp_status_block_data sp_sb_data;
9836
9837     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9838
9839     if (CHIP_INT_MODE_IS_BC(sc)) {
9840         igu_sp_sb_index = DEF_SB_IGU_ID;
9841         igu_seg_id = HC_SEG_ACCESS_DEF;
9842     } else {
9843         igu_sp_sb_index = sc->igu_dsb_id;
9844         igu_seg_id = IGU_SEG_ACCESS_DEF;
9845     }
9846
9847     /* attentions */
9848     section = ((uint64_t)mapping +
9849                offsetof(struct host_sp_status_block, atten_status_block));
9850     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9851     sc->attn_state = 0;
9852
9853     reg_offset = (port) ?
9854                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9855                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9856     reg_offset_en5 = (port) ?
9857                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9858                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9859
9860     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9861         /* take care of sig[0]..sig[4] */
9862         for (sindex = 0; sindex < 4; sindex++) {
9863             sc->attn_group[index].sig[sindex] =
9864                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9865         }
9866
9867         if (!CHIP_IS_E1x(sc)) {
9868             /*
9869              * enable5 is separate from the rest of the registers,
9870              * and the address skip is 4 and not 16 between the
9871              * different groups
9872              */
9873             sc->attn_group[index].sig[4] =
9874                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9875         } else {
9876             sc->attn_group[index].sig[4] = 0;
9877         }
9878     }
9879
9880     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9881         reg_offset = (port) ?
9882                          HC_REG_ATTN_MSG1_ADDR_L :
9883                          HC_REG_ATTN_MSG0_ADDR_L;
9884         REG_WR(sc, reg_offset, U64_LO(section));
9885         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9886     } else if (!CHIP_IS_E1x(sc)) {
9887         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9888         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9889     }
9890
9891     section = ((uint64_t)mapping +
9892                offsetof(struct host_sp_status_block, sp_sb));
9893
9894     bxe_zero_sp_sb(sc);
9895
9896     /* PCI guarantees endianity of regpair */
9897     sp_sb_data.state           = SB_ENABLED;
9898     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9899     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9900     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9901     sp_sb_data.igu_seg_id      = igu_seg_id;
9902     sp_sb_data.p_func.pf_id    = func;
9903     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9904     sp_sb_data.p_func.vf_id    = 0xff;
9905
9906     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9907
9908     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9909 }
9910
9911 static void
9912 bxe_init_sp_ring(struct bxe_softc *sc)
9913 {
9914     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9915     sc->spq_prod_idx = 0;
9916     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9917     sc->spq_prod_bd = sc->spq;
9918     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9919 }
9920
9921 static void
9922 bxe_init_eq_ring(struct bxe_softc *sc)
9923 {
9924     union event_ring_elem *elem;
9925     int i;
9926
9927     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9928         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9929
9930         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9931                                                  BCM_PAGE_SIZE *
9932                                                  (i % NUM_EQ_PAGES)));
9933         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9934                                                  BCM_PAGE_SIZE *
9935                                                  (i % NUM_EQ_PAGES)));
9936     }
9937
9938     sc->eq_cons    = 0;
9939     sc->eq_prod    = NUM_EQ_DESC;
9940     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9941
9942     atomic_store_rel_long(&sc->eq_spq_left,
9943                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9944                                NUM_EQ_DESC) - 1));
9945 }
9946
9947 static void
9948 bxe_init_internal_common(struct bxe_softc *sc)
9949 {
9950     int i;
9951
9952     /*
9953      * Zero this manually as its initialization is currently missing
9954      * in the initTool.
9955      */
9956     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9957         REG_WR(sc,
9958                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9959                0);
9960     }
9961
9962     if (!CHIP_IS_E1x(sc)) {
9963         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9964                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9965     }
9966 }
9967
9968 static void
9969 bxe_init_internal(struct bxe_softc *sc,
9970                   uint32_t         load_code)
9971 {
9972     switch (load_code) {
9973     case FW_MSG_CODE_DRV_LOAD_COMMON:
9974     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9975         bxe_init_internal_common(sc);
9976         /* no break */
9977
9978     case FW_MSG_CODE_DRV_LOAD_PORT:
9979         /* nothing to do */
9980         /* no break */
9981
9982     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9983         /* internal memory per function is initialized inside bxe_pf_init */
9984         break;
9985
9986     default:
9987         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9988         break;
9989     }
9990 }
9991
9992 static void
9993 storm_memset_func_cfg(struct bxe_softc                         *sc,
9994                       struct tstorm_eth_function_common_config *tcfg,
9995                       uint16_t                                  abs_fid)
9996 {
9997     uint32_t addr;
9998     size_t size;
9999
10000     addr = (BAR_TSTRORM_INTMEM +
10001             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
10002     size = sizeof(struct tstorm_eth_function_common_config);
10003     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
10004 }
10005
10006 static void
10007 bxe_func_init(struct bxe_softc            *sc,
10008               struct bxe_func_init_params *p)
10009 {
10010     struct tstorm_eth_function_common_config tcfg = { 0 };
10011
10012     if (CHIP_IS_E1x(sc)) {
10013         storm_memset_func_cfg(sc, &tcfg, p->func_id);
10014     }
10015
10016     /* Enable the function in the FW */
10017     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
10018     storm_memset_func_en(sc, p->func_id, 1);
10019
10020     /* spq */
10021     if (p->func_flgs & FUNC_FLG_SPQ) {
10022         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
10023         REG_WR(sc,
10024                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
10025                p->spq_prod);
10026     }
10027 }
10028
10029 /*
10030  * Calculates the sum of vn_min_rates.
10031  * It's needed for further normalizing of the min_rates.
10032  * Returns:
10033  *   sum of vn_min_rates.
10034  *     or
10035  *   0 - if all the min_rates are 0.
10036  * In the later case fainess algorithm should be deactivated.
10037  * If all min rates are not zero then those that are zeroes will be set to 1.
10038  */
10039 static void
10040 bxe_calc_vn_min(struct bxe_softc       *sc,
10041                 struct cmng_init_input *input)
10042 {
10043     uint32_t vn_cfg;
10044     uint32_t vn_min_rate;
10045     int all_zero = 1;
10046     int vn;
10047
10048     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10049         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10050         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
10051                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
10052
10053         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10054             /* skip hidden VNs */
10055             vn_min_rate = 0;
10056         } else if (!vn_min_rate) {
10057             /* If min rate is zero - set it to 100 */
10058             vn_min_rate = DEF_MIN_RATE;
10059         } else {
10060             all_zero = 0;
10061         }
10062
10063         input->vnic_min_rate[vn] = vn_min_rate;
10064     }
10065
10066     /* if ETS or all min rates are zeros - disable fairness */
10067     if (BXE_IS_ETS_ENABLED(sc)) {
10068         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10069         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10070     } else if (all_zero) {
10071         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10072         BLOGD(sc, DBG_LOAD,
10073               "Fariness disabled (all MIN values are zeroes)\n");
10074     } else {
10075         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10076     }
10077 }
10078
10079 static inline uint16_t
10080 bxe_extract_max_cfg(struct bxe_softc *sc,
10081                     uint32_t         mf_cfg)
10082 {
10083     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10084                         FUNC_MF_CFG_MAX_BW_SHIFT);
10085
10086     if (!max_cfg) {
10087         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10088         max_cfg = 100;
10089     }
10090
10091     return (max_cfg);
10092 }
10093
10094 static void
10095 bxe_calc_vn_max(struct bxe_softc       *sc,
10096                 int                    vn,
10097                 struct cmng_init_input *input)
10098 {
10099     uint16_t vn_max_rate;
10100     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10101     uint32_t max_cfg;
10102
10103     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10104         vn_max_rate = 0;
10105     } else {
10106         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10107
10108         if (IS_MF_SI(sc)) {
10109             /* max_cfg in percents of linkspeed */
10110             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10111         } else { /* SD modes */
10112             /* max_cfg is absolute in 100Mb units */
10113             vn_max_rate = (max_cfg * 100);
10114         }
10115     }
10116
10117     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10118
10119     input->vnic_max_rate[vn] = vn_max_rate;
10120 }
10121
10122 static void
10123 bxe_cmng_fns_init(struct bxe_softc *sc,
10124                   uint8_t          read_cfg,
10125                   uint8_t          cmng_type)
10126 {
10127     struct cmng_init_input input;
10128     int vn;
10129
10130     memset(&input, 0, sizeof(struct cmng_init_input));
10131
10132     input.port_rate = sc->link_vars.line_speed;
10133
10134     if (cmng_type == CMNG_FNS_MINMAX) {
10135         /* read mf conf from shmem */
10136         if (read_cfg) {
10137             bxe_read_mf_cfg(sc);
10138         }
10139
10140         /* get VN min rate and enable fairness if not 0 */
10141         bxe_calc_vn_min(sc, &input);
10142
10143         /* get VN max rate */
10144         if (sc->port.pmf) {
10145             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10146                 bxe_calc_vn_max(sc, vn, &input);
10147             }
10148         }
10149
10150         /* always enable rate shaping and fairness */
10151         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10152
10153         ecore_init_cmng(&input, &sc->cmng);
10154         return;
10155     }
10156
10157     /* rate shaping and fairness are disabled */
10158     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10159 }
10160
10161 static int
10162 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10163 {
10164     if (CHIP_REV_IS_SLOW(sc)) {
10165         return (CMNG_FNS_NONE);
10166     }
10167
10168     if (IS_MF(sc)) {
10169         return (CMNG_FNS_MINMAX);
10170     }
10171
10172     return (CMNG_FNS_NONE);
10173 }
10174
10175 static void
10176 storm_memset_cmng(struct bxe_softc *sc,
10177                   struct cmng_init *cmng,
10178                   uint8_t          port)
10179 {
10180     int vn;
10181     int func;
10182     uint32_t addr;
10183     size_t size;
10184
10185     addr = (BAR_XSTRORM_INTMEM +
10186             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10187     size = sizeof(struct cmng_struct_per_port);
10188     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10189
10190     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10191         func = func_by_vn(sc, vn);
10192
10193         addr = (BAR_XSTRORM_INTMEM +
10194                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10195         size = sizeof(struct rate_shaping_vars_per_vn);
10196         ecore_storm_memset_struct(sc, addr, size,
10197                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10198
10199         addr = (BAR_XSTRORM_INTMEM +
10200                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10201         size = sizeof(struct fairness_vars_per_vn);
10202         ecore_storm_memset_struct(sc, addr, size,
10203                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10204     }
10205 }
10206
10207 static void
10208 bxe_pf_init(struct bxe_softc *sc)
10209 {
10210     struct bxe_func_init_params func_init = { 0 };
10211     struct event_ring_data eq_data = { { 0 } };
10212     uint16_t flags;
10213
10214     if (!CHIP_IS_E1x(sc)) {
10215         /* reset IGU PF statistics: MSIX + ATTN */
10216         /* PF */
10217         REG_WR(sc,
10218                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10219                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10220                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10221                0);
10222         /* ATTN */
10223         REG_WR(sc,
10224                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10225                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10226                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10227                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10228                0);
10229     }
10230
10231     /* function setup flags */
10232     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10233
10234     /*
10235      * This flag is relevant for E1x only.
10236      * E2 doesn't have a TPA configuration in a function level.
10237      */
10238     flags |= (sc->ifnet->if_capenable & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10239
10240     func_init.func_flgs = flags;
10241     func_init.pf_id     = SC_FUNC(sc);
10242     func_init.func_id   = SC_FUNC(sc);
10243     func_init.spq_map   = sc->spq_dma.paddr;
10244     func_init.spq_prod  = sc->spq_prod_idx;
10245
10246     bxe_func_init(sc, &func_init);
10247
10248     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10249
10250     /*
10251      * Congestion management values depend on the link rate.
10252      * There is no active link so initial link rate is set to 10Gbps.
10253      * When the link comes up the congestion management values are
10254      * re-calculated according to the actual link rate.
10255      */
10256     sc->link_vars.line_speed = SPEED_10000;
10257     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10258
10259     /* Only the PMF sets the HW */
10260     if (sc->port.pmf) {
10261         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10262     }
10263
10264     /* init Event Queue - PCI bus guarantees correct endainity */
10265     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10266     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10267     eq_data.producer     = sc->eq_prod;
10268     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10269     eq_data.sb_id        = DEF_SB_ID;
10270     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10271 }
10272
10273 static void
10274 bxe_hc_int_enable(struct bxe_softc *sc)
10275 {
10276     int port = SC_PORT(sc);
10277     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10278     uint32_t val = REG_RD(sc, addr);
10279     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10280     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10281                            (sc->intr_count == 1)) ? TRUE : FALSE;
10282     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10283
10284     if (msix) {
10285         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10286                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10287         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10288                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10289         if (single_msix) {
10290             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10291         }
10292     } else if (msi) {
10293         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10294         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10295                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10296                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10297     } else {
10298         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10299                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10300                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10301                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10302
10303         if (!CHIP_IS_E1(sc)) {
10304             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10305                   val, port, addr);
10306
10307             REG_WR(sc, addr, val);
10308
10309             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10310         }
10311     }
10312
10313     if (CHIP_IS_E1(sc)) {
10314         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10315     }
10316
10317     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10318           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10319
10320     REG_WR(sc, addr, val);
10321
10322     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10323     mb();
10324
10325     if (!CHIP_IS_E1(sc)) {
10326         /* init leading/trailing edge */
10327         if (IS_MF(sc)) {
10328             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10329             if (sc->port.pmf) {
10330                 /* enable nig and gpio3 attention */
10331                 val |= 0x1100;
10332             }
10333         } else {
10334             val = 0xffff;
10335         }
10336
10337         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10338         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10339     }
10340
10341     /* make sure that interrupts are indeed enabled from here on */
10342     mb();
10343 }
10344
10345 static void
10346 bxe_igu_int_enable(struct bxe_softc *sc)
10347 {
10348     uint32_t val;
10349     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10350     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10351                            (sc->intr_count == 1)) ? TRUE : FALSE;
10352     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10353
10354     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10355
10356     if (msix) {
10357         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10358                  IGU_PF_CONF_SINGLE_ISR_EN);
10359         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10360                 IGU_PF_CONF_ATTN_BIT_EN);
10361         if (single_msix) {
10362             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10363         }
10364     } else if (msi) {
10365         val &= ~IGU_PF_CONF_INT_LINE_EN;
10366         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10367                 IGU_PF_CONF_ATTN_BIT_EN |
10368                 IGU_PF_CONF_SINGLE_ISR_EN);
10369     } else {
10370         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10371         val |= (IGU_PF_CONF_INT_LINE_EN |
10372                 IGU_PF_CONF_ATTN_BIT_EN |
10373                 IGU_PF_CONF_SINGLE_ISR_EN);
10374     }
10375
10376     /* clean previous status - need to configure igu prior to ack*/
10377     if ((!msix) || single_msix) {
10378         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10379         bxe_ack_int(sc);
10380     }
10381
10382     val |= IGU_PF_CONF_FUNC_EN;
10383
10384     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10385           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10386
10387     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10388
10389     mb();
10390
10391     /* init leading/trailing edge */
10392     if (IS_MF(sc)) {
10393         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10394         if (sc->port.pmf) {
10395             /* enable nig and gpio3 attention */
10396             val |= 0x1100;
10397         }
10398     } else {
10399         val = 0xffff;
10400     }
10401
10402     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10403     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10404
10405     /* make sure that interrupts are indeed enabled from here on */
10406     mb();
10407 }
10408
10409 static void
10410 bxe_int_enable(struct bxe_softc *sc)
10411 {
10412     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10413         bxe_hc_int_enable(sc);
10414     } else {
10415         bxe_igu_int_enable(sc);
10416     }
10417 }
10418
10419 static void
10420 bxe_hc_int_disable(struct bxe_softc *sc)
10421 {
10422     int port = SC_PORT(sc);
10423     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10424     uint32_t val = REG_RD(sc, addr);
10425
10426     /*
10427      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10428      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10429      * block
10430      */
10431     if (CHIP_IS_E1(sc)) {
10432         /*
10433          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10434          * to prevent from HC sending interrupts after we exit the function
10435          */
10436         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10437
10438         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10439                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10440                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10441     } else {
10442         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10443                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10444                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10445                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10446     }
10447
10448     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10449
10450     /* flush all outstanding writes */
10451     mb();
10452
10453     REG_WR(sc, addr, val);
10454     if (REG_RD(sc, addr) != val) {
10455         BLOGE(sc, "proper val not read from HC IGU!\n");
10456     }
10457 }
10458
10459 static void
10460 bxe_igu_int_disable(struct bxe_softc *sc)
10461 {
10462     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10463
10464     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10465              IGU_PF_CONF_INT_LINE_EN |
10466              IGU_PF_CONF_ATTN_BIT_EN);
10467
10468     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10469
10470     /* flush all outstanding writes */
10471     mb();
10472
10473     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10474     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10475         BLOGE(sc, "proper val not read from IGU!\n");
10476     }
10477 }
10478
10479 static void
10480 bxe_int_disable(struct bxe_softc *sc)
10481 {
10482     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10483         bxe_hc_int_disable(sc);
10484     } else {
10485         bxe_igu_int_disable(sc);
10486     }
10487 }
10488
10489 static void
10490 bxe_nic_init(struct bxe_softc *sc,
10491              int              load_code)
10492 {
10493     int i;
10494
10495     for (i = 0; i < sc->num_queues; i++) {
10496         bxe_init_eth_fp(sc, i);
10497     }
10498
10499     rmb(); /* ensure status block indices were read */
10500
10501     bxe_init_rx_rings(sc);
10502     bxe_init_tx_rings(sc);
10503
10504     if (IS_VF(sc)) {
10505         return;
10506     }
10507
10508     /* initialize MOD_ABS interrupts */
10509     elink_init_mod_abs_int(sc, &sc->link_vars,
10510                            sc->devinfo.chip_id,
10511                            sc->devinfo.shmem_base,
10512                            sc->devinfo.shmem2_base,
10513                            SC_PORT(sc));
10514
10515     bxe_init_def_sb(sc);
10516     bxe_update_dsb_idx(sc);
10517     bxe_init_sp_ring(sc);
10518     bxe_init_eq_ring(sc);
10519     bxe_init_internal(sc, load_code);
10520     bxe_pf_init(sc);
10521     bxe_stats_init(sc);
10522
10523     /* flush all before enabling interrupts */
10524     mb();
10525
10526     bxe_int_enable(sc);
10527
10528     /* check for SPIO5 */
10529     bxe_attn_int_deasserted0(sc,
10530                              REG_RD(sc,
10531                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10532                                      SC_PORT(sc)*4)) &
10533                              AEU_INPUTS_ATTN_BITS_SPIO5);
10534 }
10535
10536 static inline void
10537 bxe_init_objs(struct bxe_softc *sc)
10538 {
10539     /* mcast rules must be added to tx if tx switching is enabled */
10540     ecore_obj_type o_type =
10541         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10542                                          ECORE_OBJ_TYPE_RX;
10543
10544     /* RX_MODE controlling object */
10545     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10546
10547     /* multicast configuration controlling object */
10548     ecore_init_mcast_obj(sc,
10549                          &sc->mcast_obj,
10550                          sc->fp[0].cl_id,
10551                          sc->fp[0].index,
10552                          SC_FUNC(sc),
10553                          SC_FUNC(sc),
10554                          BXE_SP(sc, mcast_rdata),
10555                          BXE_SP_MAPPING(sc, mcast_rdata),
10556                          ECORE_FILTER_MCAST_PENDING,
10557                          &sc->sp_state,
10558                          o_type);
10559
10560     /* Setup CAM credit pools */
10561     ecore_init_mac_credit_pool(sc,
10562                                &sc->macs_pool,
10563                                SC_FUNC(sc),
10564                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10565                                                  VNICS_PER_PATH(sc));
10566
10567     ecore_init_vlan_credit_pool(sc,
10568                                 &sc->vlans_pool,
10569                                 SC_ABS_FUNC(sc) >> 1,
10570                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10571                                                   VNICS_PER_PATH(sc));
10572
10573     /* RSS configuration object */
10574     ecore_init_rss_config_obj(sc,
10575                               &sc->rss_conf_obj,
10576                               sc->fp[0].cl_id,
10577                               sc->fp[0].index,
10578                               SC_FUNC(sc),
10579                               SC_FUNC(sc),
10580                               BXE_SP(sc, rss_rdata),
10581                               BXE_SP_MAPPING(sc, rss_rdata),
10582                               ECORE_FILTER_RSS_CONF_PENDING,
10583                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10584 }
10585
10586 /*
10587  * Initialize the function. This must be called before sending CLIENT_SETUP
10588  * for the first client.
10589  */
10590 static inline int
10591 bxe_func_start(struct bxe_softc *sc)
10592 {
10593     struct ecore_func_state_params func_params = { NULL };
10594     struct ecore_func_start_params *start_params = &func_params.params.start;
10595
10596     /* Prepare parameters for function state transitions */
10597     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10598
10599     func_params.f_obj = &sc->func_obj;
10600     func_params.cmd = ECORE_F_CMD_START;
10601
10602     /* Function parameters */
10603     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10604     start_params->sd_vlan_tag = OVLAN(sc);
10605
10606     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10607         start_params->network_cos_mode = STATIC_COS;
10608     } else { /* CHIP_IS_E1X */
10609         start_params->network_cos_mode = FW_WRR;
10610     }
10611
10612     //start_params->gre_tunnel_mode = 0;
10613     //start_params->gre_tunnel_rss  = 0;
10614
10615     return (ecore_func_state_change(sc, &func_params));
10616 }
10617
10618 static int
10619 bxe_set_power_state(struct bxe_softc *sc,
10620                     uint8_t          state)
10621 {
10622     uint16_t pmcsr;
10623
10624     /* If there is no power capability, silently succeed */
10625     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10626         BLOGW(sc, "No power capability\n");
10627         return (0);
10628     }
10629
10630     pmcsr = pci_read_config(sc->dev,
10631                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10632                             2);
10633
10634     switch (state) {
10635     case PCI_PM_D0:
10636         pci_write_config(sc->dev,
10637                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10638                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10639
10640         if (pmcsr & PCIM_PSTAT_DMASK) {
10641             /* delay required during transition out of D3hot */
10642             DELAY(20000);
10643         }
10644
10645         break;
10646
10647     case PCI_PM_D3hot:
10648         /* XXX if there are other clients above don't shut down the power */
10649
10650         /* don't shut down the power for emulation and FPGA */
10651         if (CHIP_REV_IS_SLOW(sc)) {
10652             return (0);
10653         }
10654
10655         pmcsr &= ~PCIM_PSTAT_DMASK;
10656         pmcsr |= PCIM_PSTAT_D3;
10657
10658         if (sc->wol) {
10659             pmcsr |= PCIM_PSTAT_PMEENABLE;
10660         }
10661
10662         pci_write_config(sc->dev,
10663                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10664                          pmcsr, 4);
10665
10666         /*
10667          * No more memory access after this point until device is brought back
10668          * to D0 state.
10669          */
10670         break;
10671
10672     default:
10673         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10674             state, pmcsr);
10675         return (-1);
10676     }
10677
10678     return (0);
10679 }
10680
10681
10682 /* return true if succeeded to acquire the lock */
10683 static uint8_t
10684 bxe_trylock_hw_lock(struct bxe_softc *sc,
10685                     uint32_t         resource)
10686 {
10687     uint32_t lock_status;
10688     uint32_t resource_bit = (1 << resource);
10689     int func = SC_FUNC(sc);
10690     uint32_t hw_lock_control_reg;
10691
10692     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10693
10694     /* Validating that the resource is within range */
10695     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10696         BLOGD(sc, DBG_LOAD,
10697               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10698               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10699         return (FALSE);
10700     }
10701
10702     if (func <= 5) {
10703         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10704     } else {
10705         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10706     }
10707
10708     /* try to acquire the lock */
10709     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10710     lock_status = REG_RD(sc, hw_lock_control_reg);
10711     if (lock_status & resource_bit) {
10712         return (TRUE);
10713     }
10714
10715     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10716         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10717         lock_status, resource_bit);
10718
10719     return (FALSE);
10720 }
10721
10722 /*
10723  * Get the recovery leader resource id according to the engine this function
10724  * belongs to. Currently only only 2 engines is supported.
10725  */
10726 static int
10727 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10728 {
10729     if (SC_PATH(sc)) {
10730         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10731     } else {
10732         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10733     }
10734 }
10735
10736 /* try to acquire a leader lock for current engine */
10737 static uint8_t
10738 bxe_trylock_leader_lock(struct bxe_softc *sc)
10739 {
10740     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10741 }
10742
10743 static int
10744 bxe_release_leader_lock(struct bxe_softc *sc)
10745 {
10746     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10747 }
10748
10749 /* close gates #2, #3 and #4 */
10750 static void
10751 bxe_set_234_gates(struct bxe_softc *sc,
10752                   uint8_t          close)
10753 {
10754     uint32_t val;
10755
10756     /* gates #2 and #4a are closed/opened for "not E1" only */
10757     if (!CHIP_IS_E1(sc)) {
10758         /* #4 */
10759         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10760         /* #2 */
10761         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10762     }
10763
10764     /* #3 */
10765     if (CHIP_IS_E1x(sc)) {
10766         /* prevent interrupts from HC on both ports */
10767         val = REG_RD(sc, HC_REG_CONFIG_1);
10768         REG_WR(sc, HC_REG_CONFIG_1,
10769                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10770                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10771
10772         val = REG_RD(sc, HC_REG_CONFIG_0);
10773         REG_WR(sc, HC_REG_CONFIG_0,
10774                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10775                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10776     } else {
10777         /* Prevent incomming interrupts in IGU */
10778         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10779
10780         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10781                (!close) ?
10782                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10783                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10784     }
10785
10786     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10787           close ? "closing" : "opening");
10788
10789     wmb();
10790 }
10791
10792 /* poll for pending writes bit, it should get cleared in no more than 1s */
10793 static int
10794 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10795 {
10796     uint32_t cnt = 1000;
10797     uint32_t pend_bits = 0;
10798
10799     do {
10800         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10801
10802         if (pend_bits == 0) {
10803             break;
10804         }
10805
10806         DELAY(1000);
10807     } while (--cnt > 0);
10808
10809     if (cnt == 0) {
10810         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10811         return (-1);
10812     }
10813
10814     return (0);
10815 }
10816
10817 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10818
10819 static void
10820 bxe_clp_reset_prep(struct bxe_softc *sc,
10821                    uint32_t         *magic_val)
10822 {
10823     /* Do some magic... */
10824     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10825     *magic_val = val & SHARED_MF_CLP_MAGIC;
10826     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10827 }
10828
10829 /* restore the value of the 'magic' bit */
10830 static void
10831 bxe_clp_reset_done(struct bxe_softc *sc,
10832                    uint32_t         magic_val)
10833 {
10834     /* Restore the 'magic' bit value... */
10835     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10836     MFCFG_WR(sc, shared_mf_config.clp_mb,
10837               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10838 }
10839
10840 /* prepare for MCP reset, takes care of CLP configurations */
10841 static void
10842 bxe_reset_mcp_prep(struct bxe_softc *sc,
10843                    uint32_t         *magic_val)
10844 {
10845     uint32_t shmem;
10846     uint32_t validity_offset;
10847
10848     /* set `magic' bit in order to save MF config */
10849     if (!CHIP_IS_E1(sc)) {
10850         bxe_clp_reset_prep(sc, magic_val);
10851     }
10852
10853     /* get shmem offset */
10854     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10855     validity_offset =
10856         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10857
10858     /* Clear validity map flags */
10859     if (shmem > 0) {
10860         REG_WR(sc, shmem + validity_offset, 0);
10861     }
10862 }
10863
10864 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10865 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10866
10867 static void
10868 bxe_mcp_wait_one(struct bxe_softc *sc)
10869 {
10870     /* special handling for emulation and FPGA (10 times longer) */
10871     if (CHIP_REV_IS_SLOW(sc)) {
10872         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10873     } else {
10874         DELAY((MCP_ONE_TIMEOUT) * 1000);
10875     }
10876 }
10877
10878 /* initialize shmem_base and waits for validity signature to appear */
10879 static int
10880 bxe_init_shmem(struct bxe_softc *sc)
10881 {
10882     int cnt = 0;
10883     uint32_t val = 0;
10884
10885     do {
10886         sc->devinfo.shmem_base     =
10887         sc->link_params.shmem_base =
10888             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10889
10890         if (sc->devinfo.shmem_base) {
10891             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10892             if (val & SHR_MEM_VALIDITY_MB)
10893                 return (0);
10894         }
10895
10896         bxe_mcp_wait_one(sc);
10897
10898     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10899
10900     BLOGE(sc, "BAD MCP validity signature\n");
10901
10902     return (-1);
10903 }
10904
10905 static int
10906 bxe_reset_mcp_comp(struct bxe_softc *sc,
10907                    uint32_t         magic_val)
10908 {
10909     int rc = bxe_init_shmem(sc);
10910
10911     /* Restore the `magic' bit value */
10912     if (!CHIP_IS_E1(sc)) {
10913         bxe_clp_reset_done(sc, magic_val);
10914     }
10915
10916     return (rc);
10917 }
10918
10919 static void
10920 bxe_pxp_prep(struct bxe_softc *sc)
10921 {
10922     if (!CHIP_IS_E1(sc)) {
10923         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10924         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10925         wmb();
10926     }
10927 }
10928
10929 /*
10930  * Reset the whole chip except for:
10931  *      - PCIE core
10932  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10933  *      - IGU
10934  *      - MISC (including AEU)
10935  *      - GRC
10936  *      - RBCN, RBCP
10937  */
10938 static void
10939 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10940                             uint8_t          global)
10941 {
10942     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10943     uint32_t global_bits2, stay_reset2;
10944
10945     /*
10946      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10947      * (per chip) blocks.
10948      */
10949     global_bits2 =
10950         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10951         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10952
10953     /*
10954      * Don't reset the following blocks.
10955      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10956      *            reset, as in 4 port device they might still be owned
10957      *            by the MCP (there is only one leader per path).
10958      */
10959     not_reset_mask1 =
10960         MISC_REGISTERS_RESET_REG_1_RST_HC |
10961         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10962         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10963
10964     not_reset_mask2 =
10965         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10966         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10967         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10968         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10969         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10970         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10971         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10972         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10973         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10974         MISC_REGISTERS_RESET_REG_2_PGLC |
10975         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10976         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10977         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10978         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10979         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10980         MISC_REGISTERS_RESET_REG_2_UMAC1;
10981
10982     /*
10983      * Keep the following blocks in reset:
10984      *  - all xxMACs are handled by the elink code.
10985      */
10986     stay_reset2 =
10987         MISC_REGISTERS_RESET_REG_2_XMAC |
10988         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10989
10990     /* Full reset masks according to the chip */
10991     reset_mask1 = 0xffffffff;
10992
10993     if (CHIP_IS_E1(sc))
10994         reset_mask2 = 0xffff;
10995     else if (CHIP_IS_E1H(sc))
10996         reset_mask2 = 0x1ffff;
10997     else if (CHIP_IS_E2(sc))
10998         reset_mask2 = 0xfffff;
10999     else /* CHIP_IS_E3 */
11000         reset_mask2 = 0x3ffffff;
11001
11002     /* Don't reset global blocks unless we need to */
11003     if (!global)
11004         reset_mask2 &= ~global_bits2;
11005
11006     /*
11007      * In case of attention in the QM, we need to reset PXP
11008      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
11009      * because otherwise QM reset would release 'close the gates' shortly
11010      * before resetting the PXP, then the PSWRQ would send a write
11011      * request to PGLUE. Then when PXP is reset, PGLUE would try to
11012      * read the payload data from PSWWR, but PSWWR would not
11013      * respond. The write queue in PGLUE would stuck, dmae commands
11014      * would not return. Therefore it's important to reset the second
11015      * reset register (containing the
11016      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
11017      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
11018      * bit).
11019      */
11020     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
11021            reset_mask2 & (~not_reset_mask2));
11022
11023     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
11024            reset_mask1 & (~not_reset_mask1));
11025
11026     mb();
11027     wmb();
11028
11029     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
11030            reset_mask2 & (~stay_reset2));
11031
11032     mb();
11033     wmb();
11034
11035     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
11036     wmb();
11037 }
11038
11039 static int
11040 bxe_process_kill(struct bxe_softc *sc,
11041                  uint8_t          global)
11042 {
11043     int cnt = 1000;
11044     uint32_t val = 0;
11045     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
11046     uint32_t tags_63_32 = 0;
11047
11048     /* Empty the Tetris buffer, wait for 1s */
11049     do {
11050         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
11051         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
11052         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
11053         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
11054         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
11055         if (CHIP_IS_E3(sc)) {
11056             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
11057         }
11058
11059         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11060             ((port_is_idle_0 & 0x1) == 0x1) &&
11061             ((port_is_idle_1 & 0x1) == 0x1) &&
11062             (pgl_exp_rom2 == 0xffffffff) &&
11063             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11064             break;
11065         DELAY(1000);
11066     } while (cnt-- > 0);
11067
11068     if (cnt <= 0) {
11069         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11070                   "are still outstanding read requests after 1s! "
11071                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11072                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11073               sr_cnt, blk_cnt, port_is_idle_0,
11074               port_is_idle_1, pgl_exp_rom2);
11075         return (-1);
11076     }
11077
11078     mb();
11079
11080     /* Close gates #2, #3 and #4 */
11081     bxe_set_234_gates(sc, TRUE);
11082
11083     /* Poll for IGU VQs for 57712 and newer chips */
11084     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11085         return (-1);
11086     }
11087
11088     /* XXX indicate that "process kill" is in progress to MCP */
11089
11090     /* clear "unprepared" bit */
11091     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11092     mb();
11093
11094     /* Make sure all is written to the chip before the reset */
11095     wmb();
11096
11097     /*
11098      * Wait for 1ms to empty GLUE and PCI-E core queues,
11099      * PSWHST, GRC and PSWRD Tetris buffer.
11100      */
11101     DELAY(1000);
11102
11103     /* Prepare to chip reset: */
11104     /* MCP */
11105     if (global) {
11106         bxe_reset_mcp_prep(sc, &val);
11107     }
11108
11109     /* PXP */
11110     bxe_pxp_prep(sc);
11111     mb();
11112
11113     /* reset the chip */
11114     bxe_process_kill_chip_reset(sc, global);
11115     mb();
11116
11117     /* clear errors in PGB */
11118     if (!CHIP_IS_E1(sc))
11119         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11120
11121     /* Recover after reset: */
11122     /* MCP */
11123     if (global && bxe_reset_mcp_comp(sc, val)) {
11124         return (-1);
11125     }
11126
11127     /* XXX add resetting the NO_MCP mode DB here */
11128
11129     /* Open the gates #2, #3 and #4 */
11130     bxe_set_234_gates(sc, FALSE);
11131
11132     /* XXX
11133      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11134      * re-enable attentions
11135      */
11136
11137     return (0);
11138 }
11139
11140 static int
11141 bxe_leader_reset(struct bxe_softc *sc)
11142 {
11143     int rc = 0;
11144     uint8_t global = bxe_reset_is_global(sc);
11145     uint32_t load_code;
11146
11147     /*
11148      * If not going to reset MCP, load "fake" driver to reset HW while
11149      * driver is owner of the HW.
11150      */
11151     if (!global && !BXE_NOMCP(sc)) {
11152         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11153                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11154         if (!load_code) {
11155             BLOGE(sc, "MCP response failure, aborting\n");
11156             rc = -1;
11157             goto exit_leader_reset;
11158         }
11159
11160         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11161             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11162             BLOGE(sc, "MCP unexpected response, aborting\n");
11163             rc = -1;
11164             goto exit_leader_reset2;
11165         }
11166
11167         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11168         if (!load_code) {
11169             BLOGE(sc, "MCP response failure, aborting\n");
11170             rc = -1;
11171             goto exit_leader_reset2;
11172         }
11173     }
11174
11175     /* try to recover after the failure */
11176     if (bxe_process_kill(sc, global)) {
11177         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11178         rc = -1;
11179         goto exit_leader_reset2;
11180     }
11181
11182     /*
11183      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11184      * state.
11185      */
11186     bxe_set_reset_done(sc);
11187     if (global) {
11188         bxe_clear_reset_global(sc);
11189     }
11190
11191 exit_leader_reset2:
11192
11193     /* unload "fake driver" if it was loaded */
11194     if (!global && !BXE_NOMCP(sc)) {
11195         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11196         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11197     }
11198
11199 exit_leader_reset:
11200
11201     sc->is_leader = 0;
11202     bxe_release_leader_lock(sc);
11203
11204     mb();
11205     return (rc);
11206 }
11207
11208 /*
11209  * prepare INIT transition, parameters configured:
11210  *   - HC configuration
11211  *   - Queue's CDU context
11212  */
11213 static void
11214 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11215                    struct bxe_fastpath            *fp,
11216                    struct ecore_queue_init_params *init_params)
11217 {
11218     uint8_t cos;
11219     int cxt_index, cxt_offset;
11220
11221     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11222     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11223
11224     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11225     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11226
11227     /* HC rate */
11228     init_params->rx.hc_rate =
11229         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11230     init_params->tx.hc_rate =
11231         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11232
11233     /* FW SB ID */
11234     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11235
11236     /* CQ index among the SB indices */
11237     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11238     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11239
11240     /* set maximum number of COSs supported by this queue */
11241     init_params->max_cos = sc->max_cos;
11242
11243     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11244           fp->index, init_params->max_cos);
11245
11246     /* set the context pointers queue object */
11247     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11248         /* XXX change index/cid here if ever support multiple tx CoS */
11249         /* fp->txdata[cos]->cid */
11250         cxt_index = fp->index / ILT_PAGE_CIDS;
11251         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11252         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11253     }
11254 }
11255
11256 /* set flags that are common for the Tx-only and not normal connections */
11257 static unsigned long
11258 bxe_get_common_flags(struct bxe_softc    *sc,
11259                      struct bxe_fastpath *fp,
11260                      uint8_t             zero_stats)
11261 {
11262     unsigned long flags = 0;
11263
11264     /* PF driver will always initialize the Queue to an ACTIVE state */
11265     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11266
11267     /*
11268      * tx only connections collect statistics (on the same index as the
11269      * parent connection). The statistics are zeroed when the parent
11270      * connection is initialized.
11271      */
11272
11273     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11274     if (zero_stats) {
11275         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11276     }
11277
11278     /*
11279      * tx only connections can support tx-switching, though their
11280      * CoS-ness doesn't survive the loopback
11281      */
11282     if (sc->flags & BXE_TX_SWITCHING) {
11283         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11284     }
11285
11286     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11287
11288     return (flags);
11289 }
11290
11291 static unsigned long
11292 bxe_get_q_flags(struct bxe_softc    *sc,
11293                 struct bxe_fastpath *fp,
11294                 uint8_t             leading)
11295 {
11296     unsigned long flags = 0;
11297
11298     if (IS_MF_SD(sc)) {
11299         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11300     }
11301
11302     if (sc->ifnet->if_capenable & IFCAP_LRO) {
11303         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11304         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11305     }
11306
11307     if (leading) {
11308         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11309         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11310     }
11311
11312     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11313
11314     /* merge with common flags */
11315     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11316 }
11317
11318 static void
11319 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11320                       struct bxe_fastpath               *fp,
11321                       struct ecore_general_setup_params *gen_init,
11322                       uint8_t                           cos)
11323 {
11324     gen_init->stat_id = bxe_stats_id(fp);
11325     gen_init->spcl_id = fp->cl_id;
11326     gen_init->mtu = sc->mtu;
11327     gen_init->cos = cos;
11328 }
11329
11330 static void
11331 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11332                  struct bxe_fastpath           *fp,
11333                  struct rxq_pause_params       *pause,
11334                  struct ecore_rxq_setup_params *rxq_init)
11335 {
11336     uint8_t max_sge = 0;
11337     uint16_t sge_sz = 0;
11338     uint16_t tpa_agg_size = 0;
11339
11340     pause->sge_th_lo = SGE_TH_LO(sc);
11341     pause->sge_th_hi = SGE_TH_HI(sc);
11342
11343     /* validate SGE ring has enough to cross high threshold */
11344     if (sc->dropless_fc &&
11345             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11346             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11347         BLOGW(sc, "sge ring threshold limit\n");
11348     }
11349
11350     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11351     tpa_agg_size = (2 * sc->mtu);
11352     if (tpa_agg_size < sc->max_aggregation_size) {
11353         tpa_agg_size = sc->max_aggregation_size;
11354     }
11355
11356     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11357     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11358                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11359     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11360
11361     /* pause - not for e1 */
11362     if (!CHIP_IS_E1(sc)) {
11363         pause->bd_th_lo = BD_TH_LO(sc);
11364         pause->bd_th_hi = BD_TH_HI(sc);
11365
11366         pause->rcq_th_lo = RCQ_TH_LO(sc);
11367         pause->rcq_th_hi = RCQ_TH_HI(sc);
11368
11369         /* validate rings have enough entries to cross high thresholds */
11370         if (sc->dropless_fc &&
11371             pause->bd_th_hi + FW_PREFETCH_CNT >
11372             sc->rx_ring_size) {
11373             BLOGW(sc, "rx bd ring threshold limit\n");
11374         }
11375
11376         if (sc->dropless_fc &&
11377             pause->rcq_th_hi + FW_PREFETCH_CNT >
11378             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11379             BLOGW(sc, "rcq ring threshold limit\n");
11380         }
11381
11382         pause->pri_map = 1;
11383     }
11384
11385     /* rxq setup */
11386     rxq_init->dscr_map   = fp->rx_dma.paddr;
11387     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11388     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11389     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11390
11391     /*
11392      * This should be a maximum number of data bytes that may be
11393      * placed on the BD (not including paddings).
11394      */
11395     rxq_init->buf_sz = (fp->rx_buf_size -
11396                         IP_HEADER_ALIGNMENT_PADDING);
11397
11398     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11399     rxq_init->tpa_agg_sz      = tpa_agg_size;
11400     rxq_init->sge_buf_sz      = sge_sz;
11401     rxq_init->max_sges_pkt    = max_sge;
11402     rxq_init->rss_engine_id   = SC_FUNC(sc);
11403     rxq_init->mcast_engine_id = SC_FUNC(sc);
11404
11405     /*
11406      * Maximum number or simultaneous TPA aggregation for this Queue.
11407      * For PF Clients it should be the maximum available number.
11408      * VF driver(s) may want to define it to a smaller value.
11409      */
11410     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11411
11412     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11413     rxq_init->fw_sb_id = fp->fw_sb_id;
11414
11415     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11416
11417     /*
11418      * configure silent vlan removal
11419      * if multi function mode is afex, then mask default vlan
11420      */
11421     if (IS_MF_AFEX(sc)) {
11422         rxq_init->silent_removal_value =
11423             sc->devinfo.mf_info.afex_def_vlan_tag;
11424         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11425     }
11426 }
11427
11428 static void
11429 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11430                  struct bxe_fastpath           *fp,
11431                  struct ecore_txq_setup_params *txq_init,
11432                  uint8_t                       cos)
11433 {
11434     /*
11435      * XXX If multiple CoS is ever supported then each fastpath structure
11436      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11437      * fp->txdata[cos]->tx_dma.paddr;
11438      */
11439     txq_init->dscr_map     = fp->tx_dma.paddr;
11440     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11441     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11442     txq_init->fw_sb_id     = fp->fw_sb_id;
11443
11444     /*
11445      * set the TSS leading client id for TX classfication to the
11446      * leading RSS client id
11447      */
11448     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11449 }
11450
11451 /*
11452  * This function performs 2 steps in a queue state machine:
11453  *   1) RESET->INIT
11454  *   2) INIT->SETUP
11455  */
11456 static int
11457 bxe_setup_queue(struct bxe_softc    *sc,
11458                 struct bxe_fastpath *fp,
11459                 uint8_t             leading)
11460 {
11461     struct ecore_queue_state_params q_params = { NULL };
11462     struct ecore_queue_setup_params *setup_params =
11463                         &q_params.params.setup;
11464     int rc;
11465
11466     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11467
11468     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11469
11470     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11471
11472     /* we want to wait for completion in this context */
11473     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11474
11475     /* prepare the INIT parameters */
11476     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11477
11478     /* Set the command */
11479     q_params.cmd = ECORE_Q_CMD_INIT;
11480
11481     /* Change the state to INIT */
11482     rc = ecore_queue_state_change(sc, &q_params);
11483     if (rc) {
11484         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11485         return (rc);
11486     }
11487
11488     BLOGD(sc, DBG_LOAD, "init complete\n");
11489
11490     /* now move the Queue to the SETUP state */
11491     memset(setup_params, 0, sizeof(*setup_params));
11492
11493     /* set Queue flags */
11494     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11495
11496     /* set general SETUP parameters */
11497     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11498                           FIRST_TX_COS_INDEX);
11499
11500     bxe_pf_rx_q_prep(sc, fp,
11501                      &setup_params->pause_params,
11502                      &setup_params->rxq_params);
11503
11504     bxe_pf_tx_q_prep(sc, fp,
11505                      &setup_params->txq_params,
11506                      FIRST_TX_COS_INDEX);
11507
11508     /* Set the command */
11509     q_params.cmd = ECORE_Q_CMD_SETUP;
11510
11511     /* change the state to SETUP */
11512     rc = ecore_queue_state_change(sc, &q_params);
11513     if (rc) {
11514         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11515         return (rc);
11516     }
11517
11518     return (rc);
11519 }
11520
11521 static int
11522 bxe_setup_leading(struct bxe_softc *sc)
11523 {
11524     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11525 }
11526
11527 static int
11528 bxe_config_rss_pf(struct bxe_softc            *sc,
11529                   struct ecore_rss_config_obj *rss_obj,
11530                   uint8_t                     config_hash)
11531 {
11532     struct ecore_config_rss_params params = { NULL };
11533     int i;
11534
11535     /*
11536      * Although RSS is meaningless when there is a single HW queue we
11537      * still need it enabled in order to have HW Rx hash generated.
11538      */
11539
11540     params.rss_obj = rss_obj;
11541
11542     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11543
11544     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11545
11546     /* RSS configuration */
11547     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11548     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11549     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11550     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11551     if (rss_obj->udp_rss_v4) {
11552         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11553     }
11554     if (rss_obj->udp_rss_v6) {
11555         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11556     }
11557
11558     /* Hash bits */
11559     params.rss_result_mask = MULTI_MASK;
11560
11561     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11562
11563     if (config_hash) {
11564         /* RSS keys */
11565         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11566             params.rss_key[i] = arc4random();
11567         }
11568
11569         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11570     }
11571
11572     return (ecore_config_rss(sc, &params));
11573 }
11574
11575 static int
11576 bxe_config_rss_eth(struct bxe_softc *sc,
11577                    uint8_t          config_hash)
11578 {
11579     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11580 }
11581
11582 static int
11583 bxe_init_rss_pf(struct bxe_softc *sc)
11584 {
11585     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11586     int i;
11587
11588     /*
11589      * Prepare the initial contents of the indirection table if
11590      * RSS is enabled
11591      */
11592     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11593         sc->rss_conf_obj.ind_table[i] =
11594             (sc->fp->cl_id + (i % num_eth_queues));
11595     }
11596
11597     if (sc->udp_rss) {
11598         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11599     }
11600
11601     /*
11602      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11603      * per-port, so if explicit configuration is needed, do it only
11604      * for a PMF.
11605      *
11606      * For 57712 and newer it's a per-function configuration.
11607      */
11608     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11609 }
11610
11611 static int
11612 bxe_set_mac_one(struct bxe_softc          *sc,
11613                 uint8_t                   *mac,
11614                 struct ecore_vlan_mac_obj *obj,
11615                 uint8_t                   set,
11616                 int                       mac_type,
11617                 unsigned long             *ramrod_flags)
11618 {
11619     struct ecore_vlan_mac_ramrod_params ramrod_param;
11620     int rc;
11621
11622     memset(&ramrod_param, 0, sizeof(ramrod_param));
11623
11624     /* fill in general parameters */
11625     ramrod_param.vlan_mac_obj = obj;
11626     ramrod_param.ramrod_flags = *ramrod_flags;
11627
11628     /* fill a user request section if needed */
11629     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11630         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11631
11632         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11633
11634         /* Set the command: ADD or DEL */
11635         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11636                                             ECORE_VLAN_MAC_DEL;
11637     }
11638
11639     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11640
11641     if (rc == ECORE_EXISTS) {
11642         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11643         /* do not treat adding same MAC as error */
11644         rc = 0;
11645     } else if (rc < 0) {
11646         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11647     }
11648
11649     return (rc);
11650 }
11651
11652 static int
11653 bxe_set_eth_mac(struct bxe_softc *sc,
11654                 uint8_t          set)
11655 {
11656     unsigned long ramrod_flags = 0;
11657
11658     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11659
11660     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11661
11662     /* Eth MAC is set on RSS leading client (fp[0]) */
11663     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11664                             &sc->sp_objs->mac_obj,
11665                             set, ECORE_ETH_MAC, &ramrod_flags));
11666 }
11667
11668 static int
11669 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11670 {
11671     uint32_t sel_phy_idx = 0;
11672
11673     if (sc->link_params.num_phys <= 1) {
11674         return (ELINK_INT_PHY);
11675     }
11676
11677     if (sc->link_vars.link_up) {
11678         sel_phy_idx = ELINK_EXT_PHY1;
11679         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11680         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11681             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11682              ELINK_SUPPORTED_FIBRE))
11683             sel_phy_idx = ELINK_EXT_PHY2;
11684     } else {
11685         switch (elink_phy_selection(&sc->link_params)) {
11686         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11687         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11688         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11689                sel_phy_idx = ELINK_EXT_PHY1;
11690                break;
11691         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11692         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11693                sel_phy_idx = ELINK_EXT_PHY2;
11694                break;
11695         }
11696     }
11697
11698     return (sel_phy_idx);
11699 }
11700
11701 static int
11702 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11703 {
11704     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11705
11706     /*
11707      * The selected activated PHY is always after swapping (in case PHY
11708      * swapping is enabled). So when swapping is enabled, we need to reverse
11709      * the configuration
11710      */
11711
11712     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11713         if (sel_phy_idx == ELINK_EXT_PHY1)
11714             sel_phy_idx = ELINK_EXT_PHY2;
11715         else if (sel_phy_idx == ELINK_EXT_PHY2)
11716             sel_phy_idx = ELINK_EXT_PHY1;
11717     }
11718
11719     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11720 }
11721
11722 static void
11723 bxe_set_requested_fc(struct bxe_softc *sc)
11724 {
11725     /*
11726      * Initialize link parameters structure variables
11727      * It is recommended to turn off RX FC for jumbo frames
11728      * for better performance
11729      */
11730     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11731         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11732     } else {
11733         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11734     }
11735 }
11736
11737 static void
11738 bxe_calc_fc_adv(struct bxe_softc *sc)
11739 {
11740     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11741     switch (sc->link_vars.ieee_fc &
11742             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11743     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
11744     default:
11745         sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11746                                            ADVERTISED_Pause);
11747         break;
11748
11749     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11750         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11751                                           ADVERTISED_Pause);
11752         break;
11753
11754     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11755         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11756         break;
11757     }
11758 }
11759
11760 static uint16_t
11761 bxe_get_mf_speed(struct bxe_softc *sc)
11762 {
11763     uint16_t line_speed = sc->link_vars.line_speed;
11764     if (IS_MF(sc)) {
11765         uint16_t maxCfg =
11766             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11767
11768         /* calculate the current MAX line speed limit for the MF devices */
11769         if (IS_MF_SI(sc)) {
11770             line_speed = (line_speed * maxCfg) / 100;
11771         } else { /* SD mode */
11772             uint16_t vn_max_rate = maxCfg * 100;
11773
11774             if (vn_max_rate < line_speed) {
11775                 line_speed = vn_max_rate;
11776             }
11777         }
11778     }
11779
11780     return (line_speed);
11781 }
11782
11783 static void
11784 bxe_fill_report_data(struct bxe_softc            *sc,
11785                      struct bxe_link_report_data *data)
11786 {
11787     uint16_t line_speed = bxe_get_mf_speed(sc);
11788
11789     memset(data, 0, sizeof(*data));
11790
11791     /* fill the report data with the effective line speed */
11792     data->line_speed = line_speed;
11793
11794     /* Link is down */
11795     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11796         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11797     }
11798
11799     /* Full DUPLEX */
11800     if (sc->link_vars.duplex == DUPLEX_FULL) {
11801         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11802     }
11803
11804     /* Rx Flow Control is ON */
11805     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11806         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11807     }
11808
11809     /* Tx Flow Control is ON */
11810     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11811         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11812     }
11813 }
11814
11815 /* report link status to OS, should be called under phy_lock */
11816 static void
11817 bxe_link_report_locked(struct bxe_softc *sc)
11818 {
11819     struct bxe_link_report_data cur_data;
11820
11821     /* reread mf_cfg */
11822     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11823         bxe_read_mf_cfg(sc);
11824     }
11825
11826     /* Read the current link report info */
11827     bxe_fill_report_data(sc, &cur_data);
11828
11829     /* Don't report link down or exactly the same link status twice */
11830     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11831         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11832                       &sc->last_reported_link.link_report_flags) &&
11833          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11834                       &cur_data.link_report_flags))) {
11835         return;
11836     }
11837
11838     sc->link_cnt++;
11839
11840     /* report new link params and remember the state for the next time */
11841     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11842
11843     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11844                      &cur_data.link_report_flags)) {
11845         if_link_state_change(sc->ifnet, LINK_STATE_DOWN);
11846         BLOGI(sc, "NIC Link is Down\n");
11847     } else {
11848         const char *duplex;
11849         const char *flow;
11850
11851         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11852                                    &cur_data.link_report_flags)) {
11853             duplex = "full";
11854         } else {
11855             duplex = "half";
11856         }
11857
11858         /*
11859          * Handle the FC at the end so that only these flags would be
11860          * possibly set. This way we may easily check if there is no FC
11861          * enabled.
11862          */
11863         if (cur_data.link_report_flags) {
11864             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11865                              &cur_data.link_report_flags) &&
11866                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11867                              &cur_data.link_report_flags)) {
11868                 flow = "ON - receive & transmit";
11869             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11870                                     &cur_data.link_report_flags) &&
11871                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11872                                      &cur_data.link_report_flags)) {
11873                 flow = "ON - receive";
11874             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11875                                      &cur_data.link_report_flags) &&
11876                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11877                                     &cur_data.link_report_flags)) {
11878                 flow = "ON - transmit";
11879             } else {
11880                 flow = "none"; /* possible? */
11881             }
11882         } else {
11883             flow = "none";
11884         }
11885
11886         if_link_state_change(sc->ifnet, LINK_STATE_UP);
11887         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11888               cur_data.line_speed, duplex, flow);
11889     }
11890 }
11891
11892 static void
11893 bxe_link_report(struct bxe_softc *sc)
11894 {
11895     bxe_acquire_phy_lock(sc);
11896     bxe_link_report_locked(sc);
11897     bxe_release_phy_lock(sc);
11898 }
11899
11900 static void
11901 bxe_link_status_update(struct bxe_softc *sc)
11902 {
11903     if (sc->state != BXE_STATE_OPEN) {
11904         return;
11905     }
11906
11907     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11908         elink_link_status_update(&sc->link_params, &sc->link_vars);
11909     } else {
11910         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11911                                   ELINK_SUPPORTED_10baseT_Full |
11912                                   ELINK_SUPPORTED_100baseT_Half |
11913                                   ELINK_SUPPORTED_100baseT_Full |
11914                                   ELINK_SUPPORTED_1000baseT_Full |
11915                                   ELINK_SUPPORTED_2500baseX_Full |
11916                                   ELINK_SUPPORTED_10000baseT_Full |
11917                                   ELINK_SUPPORTED_TP |
11918                                   ELINK_SUPPORTED_FIBRE |
11919                                   ELINK_SUPPORTED_Autoneg |
11920                                   ELINK_SUPPORTED_Pause |
11921                                   ELINK_SUPPORTED_Asym_Pause);
11922         sc->port.advertising[0] = sc->port.supported[0];
11923
11924         sc->link_params.sc                = sc;
11925         sc->link_params.port              = SC_PORT(sc);
11926         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11927         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11928         sc->link_params.req_line_speed[0] = SPEED_10000;
11929         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11930         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11931
11932         if (CHIP_REV_IS_FPGA(sc)) {
11933             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11934             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11935             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11936                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11937         } else {
11938             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11939             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11940             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11941                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11942         }
11943
11944         sc->link_vars.link_up = 1;
11945
11946         sc->link_vars.duplex    = DUPLEX_FULL;
11947         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11948
11949         if (IS_PF(sc)) {
11950             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11951             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11952             bxe_link_report(sc);
11953         }
11954     }
11955
11956     if (IS_PF(sc)) {
11957         if (sc->link_vars.link_up) {
11958             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11959         } else {
11960             bxe_stats_handle(sc, STATS_EVENT_STOP);
11961         }
11962         bxe_link_report(sc);
11963     } else {
11964         bxe_link_report(sc);
11965         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11966     }
11967 }
11968
11969 static int
11970 bxe_initial_phy_init(struct bxe_softc *sc,
11971                      int              load_mode)
11972 {
11973     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11974     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11975     struct elink_params *lp = &sc->link_params;
11976
11977     bxe_set_requested_fc(sc);
11978
11979     if (CHIP_REV_IS_SLOW(sc)) {
11980         uint32_t bond = CHIP_BOND_ID(sc);
11981         uint32_t feat = 0;
11982
11983         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11984             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11985         } else if (bond & 0x4) {
11986             if (CHIP_IS_E3(sc)) {
11987                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11988             } else {
11989                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11990             }
11991         } else if (bond & 0x8) {
11992             if (CHIP_IS_E3(sc)) {
11993                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11994             } else {
11995                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11996             }
11997         }
11998
11999         /* disable EMAC for E3 and above */
12000         if (bond & 0x2) {
12001             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12002         }
12003
12004         sc->link_params.feature_config_flags |= feat;
12005     }
12006
12007     bxe_acquire_phy_lock(sc);
12008
12009     if (load_mode == LOAD_DIAG) {
12010         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
12011         /* Prefer doing PHY loopback at 10G speed, if possible */
12012         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
12013             if (lp->speed_cap_mask[cfg_idx] &
12014                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
12015                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
12016             } else {
12017                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
12018             }
12019         }
12020     }
12021
12022     if (load_mode == LOAD_LOOPBACK_EXT) {
12023         lp->loopback_mode = ELINK_LOOPBACK_EXT;
12024     }
12025
12026     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
12027
12028     bxe_release_phy_lock(sc);
12029
12030     bxe_calc_fc_adv(sc);
12031
12032     if (sc->link_vars.link_up) {
12033         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12034         bxe_link_report(sc);
12035     }
12036
12037     if (!CHIP_REV_IS_SLOW(sc)) {
12038         bxe_periodic_start(sc);
12039     }
12040
12041     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
12042     return (rc);
12043 }
12044
12045 /* must be called under IF_ADDR_LOCK */
12046 static int
12047 bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
12048                          struct ecore_mcast_ramrod_params *p)
12049 {
12050     struct ifnet *ifp = sc->ifnet;
12051     int mc_count = 0;
12052     struct ifmultiaddr *ifma;
12053     struct ecore_mcast_list_elem *mc_mac;
12054
12055     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12056         if (ifma->ifma_addr->sa_family != AF_LINK) {
12057             continue;
12058         }
12059
12060         mc_count++;
12061     }
12062
12063     ECORE_LIST_INIT(&p->mcast_list);
12064     p->mcast_list_len = 0;
12065
12066     if (!mc_count) {
12067         return (0);
12068     }
12069
12070     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12071                     (M_NOWAIT | M_ZERO));
12072     if (!mc_mac) {
12073         BLOGE(sc, "Failed to allocate temp mcast list\n");
12074         return (-1);
12075     }
12076     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12077
12078     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12079         if (ifma->ifma_addr->sa_family != AF_LINK) {
12080             continue;
12081         }
12082
12083         mc_mac->mac = (uint8_t *)LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
12084         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &p->mcast_list);
12085
12086         BLOGD(sc, DBG_LOAD,
12087               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
12088               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12089               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
12090
12091         mc_mac++;
12092     }
12093
12094     p->mcast_list_len = mc_count;
12095
12096     return (0);
12097 }
12098
12099 static void
12100 bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12101 {
12102     struct ecore_mcast_list_elem *mc_mac =
12103         ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12104                                struct ecore_mcast_list_elem,
12105                                link);
12106
12107     if (mc_mac) {
12108         /* only a single free as all mc_macs are in the same heap array */
12109         free(mc_mac, M_DEVBUF);
12110     }
12111 }
12112
12113 static int
12114 bxe_set_mc_list(struct bxe_softc *sc)
12115 {
12116     struct ecore_mcast_ramrod_params rparam = { NULL };
12117     int rc = 0;
12118
12119     rparam.mcast_obj = &sc->mcast_obj;
12120
12121     BXE_MCAST_LOCK(sc);
12122
12123     /* first, clear all configured multicast MACs */
12124     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12125     if (rc < 0) {
12126         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12127         BXE_MCAST_UNLOCK(sc);
12128         return (rc);
12129     }
12130
12131     /* configure a new MACs list */
12132     rc = bxe_init_mcast_macs_list(sc, &rparam);
12133     if (rc) {
12134         BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12135         BXE_MCAST_UNLOCK(sc);
12136         return (rc);
12137     }
12138
12139     /* Now add the new MACs */
12140     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12141     if (rc < 0) {
12142         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12143     }
12144
12145     bxe_free_mcast_macs_list(&rparam);
12146
12147     BXE_MCAST_UNLOCK(sc);
12148
12149     return (rc);
12150 }
12151
12152 static int
12153 bxe_set_uc_list(struct bxe_softc *sc)
12154 {
12155     struct ifnet *ifp = sc->ifnet;
12156     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12157     struct ifaddr *ifa;
12158     unsigned long ramrod_flags = 0;
12159     int rc;
12160
12161 #if __FreeBSD_version < 800000
12162     IF_ADDR_LOCK(ifp);
12163 #else
12164     if_addr_rlock(ifp);
12165 #endif
12166
12167     /* first schedule a cleanup up of old configuration */
12168     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12169     if (rc < 0) {
12170         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12171 #if __FreeBSD_version < 800000
12172         IF_ADDR_UNLOCK(ifp);
12173 #else
12174         if_addr_runlock(ifp);
12175 #endif
12176         return (rc);
12177     }
12178
12179     ifa = ifp->if_addr;
12180     while (ifa) {
12181         if (ifa->ifa_addr->sa_family != AF_LINK) {
12182             ifa = TAILQ_NEXT(ifa, ifa_link);
12183             continue;
12184         }
12185
12186         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12187                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12188         if (rc == -EEXIST) {
12189             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12190             /* do not treat adding same MAC as an error */
12191             rc = 0;
12192         } else if (rc < 0) {
12193             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12194 #if __FreeBSD_version < 800000
12195             IF_ADDR_UNLOCK(ifp);
12196 #else
12197             if_addr_runlock(ifp);
12198 #endif
12199             return (rc);
12200         }
12201
12202         ifa = TAILQ_NEXT(ifa, ifa_link);
12203     }
12204
12205 #if __FreeBSD_version < 800000
12206     IF_ADDR_UNLOCK(ifp);
12207 #else
12208     if_addr_runlock(ifp);
12209 #endif
12210
12211     /* Execute the pending commands */
12212     bit_set(&ramrod_flags, RAMROD_CONT);
12213     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12214                             ECORE_UC_LIST_MAC, &ramrod_flags));
12215 }
12216
12217 static void
12218 bxe_set_rx_mode(struct bxe_softc *sc)
12219 {
12220     struct ifnet *ifp = sc->ifnet;
12221     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12222
12223     if (sc->state != BXE_STATE_OPEN) {
12224         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12225         return;
12226     }
12227
12228     BLOGD(sc, DBG_SP, "ifp->if_flags=0x%x\n", ifp->if_flags);
12229
12230     if (ifp->if_flags & IFF_PROMISC) {
12231         rx_mode = BXE_RX_MODE_PROMISC;
12232     } else if ((ifp->if_flags & IFF_ALLMULTI) ||
12233                ((ifp->if_amcount > BXE_MAX_MULTICAST) &&
12234                 CHIP_IS_E1(sc))) {
12235         rx_mode = BXE_RX_MODE_ALLMULTI;
12236     } else {
12237         if (IS_PF(sc)) {
12238             /* some multicasts */
12239             if (bxe_set_mc_list(sc) < 0) {
12240                 rx_mode = BXE_RX_MODE_ALLMULTI;
12241             }
12242             if (bxe_set_uc_list(sc) < 0) {
12243                 rx_mode = BXE_RX_MODE_PROMISC;
12244             }
12245         }
12246     }
12247
12248     sc->rx_mode = rx_mode;
12249
12250     /* schedule the rx_mode command */
12251     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12252         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12253         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12254         return;
12255     }
12256
12257     if (IS_PF(sc)) {
12258         bxe_set_storm_rx_mode(sc);
12259     }
12260 }
12261
12262
12263 /* update flags in shmem */
12264 static void
12265 bxe_update_drv_flags(struct bxe_softc *sc,
12266                      uint32_t         flags,
12267                      uint32_t         set)
12268 {
12269     uint32_t drv_flags;
12270
12271     if (SHMEM2_HAS(sc, drv_flags)) {
12272         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12273         drv_flags = SHMEM2_RD(sc, drv_flags);
12274
12275         if (set) {
12276             SET_FLAGS(drv_flags, flags);
12277         } else {
12278             RESET_FLAGS(drv_flags, flags);
12279         }
12280
12281         SHMEM2_WR(sc, drv_flags, drv_flags);
12282         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12283
12284         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12285     }
12286 }
12287
12288 /* periodic timer callout routine, only runs when the interface is up */
12289
12290 static void
12291 bxe_periodic_callout_func(void *xsc)
12292 {
12293     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12294     struct bxe_fastpath *fp;
12295     uint16_t tx_bd_avail;
12296     int i;
12297
12298     if (!BXE_CORE_TRYLOCK(sc)) {
12299         /* just bail and try again next time */
12300
12301         if ((sc->state == BXE_STATE_OPEN) &&
12302             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12303             /* schedule the next periodic callout */
12304             callout_reset(&sc->periodic_callout, hz,
12305                           bxe_periodic_callout_func, sc);
12306         }
12307
12308         return;
12309     }
12310
12311     if ((sc->state != BXE_STATE_OPEN) ||
12312         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12313         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12314         BXE_CORE_UNLOCK(sc);
12315         return;
12316     }
12317
12318 #if __FreeBSD_version >= 800000
12319
12320     FOR_EACH_QUEUE(sc, i) {
12321         fp = &sc->fp[i];
12322
12323         if (BXE_FP_TX_TRYLOCK(fp)) {
12324             struct ifnet *ifp = sc->ifnet;
12325             /*
12326              * If interface was stopped due to unavailable
12327              * bds, try to process some tx completions
12328              */
12329             (void) bxe_txeof(sc, fp);
12330            
12331             tx_bd_avail = bxe_tx_avail(sc, fp);
12332             if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12333                 bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
12334             }
12335             BXE_FP_TX_UNLOCK(fp);
12336         }
12337     }
12338
12339 #else
12340
12341     fp = &sc->fp[0];
12342     if (BXE_FP_TX_TRYLOCK(fp)) {
12343         struct ifnet *ifp = sc->ifnet;
12344         /*
12345          * If interface was stopped due to unavailable
12346          * bds, try to process some tx completions
12347          */
12348         (void) bxe_txeof(sc, fp);
12349            
12350         tx_bd_avail = bxe_tx_avail(sc, fp);
12351         if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12352             bxe_tx_start_locked(sc, ifp, fp);
12353         }
12354  
12355         BXE_FP_TX_UNLOCK(fp);
12356     }
12357
12358 #endif /* #if __FreeBSD_version >= 800000 */
12359
12360     /* Check for TX timeouts on any fastpath. */
12361     FOR_EACH_QUEUE(sc, i) {
12362         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12363             /* Ruh-Roh, chip was reset! */
12364             break;
12365         }
12366     }
12367
12368     if (!CHIP_REV_IS_SLOW(sc)) {
12369         /*
12370          * This barrier is needed to ensure the ordering between the writing
12371          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12372          * the reading here.
12373          */
12374         mb();
12375         if (sc->port.pmf) {
12376             bxe_acquire_phy_lock(sc);
12377             elink_period_func(&sc->link_params, &sc->link_vars);
12378             bxe_release_phy_lock(sc);
12379         }
12380     }
12381
12382     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12383         int mb_idx = SC_FW_MB_IDX(sc);
12384         uint32_t drv_pulse;
12385         uint32_t mcp_pulse;
12386
12387         ++sc->fw_drv_pulse_wr_seq;
12388         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12389
12390         drv_pulse = sc->fw_drv_pulse_wr_seq;
12391         bxe_drv_pulse(sc);
12392
12393         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12394                      MCP_PULSE_SEQ_MASK);
12395
12396         /*
12397          * The delta between driver pulse and mcp response should
12398          * be 1 (before mcp response) or 0 (after mcp response).
12399          */
12400         if ((drv_pulse != mcp_pulse) &&
12401             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12402             /* someone lost a heartbeat... */
12403             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12404                   drv_pulse, mcp_pulse);
12405         }
12406     }
12407
12408     /* state is BXE_STATE_OPEN */
12409     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12410
12411     BXE_CORE_UNLOCK(sc);
12412
12413     if ((sc->state == BXE_STATE_OPEN) &&
12414         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12415         /* schedule the next periodic callout */
12416         callout_reset(&sc->periodic_callout, hz,
12417                       bxe_periodic_callout_func, sc);
12418     }
12419 }
12420
12421 static void
12422 bxe_periodic_start(struct bxe_softc *sc)
12423 {
12424     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12425     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12426 }
12427
12428 static void
12429 bxe_periodic_stop(struct bxe_softc *sc)
12430 {
12431     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12432     callout_drain(&sc->periodic_callout);
12433 }
12434
12435 /* start the controller */
12436 static __noinline int
12437 bxe_nic_load(struct bxe_softc *sc,
12438              int              load_mode)
12439 {
12440     uint32_t val;
12441     int load_code = 0;
12442     int i, rc = 0;
12443
12444     BXE_CORE_LOCK_ASSERT(sc);
12445
12446     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12447
12448     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12449
12450     if (IS_PF(sc)) {
12451         /* must be called before memory allocation and HW init */
12452         bxe_ilt_set_info(sc);
12453     }
12454
12455     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12456
12457     bxe_set_fp_rx_buf_size(sc);
12458
12459     if (bxe_alloc_fp_buffers(sc) != 0) {
12460         BLOGE(sc, "Failed to allocate fastpath memory\n");
12461         sc->state = BXE_STATE_CLOSED;
12462         rc = ENOMEM;
12463         goto bxe_nic_load_error0;
12464     }
12465
12466     if (bxe_alloc_mem(sc) != 0) {
12467         sc->state = BXE_STATE_CLOSED;
12468         rc = ENOMEM;
12469         goto bxe_nic_load_error0;
12470     }
12471
12472     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12473         sc->state = BXE_STATE_CLOSED;
12474         rc = ENOMEM;
12475         goto bxe_nic_load_error0;
12476     }
12477
12478     if (IS_PF(sc)) {
12479         /* set pf load just before approaching the MCP */
12480         bxe_set_pf_load(sc);
12481
12482         /* if MCP exists send load request and analyze response */
12483         if (!BXE_NOMCP(sc)) {
12484             /* attempt to load pf */
12485             if (bxe_nic_load_request(sc, &load_code) != 0) {
12486                 sc->state = BXE_STATE_CLOSED;
12487                 rc = ENXIO;
12488                 goto bxe_nic_load_error1;
12489             }
12490
12491             /* what did the MCP say? */
12492             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12493                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12494                 sc->state = BXE_STATE_CLOSED;
12495                 rc = ENXIO;
12496                 goto bxe_nic_load_error2;
12497             }
12498         } else {
12499             BLOGI(sc, "Device has no MCP!\n");
12500             load_code = bxe_nic_load_no_mcp(sc);
12501         }
12502
12503         /* mark PMF if applicable */
12504         bxe_nic_load_pmf(sc, load_code);
12505
12506         /* Init Function state controlling object */
12507         bxe_init_func_obj(sc);
12508
12509         /* Initialize HW */
12510         if (bxe_init_hw(sc, load_code) != 0) {
12511             BLOGE(sc, "HW init failed\n");
12512             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12513             sc->state = BXE_STATE_CLOSED;
12514             rc = ENXIO;
12515             goto bxe_nic_load_error2;
12516         }
12517     }
12518
12519     /* set ALWAYS_ALIVE bit in shmem */
12520     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12521     bxe_drv_pulse(sc);
12522     sc->flags |= BXE_NO_PULSE;
12523
12524     /* attach interrupts */
12525     if (bxe_interrupt_attach(sc) != 0) {
12526         sc->state = BXE_STATE_CLOSED;
12527         rc = ENXIO;
12528         goto bxe_nic_load_error2;
12529     }
12530
12531     bxe_nic_init(sc, load_code);
12532
12533     /* Init per-function objects */
12534     if (IS_PF(sc)) {
12535         bxe_init_objs(sc);
12536         // XXX bxe_iov_nic_init(sc);
12537
12538         /* set AFEX default VLAN tag to an invalid value */
12539         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12540         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12541
12542         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12543         rc = bxe_func_start(sc);
12544         if (rc) {
12545             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12546             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12547             sc->state = BXE_STATE_ERROR;
12548             goto bxe_nic_load_error3;
12549         }
12550
12551         /* send LOAD_DONE command to MCP */
12552         if (!BXE_NOMCP(sc)) {
12553             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12554             if (!load_code) {
12555                 BLOGE(sc, "MCP response failure, aborting\n");
12556                 sc->state = BXE_STATE_ERROR;
12557                 rc = ENXIO;
12558                 goto bxe_nic_load_error3;
12559             }
12560         }
12561
12562         rc = bxe_setup_leading(sc);
12563         if (rc) {
12564             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12565             sc->state = BXE_STATE_ERROR;
12566             goto bxe_nic_load_error3;
12567         }
12568
12569         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12570             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12571             if (rc) {
12572                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12573                 sc->state = BXE_STATE_ERROR;
12574                 goto bxe_nic_load_error3;
12575             }
12576         }
12577
12578         rc = bxe_init_rss_pf(sc);
12579         if (rc) {
12580             BLOGE(sc, "PF RSS init failed\n");
12581             sc->state = BXE_STATE_ERROR;
12582             goto bxe_nic_load_error3;
12583         }
12584     }
12585     /* XXX VF */
12586
12587     /* now when Clients are configured we are ready to work */
12588     sc->state = BXE_STATE_OPEN;
12589
12590     /* Configure a ucast MAC */
12591     if (IS_PF(sc)) {
12592         rc = bxe_set_eth_mac(sc, TRUE);
12593     }
12594     if (rc) {
12595         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12596         sc->state = BXE_STATE_ERROR;
12597         goto bxe_nic_load_error3;
12598     }
12599
12600     if (sc->port.pmf) {
12601         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12602         if (rc) {
12603             sc->state = BXE_STATE_ERROR;
12604             goto bxe_nic_load_error3;
12605         }
12606     }
12607
12608     sc->link_params.feature_config_flags &=
12609         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12610
12611     /* start fast path */
12612
12613     /* Initialize Rx filter */
12614     bxe_set_rx_mode(sc);
12615
12616     /* start the Tx */
12617     switch (/* XXX load_mode */LOAD_OPEN) {
12618     case LOAD_NORMAL:
12619     case LOAD_OPEN:
12620         break;
12621
12622     case LOAD_DIAG:
12623     case LOAD_LOOPBACK_EXT:
12624         sc->state = BXE_STATE_DIAG;
12625         break;
12626
12627     default:
12628         break;
12629     }
12630
12631     if (sc->port.pmf) {
12632         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12633     } else {
12634         bxe_link_status_update(sc);
12635     }
12636
12637     /* start the periodic timer callout */
12638     bxe_periodic_start(sc);
12639
12640     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12641         /* mark driver is loaded in shmem2 */
12642         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12643         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12644                   (val |
12645                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12646                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12647     }
12648
12649     /* wait for all pending SP commands to complete */
12650     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12651         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12652         bxe_periodic_stop(sc);
12653         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12654         return (ENXIO);
12655     }
12656
12657     /* Tell the stack the driver is running! */
12658     sc->ifnet->if_drv_flags = IFF_DRV_RUNNING;
12659
12660     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12661
12662     return (0);
12663
12664 bxe_nic_load_error3:
12665
12666     if (IS_PF(sc)) {
12667         bxe_int_disable_sync(sc, 1);
12668
12669         /* clean out queued objects */
12670         bxe_squeeze_objects(sc);
12671     }
12672
12673     bxe_interrupt_detach(sc);
12674
12675 bxe_nic_load_error2:
12676
12677     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12678         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12679         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12680     }
12681
12682     sc->port.pmf = 0;
12683
12684 bxe_nic_load_error1:
12685
12686     /* clear pf_load status, as it was already set */
12687     if (IS_PF(sc)) {
12688         bxe_clear_pf_load(sc);
12689     }
12690
12691 bxe_nic_load_error0:
12692
12693     bxe_free_fw_stats_mem(sc);
12694     bxe_free_fp_buffers(sc);
12695     bxe_free_mem(sc);
12696
12697     return (rc);
12698 }
12699
12700 static int
12701 bxe_init_locked(struct bxe_softc *sc)
12702 {
12703     int other_engine = SC_PATH(sc) ? 0 : 1;
12704     uint8_t other_load_status, load_status;
12705     uint8_t global = FALSE;
12706     int rc;
12707
12708     BXE_CORE_LOCK_ASSERT(sc);
12709
12710     /* check if the driver is already running */
12711     if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
12712         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12713         return (0);
12714     }
12715
12716     bxe_set_power_state(sc, PCI_PM_D0);
12717
12718     /*
12719      * If parity occurred during the unload, then attentions and/or
12720      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12721      * loaded on the current engine to complete the recovery. Parity recovery
12722      * is only relevant for PF driver.
12723      */
12724     if (IS_PF(sc)) {
12725         other_load_status = bxe_get_load_status(sc, other_engine);
12726         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12727
12728         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12729             bxe_chk_parity_attn(sc, &global, TRUE)) {
12730             do {
12731                 /*
12732                  * If there are attentions and they are in global blocks, set
12733                  * the GLOBAL_RESET bit regardless whether it will be this
12734                  * function that will complete the recovery or not.
12735                  */
12736                 if (global) {
12737                     bxe_set_reset_global(sc);
12738                 }
12739
12740                 /*
12741                  * Only the first function on the current engine should try
12742                  * to recover in open. In case of attentions in global blocks
12743                  * only the first in the chip should try to recover.
12744                  */
12745                 if ((!load_status && (!global || !other_load_status)) &&
12746                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12747                     BLOGI(sc, "Recovered during init\n");
12748                     break;
12749                 }
12750
12751                 /* recovery has failed... */
12752                 bxe_set_power_state(sc, PCI_PM_D3hot);
12753                 sc->recovery_state = BXE_RECOVERY_FAILED;
12754
12755                 BLOGE(sc, "Recovery flow hasn't properly "
12756                           "completed yet, try again later. "
12757                           "If you still see this message after a "
12758                           "few retries then power cycle is required.\n");
12759
12760                 rc = ENXIO;
12761                 goto bxe_init_locked_done;
12762             } while (0);
12763         }
12764     }
12765
12766     sc->recovery_state = BXE_RECOVERY_DONE;
12767
12768     rc = bxe_nic_load(sc, LOAD_OPEN);
12769
12770 bxe_init_locked_done:
12771
12772     if (rc) {
12773         /* Tell the stack the driver is NOT running! */
12774         BLOGE(sc, "Initialization failed, "
12775                   "stack notified driver is NOT running!\n");
12776         sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
12777     }
12778
12779     return (rc);
12780 }
12781
12782 static int
12783 bxe_stop_locked(struct bxe_softc *sc)
12784 {
12785     BXE_CORE_LOCK_ASSERT(sc);
12786     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12787 }
12788
12789 /*
12790  * Handles controller initialization when called from an unlocked routine.
12791  * ifconfig calls this function.
12792  *
12793  * Returns:
12794  *   void
12795  */
12796 static void
12797 bxe_init(void *xsc)
12798 {
12799     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12800
12801     BXE_CORE_LOCK(sc);
12802     bxe_init_locked(sc);
12803     BXE_CORE_UNLOCK(sc);
12804 }
12805
12806 static int
12807 bxe_init_ifnet(struct bxe_softc *sc)
12808 {
12809     struct ifnet *ifp;
12810
12811     /* ifconfig entrypoint for media type/status reporting */
12812     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12813                  bxe_ifmedia_update,
12814                  bxe_ifmedia_status);
12815
12816     /* set the default interface values */
12817     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12818     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12819     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12820
12821     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12822
12823     /* allocate the ifnet structure */
12824     if ((ifp = if_alloc(IFT_ETHER)) == NULL) {
12825         BLOGE(sc, "Interface allocation failed!\n");
12826         return (ENXIO);
12827     }
12828
12829     ifp->if_softc = sc;
12830     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12831     ifp->if_flags = (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
12832     ifp->if_ioctl = bxe_ioctl;
12833     ifp->if_start = bxe_tx_start;
12834 #if __FreeBSD_version >= 800000
12835     ifp->if_transmit = bxe_tx_mq_start;
12836     ifp->if_qflush = bxe_mq_flush;
12837 #endif
12838 #ifdef FreeBSD8_0
12839     ifp->if_timer = 0;
12840 #endif
12841     ifp->if_init = bxe_init;
12842     ifp->if_mtu = sc->mtu;
12843     ifp->if_hwassist = (CSUM_IP       |
12844                         CSUM_TCP      |
12845                         CSUM_UDP      |
12846                         CSUM_TSO      |
12847                         CSUM_TCP_IPV6 |
12848                         CSUM_UDP_IPV6);
12849     ifp->if_capabilities =
12850 #if __FreeBSD_version < 700000
12851         (IFCAP_VLAN_MTU       |
12852          IFCAP_VLAN_HWTAGGING |
12853          IFCAP_HWCSUM         |
12854          IFCAP_JUMBO_MTU      |
12855          IFCAP_LRO);
12856 #else
12857         (IFCAP_VLAN_MTU       |
12858          IFCAP_VLAN_HWTAGGING |
12859          IFCAP_VLAN_HWTSO     |
12860          IFCAP_VLAN_HWFILTER  |
12861          IFCAP_VLAN_HWCSUM    |
12862          IFCAP_HWCSUM         |
12863          IFCAP_JUMBO_MTU      |
12864          IFCAP_LRO            |
12865          IFCAP_TSO4           |
12866          IFCAP_TSO6           |
12867          IFCAP_WOL_MAGIC);
12868 #endif
12869     ifp->if_capenable = ifp->if_capabilities;
12870     ifp->if_capenable &= ~IFCAP_WOL_MAGIC; /* XXX not yet... */
12871 #if __FreeBSD_version < 1000025
12872     ifp->if_baudrate = 1000000000;
12873 #else
12874     if_initbaudrate(ifp, IF_Gbps(10));
12875 #endif
12876     ifp->if_snd.ifq_drv_maxlen = sc->tx_ring_size;
12877
12878     IFQ_SET_MAXLEN(&ifp->if_snd, ifp->if_snd.ifq_drv_maxlen);
12879     IFQ_SET_READY(&ifp->if_snd);
12880
12881     sc->ifnet = ifp;
12882
12883     /* attach to the Ethernet interface list */
12884     ether_ifattach(ifp, sc->link_params.mac_addr);
12885
12886     return (0);
12887 }
12888
12889 static void
12890 bxe_deallocate_bars(struct bxe_softc *sc)
12891 {
12892     int i;
12893
12894     for (i = 0; i < MAX_BARS; i++) {
12895         if (sc->bar[i].resource != NULL) {
12896             bus_release_resource(sc->dev,
12897                                  SYS_RES_MEMORY,
12898                                  sc->bar[i].rid,
12899                                  sc->bar[i].resource);
12900             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12901                   i, PCIR_BAR(i));
12902         }
12903     }
12904 }
12905
12906 static int
12907 bxe_allocate_bars(struct bxe_softc *sc)
12908 {
12909     u_int flags;
12910     int i;
12911
12912     memset(sc->bar, 0, sizeof(sc->bar));
12913
12914     for (i = 0; i < MAX_BARS; i++) {
12915
12916         /* memory resources reside at BARs 0, 2, 4 */
12917         /* Run `pciconf -lb` to see mappings */
12918         if ((i != 0) && (i != 2) && (i != 4)) {
12919             continue;
12920         }
12921
12922         sc->bar[i].rid = PCIR_BAR(i);
12923
12924         flags = RF_ACTIVE;
12925         if (i == 0) {
12926             flags |= RF_SHAREABLE;
12927         }
12928
12929         if ((sc->bar[i].resource =
12930              bus_alloc_resource_any(sc->dev,
12931                                     SYS_RES_MEMORY,
12932                                     &sc->bar[i].rid,
12933                                     flags)) == NULL) {
12934             return (0);
12935         }
12936
12937         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12938         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12939         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12940
12941         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%ld) -> %p\n",
12942               i, PCIR_BAR(i),
12943               (void *)rman_get_start(sc->bar[i].resource),
12944               (void *)rman_get_end(sc->bar[i].resource),
12945               rman_get_size(sc->bar[i].resource),
12946               (void *)sc->bar[i].kva);
12947     }
12948
12949     return (0);
12950 }
12951
12952 static void
12953 bxe_get_function_num(struct bxe_softc *sc)
12954 {
12955     uint32_t val = 0;
12956
12957     /*
12958      * Read the ME register to get the function number. The ME register
12959      * holds the relative-function number and absolute-function number. The
12960      * absolute-function number appears only in E2 and above. Before that
12961      * these bits always contained zero, therefore we cannot blindly use them.
12962      */
12963
12964     val = REG_RD(sc, BAR_ME_REGISTER);
12965
12966     sc->pfunc_rel =
12967         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12968     sc->path_id =
12969         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12970
12971     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12972         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12973     } else {
12974         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12975     }
12976
12977     BLOGD(sc, DBG_LOAD,
12978           "Relative function %d, Absolute function %d, Path %d\n",
12979           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12980 }
12981
12982 static uint32_t
12983 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12984 {
12985     uint32_t shmem2_size;
12986     uint32_t offset;
12987     uint32_t mf_cfg_offset_value;
12988
12989     /* Non 57712 */
12990     offset = (SHMEM_RD(sc, func_mb) +
12991               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12992
12993     /* 57712 plus */
12994     if (sc->devinfo.shmem2_base != 0) {
12995         shmem2_size = SHMEM2_RD(sc, size);
12996         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12997             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12998             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12999                 offset = mf_cfg_offset_value;
13000             }
13001         }
13002     }
13003
13004     return (offset);
13005 }
13006
13007 static uint32_t
13008 bxe_pcie_capability_read(struct bxe_softc *sc,
13009                          int    reg,
13010                          int    width)
13011 {
13012     int pcie_reg;
13013
13014     /* ensure PCIe capability is enabled */
13015     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
13016         if (pcie_reg != 0) {
13017             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
13018             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
13019         }
13020     }
13021
13022     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
13023
13024     return (0);
13025 }
13026
13027 static uint8_t
13028 bxe_is_pcie_pending(struct bxe_softc *sc)
13029 {
13030     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
13031             PCIM_EXP_STA_TRANSACTION_PND);
13032 }
13033
13034 /*
13035  * Walk the PCI capabiites list for the device to find what features are
13036  * supported. These capabilites may be enabled/disabled by firmware so it's
13037  * best to walk the list rather than make assumptions.
13038  */
13039 static void
13040 bxe_probe_pci_caps(struct bxe_softc *sc)
13041 {
13042     uint16_t link_status;
13043     int reg;
13044
13045     /* check if PCI Power Management is enabled */
13046     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
13047         if (reg != 0) {
13048             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
13049
13050             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
13051             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
13052         }
13053     }
13054
13055     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
13056
13057     /* handle PCIe 2.0 workarounds for 57710 */
13058     if (CHIP_IS_E1(sc)) {
13059         /* workaround for 57710 errata E4_57710_27462 */
13060         sc->devinfo.pcie_link_speed =
13061             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
13062
13063         /* workaround for 57710 errata E4_57710_27488 */
13064         sc->devinfo.pcie_link_width =
13065             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13066         if (sc->devinfo.pcie_link_speed > 1) {
13067             sc->devinfo.pcie_link_width =
13068                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
13069         }
13070     } else {
13071         sc->devinfo.pcie_link_speed =
13072             (link_status & PCIM_LINK_STA_SPEED);
13073         sc->devinfo.pcie_link_width =
13074             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13075     }
13076
13077     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
13078           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
13079
13080     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
13081     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
13082
13083     /* check if MSI capability is enabled */
13084     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
13085         if (reg != 0) {
13086             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13087
13088             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13089             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13090         }
13091     }
13092
13093     /* check if MSI-X capability is enabled */
13094     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13095         if (reg != 0) {
13096             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13097
13098             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13099             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13100         }
13101     }
13102 }
13103
13104 static int
13105 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13106 {
13107     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13108     uint32_t val;
13109
13110     /* get the outer vlan if we're in switch-dependent mode */
13111
13112     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13113     mf_info->ext_id = (uint16_t)val;
13114
13115     mf_info->multi_vnics_mode = 1;
13116
13117     if (!VALID_OVLAN(mf_info->ext_id)) {
13118         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13119         return (1);
13120     }
13121
13122     /* get the capabilities */
13123     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13124         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13125         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13126     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13127                FUNC_MF_CFG_PROTOCOL_FCOE) {
13128         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13129     } else {
13130         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13131     }
13132
13133     mf_info->vnics_per_port =
13134         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13135
13136     return (0);
13137 }
13138
13139 static uint32_t
13140 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13141 {
13142     uint32_t retval = 0;
13143     uint32_t val;
13144
13145     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13146
13147     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13148         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13149             retval |= MF_PROTO_SUPPORT_ETHERNET;
13150         }
13151         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13152             retval |= MF_PROTO_SUPPORT_ISCSI;
13153         }
13154         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13155             retval |= MF_PROTO_SUPPORT_FCOE;
13156         }
13157     }
13158
13159     return (retval);
13160 }
13161
13162 static int
13163 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13164 {
13165     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13166     uint32_t val;
13167
13168     /*
13169      * There is no outer vlan if we're in switch-independent mode.
13170      * If the mac is valid then assume multi-function.
13171      */
13172
13173     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13174
13175     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13176
13177     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13178
13179     mf_info->vnics_per_port =
13180         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13181
13182     return (0);
13183 }
13184
13185 static int
13186 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13187 {
13188     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13189     uint32_t e1hov_tag;
13190     uint32_t func_config;
13191     uint32_t niv_config;
13192
13193     mf_info->multi_vnics_mode = 1;
13194
13195     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13196     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13197     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13198
13199     mf_info->ext_id =
13200         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13201                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13202
13203     mf_info->default_vlan =
13204         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13205                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13206
13207     mf_info->niv_allowed_priorities =
13208         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13209                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13210
13211     mf_info->niv_default_cos =
13212         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13213                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13214
13215     mf_info->afex_vlan_mode =
13216         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13217          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13218
13219     mf_info->niv_mba_enabled =
13220         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13221          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13222
13223     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13224
13225     mf_info->vnics_per_port =
13226         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13227
13228     return (0);
13229 }
13230
13231 static int
13232 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13233 {
13234     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13235     uint32_t mf_cfg1;
13236     uint32_t mf_cfg2;
13237     uint32_t ovlan1;
13238     uint32_t ovlan2;
13239     uint8_t i, j;
13240
13241     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13242           SC_PORT(sc));
13243     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13244           mf_info->mf_config[SC_VN(sc)]);
13245     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13246           mf_info->multi_vnics_mode);
13247     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13248           mf_info->vnics_per_port);
13249     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13250           mf_info->ext_id);
13251     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13252           mf_info->min_bw[0], mf_info->min_bw[1],
13253           mf_info->min_bw[2], mf_info->min_bw[3]);
13254     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13255           mf_info->max_bw[0], mf_info->max_bw[1],
13256           mf_info->max_bw[2], mf_info->max_bw[3]);
13257     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13258           sc->mac_addr_str);
13259
13260     /* various MF mode sanity checks... */
13261
13262     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13263         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13264               SC_PORT(sc));
13265         return (1);
13266     }
13267
13268     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13269         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13270               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13271         return (1);
13272     }
13273
13274     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13275         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13276         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13277             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13278                   SC_VN(sc), OVLAN(sc));
13279             return (1);
13280         }
13281
13282         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13283             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13284                   mf_info->multi_vnics_mode, OVLAN(sc));
13285             return (1);
13286         }
13287
13288         /*
13289          * Verify all functions are either MF or SF mode. If MF, make sure
13290          * sure that all non-hidden functions have a valid ovlan. If SF,
13291          * make sure that all non-hidden functions have an invalid ovlan.
13292          */
13293         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13294             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13295             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13296             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13297                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13298                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13299                 BLOGE(sc, "mf_mode=SD function %d MF config "
13300                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13301                       i, mf_info->multi_vnics_mode, ovlan1);
13302                 return (1);
13303             }
13304         }
13305
13306         /* Verify all funcs on the same port each have a different ovlan. */
13307         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13308             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13309             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13310             /* iterate from the next function on the port to the max func */
13311             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13312                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13313                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13314                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13315                     VALID_OVLAN(ovlan1) &&
13316                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13317                     VALID_OVLAN(ovlan2) &&
13318                     (ovlan1 == ovlan2)) {
13319                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13320                               "have the same ovlan (%d)\n",
13321                           i, j, ovlan1);
13322                     return (1);
13323                 }
13324             }
13325         }
13326     } /* MULTI_FUNCTION_SD */
13327
13328     return (0);
13329 }
13330
13331 static int
13332 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13333 {
13334     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13335     uint32_t val, mac_upper;
13336     uint8_t i, vnic;
13337
13338     /* initialize mf_info defaults */
13339     mf_info->vnics_per_port   = 1;
13340     mf_info->multi_vnics_mode = FALSE;
13341     mf_info->path_has_ovlan   = FALSE;
13342     mf_info->mf_mode          = SINGLE_FUNCTION;
13343
13344     if (!CHIP_IS_MF_CAP(sc)) {
13345         return (0);
13346     }
13347
13348     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13349         BLOGE(sc, "Invalid mf_cfg_base!\n");
13350         return (1);
13351     }
13352
13353     /* get the MF mode (switch dependent / independent / single-function) */
13354
13355     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13356
13357     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13358     {
13359     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13360
13361         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13362
13363         /* check for legal upper mac bytes */
13364         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13365             mf_info->mf_mode = MULTI_FUNCTION_SI;
13366         } else {
13367             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13368         }
13369
13370         break;
13371
13372     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13373     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13374
13375         /* get outer vlan configuration */
13376         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13377
13378         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13379             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13380             mf_info->mf_mode = MULTI_FUNCTION_SD;
13381         } else {
13382             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13383         }
13384
13385         break;
13386
13387     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13388
13389         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13390         return (0);
13391
13392     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13393
13394         /*
13395          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13396          * and the MAC address is valid.
13397          */
13398         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13399
13400         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13401             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13402             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13403         } else {
13404             BLOGE(sc, "Invalid config for AFEX mode\n");
13405         }
13406
13407         break;
13408
13409     default:
13410
13411         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13412               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13413
13414         return (1);
13415     }
13416
13417     /* set path mf_mode (which could be different than function mf_mode) */
13418     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13419         mf_info->path_has_ovlan = TRUE;
13420     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13421         /*
13422          * Decide on path multi vnics mode. If we're not in MF mode and in
13423          * 4-port mode, this is good enough to check vnic-0 of the other port
13424          * on the same path
13425          */
13426         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13427             uint8_t other_port = !(PORT_ID(sc) & 1);
13428             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13429
13430             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13431
13432             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13433         }
13434     }
13435
13436     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13437         /* invalid MF config */
13438         if (SC_VN(sc) >= 1) {
13439             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13440             return (1);
13441         }
13442
13443         return (0);
13444     }
13445
13446     /* get the MF configuration */
13447     mf_info->mf_config[SC_VN(sc)] =
13448         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13449
13450     switch(mf_info->mf_mode)
13451     {
13452     case MULTI_FUNCTION_SD:
13453
13454         bxe_get_shmem_mf_cfg_info_sd(sc);
13455         break;
13456
13457     case MULTI_FUNCTION_SI:
13458
13459         bxe_get_shmem_mf_cfg_info_si(sc);
13460         break;
13461
13462     case MULTI_FUNCTION_AFEX:
13463
13464         bxe_get_shmem_mf_cfg_info_niv(sc);
13465         break;
13466
13467     default:
13468
13469         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13470               mf_info->mf_mode);
13471         return (1);
13472     }
13473
13474     /* get the congestion management parameters */
13475
13476     vnic = 0;
13477     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13478         /* get min/max bw */
13479         val = MFCFG_RD(sc, func_mf_config[i].config);
13480         mf_info->min_bw[vnic] =
13481             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13482         mf_info->max_bw[vnic] =
13483             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13484         vnic++;
13485     }
13486
13487     return (bxe_check_valid_mf_cfg(sc));
13488 }
13489
13490 static int
13491 bxe_get_shmem_info(struct bxe_softc *sc)
13492 {
13493     int port;
13494     uint32_t mac_hi, mac_lo, val;
13495
13496     port = SC_PORT(sc);
13497     mac_hi = mac_lo = 0;
13498
13499     sc->link_params.sc   = sc;
13500     sc->link_params.port = port;
13501
13502     /* get the hardware config info */
13503     sc->devinfo.hw_config =
13504         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13505     sc->devinfo.hw_config2 =
13506         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13507
13508     sc->link_params.hw_led_mode =
13509         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13510          SHARED_HW_CFG_LED_MODE_SHIFT);
13511
13512     /* get the port feature config */
13513     sc->port.config =
13514         SHMEM_RD(sc, dev_info.port_feature_config[port].config),
13515
13516     /* get the link params */
13517     sc->link_params.speed_cap_mask[0] =
13518         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13519     sc->link_params.speed_cap_mask[1] =
13520         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13521
13522     /* get the lane config */
13523     sc->link_params.lane_config =
13524         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13525
13526     /* get the link config */
13527     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13528     sc->port.link_config[ELINK_INT_PHY] = val;
13529     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13530     sc->port.link_config[ELINK_EXT_PHY1] =
13531         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13532
13533     /* get the override preemphasis flag and enable it or turn it off */
13534     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13535     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13536         sc->link_params.feature_config_flags |=
13537             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13538     } else {
13539         sc->link_params.feature_config_flags &=
13540             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13541     }
13542
13543     /* get the initial value of the link params */
13544     sc->link_params.multi_phy_config =
13545         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13546
13547     /* get external phy info */
13548     sc->port.ext_phy_config =
13549         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13550
13551     /* get the multifunction configuration */
13552     bxe_get_mf_cfg_info(sc);
13553
13554     /* get the mac address */
13555     if (IS_MF(sc)) {
13556         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13557         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13558     } else {
13559         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13560         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13561     }
13562
13563     if ((mac_lo == 0) && (mac_hi == 0)) {
13564         *sc->mac_addr_str = 0;
13565         BLOGE(sc, "No Ethernet address programmed!\n");
13566     } else {
13567         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13568         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13569         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13570         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13571         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13572         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13573         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13574                  "%02x:%02x:%02x:%02x:%02x:%02x",
13575                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13576                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13577                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13578         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13579     }
13580
13581     return (0);
13582 }
13583
13584 static void
13585 bxe_get_tunable_params(struct bxe_softc *sc)
13586 {
13587     /* sanity checks */
13588
13589     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13590         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13591         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13592         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13593         bxe_interrupt_mode = INTR_MODE_MSIX;
13594     }
13595
13596     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13597         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13598         bxe_queue_count = 0;
13599     }
13600
13601     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13602         if (bxe_max_rx_bufs == 0) {
13603             bxe_max_rx_bufs = RX_BD_USABLE;
13604         } else {
13605             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13606             bxe_max_rx_bufs = 2048;
13607         }
13608     }
13609
13610     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13611         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13612         bxe_hc_rx_ticks = 25;
13613     }
13614
13615     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13616         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13617         bxe_hc_tx_ticks = 50;
13618     }
13619
13620     if (bxe_max_aggregation_size == 0) {
13621         bxe_max_aggregation_size = TPA_AGG_SIZE;
13622     }
13623
13624     if (bxe_max_aggregation_size > 0xffff) {
13625         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13626               bxe_max_aggregation_size);
13627         bxe_max_aggregation_size = TPA_AGG_SIZE;
13628     }
13629
13630     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13631         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13632         bxe_mrrs = -1;
13633     }
13634
13635     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13636         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13637         bxe_autogreeen = 0;
13638     }
13639
13640     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13641         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13642         bxe_udp_rss = 0;
13643     }
13644
13645     /* pull in user settings */
13646
13647     sc->interrupt_mode       = bxe_interrupt_mode;
13648     sc->max_rx_bufs          = bxe_max_rx_bufs;
13649     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13650     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13651     sc->max_aggregation_size = bxe_max_aggregation_size;
13652     sc->mrrs                 = bxe_mrrs;
13653     sc->autogreeen           = bxe_autogreeen;
13654     sc->udp_rss              = bxe_udp_rss;
13655
13656     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13657         sc->num_queues = 1;
13658     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13659         sc->num_queues =
13660             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13661                 MAX_RSS_CHAINS);
13662         if (sc->num_queues > mp_ncpus) {
13663             sc->num_queues = mp_ncpus;
13664         }
13665     }
13666
13667     BLOGD(sc, DBG_LOAD,
13668           "User Config: "
13669           "debug=0x%lx "
13670           "interrupt_mode=%d "
13671           "queue_count=%d "
13672           "hc_rx_ticks=%d "
13673           "hc_tx_ticks=%d "
13674           "rx_budget=%d "
13675           "max_aggregation_size=%d "
13676           "mrrs=%d "
13677           "autogreeen=%d "
13678           "udp_rss=%d\n",
13679           bxe_debug,
13680           sc->interrupt_mode,
13681           sc->num_queues,
13682           sc->hc_rx_ticks,
13683           sc->hc_tx_ticks,
13684           bxe_rx_budget,
13685           sc->max_aggregation_size,
13686           sc->mrrs,
13687           sc->autogreeen,
13688           sc->udp_rss);
13689 }
13690
13691 static int
13692 bxe_media_detect(struct bxe_softc *sc)
13693 {
13694     int port_type;
13695     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13696
13697     switch (sc->link_params.phy[phy_idx].media_type) {
13698     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13699     case ELINK_ETH_PHY_XFP_FIBER:
13700         BLOGI(sc, "Found 10Gb Fiber media.\n");
13701         sc->media = IFM_10G_SR;
13702         port_type = PORT_FIBRE;
13703         break;
13704     case ELINK_ETH_PHY_SFP_1G_FIBER:
13705         BLOGI(sc, "Found 1Gb Fiber media.\n");
13706         sc->media = IFM_1000_SX;
13707         port_type = PORT_FIBRE;
13708         break;
13709     case ELINK_ETH_PHY_KR:
13710     case ELINK_ETH_PHY_CX4:
13711         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13712         sc->media = IFM_10G_CX4;
13713         port_type = PORT_FIBRE;
13714         break;
13715     case ELINK_ETH_PHY_DA_TWINAX:
13716         BLOGI(sc, "Found 10Gb Twinax media.\n");
13717         sc->media = IFM_10G_TWINAX;
13718         port_type = PORT_DA;
13719         break;
13720     case ELINK_ETH_PHY_BASE_T:
13721         if (sc->link_params.speed_cap_mask[0] &
13722             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13723             BLOGI(sc, "Found 10GBase-T media.\n");
13724             sc->media = IFM_10G_T;
13725             port_type = PORT_TP;
13726         } else {
13727             BLOGI(sc, "Found 1000Base-T media.\n");
13728             sc->media = IFM_1000_T;
13729             port_type = PORT_TP;
13730         }
13731         break;
13732     case ELINK_ETH_PHY_NOT_PRESENT:
13733         BLOGI(sc, "Media not present.\n");
13734         sc->media = 0;
13735         port_type = PORT_OTHER;
13736         break;
13737     case ELINK_ETH_PHY_UNSPECIFIED:
13738     default:
13739         BLOGI(sc, "Unknown media!\n");
13740         sc->media = 0;
13741         port_type = PORT_OTHER;
13742         break;
13743     }
13744     return port_type;
13745 }
13746
13747 #define GET_FIELD(value, fname)                     \
13748     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13749 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13750 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13751
13752 static int
13753 bxe_get_igu_cam_info(struct bxe_softc *sc)
13754 {
13755     int pfid = SC_FUNC(sc);
13756     int igu_sb_id;
13757     uint32_t val;
13758     uint8_t fid, igu_sb_cnt = 0;
13759
13760     sc->igu_base_sb = 0xff;
13761
13762     if (CHIP_INT_MODE_IS_BC(sc)) {
13763         int vn = SC_VN(sc);
13764         igu_sb_cnt = sc->igu_sb_cnt;
13765         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13766                            FP_SB_MAX_E1x);
13767         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13768                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13769         return (0);
13770     }
13771
13772     /* IGU in normal mode - read CAM */
13773     for (igu_sb_id = 0;
13774          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13775          igu_sb_id++) {
13776         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13777         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13778             continue;
13779         }
13780         fid = IGU_FID(val);
13781         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13782             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13783                 continue;
13784             }
13785             if (IGU_VEC(val) == 0) {
13786                 /* default status block */
13787                 sc->igu_dsb_id = igu_sb_id;
13788             } else {
13789                 if (sc->igu_base_sb == 0xff) {
13790                     sc->igu_base_sb = igu_sb_id;
13791                 }
13792                 igu_sb_cnt++;
13793             }
13794         }
13795     }
13796
13797     /*
13798      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13799      * that number of CAM entries will not be equal to the value advertised in
13800      * PCI. Driver should use the minimal value of both as the actual status
13801      * block count
13802      */
13803     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13804
13805     if (igu_sb_cnt == 0) {
13806         BLOGE(sc, "CAM configuration error\n");
13807         return (-1);
13808     }
13809
13810     return (0);
13811 }
13812
13813 /*
13814  * Gather various information from the device config space, the device itself,
13815  * shmem, and the user input.
13816  */
13817 static int
13818 bxe_get_device_info(struct bxe_softc *sc)
13819 {
13820     uint32_t val;
13821     int rc;
13822
13823     /* Get the data for the device */
13824     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13825     sc->devinfo.device_id    = pci_get_device(sc->dev);
13826     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13827     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13828
13829     /* get the chip revision (chip metal comes from pci config space) */
13830     sc->devinfo.chip_id     =
13831     sc->link_params.chip_id =
13832         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13833          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13834          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13835          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13836
13837     /* force 57811 according to MISC register */
13838     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13839         if (CHIP_IS_57810(sc)) {
13840             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13841                                    (sc->devinfo.chip_id & 0x0000ffff));
13842         } else if (CHIP_IS_57810_MF(sc)) {
13843             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13844                                    (sc->devinfo.chip_id & 0x0000ffff));
13845         }
13846         sc->devinfo.chip_id |= 0x1;
13847     }
13848
13849     BLOGD(sc, DBG_LOAD,
13850           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13851           sc->devinfo.chip_id,
13852           ((sc->devinfo.chip_id >> 16) & 0xffff),
13853           ((sc->devinfo.chip_id >> 12) & 0xf),
13854           ((sc->devinfo.chip_id >>  4) & 0xff),
13855           ((sc->devinfo.chip_id >>  0) & 0xf));
13856
13857     val = (REG_RD(sc, 0x2874) & 0x55);
13858     if ((sc->devinfo.chip_id & 0x1) ||
13859         (CHIP_IS_E1(sc) && val) ||
13860         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13861         sc->flags |= BXE_ONE_PORT_FLAG;
13862         BLOGD(sc, DBG_LOAD, "single port device\n");
13863     }
13864
13865     /* set the doorbell size */
13866     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13867
13868     /* determine whether the device is in 2 port or 4 port mode */
13869     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13870     if (CHIP_IS_E2E3(sc)) {
13871         /*
13872          * Read port4mode_en_ovwr[0]:
13873          *   If 1, four port mode is in port4mode_en_ovwr[1].
13874          *   If 0, four port mode is in port4mode_en[0].
13875          */
13876         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13877         if (val & 1) {
13878             val = ((val >> 1) & 1);
13879         } else {
13880             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13881         }
13882
13883         sc->devinfo.chip_port_mode =
13884             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13885
13886         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13887     }
13888
13889     /* get the function and path info for the device */
13890     bxe_get_function_num(sc);
13891
13892     /* get the shared memory base address */
13893     sc->devinfo.shmem_base     =
13894     sc->link_params.shmem_base =
13895         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13896     sc->devinfo.shmem2_base =
13897         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13898                                   MISC_REG_GENERIC_CR_0));
13899
13900     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13901           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13902
13903     if (!sc->devinfo.shmem_base) {
13904         /* this should ONLY prevent upcoming shmem reads */
13905         BLOGI(sc, "MCP not active\n");
13906         sc->flags |= BXE_NO_MCP_FLAG;
13907         return (0);
13908     }
13909
13910     /* make sure the shared memory contents are valid */
13911     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13912     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13913         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13914         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13915         return (0);
13916     }
13917     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13918
13919     /* get the bootcode version */
13920     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13921     snprintf(sc->devinfo.bc_ver_str,
13922              sizeof(sc->devinfo.bc_ver_str),
13923              "%d.%d.%d",
13924              ((sc->devinfo.bc_ver >> 24) & 0xff),
13925              ((sc->devinfo.bc_ver >> 16) & 0xff),
13926              ((sc->devinfo.bc_ver >>  8) & 0xff));
13927     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13928
13929     /* get the bootcode shmem address */
13930     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13931     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13932
13933     /* clean indirect addresses as they're not used */
13934     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13935     if (IS_PF(sc)) {
13936         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13937         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13938         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13939         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13940         if (CHIP_IS_E1x(sc)) {
13941             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13942             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13943             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13944             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13945         }
13946
13947         /*
13948          * Enable internal target-read (in case we are probed after PF
13949          * FLR). Must be done prior to any BAR read access. Only for
13950          * 57712 and up
13951          */
13952         if (!CHIP_IS_E1x(sc)) {
13953             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13954         }
13955     }
13956
13957     /* get the nvram size */
13958     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13959     sc->devinfo.flash_size =
13960         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13961     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13962
13963     /* get PCI capabilites */
13964     bxe_probe_pci_caps(sc);
13965
13966     bxe_set_power_state(sc, PCI_PM_D0);
13967
13968     /* get various configuration parameters from shmem */
13969     bxe_get_shmem_info(sc);
13970
13971     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13972         val = pci_read_config(sc->dev,
13973                               (sc->devinfo.pcie_msix_cap_reg +
13974                                PCIR_MSIX_CTRL),
13975                               2);
13976         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13977     } else {
13978         sc->igu_sb_cnt = 1;
13979     }
13980
13981     sc->igu_base_addr = BAR_IGU_INTMEM;
13982
13983     /* initialize IGU parameters */
13984     if (CHIP_IS_E1x(sc)) {
13985         sc->devinfo.int_block = INT_BLOCK_HC;
13986         sc->igu_dsb_id = DEF_SB_IGU_ID;
13987         sc->igu_base_sb = 0;
13988     } else {
13989         sc->devinfo.int_block = INT_BLOCK_IGU;
13990
13991         /* do not allow device reset during IGU info preocessing */
13992         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13993
13994         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13995
13996         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13997             int tout = 5000;
13998
13999             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
14000
14001             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
14002             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
14003             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
14004
14005             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14006                 tout--;
14007                 DELAY(1000);
14008             }
14009
14010             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14011                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
14012                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14013                 return (-1);
14014             }
14015         }
14016
14017         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
14018             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
14019             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
14020         } else {
14021             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
14022         }
14023
14024         rc = bxe_get_igu_cam_info(sc);
14025
14026         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14027
14028         if (rc) {
14029             return (rc);
14030         }
14031     }
14032
14033     /*
14034      * Get base FW non-default (fast path) status block ID. This value is
14035      * used to initialize the fw_sb_id saved on the fp/queue structure to
14036      * determine the id used by the FW.
14037      */
14038     if (CHIP_IS_E1x(sc)) {
14039         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
14040     } else {
14041         /*
14042          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
14043          * the same queue are indicated on the same IGU SB). So we prefer
14044          * FW and IGU SBs to be the same value.
14045          */
14046         sc->base_fw_ndsb = sc->igu_base_sb;
14047     }
14048
14049     BLOGD(sc, DBG_LOAD,
14050           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
14051           sc->igu_dsb_id, sc->igu_base_sb,
14052           sc->igu_sb_cnt, sc->base_fw_ndsb);
14053
14054     elink_phy_probe(&sc->link_params);
14055
14056     return (0);
14057 }
14058
14059 static void
14060 bxe_link_settings_supported(struct bxe_softc *sc,
14061                             uint32_t         switch_cfg)
14062 {
14063     uint32_t cfg_size = 0;
14064     uint32_t idx;
14065     uint8_t port = SC_PORT(sc);
14066
14067     /* aggregation of supported attributes of all external phys */
14068     sc->port.supported[0] = 0;
14069     sc->port.supported[1] = 0;
14070
14071     switch (sc->link_params.num_phys) {
14072     case 1:
14073         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
14074         cfg_size = 1;
14075         break;
14076     case 2:
14077         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
14078         cfg_size = 1;
14079         break;
14080     case 3:
14081         if (sc->link_params.multi_phy_config &
14082             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
14083             sc->port.supported[1] =
14084                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14085             sc->port.supported[0] =
14086                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14087         } else {
14088             sc->port.supported[0] =
14089                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14090             sc->port.supported[1] =
14091                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14092         }
14093         cfg_size = 2;
14094         break;
14095     }
14096
14097     if (!(sc->port.supported[0] || sc->port.supported[1])) {
14098         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14099               SHMEM_RD(sc,
14100                        dev_info.port_hw_config[port].external_phy_config),
14101               SHMEM_RD(sc,
14102                        dev_info.port_hw_config[port].external_phy_config2));
14103         return;
14104     }
14105
14106     if (CHIP_IS_E3(sc))
14107         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14108     else {
14109         switch (switch_cfg) {
14110         case ELINK_SWITCH_CFG_1G:
14111             sc->port.phy_addr =
14112                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14113             break;
14114         case ELINK_SWITCH_CFG_10G:
14115             sc->port.phy_addr =
14116                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14117             break;
14118         default:
14119             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14120                   sc->port.link_config[0]);
14121             return;
14122         }
14123     }
14124
14125     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14126
14127     /* mask what we support according to speed_cap_mask per configuration */
14128     for (idx = 0; idx < cfg_size; idx++) {
14129         if (!(sc->link_params.speed_cap_mask[idx] &
14130               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14131             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14132         }
14133
14134         if (!(sc->link_params.speed_cap_mask[idx] &
14135               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14136             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14137         }
14138
14139         if (!(sc->link_params.speed_cap_mask[idx] &
14140               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14141             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14142         }
14143
14144         if (!(sc->link_params.speed_cap_mask[idx] &
14145               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14146             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14147         }
14148
14149         if (!(sc->link_params.speed_cap_mask[idx] &
14150               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14151             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14152         }
14153
14154         if (!(sc->link_params.speed_cap_mask[idx] &
14155               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14156             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14157         }
14158
14159         if (!(sc->link_params.speed_cap_mask[idx] &
14160               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14161             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14162         }
14163
14164         if (!(sc->link_params.speed_cap_mask[idx] &
14165               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14166             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14167         }
14168     }
14169
14170     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14171           sc->port.supported[0], sc->port.supported[1]);
14172 }
14173
14174 static void
14175 bxe_link_settings_requested(struct bxe_softc *sc)
14176 {
14177     uint32_t link_config;
14178     uint32_t idx;
14179     uint32_t cfg_size = 0;
14180
14181     sc->port.advertising[0] = 0;
14182     sc->port.advertising[1] = 0;
14183
14184     switch (sc->link_params.num_phys) {
14185     case 1:
14186     case 2:
14187         cfg_size = 1;
14188         break;
14189     case 3:
14190         cfg_size = 2;
14191         break;
14192     }
14193
14194     for (idx = 0; idx < cfg_size; idx++) {
14195         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14196         link_config = sc->port.link_config[idx];
14197
14198         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14199         case PORT_FEATURE_LINK_SPEED_AUTO:
14200             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14201                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14202                 sc->port.advertising[idx] |= sc->port.supported[idx];
14203                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14204                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14205                     sc->port.advertising[idx] |=
14206                         (ELINK_SUPPORTED_100baseT_Half |
14207                          ELINK_SUPPORTED_100baseT_Full);
14208             } else {
14209                 /* force 10G, no AN */
14210                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14211                 sc->port.advertising[idx] |=
14212                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14213                 continue;
14214             }
14215             break;
14216
14217         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14218             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14219                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14220                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14221                                               ADVERTISED_TP);
14222             } else {
14223                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14224                           "speed_cap_mask=0x%08x\n",
14225                       link_config, sc->link_params.speed_cap_mask[idx]);
14226                 return;
14227             }
14228             break;
14229
14230         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14231             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14232                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14233                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14234                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14235                                               ADVERTISED_TP);
14236             } else {
14237                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14238                           "speed_cap_mask=0x%08x\n",
14239                       link_config, sc->link_params.speed_cap_mask[idx]);
14240                 return;
14241             }
14242             break;
14243
14244         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14245             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14246                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14247                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14248                                               ADVERTISED_TP);
14249             } else {
14250                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14251                           "speed_cap_mask=0x%08x\n",
14252                       link_config, sc->link_params.speed_cap_mask[idx]);
14253                 return;
14254             }
14255             break;
14256
14257         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14258             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14259                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14260                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14261                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14262                                               ADVERTISED_TP);
14263             } else {
14264                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14265                           "speed_cap_mask=0x%08x\n",
14266                       link_config, sc->link_params.speed_cap_mask[idx]);
14267                 return;
14268             }
14269             break;
14270
14271         case PORT_FEATURE_LINK_SPEED_1G:
14272             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14273                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14274                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14275                                               ADVERTISED_TP);
14276             } else {
14277                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14278                           "speed_cap_mask=0x%08x\n",
14279                       link_config, sc->link_params.speed_cap_mask[idx]);
14280                 return;
14281             }
14282             break;
14283
14284         case PORT_FEATURE_LINK_SPEED_2_5G:
14285             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14286                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14287                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14288                                               ADVERTISED_TP);
14289             } else {
14290                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14291                           "speed_cap_mask=0x%08x\n",
14292                       link_config, sc->link_params.speed_cap_mask[idx]);
14293                 return;
14294             }
14295             break;
14296
14297         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14298             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14299                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14300                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14301                                               ADVERTISED_FIBRE);
14302             } else {
14303                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14304                           "speed_cap_mask=0x%08x\n",
14305                       link_config, sc->link_params.speed_cap_mask[idx]);
14306                 return;
14307             }
14308             break;
14309
14310         case PORT_FEATURE_LINK_SPEED_20G:
14311             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14312             break;
14313
14314         default:
14315             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14316                       "speed_cap_mask=0x%08x\n",
14317                   link_config, sc->link_params.speed_cap_mask[idx]);
14318             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14319             sc->port.advertising[idx] = sc->port.supported[idx];
14320             break;
14321         }
14322
14323         sc->link_params.req_flow_ctrl[idx] =
14324             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14325
14326         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14327             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14328                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14329             } else {
14330                 bxe_set_requested_fc(sc);
14331             }
14332         }
14333
14334         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14335                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14336               sc->link_params.req_line_speed[idx],
14337               sc->link_params.req_duplex[idx],
14338               sc->link_params.req_flow_ctrl[idx],
14339               sc->port.advertising[idx]);
14340     }
14341 }
14342
14343 static void
14344 bxe_get_phy_info(struct bxe_softc *sc)
14345 {
14346     uint8_t port = SC_PORT(sc);
14347     uint32_t config = sc->port.config;
14348     uint32_t eee_mode;
14349
14350     /* shmem data already read in bxe_get_shmem_info() */
14351
14352     BLOGD(sc, DBG_LOAD, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14353                         "link_config0=0x%08x\n",
14354                sc->link_params.lane_config,
14355                sc->link_params.speed_cap_mask[0],
14356                sc->port.link_config[0]);
14357
14358     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14359     bxe_link_settings_requested(sc);
14360
14361     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14362         sc->link_params.feature_config_flags |=
14363             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14364     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14365         sc->link_params.feature_config_flags &=
14366             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14367     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14368         sc->link_params.feature_config_flags |=
14369             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14370     }
14371
14372     /* configure link feature according to nvram value */
14373     eee_mode =
14374         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14375           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14376          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14377     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14378         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14379                                     ELINK_EEE_MODE_ENABLE_LPI |
14380                                     ELINK_EEE_MODE_OUTPUT_TIME);
14381     } else {
14382         sc->link_params.eee_mode = 0;
14383     }
14384
14385     /* get the media type */
14386     bxe_media_detect(sc);
14387 }
14388
14389 static void
14390 bxe_get_params(struct bxe_softc *sc)
14391 {
14392     /* get user tunable params */
14393     bxe_get_tunable_params(sc);
14394
14395     /* select the RX and TX ring sizes */
14396     sc->tx_ring_size = TX_BD_USABLE;
14397     sc->rx_ring_size = RX_BD_USABLE;
14398
14399     /* XXX disable WoL */
14400     sc->wol = 0;
14401 }
14402
14403 static void
14404 bxe_set_modes_bitmap(struct bxe_softc *sc)
14405 {
14406     uint32_t flags = 0;
14407
14408     if (CHIP_REV_IS_FPGA(sc)) {
14409         SET_FLAGS(flags, MODE_FPGA);
14410     } else if (CHIP_REV_IS_EMUL(sc)) {
14411         SET_FLAGS(flags, MODE_EMUL);
14412     } else {
14413         SET_FLAGS(flags, MODE_ASIC);
14414     }
14415
14416     if (CHIP_IS_MODE_4_PORT(sc)) {
14417         SET_FLAGS(flags, MODE_PORT4);
14418     } else {
14419         SET_FLAGS(flags, MODE_PORT2);
14420     }
14421
14422     if (CHIP_IS_E2(sc)) {
14423         SET_FLAGS(flags, MODE_E2);
14424     } else if (CHIP_IS_E3(sc)) {
14425         SET_FLAGS(flags, MODE_E3);
14426         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14427             SET_FLAGS(flags, MODE_E3_A0);
14428         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14429             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14430         }
14431     }
14432
14433     if (IS_MF(sc)) {
14434         SET_FLAGS(flags, MODE_MF);
14435         switch (sc->devinfo.mf_info.mf_mode) {
14436         case MULTI_FUNCTION_SD:
14437             SET_FLAGS(flags, MODE_MF_SD);
14438             break;
14439         case MULTI_FUNCTION_SI:
14440             SET_FLAGS(flags, MODE_MF_SI);
14441             break;
14442         case MULTI_FUNCTION_AFEX:
14443             SET_FLAGS(flags, MODE_MF_AFEX);
14444             break;
14445         }
14446     } else {
14447         SET_FLAGS(flags, MODE_SF);
14448     }
14449
14450 #if defined(__LITTLE_ENDIAN)
14451     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14452 #else /* __BIG_ENDIAN */
14453     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14454 #endif
14455
14456     INIT_MODE_FLAGS(sc) = flags;
14457 }
14458
14459 static int
14460 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14461 {
14462     struct bxe_fastpath *fp;
14463     bus_addr_t busaddr;
14464     int max_agg_queues;
14465     int max_segments;
14466     bus_size_t max_size;
14467     bus_size_t max_seg_size;
14468     char buf[32];
14469     int rc;
14470     int i, j;
14471
14472     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14473
14474     /* allocate the parent bus DMA tag */
14475     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14476                             1,                        /* alignment */
14477                             0,                        /* boundary limit */
14478                             BUS_SPACE_MAXADDR,        /* restricted low */
14479                             BUS_SPACE_MAXADDR,        /* restricted hi */
14480                             NULL,                     /* addr filter() */
14481                             NULL,                     /* addr filter() arg */
14482                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14483                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14484                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14485                             0,                        /* flags */
14486                             NULL,                     /* lock() */
14487                             NULL,                     /* lock() arg */
14488                             &sc->parent_dma_tag);     /* returned dma tag */
14489     if (rc != 0) {
14490         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14491         return (1);
14492     }
14493
14494     /************************/
14495     /* DEFAULT STATUS BLOCK */
14496     /************************/
14497
14498     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14499                       &sc->def_sb_dma, "default status block") != 0) {
14500         /* XXX */
14501         bus_dma_tag_destroy(sc->parent_dma_tag);
14502         return (1);
14503     }
14504
14505     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14506
14507     /***************/
14508     /* EVENT QUEUE */
14509     /***************/
14510
14511     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14512                       &sc->eq_dma, "event queue") != 0) {
14513         /* XXX */
14514         bxe_dma_free(sc, &sc->def_sb_dma);
14515         sc->def_sb = NULL;
14516         bus_dma_tag_destroy(sc->parent_dma_tag);
14517         return (1);
14518     }
14519
14520     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14521
14522     /*************/
14523     /* SLOW PATH */
14524     /*************/
14525
14526     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14527                       &sc->sp_dma, "slow path") != 0) {
14528         /* XXX */
14529         bxe_dma_free(sc, &sc->eq_dma);
14530         sc->eq = NULL;
14531         bxe_dma_free(sc, &sc->def_sb_dma);
14532         sc->def_sb = NULL;
14533         bus_dma_tag_destroy(sc->parent_dma_tag);
14534         return (1);
14535     }
14536
14537     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14538
14539     /*******************/
14540     /* SLOW PATH QUEUE */
14541     /*******************/
14542
14543     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14544                       &sc->spq_dma, "slow path queue") != 0) {
14545         /* XXX */
14546         bxe_dma_free(sc, &sc->sp_dma);
14547         sc->sp = NULL;
14548         bxe_dma_free(sc, &sc->eq_dma);
14549         sc->eq = NULL;
14550         bxe_dma_free(sc, &sc->def_sb_dma);
14551         sc->def_sb = NULL;
14552         bus_dma_tag_destroy(sc->parent_dma_tag);
14553         return (1);
14554     }
14555
14556     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14557
14558     /***************************/
14559     /* FW DECOMPRESSION BUFFER */
14560     /***************************/
14561
14562     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14563                       "fw decompression buffer") != 0) {
14564         /* XXX */
14565         bxe_dma_free(sc, &sc->spq_dma);
14566         sc->spq = NULL;
14567         bxe_dma_free(sc, &sc->sp_dma);
14568         sc->sp = NULL;
14569         bxe_dma_free(sc, &sc->eq_dma);
14570         sc->eq = NULL;
14571         bxe_dma_free(sc, &sc->def_sb_dma);
14572         sc->def_sb = NULL;
14573         bus_dma_tag_destroy(sc->parent_dma_tag);
14574         return (1);
14575     }
14576
14577     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14578
14579     if ((sc->gz_strm =
14580          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14581         /* XXX */
14582         bxe_dma_free(sc, &sc->gz_buf_dma);
14583         sc->gz_buf = NULL;
14584         bxe_dma_free(sc, &sc->spq_dma);
14585         sc->spq = NULL;
14586         bxe_dma_free(sc, &sc->sp_dma);
14587         sc->sp = NULL;
14588         bxe_dma_free(sc, &sc->eq_dma);
14589         sc->eq = NULL;
14590         bxe_dma_free(sc, &sc->def_sb_dma);
14591         sc->def_sb = NULL;
14592         bus_dma_tag_destroy(sc->parent_dma_tag);
14593         return (1);
14594     }
14595
14596     /*************/
14597     /* FASTPATHS */
14598     /*************/
14599
14600     /* allocate DMA memory for each fastpath structure */
14601     for (i = 0; i < sc->num_queues; i++) {
14602         fp = &sc->fp[i];
14603         fp->sc    = sc;
14604         fp->index = i;
14605
14606         /*******************/
14607         /* FP STATUS BLOCK */
14608         /*******************/
14609
14610         snprintf(buf, sizeof(buf), "fp %d status block", i);
14611         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14612                           &fp->sb_dma, buf) != 0) {
14613             /* XXX unwind and free previous fastpath allocations */
14614             BLOGE(sc, "Failed to alloc %s\n", buf);
14615             return (1);
14616         } else {
14617             if (CHIP_IS_E2E3(sc)) {
14618                 fp->status_block.e2_sb =
14619                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14620             } else {
14621                 fp->status_block.e1x_sb =
14622                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14623             }
14624         }
14625
14626         /******************/
14627         /* FP TX BD CHAIN */
14628         /******************/
14629
14630         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14631         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14632                           &fp->tx_dma, buf) != 0) {
14633             /* XXX unwind and free previous fastpath allocations */
14634             BLOGE(sc, "Failed to alloc %s\n", buf);
14635             return (1);
14636         } else {
14637             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14638         }
14639
14640         /* link together the tx bd chain pages */
14641         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14642             /* index into the tx bd chain array to last entry per page */
14643             struct eth_tx_next_bd *tx_next_bd =
14644                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14645             /* point to the next page and wrap from last page */
14646             busaddr = (fp->tx_dma.paddr +
14647                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14648             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14649             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14650         }
14651
14652         /******************/
14653         /* FP RX BD CHAIN */
14654         /******************/
14655
14656         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14657         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14658                           &fp->rx_dma, buf) != 0) {
14659             /* XXX unwind and free previous fastpath allocations */
14660             BLOGE(sc, "Failed to alloc %s\n", buf);
14661             return (1);
14662         } else {
14663             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14664         }
14665
14666         /* link together the rx bd chain pages */
14667         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14668             /* index into the rx bd chain array to last entry per page */
14669             struct eth_rx_bd *rx_bd =
14670                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14671             /* point to the next page and wrap from last page */
14672             busaddr = (fp->rx_dma.paddr +
14673                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14674             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14675             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14676         }
14677
14678         /*******************/
14679         /* FP RX RCQ CHAIN */
14680         /*******************/
14681
14682         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14683         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14684                           &fp->rcq_dma, buf) != 0) {
14685             /* XXX unwind and free previous fastpath allocations */
14686             BLOGE(sc, "Failed to alloc %s\n", buf);
14687             return (1);
14688         } else {
14689             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14690         }
14691
14692         /* link together the rcq chain pages */
14693         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14694             /* index into the rcq chain array to last entry per page */
14695             struct eth_rx_cqe_next_page *rx_cqe_next =
14696                 (struct eth_rx_cqe_next_page *)
14697                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14698             /* point to the next page and wrap from last page */
14699             busaddr = (fp->rcq_dma.paddr +
14700                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14701             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14702             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14703         }
14704
14705         /*******************/
14706         /* FP RX SGE CHAIN */
14707         /*******************/
14708
14709         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14710         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14711                           &fp->rx_sge_dma, buf) != 0) {
14712             /* XXX unwind and free previous fastpath allocations */
14713             BLOGE(sc, "Failed to alloc %s\n", buf);
14714             return (1);
14715         } else {
14716             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14717         }
14718
14719         /* link together the sge chain pages */
14720         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14721             /* index into the rcq chain array to last entry per page */
14722             struct eth_rx_sge *rx_sge =
14723                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14724             /* point to the next page and wrap from last page */
14725             busaddr = (fp->rx_sge_dma.paddr +
14726                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14727             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14728             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14729         }
14730
14731         /***********************/
14732         /* FP TX MBUF DMA MAPS */
14733         /***********************/
14734
14735         /* set required sizes before mapping to conserve resources */
14736         if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
14737             max_size     = BXE_TSO_MAX_SIZE;
14738             max_segments = BXE_TSO_MAX_SEGMENTS;
14739             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14740         } else {
14741             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14742             max_segments = BXE_MAX_SEGMENTS;
14743             max_seg_size = MCLBYTES;
14744         }
14745
14746         /* create a dma tag for the tx mbufs */
14747         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14748                                 1,                  /* alignment */
14749                                 0,                  /* boundary limit */
14750                                 BUS_SPACE_MAXADDR,  /* restricted low */
14751                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14752                                 NULL,               /* addr filter() */
14753                                 NULL,               /* addr filter() arg */
14754                                 max_size,           /* max map size */
14755                                 max_segments,       /* num discontinuous */
14756                                 max_seg_size,       /* max seg size */
14757                                 0,                  /* flags */
14758                                 NULL,               /* lock() */
14759                                 NULL,               /* lock() arg */
14760                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14761         if (rc != 0) {
14762             /* XXX unwind and free previous fastpath allocations */
14763             BLOGE(sc, "Failed to create dma tag for "
14764                       "'fp %d tx mbufs' (%d)\n", i, rc);
14765             return (1);
14766         }
14767
14768         /* create dma maps for each of the tx mbuf clusters */
14769         for (j = 0; j < TX_BD_TOTAL; j++) {
14770             if (bus_dmamap_create(fp->tx_mbuf_tag,
14771                                   BUS_DMA_NOWAIT,
14772                                   &fp->tx_mbuf_chain[j].m_map)) {
14773                 /* XXX unwind and free previous fastpath allocations */
14774                 BLOGE(sc, "Failed to create dma map for "
14775                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14776                 return (1);
14777             }
14778         }
14779
14780         /***********************/
14781         /* FP RX MBUF DMA MAPS */
14782         /***********************/
14783
14784         /* create a dma tag for the rx mbufs */
14785         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14786                                 1,                  /* alignment */
14787                                 0,                  /* boundary limit */
14788                                 BUS_SPACE_MAXADDR,  /* restricted low */
14789                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14790                                 NULL,               /* addr filter() */
14791                                 NULL,               /* addr filter() arg */
14792                                 MJUM9BYTES,         /* max map size */
14793                                 1,                  /* num discontinuous */
14794                                 MJUM9BYTES,         /* max seg size */
14795                                 0,                  /* flags */
14796                                 NULL,               /* lock() */
14797                                 NULL,               /* lock() arg */
14798                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14799         if (rc != 0) {
14800             /* XXX unwind and free previous fastpath allocations */
14801             BLOGE(sc, "Failed to create dma tag for "
14802                       "'fp %d rx mbufs' (%d)\n", i, rc);
14803             return (1);
14804         }
14805
14806         /* create dma maps for each of the rx mbuf clusters */
14807         for (j = 0; j < RX_BD_TOTAL; j++) {
14808             if (bus_dmamap_create(fp->rx_mbuf_tag,
14809                                   BUS_DMA_NOWAIT,
14810                                   &fp->rx_mbuf_chain[j].m_map)) {
14811                 /* XXX unwind and free previous fastpath allocations */
14812                 BLOGE(sc, "Failed to create dma map for "
14813                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14814                 return (1);
14815             }
14816         }
14817
14818         /* create dma map for the spare rx mbuf cluster */
14819         if (bus_dmamap_create(fp->rx_mbuf_tag,
14820                               BUS_DMA_NOWAIT,
14821                               &fp->rx_mbuf_spare_map)) {
14822             /* XXX unwind and free previous fastpath allocations */
14823             BLOGE(sc, "Failed to create dma map for "
14824                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14825             return (1);
14826         }
14827
14828         /***************************/
14829         /* FP RX SGE MBUF DMA MAPS */
14830         /***************************/
14831
14832         /* create a dma tag for the rx sge mbufs */
14833         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14834                                 1,                  /* alignment */
14835                                 0,                  /* boundary limit */
14836                                 BUS_SPACE_MAXADDR,  /* restricted low */
14837                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14838                                 NULL,               /* addr filter() */
14839                                 NULL,               /* addr filter() arg */
14840                                 BCM_PAGE_SIZE,      /* max map size */
14841                                 1,                  /* num discontinuous */
14842                                 BCM_PAGE_SIZE,      /* max seg size */
14843                                 0,                  /* flags */
14844                                 NULL,               /* lock() */
14845                                 NULL,               /* lock() arg */
14846                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14847         if (rc != 0) {
14848             /* XXX unwind and free previous fastpath allocations */
14849             BLOGE(sc, "Failed to create dma tag for "
14850                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14851             return (1);
14852         }
14853
14854         /* create dma maps for the rx sge mbuf clusters */
14855         for (j = 0; j < RX_SGE_TOTAL; j++) {
14856             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14857                                   BUS_DMA_NOWAIT,
14858                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14859                 /* XXX unwind and free previous fastpath allocations */
14860                 BLOGE(sc, "Failed to create dma map for "
14861                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14862                 return (1);
14863             }
14864         }
14865
14866         /* create dma map for the spare rx sge mbuf cluster */
14867         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14868                               BUS_DMA_NOWAIT,
14869                               &fp->rx_sge_mbuf_spare_map)) {
14870             /* XXX unwind and free previous fastpath allocations */
14871             BLOGE(sc, "Failed to create dma map for "
14872                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14873             return (1);
14874         }
14875
14876         /***************************/
14877         /* FP RX TPA MBUF DMA MAPS */
14878         /***************************/
14879
14880         /* create dma maps for the rx tpa mbuf clusters */
14881         max_agg_queues = MAX_AGG_QS(sc);
14882
14883         for (j = 0; j < max_agg_queues; j++) {
14884             if (bus_dmamap_create(fp->rx_mbuf_tag,
14885                                   BUS_DMA_NOWAIT,
14886                                   &fp->rx_tpa_info[j].bd.m_map)) {
14887                 /* XXX unwind and free previous fastpath allocations */
14888                 BLOGE(sc, "Failed to create dma map for "
14889                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14890                 return (1);
14891             }
14892         }
14893
14894         /* create dma map for the spare rx tpa mbuf cluster */
14895         if (bus_dmamap_create(fp->rx_mbuf_tag,
14896                               BUS_DMA_NOWAIT,
14897                               &fp->rx_tpa_info_mbuf_spare_map)) {
14898             /* XXX unwind and free previous fastpath allocations */
14899             BLOGE(sc, "Failed to create dma map for "
14900                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14901             return (1);
14902         }
14903
14904         bxe_init_sge_ring_bit_mask(fp);
14905     }
14906
14907     return (0);
14908 }
14909
14910 static void
14911 bxe_free_hsi_mem(struct bxe_softc *sc)
14912 {
14913     struct bxe_fastpath *fp;
14914     int max_agg_queues;
14915     int i, j;
14916
14917     if (sc->parent_dma_tag == NULL) {
14918         return; /* assume nothing was allocated */
14919     }
14920
14921     for (i = 0; i < sc->num_queues; i++) {
14922         fp = &sc->fp[i];
14923
14924         /*******************/
14925         /* FP STATUS BLOCK */
14926         /*******************/
14927
14928         bxe_dma_free(sc, &fp->sb_dma);
14929         memset(&fp->status_block, 0, sizeof(fp->status_block));
14930
14931         /******************/
14932         /* FP TX BD CHAIN */
14933         /******************/
14934
14935         bxe_dma_free(sc, &fp->tx_dma);
14936         fp->tx_chain = NULL;
14937
14938         /******************/
14939         /* FP RX BD CHAIN */
14940         /******************/
14941
14942         bxe_dma_free(sc, &fp->rx_dma);
14943         fp->rx_chain = NULL;
14944
14945         /*******************/
14946         /* FP RX RCQ CHAIN */
14947         /*******************/
14948
14949         bxe_dma_free(sc, &fp->rcq_dma);
14950         fp->rcq_chain = NULL;
14951
14952         /*******************/
14953         /* FP RX SGE CHAIN */
14954         /*******************/
14955
14956         bxe_dma_free(sc, &fp->rx_sge_dma);
14957         fp->rx_sge_chain = NULL;
14958
14959         /***********************/
14960         /* FP TX MBUF DMA MAPS */
14961         /***********************/
14962
14963         if (fp->tx_mbuf_tag != NULL) {
14964             for (j = 0; j < TX_BD_TOTAL; j++) {
14965                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14966                     bus_dmamap_unload(fp->tx_mbuf_tag,
14967                                       fp->tx_mbuf_chain[j].m_map);
14968                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14969                                        fp->tx_mbuf_chain[j].m_map);
14970                 }
14971             }
14972
14973             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14974             fp->tx_mbuf_tag = NULL;
14975         }
14976
14977         /***********************/
14978         /* FP RX MBUF DMA MAPS */
14979         /***********************/
14980
14981         if (fp->rx_mbuf_tag != NULL) {
14982             for (j = 0; j < RX_BD_TOTAL; j++) {
14983                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14984                     bus_dmamap_unload(fp->rx_mbuf_tag,
14985                                       fp->rx_mbuf_chain[j].m_map);
14986                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14987                                        fp->rx_mbuf_chain[j].m_map);
14988                 }
14989             }
14990
14991             if (fp->rx_mbuf_spare_map != NULL) {
14992                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14993                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14994             }
14995
14996             /***************************/
14997             /* FP RX TPA MBUF DMA MAPS */
14998             /***************************/
14999
15000             max_agg_queues = MAX_AGG_QS(sc);
15001
15002             for (j = 0; j < max_agg_queues; j++) {
15003                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
15004                     bus_dmamap_unload(fp->rx_mbuf_tag,
15005                                       fp->rx_tpa_info[j].bd.m_map);
15006                     bus_dmamap_destroy(fp->rx_mbuf_tag,
15007                                        fp->rx_tpa_info[j].bd.m_map);
15008                 }
15009             }
15010
15011             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
15012                 bus_dmamap_unload(fp->rx_mbuf_tag,
15013                                   fp->rx_tpa_info_mbuf_spare_map);
15014                 bus_dmamap_destroy(fp->rx_mbuf_tag,
15015                                    fp->rx_tpa_info_mbuf_spare_map);
15016             }
15017
15018             bus_dma_tag_destroy(fp->rx_mbuf_tag);
15019             fp->rx_mbuf_tag = NULL;
15020         }
15021
15022         /***************************/
15023         /* FP RX SGE MBUF DMA MAPS */
15024         /***************************/
15025
15026         if (fp->rx_sge_mbuf_tag != NULL) {
15027             for (j = 0; j < RX_SGE_TOTAL; j++) {
15028                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
15029                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15030                                       fp->rx_sge_mbuf_chain[j].m_map);
15031                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15032                                        fp->rx_sge_mbuf_chain[j].m_map);
15033                 }
15034             }
15035
15036             if (fp->rx_sge_mbuf_spare_map != NULL) {
15037                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15038                                   fp->rx_sge_mbuf_spare_map);
15039                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15040                                    fp->rx_sge_mbuf_spare_map);
15041             }
15042
15043             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
15044             fp->rx_sge_mbuf_tag = NULL;
15045         }
15046     }
15047
15048     /***************************/
15049     /* FW DECOMPRESSION BUFFER */
15050     /***************************/
15051
15052     bxe_dma_free(sc, &sc->gz_buf_dma);
15053     sc->gz_buf = NULL;
15054     free(sc->gz_strm, M_DEVBUF);
15055     sc->gz_strm = NULL;
15056
15057     /*******************/
15058     /* SLOW PATH QUEUE */
15059     /*******************/
15060
15061     bxe_dma_free(sc, &sc->spq_dma);
15062     sc->spq = NULL;
15063
15064     /*************/
15065     /* SLOW PATH */
15066     /*************/
15067
15068     bxe_dma_free(sc, &sc->sp_dma);
15069     sc->sp = NULL;
15070
15071     /***************/
15072     /* EVENT QUEUE */
15073     /***************/
15074
15075     bxe_dma_free(sc, &sc->eq_dma);
15076     sc->eq = NULL;
15077
15078     /************************/
15079     /* DEFAULT STATUS BLOCK */
15080     /************************/
15081
15082     bxe_dma_free(sc, &sc->def_sb_dma);
15083     sc->def_sb = NULL;
15084
15085     bus_dma_tag_destroy(sc->parent_dma_tag);
15086     sc->parent_dma_tag = NULL;
15087 }
15088
15089 /*
15090  * Previous driver DMAE transaction may have occurred when pre-boot stage
15091  * ended and boot began. This would invalidate the addresses of the
15092  * transaction, resulting in was-error bit set in the PCI causing all
15093  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15094  * the interrupt which detected this from the pglueb and the was-done bit
15095  */
15096 static void
15097 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15098 {
15099     uint32_t val;
15100
15101     if (!CHIP_IS_E1x(sc)) {
15102         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15103         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15104             BLOGD(sc, DBG_LOAD,
15105                   "Clearing 'was-error' bit that was set in pglueb");
15106             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15107         }
15108     }
15109 }
15110
15111 static int
15112 bxe_prev_mcp_done(struct bxe_softc *sc)
15113 {
15114     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15115                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15116     if (!rc) {
15117         BLOGE(sc, "MCP response failure, aborting\n");
15118         return (-1);
15119     }
15120
15121     return (0);
15122 }
15123
15124 static struct bxe_prev_list_node *
15125 bxe_prev_path_get_entry(struct bxe_softc *sc)
15126 {
15127     struct bxe_prev_list_node *tmp;
15128
15129     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15130         if ((sc->pcie_bus == tmp->bus) &&
15131             (sc->pcie_device == tmp->slot) &&
15132             (SC_PATH(sc) == tmp->path)) {
15133             return (tmp);
15134         }
15135     }
15136
15137     return (NULL);
15138 }
15139
15140 static uint8_t
15141 bxe_prev_is_path_marked(struct bxe_softc *sc)
15142 {
15143     struct bxe_prev_list_node *tmp;
15144     int rc = FALSE;
15145
15146     mtx_lock(&bxe_prev_mtx);
15147
15148     tmp = bxe_prev_path_get_entry(sc);
15149     if (tmp) {
15150         if (tmp->aer) {
15151             BLOGD(sc, DBG_LOAD,
15152                   "Path %d/%d/%d was marked by AER\n",
15153                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15154         } else {
15155             rc = TRUE;
15156             BLOGD(sc, DBG_LOAD,
15157                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15158                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15159         }
15160     }
15161
15162     mtx_unlock(&bxe_prev_mtx);
15163
15164     return (rc);
15165 }
15166
15167 static int
15168 bxe_prev_mark_path(struct bxe_softc *sc,
15169                    uint8_t          after_undi)
15170 {
15171     struct bxe_prev_list_node *tmp;
15172
15173     mtx_lock(&bxe_prev_mtx);
15174
15175     /* Check whether the entry for this path already exists */
15176     tmp = bxe_prev_path_get_entry(sc);
15177     if (tmp) {
15178         if (!tmp->aer) {
15179             BLOGD(sc, DBG_LOAD,
15180                   "Re-marking AER in path %d/%d/%d\n",
15181                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15182         } else {
15183             BLOGD(sc, DBG_LOAD,
15184                   "Removing AER indication from path %d/%d/%d\n",
15185                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15186             tmp->aer = 0;
15187         }
15188
15189         mtx_unlock(&bxe_prev_mtx);
15190         return (0);
15191     }
15192
15193     mtx_unlock(&bxe_prev_mtx);
15194
15195     /* Create an entry for this path and add it */
15196     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15197                  (M_NOWAIT | M_ZERO));
15198     if (!tmp) {
15199         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15200         return (-1);
15201     }
15202
15203     tmp->bus  = sc->pcie_bus;
15204     tmp->slot = sc->pcie_device;
15205     tmp->path = SC_PATH(sc);
15206     tmp->aer  = 0;
15207     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15208
15209     mtx_lock(&bxe_prev_mtx);
15210
15211     BLOGD(sc, DBG_LOAD,
15212           "Marked path %d/%d/%d - finished previous unload\n",
15213           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15214     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15215
15216     mtx_unlock(&bxe_prev_mtx);
15217
15218     return (0);
15219 }
15220
15221 static int
15222 bxe_do_flr(struct bxe_softc *sc)
15223 {
15224     int i;
15225
15226     /* only E2 and onwards support FLR */
15227     if (CHIP_IS_E1x(sc)) {
15228         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15229         return (-1);
15230     }
15231
15232     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15233     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15234         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15235               sc->devinfo.bc_ver);
15236         return (-1);
15237     }
15238
15239     /* Wait for Transaction Pending bit clean */
15240     for (i = 0; i < 4; i++) {
15241         if (i) {
15242             DELAY(((1 << (i - 1)) * 100) * 1000);
15243         }
15244
15245         if (!bxe_is_pcie_pending(sc)) {
15246             goto clear;
15247         }
15248     }
15249
15250     BLOGE(sc, "PCIE transaction is not cleared, "
15251               "proceeding with reset anyway\n");
15252
15253 clear:
15254
15255     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15256     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15257
15258     return (0);
15259 }
15260
15261 struct bxe_mac_vals {
15262     uint32_t xmac_addr;
15263     uint32_t xmac_val;
15264     uint32_t emac_addr;
15265     uint32_t emac_val;
15266     uint32_t umac_addr;
15267     uint32_t umac_val;
15268     uint32_t bmac_addr;
15269     uint32_t bmac_val[2];
15270 };
15271
15272 static void
15273 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15274                           struct bxe_mac_vals *vals)
15275 {
15276     uint32_t val, base_addr, offset, mask, reset_reg;
15277     uint8_t mac_stopped = FALSE;
15278     uint8_t port = SC_PORT(sc);
15279     uint32_t wb_data[2];
15280
15281     /* reset addresses as they also mark which values were changed */
15282     vals->bmac_addr = 0;
15283     vals->umac_addr = 0;
15284     vals->xmac_addr = 0;
15285     vals->emac_addr = 0;
15286
15287     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15288
15289     if (!CHIP_IS_E3(sc)) {
15290         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15291         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15292         if ((mask & reset_reg) && val) {
15293             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15294             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15295                                     : NIG_REG_INGRESS_BMAC0_MEM;
15296             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15297                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15298
15299             /*
15300              * use rd/wr since we cannot use dmae. This is safe
15301              * since MCP won't access the bus due to the request
15302              * to unload, and no function on the path can be
15303              * loaded at this time.
15304              */
15305             wb_data[0] = REG_RD(sc, base_addr + offset);
15306             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15307             vals->bmac_addr = base_addr + offset;
15308             vals->bmac_val[0] = wb_data[0];
15309             vals->bmac_val[1] = wb_data[1];
15310             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15311             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15312             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15313         }
15314
15315         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15316         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15317         vals->emac_val = REG_RD(sc, vals->emac_addr);
15318         REG_WR(sc, vals->emac_addr, 0);
15319         mac_stopped = TRUE;
15320     } else {
15321         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15322             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15323             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15324             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15325             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15326             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15327             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15328             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15329             REG_WR(sc, vals->xmac_addr, 0);
15330             mac_stopped = TRUE;
15331         }
15332
15333         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15334         if (mask & reset_reg) {
15335             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15336             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15337             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15338             vals->umac_val = REG_RD(sc, vals->umac_addr);
15339             REG_WR(sc, vals->umac_addr, 0);
15340             mac_stopped = TRUE;
15341         }
15342     }
15343
15344     if (mac_stopped) {
15345         DELAY(20000);
15346     }
15347 }
15348
15349 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15350 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15351 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15352 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15353
15354 static void
15355 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15356                          uint8_t          port,
15357                          uint8_t          inc)
15358 {
15359     uint16_t rcq, bd;
15360     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15361
15362     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15363     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15364
15365     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15366     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15367
15368     BLOGD(sc, DBG_LOAD,
15369           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15370           port, bd, rcq);
15371 }
15372
15373 static int
15374 bxe_prev_unload_common(struct bxe_softc *sc)
15375 {
15376     uint32_t reset_reg, tmp_reg = 0, rc;
15377     uint8_t prev_undi = FALSE;
15378     struct bxe_mac_vals mac_vals;
15379     uint32_t timer_count = 1000;
15380     uint32_t prev_brb;
15381
15382     /*
15383      * It is possible a previous function received 'common' answer,
15384      * but hasn't loaded yet, therefore creating a scenario of
15385      * multiple functions receiving 'common' on the same path.
15386      */
15387     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15388
15389     memset(&mac_vals, 0, sizeof(mac_vals));
15390
15391     if (bxe_prev_is_path_marked(sc)) {
15392         return (bxe_prev_mcp_done(sc));
15393     }
15394
15395     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15396
15397     /* Reset should be performed after BRB is emptied */
15398     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15399         /* Close the MAC Rx to prevent BRB from filling up */
15400         bxe_prev_unload_close_mac(sc, &mac_vals);
15401
15402         /* close LLH filters towards the BRB */
15403         elink_set_rx_filter(&sc->link_params, 0);
15404
15405         /*
15406          * Check if the UNDI driver was previously loaded.
15407          * UNDI driver initializes CID offset for normal bell to 0x7
15408          */
15409         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15410             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15411             if (tmp_reg == 0x7) {
15412                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15413                 prev_undi = TRUE;
15414                 /* clear the UNDI indication */
15415                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15416                 /* clear possible idle check errors */
15417                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15418             }
15419         }
15420
15421         /* wait until BRB is empty */
15422         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15423         while (timer_count) {
15424             prev_brb = tmp_reg;
15425
15426             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15427             if (!tmp_reg) {
15428                 break;
15429             }
15430
15431             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15432
15433             /* reset timer as long as BRB actually gets emptied */
15434             if (prev_brb > tmp_reg) {
15435                 timer_count = 1000;
15436             } else {
15437                 timer_count--;
15438             }
15439
15440             /* If UNDI resides in memory, manually increment it */
15441             if (prev_undi) {
15442                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15443             }
15444
15445             DELAY(10);
15446         }
15447
15448         if (!timer_count) {
15449             BLOGE(sc, "Failed to empty BRB\n");
15450         }
15451     }
15452
15453     /* No packets are in the pipeline, path is ready for reset */
15454     bxe_reset_common(sc);
15455
15456     if (mac_vals.xmac_addr) {
15457         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15458     }
15459     if (mac_vals.umac_addr) {
15460         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15461     }
15462     if (mac_vals.emac_addr) {
15463         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15464     }
15465     if (mac_vals.bmac_addr) {
15466         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15467         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15468     }
15469
15470     rc = bxe_prev_mark_path(sc, prev_undi);
15471     if (rc) {
15472         bxe_prev_mcp_done(sc);
15473         return (rc);
15474     }
15475
15476     return (bxe_prev_mcp_done(sc));
15477 }
15478
15479 static int
15480 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15481 {
15482     int rc;
15483
15484     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15485
15486     /* Test if previous unload process was already finished for this path */
15487     if (bxe_prev_is_path_marked(sc)) {
15488         return (bxe_prev_mcp_done(sc));
15489     }
15490
15491     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15492
15493     /*
15494      * If function has FLR capabilities, and existing FW version matches
15495      * the one required, then FLR will be sufficient to clean any residue
15496      * left by previous driver
15497      */
15498     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15499     if (!rc) {
15500         /* fw version is good */
15501         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15502         rc = bxe_do_flr(sc);
15503     }
15504
15505     if (!rc) {
15506         /* FLR was performed */
15507         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15508         return (0);
15509     }
15510
15511     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15512
15513     /* Close the MCP request, return failure*/
15514     rc = bxe_prev_mcp_done(sc);
15515     if (!rc) {
15516         rc = BXE_PREV_WAIT_NEEDED;
15517     }
15518
15519     return (rc);
15520 }
15521
15522 static int
15523 bxe_prev_unload(struct bxe_softc *sc)
15524 {
15525     int time_counter = 10;
15526     uint32_t fw, hw_lock_reg, hw_lock_val;
15527     uint32_t rc = 0;
15528
15529     /*
15530      * Clear HW from errors which may have resulted from an interrupted
15531      * DMAE transaction.
15532      */
15533     bxe_prev_interrupted_dmae(sc);
15534
15535     /* Release previously held locks */
15536     hw_lock_reg =
15537         (SC_FUNC(sc) <= 5) ?
15538             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15539             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15540
15541     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15542     if (hw_lock_val) {
15543         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15544             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15545             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15546                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15547         }
15548         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15549         REG_WR(sc, hw_lock_reg, 0xffffffff);
15550     } else {
15551         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15552     }
15553
15554     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15555         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15556         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15557     }
15558
15559     do {
15560         /* Lock MCP using an unload request */
15561         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15562         if (!fw) {
15563             BLOGE(sc, "MCP response failure, aborting\n");
15564             rc = -1;
15565             break;
15566         }
15567
15568         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15569             rc = bxe_prev_unload_common(sc);
15570             break;
15571         }
15572
15573         /* non-common reply from MCP night require looping */
15574         rc = bxe_prev_unload_uncommon(sc);
15575         if (rc != BXE_PREV_WAIT_NEEDED) {
15576             break;
15577         }
15578
15579         DELAY(20000);
15580     } while (--time_counter);
15581
15582     if (!time_counter || rc) {
15583         BLOGE(sc, "Failed to unload previous driver!"
15584             " time_counter %d rc %d\n", time_counter, rc);
15585         rc = -1;
15586     }
15587
15588     return (rc);
15589 }
15590
15591 void
15592 bxe_dcbx_set_state(struct bxe_softc *sc,
15593                    uint8_t          dcb_on,
15594                    uint32_t         dcbx_enabled)
15595 {
15596     if (!CHIP_IS_E1x(sc)) {
15597         sc->dcb_state = dcb_on;
15598         sc->dcbx_enabled = dcbx_enabled;
15599     } else {
15600         sc->dcb_state = FALSE;
15601         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15602     }
15603     BLOGD(sc, DBG_LOAD,
15604           "DCB state [%s:%s]\n",
15605           dcb_on ? "ON" : "OFF",
15606           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15607           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15608           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15609           "on-chip with negotiation" : "invalid");
15610 }
15611
15612 /* must be called after sriov-enable */
15613 static int
15614 bxe_set_qm_cid_count(struct bxe_softc *sc)
15615 {
15616     int cid_count = BXE_L2_MAX_CID(sc);
15617
15618     if (IS_SRIOV(sc)) {
15619         cid_count += BXE_VF_CIDS;
15620     }
15621
15622     if (CNIC_SUPPORT(sc)) {
15623         cid_count += CNIC_CID_MAX;
15624     }
15625
15626     return (roundup(cid_count, QM_CID_ROUND));
15627 }
15628
15629 static void
15630 bxe_init_multi_cos(struct bxe_softc *sc)
15631 {
15632     int pri, cos;
15633
15634     uint32_t pri_map = 0; /* XXX change to user config */
15635
15636     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15637         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15638         if (cos < sc->max_cos) {
15639             sc->prio_to_cos[pri] = cos;
15640         } else {
15641             BLOGW(sc, "Invalid COS %d for priority %d "
15642                       "(max COS is %d), setting to 0\n",
15643                   cos, pri, (sc->max_cos - 1));
15644             sc->prio_to_cos[pri] = 0;
15645         }
15646     }
15647 }
15648
15649 static int
15650 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15651 {
15652     struct bxe_softc *sc;
15653     int error, result;
15654
15655     result = 0;
15656     error = sysctl_handle_int(oidp, &result, 0, req);
15657
15658     if (error || !req->newptr) {
15659         return (error);
15660     }
15661
15662     if (result == 1) {
15663         uint32_t  temp;
15664         sc = (struct bxe_softc *)arg1;
15665
15666         BLOGI(sc, "... dumping driver state ...\n");
15667         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15668         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15669     }
15670
15671     return (error);
15672 }
15673
15674 static int
15675 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15676 {
15677     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15678     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15679     uint32_t *offset;
15680     uint64_t value = 0;
15681     int index = (int)arg2;
15682
15683     if (index >= BXE_NUM_ETH_STATS) {
15684         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15685         return (-1);
15686     }
15687
15688     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15689
15690     switch (bxe_eth_stats_arr[index].size) {
15691     case 4:
15692         value = (uint64_t)*offset;
15693         break;
15694     case 8:
15695         value = HILO_U64(*offset, *(offset + 1));
15696         break;
15697     default:
15698         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15699               index, bxe_eth_stats_arr[index].size);
15700         return (-1);
15701     }
15702
15703     return (sysctl_handle_64(oidp, &value, 0, req));
15704 }
15705
15706 static int
15707 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15708 {
15709     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15710     uint32_t *eth_stats;
15711     uint32_t *offset;
15712     uint64_t value = 0;
15713     uint32_t q_stat = (uint32_t)arg2;
15714     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15715     uint32_t index = (q_stat & 0xffff);
15716
15717     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15718
15719     if (index >= BXE_NUM_ETH_Q_STATS) {
15720         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15721         return (-1);
15722     }
15723
15724     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15725
15726     switch (bxe_eth_q_stats_arr[index].size) {
15727     case 4:
15728         value = (uint64_t)*offset;
15729         break;
15730     case 8:
15731         value = HILO_U64(*offset, *(offset + 1));
15732         break;
15733     default:
15734         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15735               index, bxe_eth_q_stats_arr[index].size);
15736         return (-1);
15737     }
15738
15739     return (sysctl_handle_64(oidp, &value, 0, req));
15740 }
15741
15742 static void
15743 bxe_add_sysctls(struct bxe_softc *sc)
15744 {
15745     struct sysctl_ctx_list *ctx;
15746     struct sysctl_oid_list *children;
15747     struct sysctl_oid *queue_top, *queue;
15748     struct sysctl_oid_list *queue_top_children, *queue_children;
15749     char queue_num_buf[32];
15750     uint32_t q_stat;
15751     int i, j;
15752
15753     ctx = device_get_sysctl_ctx(sc->dev);
15754     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15755
15756     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15757                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15758                       "version");
15759
15760     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15761              BCM_5710_FW_MAJOR_VERSION,
15762              BCM_5710_FW_MINOR_VERSION,
15763              BCM_5710_FW_REVISION_VERSION,
15764              BCM_5710_FW_ENGINEERING_VERSION);
15765
15766     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15767         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15768          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15769          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15770          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15771                                                                 "Unknown"));
15772     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15773                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15774                     "multifunction vnics per port");
15775
15776     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15777         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15778          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15779          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15780                                               "???GT/s"),
15781         sc->devinfo.pcie_link_width);
15782
15783     sc->debug = bxe_debug;
15784
15785 #if __FreeBSD_version >= 900000
15786     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15787                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15788                       "bootcode version");
15789     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15790                       CTLFLAG_RD, sc->fw_ver_str, 0,
15791                       "firmware version");
15792     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15793                       CTLFLAG_RD, sc->mf_mode_str, 0,
15794                       "multifunction mode");
15795     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15796                       CTLFLAG_RD, sc->mac_addr_str, 0,
15797                       "mac address");
15798     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15799                       CTLFLAG_RD, &sc->pci_link_str, 0,
15800                       "pci link status");
15801     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15802                     CTLFLAG_RW, &sc->debug, 0,
15803                     "debug logging mode");
15804 #else
15805     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15806                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15807                       "bootcode version");
15808     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15809                       CTLFLAG_RD, &sc->fw_ver_str, 0,
15810                       "firmware version");
15811     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15812                       CTLFLAG_RD, &sc->mf_mode_str, 0,
15813                       "multifunction mode");
15814     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15815                       CTLFLAG_RD, &sc->mac_addr_str, 0,
15816                       "mac address");
15817     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15818                       CTLFLAG_RD, &sc->pci_link_str, 0,
15819                       "pci link status");
15820     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15821                     CTLFLAG_RW, &sc->debug, 0,
15822                     "debug logging mode");
15823 #endif /* #if __FreeBSD_version >= 900000 */
15824
15825     sc->trigger_grcdump = 0;
15826     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
15827                    CTLFLAG_RW, &sc->trigger_grcdump, 0,
15828                    "trigger grcdump should be invoked"
15829                    "  before collecting grcdump");
15830
15831     sc->grcdump_started = 0;
15832     sc->grcdump_done = 0;
15833     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15834                    CTLFLAG_RD, &sc->grcdump_done, 0,
15835                    "set by driver when grcdump is done");
15836
15837     sc->rx_budget = bxe_rx_budget;
15838     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15839                     CTLFLAG_RW, &sc->rx_budget, 0,
15840                     "rx processing budget");
15841
15842     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15843                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15844                     bxe_sysctl_state, "IU", "dump driver state");
15845
15846     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15847         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15848                         bxe_eth_stats_arr[i].string,
15849                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15850                         bxe_sysctl_eth_stat, "LU",
15851                         bxe_eth_stats_arr[i].string);
15852     }
15853
15854     /* add a new parent node for all queues "dev.bxe.#.queue" */
15855     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15856                                 CTLFLAG_RD, NULL, "queue");
15857     queue_top_children = SYSCTL_CHILDREN(queue_top);
15858
15859     for (i = 0; i < sc->num_queues; i++) {
15860         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15861         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15862         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15863                                 queue_num_buf, CTLFLAG_RD, NULL,
15864                                 "single queue");
15865         queue_children = SYSCTL_CHILDREN(queue);
15866
15867         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15868             q_stat = ((i << 16) | j);
15869             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15870                             bxe_eth_q_stats_arr[j].string,
15871                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15872                             bxe_sysctl_eth_q_stat, "LU",
15873                             bxe_eth_q_stats_arr[j].string);
15874         }
15875     }
15876 }
15877
15878 static int
15879 bxe_alloc_buf_rings(struct bxe_softc *sc)
15880 {
15881 #if __FreeBSD_version >= 800000
15882
15883     int i;
15884     struct bxe_fastpath *fp;
15885
15886     for (i = 0; i < sc->num_queues; i++) {
15887
15888         fp = &sc->fp[i];
15889
15890         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15891                                    M_NOWAIT, &fp->tx_mtx);
15892         if (fp->tx_br == NULL)
15893             return (-1);
15894     }
15895 #endif
15896     return (0);
15897 }
15898
15899 static void
15900 bxe_free_buf_rings(struct bxe_softc *sc)
15901 {
15902 #if __FreeBSD_version >= 800000
15903
15904     int i;
15905     struct bxe_fastpath *fp;
15906
15907     for (i = 0; i < sc->num_queues; i++) {
15908
15909         fp = &sc->fp[i];
15910
15911         if (fp->tx_br) {
15912             buf_ring_free(fp->tx_br, M_DEVBUF);
15913             fp->tx_br = NULL;
15914         }
15915     }
15916
15917 #endif
15918 }
15919
15920 static void
15921 bxe_init_fp_mutexs(struct bxe_softc *sc)
15922 {
15923     int i;
15924     struct bxe_fastpath *fp;
15925
15926     for (i = 0; i < sc->num_queues; i++) {
15927
15928         fp = &sc->fp[i];
15929
15930         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15931             "bxe%d_fp%d_tx_lock", sc->unit, i);
15932         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15933
15934         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15935             "bxe%d_fp%d_rx_lock", sc->unit, i);
15936         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15937     }
15938 }
15939
15940 static void
15941 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15942 {
15943     int i;
15944     struct bxe_fastpath *fp;
15945
15946     for (i = 0; i < sc->num_queues; i++) {
15947
15948         fp = &sc->fp[i];
15949
15950         if (mtx_initialized(&fp->tx_mtx)) {
15951             mtx_destroy(&fp->tx_mtx);
15952         }
15953
15954         if (mtx_initialized(&fp->rx_mtx)) {
15955             mtx_destroy(&fp->rx_mtx);
15956         }
15957     }
15958 }
15959
15960
15961 /*
15962  * Device attach function.
15963  *
15964  * Allocates device resources, performs secondary chip identification, and
15965  * initializes driver instance variables. This function is called from driver
15966  * load after a successful probe.
15967  *
15968  * Returns:
15969  *   0 = Success, >0 = Failure
15970  */
15971 static int
15972 bxe_attach(device_t dev)
15973 {
15974     struct bxe_softc *sc;
15975
15976     sc = device_get_softc(dev);
15977
15978     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15979
15980     sc->state = BXE_STATE_CLOSED;
15981
15982     sc->dev  = dev;
15983     sc->unit = device_get_unit(dev);
15984
15985     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
15986
15987     sc->pcie_bus    = pci_get_bus(dev);
15988     sc->pcie_device = pci_get_slot(dev);
15989     sc->pcie_func   = pci_get_function(dev);
15990
15991     /* enable bus master capability */
15992     pci_enable_busmaster(dev);
15993
15994     /* get the BARs */
15995     if (bxe_allocate_bars(sc) != 0) {
15996         return (ENXIO);
15997     }
15998
15999     /* initialize the mutexes */
16000     bxe_init_mutexes(sc);
16001
16002     /* prepare the periodic callout */
16003     callout_init(&sc->periodic_callout, 0);
16004
16005     /* prepare the chip taskqueue */
16006     sc->chip_tq_flags = CHIP_TQ_NONE;
16007     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
16008              "bxe%d_chip_tq", sc->unit);
16009     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
16010     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
16011                                    taskqueue_thread_enqueue,
16012                                    &sc->chip_tq);
16013     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
16014                             "%s", sc->chip_tq_name);
16015
16016     /* get device info and set params */
16017     if (bxe_get_device_info(sc) != 0) {
16018         BLOGE(sc, "getting device info\n");
16019         bxe_deallocate_bars(sc);
16020         pci_disable_busmaster(dev);
16021         return (ENXIO);
16022     }
16023
16024     /* get final misc params */
16025     bxe_get_params(sc);
16026
16027     /* set the default MTU (changed via ifconfig) */
16028     sc->mtu = ETHERMTU;
16029
16030     bxe_set_modes_bitmap(sc);
16031
16032     /* XXX
16033      * If in AFEX mode and the function is configured for FCoE
16034      * then bail... no L2 allowed.
16035      */
16036
16037     /* get phy settings from shmem and 'and' against admin settings */
16038     bxe_get_phy_info(sc);
16039
16040     /* initialize the FreeBSD ifnet interface */
16041     if (bxe_init_ifnet(sc) != 0) {
16042         bxe_release_mutexes(sc);
16043         bxe_deallocate_bars(sc);
16044         pci_disable_busmaster(dev);
16045         return (ENXIO);
16046     }
16047
16048     if (bxe_add_cdev(sc) != 0) {
16049         if (sc->ifnet != NULL) {
16050             ether_ifdetach(sc->ifnet);
16051         }
16052         ifmedia_removeall(&sc->ifmedia);
16053         bxe_release_mutexes(sc);
16054         bxe_deallocate_bars(sc);
16055         pci_disable_busmaster(dev);
16056         return (ENXIO);
16057     }
16058
16059     /* allocate device interrupts */
16060     if (bxe_interrupt_alloc(sc) != 0) {
16061         bxe_del_cdev(sc);
16062         if (sc->ifnet != NULL) {
16063             ether_ifdetach(sc->ifnet);
16064         }
16065         ifmedia_removeall(&sc->ifmedia);
16066         bxe_release_mutexes(sc);
16067         bxe_deallocate_bars(sc);
16068         pci_disable_busmaster(dev);
16069         return (ENXIO);
16070     }
16071
16072     bxe_init_fp_mutexs(sc);
16073
16074     if (bxe_alloc_buf_rings(sc) != 0) {
16075         bxe_free_buf_rings(sc);
16076         bxe_interrupt_free(sc);
16077         bxe_del_cdev(sc);
16078         if (sc->ifnet != NULL) {
16079             ether_ifdetach(sc->ifnet);
16080         }
16081         ifmedia_removeall(&sc->ifmedia);
16082         bxe_release_mutexes(sc);
16083         bxe_deallocate_bars(sc);
16084         pci_disable_busmaster(dev);
16085         return (ENXIO);
16086     }
16087
16088     /* allocate ilt */
16089     if (bxe_alloc_ilt_mem(sc) != 0) {
16090         bxe_free_buf_rings(sc);
16091         bxe_interrupt_free(sc);
16092         bxe_del_cdev(sc);
16093         if (sc->ifnet != NULL) {
16094             ether_ifdetach(sc->ifnet);
16095         }
16096         ifmedia_removeall(&sc->ifmedia);
16097         bxe_release_mutexes(sc);
16098         bxe_deallocate_bars(sc);
16099         pci_disable_busmaster(dev);
16100         return (ENXIO);
16101     }
16102
16103     /* allocate the host hardware/software hsi structures */
16104     if (bxe_alloc_hsi_mem(sc) != 0) {
16105         bxe_free_ilt_mem(sc);
16106         bxe_free_buf_rings(sc);
16107         bxe_interrupt_free(sc);
16108         bxe_del_cdev(sc);
16109         if (sc->ifnet != NULL) {
16110             ether_ifdetach(sc->ifnet);
16111         }
16112         ifmedia_removeall(&sc->ifmedia);
16113         bxe_release_mutexes(sc);
16114         bxe_deallocate_bars(sc);
16115         pci_disable_busmaster(dev);
16116         return (ENXIO);
16117     }
16118
16119     /* need to reset chip if UNDI was active */
16120     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16121         /* init fw_seq */
16122         sc->fw_seq =
16123             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16124              DRV_MSG_SEQ_NUMBER_MASK);
16125         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16126         bxe_prev_unload(sc);
16127     }
16128
16129 #if 1
16130     /* XXX */
16131     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16132 #else
16133     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16134         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16135         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16136         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16137         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16138         bxe_dcbx_init_params(sc);
16139     } else {
16140         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16141     }
16142 #endif
16143
16144     /* calculate qm_cid_count */
16145     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16146     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16147
16148     sc->max_cos = 1;
16149     bxe_init_multi_cos(sc);
16150
16151     bxe_add_sysctls(sc);
16152
16153     return (0);
16154 }
16155
16156 /*
16157  * Device detach function.
16158  *
16159  * Stops the controller, resets the controller, and releases resources.
16160  *
16161  * Returns:
16162  *   0 = Success, >0 = Failure
16163  */
16164 static int
16165 bxe_detach(device_t dev)
16166 {
16167     struct bxe_softc *sc;
16168     struct ifnet *ifp;
16169
16170     sc = device_get_softc(dev);
16171
16172     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16173
16174     ifp = sc->ifnet;
16175     if (ifp != NULL && ifp->if_vlantrunk != NULL) {
16176         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16177         return(EBUSY);
16178     }
16179
16180     bxe_del_cdev(sc);
16181
16182     /* stop the periodic callout */
16183     bxe_periodic_stop(sc);
16184
16185     /* stop the chip taskqueue */
16186     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16187     if (sc->chip_tq) {
16188         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16189         taskqueue_free(sc->chip_tq);
16190         sc->chip_tq = NULL;
16191     }
16192
16193     /* stop and reset the controller if it was open */
16194     if (sc->state != BXE_STATE_CLOSED) {
16195         BXE_CORE_LOCK(sc);
16196         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16197         sc->state = BXE_STATE_DISABLED;
16198         BXE_CORE_UNLOCK(sc);
16199     }
16200
16201     /* release the network interface */
16202     if (ifp != NULL) {
16203         ether_ifdetach(ifp);
16204     }
16205     ifmedia_removeall(&sc->ifmedia);
16206
16207     /* XXX do the following based on driver state... */
16208
16209     /* free the host hardware/software hsi structures */
16210     bxe_free_hsi_mem(sc);
16211
16212     /* free ilt */
16213     bxe_free_ilt_mem(sc);
16214
16215     bxe_free_buf_rings(sc);
16216
16217     /* release the interrupts */
16218     bxe_interrupt_free(sc);
16219
16220     /* Release the mutexes*/
16221     bxe_destroy_fp_mutexs(sc);
16222     bxe_release_mutexes(sc);
16223
16224
16225     /* Release the PCIe BAR mapped memory */
16226     bxe_deallocate_bars(sc);
16227
16228     /* Release the FreeBSD interface. */
16229     if (sc->ifnet != NULL) {
16230         if_free(sc->ifnet);
16231     }
16232
16233     pci_disable_busmaster(dev);
16234
16235     return (0);
16236 }
16237
16238 /*
16239  * Device shutdown function.
16240  *
16241  * Stops and resets the controller.
16242  *
16243  * Returns:
16244  *   Nothing
16245  */
16246 static int
16247 bxe_shutdown(device_t dev)
16248 {
16249     struct bxe_softc *sc;
16250
16251     sc = device_get_softc(dev);
16252
16253     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16254
16255     /* stop the periodic callout */
16256     bxe_periodic_stop(sc);
16257
16258     BXE_CORE_LOCK(sc);
16259     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16260     BXE_CORE_UNLOCK(sc);
16261
16262     return (0);
16263 }
16264
16265 void
16266 bxe_igu_ack_sb(struct bxe_softc *sc,
16267                uint8_t          igu_sb_id,
16268                uint8_t          segment,
16269                uint16_t         index,
16270                uint8_t          op,
16271                uint8_t          update)
16272 {
16273     uint32_t igu_addr = sc->igu_base_addr;
16274     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16275     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16276 }
16277
16278 static void
16279 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16280                      uint8_t          func,
16281                      uint8_t          idu_sb_id,
16282                      uint8_t          is_pf)
16283 {
16284     uint32_t data, ctl, cnt = 100;
16285     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16286     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16287     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16288     uint32_t sb_bit =  1 << (idu_sb_id%32);
16289     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16290     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16291
16292     /* Not supported in BC mode */
16293     if (CHIP_INT_MODE_IS_BC(sc)) {
16294         return;
16295     }
16296
16297     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16298              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16299             IGU_REGULAR_CLEANUP_SET |
16300             IGU_REGULAR_BCLEANUP);
16301
16302     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16303            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16304            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16305
16306     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16307             data, igu_addr_data);
16308     REG_WR(sc, igu_addr_data, data);
16309
16310     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16311                       BUS_SPACE_BARRIER_WRITE);
16312     mb();
16313
16314     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16315             ctl, igu_addr_ctl);
16316     REG_WR(sc, igu_addr_ctl, ctl);
16317
16318     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16319                       BUS_SPACE_BARRIER_WRITE);
16320     mb();
16321
16322     /* wait for clean up to finish */
16323     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16324         DELAY(20000);
16325     }
16326
16327     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16328         BLOGD(sc, DBG_LOAD,
16329               "Unable to finish IGU cleanup: "
16330               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16331               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16332     }
16333 }
16334
16335 static void
16336 bxe_igu_clear_sb(struct bxe_softc *sc,
16337                  uint8_t          idu_sb_id)
16338 {
16339     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16340 }
16341
16342
16343
16344
16345
16346
16347
16348 /*******************/
16349 /* ECORE CALLBACKS */
16350 /*******************/
16351
16352 static void
16353 bxe_reset_common(struct bxe_softc *sc)
16354 {
16355     uint32_t val = 0x1400;
16356
16357     /* reset_common */
16358     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16359
16360     if (CHIP_IS_E3(sc)) {
16361         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16362         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16363     }
16364
16365     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16366 }
16367
16368 static void
16369 bxe_common_init_phy(struct bxe_softc *sc)
16370 {
16371     uint32_t shmem_base[2];
16372     uint32_t shmem2_base[2];
16373
16374     /* Avoid common init in case MFW supports LFA */
16375     if (SHMEM2_RD(sc, size) >
16376         (uint32_t)offsetof(struct shmem2_region,
16377                            lfa_host_addr[SC_PORT(sc)])) {
16378         return;
16379     }
16380
16381     shmem_base[0]  = sc->devinfo.shmem_base;
16382     shmem2_base[0] = sc->devinfo.shmem2_base;
16383
16384     if (!CHIP_IS_E1x(sc)) {
16385         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16386         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16387     }
16388
16389     bxe_acquire_phy_lock(sc);
16390     elink_common_init_phy(sc, shmem_base, shmem2_base,
16391                           sc->devinfo.chip_id, 0);
16392     bxe_release_phy_lock(sc);
16393 }
16394
16395 static void
16396 bxe_pf_disable(struct bxe_softc *sc)
16397 {
16398     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16399
16400     val &= ~IGU_PF_CONF_FUNC_EN;
16401
16402     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16403     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16404     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16405 }
16406
16407 static void
16408 bxe_init_pxp(struct bxe_softc *sc)
16409 {
16410     uint16_t devctl;
16411     int r_order, w_order;
16412
16413     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16414
16415     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16416
16417     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16418
16419     if (sc->mrrs == -1) {
16420         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16421     } else {
16422         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16423         r_order = sc->mrrs;
16424     }
16425
16426     ecore_init_pxp_arb(sc, r_order, w_order);
16427 }
16428
16429 static uint32_t
16430 bxe_get_pretend_reg(struct bxe_softc *sc)
16431 {
16432     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16433     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16434     return (base + (SC_ABS_FUNC(sc)) * stride);
16435 }
16436
16437 /*
16438  * Called only on E1H or E2.
16439  * When pretending to be PF, the pretend value is the function number 0..7.
16440  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16441  * combination.
16442  */
16443 static int
16444 bxe_pretend_func(struct bxe_softc *sc,
16445                  uint16_t         pretend_func_val)
16446 {
16447     uint32_t pretend_reg;
16448
16449     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16450         return (-1);
16451     }
16452
16453     /* get my own pretend register */
16454     pretend_reg = bxe_get_pretend_reg(sc);
16455     REG_WR(sc, pretend_reg, pretend_func_val);
16456     REG_RD(sc, pretend_reg);
16457     return (0);
16458 }
16459
16460 static void
16461 bxe_iov_init_dmae(struct bxe_softc *sc)
16462 {
16463     return;
16464 }
16465
16466 static void
16467 bxe_iov_init_dq(struct bxe_softc *sc)
16468 {
16469     return;
16470 }
16471
16472 /* send a NIG loopback debug packet */
16473 static void
16474 bxe_lb_pckt(struct bxe_softc *sc)
16475 {
16476     uint32_t wb_write[3];
16477
16478     /* Ethernet source and destination addresses */
16479     wb_write[0] = 0x55555555;
16480     wb_write[1] = 0x55555555;
16481     wb_write[2] = 0x20;     /* SOP */
16482     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16483
16484     /* NON-IP protocol */
16485     wb_write[0] = 0x09000000;
16486     wb_write[1] = 0x55555555;
16487     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16488     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16489 }
16490
16491 /*
16492  * Some of the internal memories are not directly readable from the driver.
16493  * To test them we send debug packets.
16494  */
16495 static int
16496 bxe_int_mem_test(struct bxe_softc *sc)
16497 {
16498     int factor;
16499     int count, i;
16500     uint32_t val = 0;
16501
16502     if (CHIP_REV_IS_FPGA(sc)) {
16503         factor = 120;
16504     } else if (CHIP_REV_IS_EMUL(sc)) {
16505         factor = 200;
16506     } else {
16507         factor = 1;
16508     }
16509
16510     /* disable inputs of parser neighbor blocks */
16511     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16512     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16513     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16514     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16515
16516     /*  write 0 to parser credits for CFC search request */
16517     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16518
16519     /* send Ethernet packet */
16520     bxe_lb_pckt(sc);
16521
16522     /* TODO do i reset NIG statistic? */
16523     /* Wait until NIG register shows 1 packet of size 0x10 */
16524     count = 1000 * factor;
16525     while (count) {
16526         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16527         val = *BXE_SP(sc, wb_data[0]);
16528         if (val == 0x10) {
16529             break;
16530         }
16531
16532         DELAY(10000);
16533         count--;
16534     }
16535
16536     if (val != 0x10) {
16537         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16538         return (-1);
16539     }
16540
16541     /* wait until PRS register shows 1 packet */
16542     count = (1000 * factor);
16543     while (count) {
16544         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16545         if (val == 1) {
16546             break;
16547         }
16548
16549         DELAY(10000);
16550         count--;
16551     }
16552
16553     if (val != 0x1) {
16554         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16555         return (-2);
16556     }
16557
16558     /* Reset and init BRB, PRS */
16559     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16560     DELAY(50000);
16561     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16562     DELAY(50000);
16563     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16564     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16565
16566     /* Disable inputs of parser neighbor blocks */
16567     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16568     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16569     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16570     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16571
16572     /* Write 0 to parser credits for CFC search request */
16573     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16574
16575     /* send 10 Ethernet packets */
16576     for (i = 0; i < 10; i++) {
16577         bxe_lb_pckt(sc);
16578     }
16579
16580     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16581     count = (1000 * factor);
16582     while (count) {
16583         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16584         val = *BXE_SP(sc, wb_data[0]);
16585         if (val == 0xb0) {
16586             break;
16587         }
16588
16589         DELAY(10000);
16590         count--;
16591     }
16592
16593     if (val != 0xb0) {
16594         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16595         return (-3);
16596     }
16597
16598     /* Wait until PRS register shows 2 packets */
16599     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16600     if (val != 2) {
16601         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16602     }
16603
16604     /* Write 1 to parser credits for CFC search request */
16605     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16606
16607     /* Wait until PRS register shows 3 packets */
16608     DELAY(10000 * factor);
16609
16610     /* Wait until NIG register shows 1 packet of size 0x10 */
16611     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16612     if (val != 3) {
16613         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16614     }
16615
16616     /* clear NIG EOP FIFO */
16617     for (i = 0; i < 11; i++) {
16618         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16619     }
16620
16621     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16622     if (val != 1) {
16623         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16624         return (-4);
16625     }
16626
16627     /* Reset and init BRB, PRS, NIG */
16628     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16629     DELAY(50000);
16630     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16631     DELAY(50000);
16632     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16633     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16634     if (!CNIC_SUPPORT(sc)) {
16635         /* set NIC mode */
16636         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16637     }
16638
16639     /* Enable inputs of parser neighbor blocks */
16640     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16641     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16642     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16643     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16644
16645     return (0);
16646 }
16647
16648 static void
16649 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16650 {
16651     int is_required;
16652     uint32_t val;
16653     int port;
16654
16655     is_required = 0;
16656     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16657            SHARED_HW_CFG_FAN_FAILURE_MASK);
16658
16659     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16660         is_required = 1;
16661     }
16662     /*
16663      * The fan failure mechanism is usually related to the PHY type since
16664      * the power consumption of the board is affected by the PHY. Currently,
16665      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16666      */
16667     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16668         for (port = PORT_0; port < PORT_MAX; port++) {
16669             is_required |= elink_fan_failure_det_req(sc,
16670                                                      sc->devinfo.shmem_base,
16671                                                      sc->devinfo.shmem2_base,
16672                                                      port);
16673         }
16674     }
16675
16676     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16677
16678     if (is_required == 0) {
16679         return;
16680     }
16681
16682     /* Fan failure is indicated by SPIO 5 */
16683     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16684
16685     /* set to active low mode */
16686     val = REG_RD(sc, MISC_REG_SPIO_INT);
16687     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16688     REG_WR(sc, MISC_REG_SPIO_INT, val);
16689
16690     /* enable interrupt to signal the IGU */
16691     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16692     val |= MISC_SPIO_SPIO5;
16693     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16694 }
16695
16696 static void
16697 bxe_enable_blocks_attention(struct bxe_softc *sc)
16698 {
16699     uint32_t val;
16700
16701     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16702     if (!CHIP_IS_E1x(sc)) {
16703         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16704     } else {
16705         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16706     }
16707     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16708     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16709     /*
16710      * mask read length error interrupts in brb for parser
16711      * (parsing unit and 'checksum and crc' unit)
16712      * these errors are legal (PU reads fixed length and CAC can cause
16713      * read length error on truncated packets)
16714      */
16715     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16716     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16717     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16718     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16719     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16720     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16721 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16722 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16723     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16724     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16725     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16726 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16727 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16728     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16729     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16730     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16731     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16732 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16733 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16734
16735     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16736            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16737            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16738     if (!CHIP_IS_E1x(sc)) {
16739         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16740                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16741     }
16742     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16743
16744     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16745     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16746     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16747 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16748
16749     if (!CHIP_IS_E1x(sc)) {
16750         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16751         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16752     }
16753
16754     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16755     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16756 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16757     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16758 }
16759
16760 /**
16761  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16762  *
16763  * @sc:     driver handle
16764  */
16765 static int
16766 bxe_init_hw_common(struct bxe_softc *sc)
16767 {
16768     uint8_t abs_func_id;
16769     uint32_t val;
16770
16771     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16772           SC_ABS_FUNC(sc));
16773
16774     /*
16775      * take the RESET lock to protect undi_unload flow from accessing
16776      * registers while we are resetting the chip
16777      */
16778     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16779
16780     bxe_reset_common(sc);
16781
16782     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16783
16784     val = 0xfffc;
16785     if (CHIP_IS_E3(sc)) {
16786         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16787         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16788     }
16789
16790     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16791
16792     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16793
16794     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16795     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16796
16797     if (!CHIP_IS_E1x(sc)) {
16798         /*
16799          * 4-port mode or 2-port mode we need to turn off master-enable for
16800          * everyone. After that we turn it back on for self. So, we disregard
16801          * multi-function, and always disable all functions on the given path,
16802          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16803          */
16804         for (abs_func_id = SC_PATH(sc);
16805              abs_func_id < (E2_FUNC_MAX * 2);
16806              abs_func_id += 2) {
16807             if (abs_func_id == SC_ABS_FUNC(sc)) {
16808                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16809                 continue;
16810             }
16811
16812             bxe_pretend_func(sc, abs_func_id);
16813
16814             /* clear pf enable */
16815             bxe_pf_disable(sc);
16816
16817             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16818         }
16819     }
16820
16821     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16822
16823     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16824
16825     if (CHIP_IS_E1(sc)) {
16826         /*
16827          * enable HW interrupt from PXP on USDM overflow
16828          * bit 16 on INT_MASK_0
16829          */
16830         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16831     }
16832
16833     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16834     bxe_init_pxp(sc);
16835
16836 #ifdef __BIG_ENDIAN
16837     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16838     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16839     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16840     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16841     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16842     /* make sure this value is 0 */
16843     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16844
16845     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16846     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16847     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16848     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16849     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16850 #endif
16851
16852     ecore_ilt_init_page_size(sc, INITOP_SET);
16853
16854     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16855         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16856     }
16857
16858     /* let the HW do it's magic... */
16859     DELAY(100000);
16860
16861     /* finish PXP init */
16862     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16863     if (val != 1) {
16864         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16865             val);
16866         return (-1);
16867     }
16868     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16869     if (val != 1) {
16870         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16871         return (-1);
16872     }
16873
16874     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16875
16876     /*
16877      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16878      * entries with value "0" and valid bit on. This needs to be done by the
16879      * first PF that is loaded in a path (i.e. common phase)
16880      */
16881     if (!CHIP_IS_E1x(sc)) {
16882 /*
16883  * In E2 there is a bug in the timers block that can cause function 6 / 7
16884  * (i.e. vnic3) to start even if it is marked as "scan-off".
16885  * This occurs when a different function (func2,3) is being marked
16886  * as "scan-off". Real-life scenario for example: if a driver is being
16887  * load-unloaded while func6,7 are down. This will cause the timer to access
16888  * the ilt, translate to a logical address and send a request to read/write.
16889  * Since the ilt for the function that is down is not valid, this will cause
16890  * a translation error which is unrecoverable.
16891  * The Workaround is intended to make sure that when this happens nothing
16892  * fatal will occur. The workaround:
16893  *  1.  First PF driver which loads on a path will:
16894  *      a.  After taking the chip out of reset, by using pretend,
16895  *          it will write "0" to the following registers of
16896  *          the other vnics.
16897  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16898  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16899  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16900  *          And for itself it will write '1' to
16901  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16902  *          dmae-operations (writing to pram for example.)
16903  *          note: can be done for only function 6,7 but cleaner this
16904  *            way.
16905  *      b.  Write zero+valid to the entire ILT.
16906  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16907  *          VNIC3 (of that port). The range allocated will be the
16908  *          entire ILT. This is needed to prevent  ILT range error.
16909  *  2.  Any PF driver load flow:
16910  *      a.  ILT update with the physical addresses of the allocated
16911  *          logical pages.
16912  *      b.  Wait 20msec. - note that this timeout is needed to make
16913  *          sure there are no requests in one of the PXP internal
16914  *          queues with "old" ILT addresses.
16915  *      c.  PF enable in the PGLC.
16916  *      d.  Clear the was_error of the PF in the PGLC. (could have
16917  *          occurred while driver was down)
16918  *      e.  PF enable in the CFC (WEAK + STRONG)
16919  *      f.  Timers scan enable
16920  *  3.  PF driver unload flow:
16921  *      a.  Clear the Timers scan_en.
16922  *      b.  Polling for scan_on=0 for that PF.
16923  *      c.  Clear the PF enable bit in the PXP.
16924  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16925  *      e.  Write zero+valid to all ILT entries (The valid bit must
16926  *          stay set)
16927  *      f.  If this is VNIC 3 of a port then also init
16928  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16929  *          to the last enrty in the ILT.
16930  *
16931  *      Notes:
16932  *      Currently the PF error in the PGLC is non recoverable.
16933  *      In the future the there will be a recovery routine for this error.
16934  *      Currently attention is masked.
16935  *      Having an MCP lock on the load/unload process does not guarantee that
16936  *      there is no Timer disable during Func6/7 enable. This is because the
16937  *      Timers scan is currently being cleared by the MCP on FLR.
16938  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16939  *      there is error before clearing it. But the flow above is simpler and
16940  *      more general.
16941  *      All ILT entries are written by zero+valid and not just PF6/7
16942  *      ILT entries since in the future the ILT entries allocation for
16943  *      PF-s might be dynamic.
16944  */
16945         struct ilt_client_info ilt_cli;
16946         struct ecore_ilt ilt;
16947
16948         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16949         memset(&ilt, 0, sizeof(struct ecore_ilt));
16950
16951         /* initialize dummy TM client */
16952         ilt_cli.start      = 0;
16953         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16954         ilt_cli.client_num = ILT_CLIENT_TM;
16955
16956         /*
16957          * Step 1: set zeroes to all ilt page entries with valid bit on
16958          * Step 2: set the timers first/last ilt entry to point
16959          * to the entire range to prevent ILT range error for 3rd/4th
16960          * vnic (this code assumes existence of the vnic)
16961          *
16962          * both steps performed by call to ecore_ilt_client_init_op()
16963          * with dummy TM client
16964          *
16965          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16966          * and his brother are split registers
16967          */
16968
16969         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16970         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16971         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16972
16973         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16974         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16975         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16976     }
16977
16978     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16979     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16980
16981     if (!CHIP_IS_E1x(sc)) {
16982         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16983                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
16984
16985         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
16986         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
16987
16988         /* let the HW do it's magic... */
16989         do {
16990             DELAY(200000);
16991             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
16992         } while (factor-- && (val != 1));
16993
16994         if (val != 1) {
16995             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
16996             return (-1);
16997         }
16998     }
16999
17000     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
17001
17002     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
17003
17004     bxe_iov_init_dmae(sc);
17005
17006     /* clean the DMAE memory */
17007     sc->dmae_ready = 1;
17008     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
17009
17010     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
17011
17012     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
17013
17014     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
17015
17016     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
17017
17018     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
17019     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17020     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17021     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17022
17023     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17024
17025     /* QM queues pointers table */
17026     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17027
17028     /* soft reset pulse */
17029     REG_WR(sc, QM_REG_SOFT_RESET, 1);
17030     REG_WR(sc, QM_REG_SOFT_RESET, 0);
17031
17032     if (CNIC_SUPPORT(sc))
17033         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17034
17035     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17036     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17037     if (!CHIP_REV_IS_SLOW(sc)) {
17038         /* enable hw interrupt from doorbell Q */
17039         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17040     }
17041
17042     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17043
17044     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17045     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17046
17047     if (!CHIP_IS_E1(sc)) {
17048         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17049     }
17050
17051     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17052         if (IS_MF_AFEX(sc)) {
17053             /*
17054              * configure that AFEX and VLAN headers must be
17055              * received in AFEX mode
17056              */
17057             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17058             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17059             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17060             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17061             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17062         } else {
17063             /*
17064              * Bit-map indicating which L2 hdrs may appear
17065              * after the basic Ethernet header
17066              */
17067             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17068                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17069         }
17070     }
17071
17072     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17073     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17074     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17075     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17076
17077     if (!CHIP_IS_E1x(sc)) {
17078         /* reset VFC memories */
17079         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17080                VFC_MEMORIES_RST_REG_CAM_RST |
17081                VFC_MEMORIES_RST_REG_RAM_RST);
17082         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17083                VFC_MEMORIES_RST_REG_CAM_RST |
17084                VFC_MEMORIES_RST_REG_RAM_RST);
17085
17086         DELAY(20000);
17087     }
17088
17089     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17090     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17091     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17092     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17093
17094     /* sync semi rtc */
17095     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17096            0x80000000);
17097     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17098            0x80000000);
17099
17100     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17101     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17102     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17103
17104     if (!CHIP_IS_E1x(sc)) {
17105         if (IS_MF_AFEX(sc)) {
17106             /*
17107              * configure that AFEX and VLAN headers must be
17108              * sent in AFEX mode
17109              */
17110             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17111             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17112             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17113             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17114             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17115         } else {
17116             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17117                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17118         }
17119     }
17120
17121     REG_WR(sc, SRC_REG_SOFT_RST, 1);
17122
17123     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17124
17125     if (CNIC_SUPPORT(sc)) {
17126         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17127         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17128         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17129         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17130         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17131         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17132         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17133         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17134         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17135         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17136     }
17137     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17138
17139     if (sizeof(union cdu_context) != 1024) {
17140         /* we currently assume that a context is 1024 bytes */
17141         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17142               (long)sizeof(union cdu_context));
17143     }
17144
17145     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17146     val = (4 << 24) + (0 << 12) + 1024;
17147     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17148
17149     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17150
17151     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17152     /* enable context validation interrupt from CFC */
17153     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17154
17155     /* set the thresholds to prevent CFC/CDU race */
17156     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17157     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17158
17159     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17160         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17161     }
17162
17163     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17164     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17165
17166     /* Reset PCIE errors for debug */
17167     REG_WR(sc, 0x2814, 0xffffffff);
17168     REG_WR(sc, 0x3820, 0xffffffff);
17169
17170     if (!CHIP_IS_E1x(sc)) {
17171         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17172                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17173                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17174         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17175                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17176                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17177                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17178         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17179                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17180                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17181                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17182     }
17183
17184     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17185
17186     if (!CHIP_IS_E1(sc)) {
17187         /* in E3 this done in per-port section */
17188         if (!CHIP_IS_E3(sc))
17189             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17190     }
17191
17192     if (CHIP_IS_E1H(sc)) {
17193         /* not applicable for E2 (and above ...) */
17194         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17195     }
17196
17197     if (CHIP_REV_IS_SLOW(sc)) {
17198         DELAY(200000);
17199     }
17200
17201     /* finish CFC init */
17202     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17203     if (val != 1) {
17204         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17205         return (-1);
17206     }
17207     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17208     if (val != 1) {
17209         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17210         return (-1);
17211     }
17212     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17213     if (val != 1) {
17214         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17215         return (-1);
17216     }
17217     REG_WR(sc, CFC_REG_DEBUG0, 0);
17218
17219     if (CHIP_IS_E1(sc)) {
17220         /* read NIG statistic to see if this is our first up since powerup */
17221         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17222         val = *BXE_SP(sc, wb_data[0]);
17223
17224         /* do internal memory self test */
17225         if ((val == 0) && bxe_int_mem_test(sc)) {
17226             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17227             return (-1);
17228         }
17229     }
17230
17231     bxe_setup_fan_failure_detection(sc);
17232
17233     /* clear PXP2 attentions */
17234     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17235
17236     bxe_enable_blocks_attention(sc);
17237
17238     if (!CHIP_REV_IS_SLOW(sc)) {
17239         ecore_enable_blocks_parity(sc);
17240     }
17241
17242     if (!BXE_NOMCP(sc)) {
17243         if (CHIP_IS_E1x(sc)) {
17244             bxe_common_init_phy(sc);
17245         }
17246     }
17247
17248     return (0);
17249 }
17250
17251 /**
17252  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17253  *
17254  * @sc:     driver handle
17255  */
17256 static int
17257 bxe_init_hw_common_chip(struct bxe_softc *sc)
17258 {
17259     int rc = bxe_init_hw_common(sc);
17260
17261     if (rc) {
17262         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17263         return (rc);
17264     }
17265
17266     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17267     if (!BXE_NOMCP(sc)) {
17268         bxe_common_init_phy(sc);
17269     }
17270
17271     return (0);
17272 }
17273
17274 static int
17275 bxe_init_hw_port(struct bxe_softc *sc)
17276 {
17277     int port = SC_PORT(sc);
17278     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17279     uint32_t low, high;
17280     uint32_t val;
17281
17282     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17283
17284     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17285
17286     ecore_init_block(sc, BLOCK_MISC, init_phase);
17287     ecore_init_block(sc, BLOCK_PXP, init_phase);
17288     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17289
17290     /*
17291      * Timers bug workaround: disables the pf_master bit in pglue at
17292      * common phase, we need to enable it here before any dmae access are
17293      * attempted. Therefore we manually added the enable-master to the
17294      * port phase (it also happens in the function phase)
17295      */
17296     if (!CHIP_IS_E1x(sc)) {
17297         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17298     }
17299
17300     ecore_init_block(sc, BLOCK_ATC, init_phase);
17301     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17302     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17303     ecore_init_block(sc, BLOCK_QM, init_phase);
17304
17305     ecore_init_block(sc, BLOCK_TCM, init_phase);
17306     ecore_init_block(sc, BLOCK_UCM, init_phase);
17307     ecore_init_block(sc, BLOCK_CCM, init_phase);
17308     ecore_init_block(sc, BLOCK_XCM, init_phase);
17309
17310     /* QM cid (connection) count */
17311     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17312
17313     if (CNIC_SUPPORT(sc)) {
17314         ecore_init_block(sc, BLOCK_TM, init_phase);
17315         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17316         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17317     }
17318
17319     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17320
17321     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17322
17323     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17324         if (IS_MF(sc)) {
17325             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17326         } else if (sc->mtu > 4096) {
17327             if (BXE_ONE_PORT(sc)) {
17328                 low = 160;
17329             } else {
17330                 val = sc->mtu;
17331                 /* (24*1024 + val*4)/256 */
17332                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17333             }
17334         } else {
17335             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17336         }
17337         high = (low + 56); /* 14*1024/256 */
17338         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17339         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17340     }
17341
17342     if (CHIP_IS_MODE_4_PORT(sc)) {
17343         REG_WR(sc, SC_PORT(sc) ?
17344                BRB1_REG_MAC_GUARANTIED_1 :
17345                BRB1_REG_MAC_GUARANTIED_0, 40);
17346     }
17347
17348     ecore_init_block(sc, BLOCK_PRS, init_phase);
17349     if (CHIP_IS_E3B0(sc)) {
17350         if (IS_MF_AFEX(sc)) {
17351             /* configure headers for AFEX mode */
17352             REG_WR(sc, SC_PORT(sc) ?
17353                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17354                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17355             REG_WR(sc, SC_PORT(sc) ?
17356                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17357                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17358             REG_WR(sc, SC_PORT(sc) ?
17359                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17360                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17361         } else {
17362             /* Ovlan exists only if we are in multi-function +
17363              * switch-dependent mode, in switch-independent there
17364              * is no ovlan headers
17365              */
17366             REG_WR(sc, SC_PORT(sc) ?
17367                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17368                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17369                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17370         }
17371     }
17372
17373     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17374     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17375     ecore_init_block(sc, BLOCK_USDM, init_phase);
17376     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17377
17378     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17379     ecore_init_block(sc, BLOCK_USEM, init_phase);
17380     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17381     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17382
17383     ecore_init_block(sc, BLOCK_UPB, init_phase);
17384     ecore_init_block(sc, BLOCK_XPB, init_phase);
17385
17386     ecore_init_block(sc, BLOCK_PBF, init_phase);
17387
17388     if (CHIP_IS_E1x(sc)) {
17389         /* configure PBF to work without PAUSE mtu 9000 */
17390         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17391
17392         /* update threshold */
17393         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17394         /* update init credit */
17395         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17396
17397         /* probe changes */
17398         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17399         DELAY(50);
17400         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17401     }
17402
17403     if (CNIC_SUPPORT(sc)) {
17404         ecore_init_block(sc, BLOCK_SRC, init_phase);
17405     }
17406
17407     ecore_init_block(sc, BLOCK_CDU, init_phase);
17408     ecore_init_block(sc, BLOCK_CFC, init_phase);
17409
17410     if (CHIP_IS_E1(sc)) {
17411         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17412         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17413     }
17414     ecore_init_block(sc, BLOCK_HC, init_phase);
17415
17416     ecore_init_block(sc, BLOCK_IGU, init_phase);
17417
17418     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17419     /* init aeu_mask_attn_func_0/1:
17420      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17421      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17422      *             bits 4-7 are used for "per vn group attention" */
17423     val = IS_MF(sc) ? 0xF7 : 0x7;
17424     /* Enable DCBX attention for all but E1 */
17425     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17426     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17427
17428     ecore_init_block(sc, BLOCK_NIG, init_phase);
17429
17430     if (!CHIP_IS_E1x(sc)) {
17431         /* Bit-map indicating which L2 hdrs may appear after the
17432          * basic Ethernet header
17433          */
17434         if (IS_MF_AFEX(sc)) {
17435             REG_WR(sc, SC_PORT(sc) ?
17436                    NIG_REG_P1_HDRS_AFTER_BASIC :
17437                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17438         } else {
17439             REG_WR(sc, SC_PORT(sc) ?
17440                    NIG_REG_P1_HDRS_AFTER_BASIC :
17441                    NIG_REG_P0_HDRS_AFTER_BASIC,
17442                    IS_MF_SD(sc) ? 7 : 6);
17443         }
17444
17445         if (CHIP_IS_E3(sc)) {
17446             REG_WR(sc, SC_PORT(sc) ?
17447                    NIG_REG_LLH1_MF_MODE :
17448                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17449         }
17450     }
17451     if (!CHIP_IS_E3(sc)) {
17452         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17453     }
17454
17455     if (!CHIP_IS_E1(sc)) {
17456         /* 0x2 disable mf_ov, 0x1 enable */
17457         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17458                (IS_MF_SD(sc) ? 0x1 : 0x2));
17459
17460         if (!CHIP_IS_E1x(sc)) {
17461             val = 0;
17462             switch (sc->devinfo.mf_info.mf_mode) {
17463             case MULTI_FUNCTION_SD:
17464                 val = 1;
17465                 break;
17466             case MULTI_FUNCTION_SI:
17467             case MULTI_FUNCTION_AFEX:
17468                 val = 2;
17469                 break;
17470             }
17471
17472             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17473                         NIG_REG_LLH0_CLS_TYPE), val);
17474         }
17475         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17476         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17477         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17478     }
17479
17480     /* If SPIO5 is set to generate interrupts, enable it for this port */
17481     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17482     if (val & MISC_SPIO_SPIO5) {
17483         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17484                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17485         val = REG_RD(sc, reg_addr);
17486         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17487         REG_WR(sc, reg_addr, val);
17488     }
17489
17490     return (0);
17491 }
17492
17493 static uint32_t
17494 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17495                        uint32_t         reg,
17496                        uint32_t         expected,
17497                        uint32_t         poll_count)
17498 {
17499     uint32_t cur_cnt = poll_count;
17500     uint32_t val;
17501
17502     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17503         DELAY(FLR_WAIT_INTERVAL);
17504     }
17505
17506     return (val);
17507 }
17508
17509 static int
17510 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17511                               uint32_t         reg,
17512                               char             *msg,
17513                               uint32_t         poll_cnt)
17514 {
17515     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17516
17517     if (val != 0) {
17518         BLOGE(sc, "%s usage count=%d\n", msg, val);
17519         return (1);
17520     }
17521
17522     return (0);
17523 }
17524
17525 /* Common routines with VF FLR cleanup */
17526 static uint32_t
17527 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17528 {
17529     /* adjust polling timeout */
17530     if (CHIP_REV_IS_EMUL(sc)) {
17531         return (FLR_POLL_CNT * 2000);
17532     }
17533
17534     if (CHIP_REV_IS_FPGA(sc)) {
17535         return (FLR_POLL_CNT * 120);
17536     }
17537
17538     return (FLR_POLL_CNT);
17539 }
17540
17541 static int
17542 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17543                            uint32_t         poll_cnt)
17544 {
17545     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17546     if (bxe_flr_clnup_poll_hw_counter(sc,
17547                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17548                                       "CFC PF usage counter timed out",
17549                                       poll_cnt)) {
17550         return (1);
17551     }
17552
17553     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17554     if (bxe_flr_clnup_poll_hw_counter(sc,
17555                                       DORQ_REG_PF_USAGE_CNT,
17556                                       "DQ PF usage counter timed out",
17557                                       poll_cnt)) {
17558         return (1);
17559     }
17560
17561     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17562     if (bxe_flr_clnup_poll_hw_counter(sc,
17563                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17564                                       "QM PF usage counter timed out",
17565                                       poll_cnt)) {
17566         return (1);
17567     }
17568
17569     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17570     if (bxe_flr_clnup_poll_hw_counter(sc,
17571                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17572                                       "Timers VNIC usage counter timed out",
17573                                       poll_cnt)) {
17574         return (1);
17575     }
17576
17577     if (bxe_flr_clnup_poll_hw_counter(sc,
17578                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17579                                       "Timers NUM_SCANS usage counter timed out",
17580                                       poll_cnt)) {
17581         return (1);
17582     }
17583
17584     /* Wait DMAE PF usage counter to zero */
17585     if (bxe_flr_clnup_poll_hw_counter(sc,
17586                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17587                                       "DMAE dommand register timed out",
17588                                       poll_cnt)) {
17589         return (1);
17590     }
17591
17592     return (0);
17593 }
17594
17595 #define OP_GEN_PARAM(param)                                            \
17596     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17597 #define OP_GEN_TYPE(type)                                           \
17598     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17599 #define OP_GEN_AGG_VECT(index)                                             \
17600     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17601
17602 static int
17603 bxe_send_final_clnup(struct bxe_softc *sc,
17604                      uint8_t          clnup_func,
17605                      uint32_t         poll_cnt)
17606 {
17607     uint32_t op_gen_command = 0;
17608     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17609                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17610     int ret = 0;
17611
17612     if (REG_RD(sc, comp_addr)) {
17613         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17614         return (1);
17615     }
17616
17617     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17618     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17619     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17620     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17621
17622     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17623     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17624
17625     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17626         BLOGE(sc, "FW final cleanup did not succeed\n");
17627         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17628               (REG_RD(sc, comp_addr)));
17629         bxe_panic(sc, ("FLR cleanup failed\n"));
17630         return (1);
17631     }
17632
17633     /* Zero completion for nxt FLR */
17634     REG_WR(sc, comp_addr, 0);
17635
17636     return (ret);
17637 }
17638
17639 static void
17640 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17641                        struct pbf_pN_buf_regs *regs,
17642                        uint32_t               poll_count)
17643 {
17644     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17645     uint32_t cur_cnt = poll_count;
17646
17647     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17648     crd = crd_start = REG_RD(sc, regs->crd);
17649     init_crd = REG_RD(sc, regs->init_crd);
17650
17651     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17652     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17653     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17654
17655     while ((crd != init_crd) &&
17656            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17657             (init_crd - crd_start))) {
17658         if (cur_cnt--) {
17659             DELAY(FLR_WAIT_INTERVAL);
17660             crd = REG_RD(sc, regs->crd);
17661             crd_freed = REG_RD(sc, regs->crd_freed);
17662         } else {
17663             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17664             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17665             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17666             break;
17667         }
17668     }
17669
17670     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17671           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17672 }
17673
17674 static void
17675 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17676                        struct pbf_pN_cmd_regs *regs,
17677                        uint32_t               poll_count)
17678 {
17679     uint32_t occup, to_free, freed, freed_start;
17680     uint32_t cur_cnt = poll_count;
17681
17682     occup = to_free = REG_RD(sc, regs->lines_occup);
17683     freed = freed_start = REG_RD(sc, regs->lines_freed);
17684
17685     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17686     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17687
17688     while (occup &&
17689            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17690         if (cur_cnt--) {
17691             DELAY(FLR_WAIT_INTERVAL);
17692             occup = REG_RD(sc, regs->lines_occup);
17693             freed = REG_RD(sc, regs->lines_freed);
17694         } else {
17695             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17696             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17697             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17698             break;
17699         }
17700     }
17701
17702     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17703           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17704 }
17705
17706 static void
17707 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17708 {
17709     struct pbf_pN_cmd_regs cmd_regs[] = {
17710         {0, (CHIP_IS_E3B0(sc)) ?
17711             PBF_REG_TQ_OCCUPANCY_Q0 :
17712             PBF_REG_P0_TQ_OCCUPANCY,
17713             (CHIP_IS_E3B0(sc)) ?
17714             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17715             PBF_REG_P0_TQ_LINES_FREED_CNT},
17716         {1, (CHIP_IS_E3B0(sc)) ?
17717             PBF_REG_TQ_OCCUPANCY_Q1 :
17718             PBF_REG_P1_TQ_OCCUPANCY,
17719             (CHIP_IS_E3B0(sc)) ?
17720             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17721             PBF_REG_P1_TQ_LINES_FREED_CNT},
17722         {4, (CHIP_IS_E3B0(sc)) ?
17723             PBF_REG_TQ_OCCUPANCY_LB_Q :
17724             PBF_REG_P4_TQ_OCCUPANCY,
17725             (CHIP_IS_E3B0(sc)) ?
17726             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17727             PBF_REG_P4_TQ_LINES_FREED_CNT}
17728     };
17729
17730     struct pbf_pN_buf_regs buf_regs[] = {
17731         {0, (CHIP_IS_E3B0(sc)) ?
17732             PBF_REG_INIT_CRD_Q0 :
17733             PBF_REG_P0_INIT_CRD ,
17734             (CHIP_IS_E3B0(sc)) ?
17735             PBF_REG_CREDIT_Q0 :
17736             PBF_REG_P0_CREDIT,
17737             (CHIP_IS_E3B0(sc)) ?
17738             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17739             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17740         {1, (CHIP_IS_E3B0(sc)) ?
17741             PBF_REG_INIT_CRD_Q1 :
17742             PBF_REG_P1_INIT_CRD,
17743             (CHIP_IS_E3B0(sc)) ?
17744             PBF_REG_CREDIT_Q1 :
17745             PBF_REG_P1_CREDIT,
17746             (CHIP_IS_E3B0(sc)) ?
17747             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17748             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17749         {4, (CHIP_IS_E3B0(sc)) ?
17750             PBF_REG_INIT_CRD_LB_Q :
17751             PBF_REG_P4_INIT_CRD,
17752             (CHIP_IS_E3B0(sc)) ?
17753             PBF_REG_CREDIT_LB_Q :
17754             PBF_REG_P4_CREDIT,
17755             (CHIP_IS_E3B0(sc)) ?
17756             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17757             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17758     };
17759
17760     int i;
17761
17762     /* Verify the command queues are flushed P0, P1, P4 */
17763     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17764         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17765     }
17766
17767     /* Verify the transmission buffers are flushed P0, P1, P4 */
17768     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17769         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17770     }
17771 }
17772
17773 static void
17774 bxe_hw_enable_status(struct bxe_softc *sc)
17775 {
17776     uint32_t val;
17777
17778     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17779     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17780
17781     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17782     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17783
17784     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17785     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17786
17787     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17788     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17789
17790     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17791     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17792
17793     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17794     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17795
17796     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17797     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17798
17799     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17800     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17801 }
17802
17803 static int
17804 bxe_pf_flr_clnup(struct bxe_softc *sc)
17805 {
17806     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17807
17808     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17809
17810     /* Re-enable PF target read access */
17811     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17812
17813     /* Poll HW usage counters */
17814     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17815     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17816         return (-1);
17817     }
17818
17819     /* Zero the igu 'trailing edge' and 'leading edge' */
17820
17821     /* Send the FW cleanup command */
17822     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17823         return (-1);
17824     }
17825
17826     /* ATC cleanup */
17827
17828     /* Verify TX hw is flushed */
17829     bxe_tx_hw_flushed(sc, poll_cnt);
17830
17831     /* Wait 100ms (not adjusted according to platform) */
17832     DELAY(100000);
17833
17834     /* Verify no pending pci transactions */
17835     if (bxe_is_pcie_pending(sc)) {
17836         BLOGE(sc, "PCIE Transactions still pending\n");
17837     }
17838
17839     /* Debug */
17840     bxe_hw_enable_status(sc);
17841
17842     /*
17843      * Master enable - Due to WB DMAE writes performed before this
17844      * register is re-initialized as part of the regular function init
17845      */
17846     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17847
17848     return (0);
17849 }
17850
17851 static int
17852 bxe_init_hw_func(struct bxe_softc *sc)
17853 {
17854     int port = SC_PORT(sc);
17855     int func = SC_FUNC(sc);
17856     int init_phase = PHASE_PF0 + func;
17857     struct ecore_ilt *ilt = sc->ilt;
17858     uint16_t cdu_ilt_start;
17859     uint32_t addr, val;
17860     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17861     int i, main_mem_width, rc;
17862
17863     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17864
17865     /* FLR cleanup */
17866     if (!CHIP_IS_E1x(sc)) {
17867         rc = bxe_pf_flr_clnup(sc);
17868         if (rc) {
17869             BLOGE(sc, "FLR cleanup failed!\n");
17870             // XXX bxe_fw_dump(sc);
17871             // XXX bxe_idle_chk(sc);
17872             return (rc);
17873         }
17874     }
17875
17876     /* set MSI reconfigure capability */
17877     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17878         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17879         val = REG_RD(sc, addr);
17880         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17881         REG_WR(sc, addr, val);
17882     }
17883
17884     ecore_init_block(sc, BLOCK_PXP, init_phase);
17885     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17886
17887     ilt = sc->ilt;
17888     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17889
17890     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17891         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17892         ilt->lines[cdu_ilt_start + i].page_mapping =
17893             sc->context[i].vcxt_dma.paddr;
17894         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17895     }
17896     ecore_ilt_init_op(sc, INITOP_SET);
17897
17898     /* Set NIC mode */
17899     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17900     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17901
17902     if (!CHIP_IS_E1x(sc)) {
17903         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17904
17905         /* Turn on a single ISR mode in IGU if driver is going to use
17906          * INT#x or MSI
17907          */
17908         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17909             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17910         }
17911
17912         /*
17913          * Timers workaround bug: function init part.
17914          * Need to wait 20msec after initializing ILT,
17915          * needed to make sure there are no requests in
17916          * one of the PXP internal queues with "old" ILT addresses
17917          */
17918         DELAY(20000);
17919
17920         /*
17921          * Master enable - Due to WB DMAE writes performed before this
17922          * register is re-initialized as part of the regular function
17923          * init
17924          */
17925         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17926         /* Enable the function in IGU */
17927         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17928     }
17929
17930     sc->dmae_ready = 1;
17931
17932     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17933
17934     if (!CHIP_IS_E1x(sc))
17935         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17936
17937     ecore_init_block(sc, BLOCK_ATC, init_phase);
17938     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17939     ecore_init_block(sc, BLOCK_NIG, init_phase);
17940     ecore_init_block(sc, BLOCK_SRC, init_phase);
17941     ecore_init_block(sc, BLOCK_MISC, init_phase);
17942     ecore_init_block(sc, BLOCK_TCM, init_phase);
17943     ecore_init_block(sc, BLOCK_UCM, init_phase);
17944     ecore_init_block(sc, BLOCK_CCM, init_phase);
17945     ecore_init_block(sc, BLOCK_XCM, init_phase);
17946     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17947     ecore_init_block(sc, BLOCK_USEM, init_phase);
17948     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17949     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17950
17951     if (!CHIP_IS_E1x(sc))
17952         REG_WR(sc, QM_REG_PF_EN, 1);
17953
17954     if (!CHIP_IS_E1x(sc)) {
17955         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17956         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17957         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17958         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17959     }
17960     ecore_init_block(sc, BLOCK_QM, init_phase);
17961
17962     ecore_init_block(sc, BLOCK_TM, init_phase);
17963     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17964
17965     bxe_iov_init_dq(sc);
17966
17967     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17968     ecore_init_block(sc, BLOCK_PRS, init_phase);
17969     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17970     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17971     ecore_init_block(sc, BLOCK_USDM, init_phase);
17972     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17973     ecore_init_block(sc, BLOCK_UPB, init_phase);
17974     ecore_init_block(sc, BLOCK_XPB, init_phase);
17975     ecore_init_block(sc, BLOCK_PBF, init_phase);
17976     if (!CHIP_IS_E1x(sc))
17977         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17978
17979     ecore_init_block(sc, BLOCK_CDU, init_phase);
17980
17981     ecore_init_block(sc, BLOCK_CFC, init_phase);
17982
17983     if (!CHIP_IS_E1x(sc))
17984         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
17985
17986     if (IS_MF(sc)) {
17987         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
17988         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
17989     }
17990
17991     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17992
17993     /* HC init per function */
17994     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17995         if (CHIP_IS_E1H(sc)) {
17996             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17997
17998             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17999             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18000         }
18001         ecore_init_block(sc, BLOCK_HC, init_phase);
18002
18003     } else {
18004         int num_segs, sb_idx, prod_offset;
18005
18006         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18007
18008         if (!CHIP_IS_E1x(sc)) {
18009             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18010             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18011         }
18012
18013         ecore_init_block(sc, BLOCK_IGU, init_phase);
18014
18015         if (!CHIP_IS_E1x(sc)) {
18016             int dsb_idx = 0;
18017             /**
18018              * Producer memory:
18019              * E2 mode: address 0-135 match to the mapping memory;
18020              * 136 - PF0 default prod; 137 - PF1 default prod;
18021              * 138 - PF2 default prod; 139 - PF3 default prod;
18022              * 140 - PF0 attn prod;    141 - PF1 attn prod;
18023              * 142 - PF2 attn prod;    143 - PF3 attn prod;
18024              * 144-147 reserved.
18025              *
18026              * E1.5 mode - In backward compatible mode;
18027              * for non default SB; each even line in the memory
18028              * holds the U producer and each odd line hold
18029              * the C producer. The first 128 producers are for
18030              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18031              * producers are for the DSB for each PF.
18032              * Each PF has five segments: (the order inside each
18033              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18034              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18035              * 144-147 attn prods;
18036              */
18037             /* non-default-status-blocks */
18038             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18039                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18040             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18041                 prod_offset = (sc->igu_base_sb + sb_idx) *
18042                     num_segs;
18043
18044                 for (i = 0; i < num_segs; i++) {
18045                     addr = IGU_REG_PROD_CONS_MEMORY +
18046                             (prod_offset + i) * 4;
18047                     REG_WR(sc, addr, 0);
18048                 }
18049                 /* send consumer update with value 0 */
18050                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18051                            USTORM_ID, 0, IGU_INT_NOP, 1);
18052                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18053             }
18054
18055             /* default-status-blocks */
18056             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18057                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18058
18059             if (CHIP_IS_MODE_4_PORT(sc))
18060                 dsb_idx = SC_FUNC(sc);
18061             else
18062                 dsb_idx = SC_VN(sc);
18063
18064             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18065                        IGU_BC_BASE_DSB_PROD + dsb_idx :
18066                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
18067
18068             /*
18069              * igu prods come in chunks of E1HVN_MAX (4) -
18070              * does not matters what is the current chip mode
18071              */
18072             for (i = 0; i < (num_segs * E1HVN_MAX);
18073                  i += E1HVN_MAX) {
18074                 addr = IGU_REG_PROD_CONS_MEMORY +
18075                             (prod_offset + i)*4;
18076                 REG_WR(sc, addr, 0);
18077             }
18078             /* send consumer update with 0 */
18079             if (CHIP_INT_MODE_IS_BC(sc)) {
18080                 bxe_ack_sb(sc, sc->igu_dsb_id,
18081                            USTORM_ID, 0, IGU_INT_NOP, 1);
18082                 bxe_ack_sb(sc, sc->igu_dsb_id,
18083                            CSTORM_ID, 0, IGU_INT_NOP, 1);
18084                 bxe_ack_sb(sc, sc->igu_dsb_id,
18085                            XSTORM_ID, 0, IGU_INT_NOP, 1);
18086                 bxe_ack_sb(sc, sc->igu_dsb_id,
18087                            TSTORM_ID, 0, IGU_INT_NOP, 1);
18088                 bxe_ack_sb(sc, sc->igu_dsb_id,
18089                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18090             } else {
18091                 bxe_ack_sb(sc, sc->igu_dsb_id,
18092                            USTORM_ID, 0, IGU_INT_NOP, 1);
18093                 bxe_ack_sb(sc, sc->igu_dsb_id,
18094                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18095             }
18096             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18097
18098             /* !!! these should become driver const once
18099                rf-tool supports split-68 const */
18100             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18101             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18102             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18103             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18104             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18105             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18106         }
18107     }
18108
18109     /* Reset PCIE errors for debug */
18110     REG_WR(sc, 0x2114, 0xffffffff);
18111     REG_WR(sc, 0x2120, 0xffffffff);
18112
18113     if (CHIP_IS_E1x(sc)) {
18114         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18115         main_mem_base = HC_REG_MAIN_MEMORY +
18116                 SC_PORT(sc) * (main_mem_size * 4);
18117         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18118         main_mem_width = 8;
18119
18120         val = REG_RD(sc, main_mem_prty_clr);
18121         if (val) {
18122             BLOGD(sc, DBG_LOAD,
18123                   "Parity errors in HC block during function init (0x%x)!\n",
18124                   val);
18125         }
18126
18127         /* Clear "false" parity errors in MSI-X table */
18128         for (i = main_mem_base;
18129              i < main_mem_base + main_mem_size * 4;
18130              i += main_mem_width) {
18131             bxe_read_dmae(sc, i, main_mem_width / 4);
18132             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18133                            i, main_mem_width / 4);
18134         }
18135         /* Clear HC parity attention */
18136         REG_RD(sc, main_mem_prty_clr);
18137     }
18138
18139 #if 1
18140     /* Enable STORMs SP logging */
18141     REG_WR8(sc, BAR_USTRORM_INTMEM +
18142            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18143     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18144            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18145     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18146            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18147     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18148            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18149 #endif
18150
18151     elink_phy_probe(&sc->link_params);
18152
18153     return (0);
18154 }
18155
18156 static void
18157 bxe_link_reset(struct bxe_softc *sc)
18158 {
18159     if (!BXE_NOMCP(sc)) {
18160         bxe_acquire_phy_lock(sc);
18161         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18162         bxe_release_phy_lock(sc);
18163     } else {
18164         if (!CHIP_REV_IS_SLOW(sc)) {
18165             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18166         }
18167     }
18168 }
18169
18170 static void
18171 bxe_reset_port(struct bxe_softc *sc)
18172 {
18173     int port = SC_PORT(sc);
18174     uint32_t val;
18175
18176     /* reset physical Link */
18177     bxe_link_reset(sc);
18178
18179     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18180
18181     /* Do not rcv packets to BRB */
18182     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18183     /* Do not direct rcv packets that are not for MCP to the BRB */
18184     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18185                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18186
18187     /* Configure AEU */
18188     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18189
18190     DELAY(100000);
18191
18192     /* Check for BRB port occupancy */
18193     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18194     if (val) {
18195         BLOGD(sc, DBG_LOAD,
18196               "BRB1 is not empty, %d blocks are occupied\n", val);
18197     }
18198
18199     /* TODO: Close Doorbell port? */
18200 }
18201
18202 static void
18203 bxe_ilt_wr(struct bxe_softc *sc,
18204            uint32_t         index,
18205            bus_addr_t       addr)
18206 {
18207     int reg;
18208     uint32_t wb_write[2];
18209
18210     if (CHIP_IS_E1(sc)) {
18211         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18212     } else {
18213         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18214     }
18215
18216     wb_write[0] = ONCHIP_ADDR1(addr);
18217     wb_write[1] = ONCHIP_ADDR2(addr);
18218     REG_WR_DMAE(sc, reg, wb_write, 2);
18219 }
18220
18221 static void
18222 bxe_clear_func_ilt(struct bxe_softc *sc,
18223                    uint32_t         func)
18224 {
18225     uint32_t i, base = FUNC_ILT_BASE(func);
18226     for (i = base; i < base + ILT_PER_FUNC; i++) {
18227         bxe_ilt_wr(sc, i, 0);
18228     }
18229 }
18230
18231 static void
18232 bxe_reset_func(struct bxe_softc *sc)
18233 {
18234     struct bxe_fastpath *fp;
18235     int port = SC_PORT(sc);
18236     int func = SC_FUNC(sc);
18237     int i;
18238
18239     /* Disable the function in the FW */
18240     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18241     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18242     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18243     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18244
18245     /* FP SBs */
18246     FOR_EACH_ETH_QUEUE(sc, i) {
18247         fp = &sc->fp[i];
18248         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18249                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18250                 SB_DISABLED);
18251     }
18252
18253     /* SP SB */
18254     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18255             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18256             SB_DISABLED);
18257
18258     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18259         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18260     }
18261
18262     /* Configure IGU */
18263     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18264         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18265         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18266     } else {
18267         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18268         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18269     }
18270
18271     if (CNIC_LOADED(sc)) {
18272         /* Disable Timer scan */
18273         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18274         /*
18275          * Wait for at least 10ms and up to 2 second for the timers
18276          * scan to complete
18277          */
18278         for (i = 0; i < 200; i++) {
18279             DELAY(10000);
18280             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18281                 break;
18282         }
18283     }
18284
18285     /* Clear ILT */
18286     bxe_clear_func_ilt(sc, func);
18287
18288     /*
18289      * Timers workaround bug for E2: if this is vnic-3,
18290      * we need to set the entire ilt range for this timers.
18291      */
18292     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18293         struct ilt_client_info ilt_cli;
18294         /* use dummy TM client */
18295         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18296         ilt_cli.start = 0;
18297         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18298         ilt_cli.client_num = ILT_CLIENT_TM;
18299
18300         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18301     }
18302
18303     /* this assumes that reset_port() called before reset_func()*/
18304     if (!CHIP_IS_E1x(sc)) {
18305         bxe_pf_disable(sc);
18306     }
18307
18308     sc->dmae_ready = 0;
18309 }
18310
18311 static int
18312 bxe_gunzip_init(struct bxe_softc *sc)
18313 {
18314     return (0);
18315 }
18316
18317 static void
18318 bxe_gunzip_end(struct bxe_softc *sc)
18319 {
18320     return;
18321 }
18322
18323 static int
18324 bxe_init_firmware(struct bxe_softc *sc)
18325 {
18326     if (CHIP_IS_E1(sc)) {
18327         ecore_init_e1_firmware(sc);
18328         sc->iro_array = e1_iro_arr;
18329     } else if (CHIP_IS_E1H(sc)) {
18330         ecore_init_e1h_firmware(sc);
18331         sc->iro_array = e1h_iro_arr;
18332     } else if (!CHIP_IS_E1x(sc)) {
18333         ecore_init_e2_firmware(sc);
18334         sc->iro_array = e2_iro_arr;
18335     } else {
18336         BLOGE(sc, "Unsupported chip revision\n");
18337         return (-1);
18338     }
18339
18340     return (0);
18341 }
18342
18343 static void
18344 bxe_release_firmware(struct bxe_softc *sc)
18345 {
18346     /* Do nothing */
18347     return;
18348 }
18349
18350 static int
18351 ecore_gunzip(struct bxe_softc *sc,
18352              const uint8_t    *zbuf,
18353              int              len)
18354 {
18355     /* XXX : Implement... */
18356     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18357     return (FALSE);
18358 }
18359
18360 static void
18361 ecore_reg_wr_ind(struct bxe_softc *sc,
18362                  uint32_t         addr,
18363                  uint32_t         val)
18364 {
18365     bxe_reg_wr_ind(sc, addr, val);
18366 }
18367
18368 static void
18369 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18370                           bus_addr_t       phys_addr,
18371                           uint32_t         addr,
18372                           uint32_t         len)
18373 {
18374     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18375 }
18376
18377 void
18378 ecore_storm_memset_struct(struct bxe_softc *sc,
18379                           uint32_t         addr,
18380                           size_t           size,
18381                           uint32_t         *data)
18382 {
18383     uint8_t i;
18384     for (i = 0; i < size/4; i++) {
18385         REG_WR(sc, addr + (i * 4), data[i]);
18386     }
18387 }
18388
18389
18390 /*
18391  * character device - ioctl interface definitions
18392  */
18393
18394
18395 #include "bxe_dump.h"
18396 #include "bxe_ioctl.h"
18397 #include <sys/conf.h>
18398
18399 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18400                 struct thread *td);
18401
18402 static struct cdevsw bxe_cdevsw = {
18403     .d_version = D_VERSION,
18404     .d_ioctl = bxe_eioctl,
18405     .d_name = "bxecnic",
18406 };
18407
18408 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18409
18410
18411 #define DUMP_ALL_PRESETS        0x1FFF
18412 #define DUMP_MAX_PRESETS        13
18413 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18414 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18415 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18416 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18417 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18418
18419 #define IS_REG_IN_PRESET(presets, idx)  \
18420                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18421
18422
18423 static int
18424 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18425 {
18426     if (CHIP_IS_E1(sc))
18427         return dump_num_registers[0][preset-1];
18428     else if (CHIP_IS_E1H(sc))
18429         return dump_num_registers[1][preset-1];
18430     else if (CHIP_IS_E2(sc))
18431         return dump_num_registers[2][preset-1];
18432     else if (CHIP_IS_E3A0(sc))
18433         return dump_num_registers[3][preset-1];
18434     else if (CHIP_IS_E3B0(sc))
18435         return dump_num_registers[4][preset-1];
18436     else
18437         return 0;
18438 }
18439
18440 static int
18441 bxe_get_total_regs_len32(struct bxe_softc *sc)
18442 {
18443     uint32_t preset_idx;
18444     int regdump_len32 = 0;
18445
18446
18447     /* Calculate the total preset regs length */
18448     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18449         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18450     }
18451
18452     return regdump_len32;
18453 }
18454
18455 static const uint32_t *
18456 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18457 {
18458     if (CHIP_IS_E2(sc))
18459         return page_vals_e2;
18460     else if (CHIP_IS_E3(sc))
18461         return page_vals_e3;
18462     else
18463         return NULL;
18464 }
18465
18466 static uint32_t
18467 __bxe_get_page_reg_num(struct bxe_softc *sc)
18468 {
18469     if (CHIP_IS_E2(sc))
18470         return PAGE_MODE_VALUES_E2;
18471     else if (CHIP_IS_E3(sc))
18472         return PAGE_MODE_VALUES_E3;
18473     else
18474         return 0;
18475 }
18476
18477 static const uint32_t *
18478 __bxe_get_page_write_ar(struct bxe_softc *sc)
18479 {
18480     if (CHIP_IS_E2(sc))
18481         return page_write_regs_e2;
18482     else if (CHIP_IS_E3(sc))
18483         return page_write_regs_e3;
18484     else
18485         return NULL;
18486 }
18487
18488 static uint32_t
18489 __bxe_get_page_write_num(struct bxe_softc *sc)
18490 {
18491     if (CHIP_IS_E2(sc))
18492         return PAGE_WRITE_REGS_E2;
18493     else if (CHIP_IS_E3(sc))
18494         return PAGE_WRITE_REGS_E3;
18495     else
18496         return 0;
18497 }
18498
18499 static const struct reg_addr *
18500 __bxe_get_page_read_ar(struct bxe_softc *sc)
18501 {
18502     if (CHIP_IS_E2(sc))
18503         return page_read_regs_e2;
18504     else if (CHIP_IS_E3(sc))
18505         return page_read_regs_e3;
18506     else
18507         return NULL;
18508 }
18509
18510 static uint32_t
18511 __bxe_get_page_read_num(struct bxe_softc *sc)
18512 {
18513     if (CHIP_IS_E2(sc))
18514         return PAGE_READ_REGS_E2;
18515     else if (CHIP_IS_E3(sc))
18516         return PAGE_READ_REGS_E3;
18517     else
18518         return 0;
18519 }
18520
18521 static bool
18522 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18523 {
18524     if (CHIP_IS_E1(sc))
18525         return IS_E1_REG(reg_info->chips);
18526     else if (CHIP_IS_E1H(sc))
18527         return IS_E1H_REG(reg_info->chips);
18528     else if (CHIP_IS_E2(sc))
18529         return IS_E2_REG(reg_info->chips);
18530     else if (CHIP_IS_E3A0(sc))
18531         return IS_E3A0_REG(reg_info->chips);
18532     else if (CHIP_IS_E3B0(sc))
18533         return IS_E3B0_REG(reg_info->chips);
18534     else
18535         return 0;
18536 }
18537
18538 static bool
18539 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18540 {
18541     if (CHIP_IS_E1(sc))
18542         return IS_E1_REG(wreg_info->chips);
18543     else if (CHIP_IS_E1H(sc))
18544         return IS_E1H_REG(wreg_info->chips);
18545     else if (CHIP_IS_E2(sc))
18546         return IS_E2_REG(wreg_info->chips);
18547     else if (CHIP_IS_E3A0(sc))
18548         return IS_E3A0_REG(wreg_info->chips);
18549     else if (CHIP_IS_E3B0(sc))
18550         return IS_E3B0_REG(wreg_info->chips);
18551     else
18552         return 0;
18553 }
18554
18555 /**
18556  * bxe_read_pages_regs - read "paged" registers
18557  *
18558  * @bp          device handle
18559  * @p           output buffer
18560  *
18561  * Reads "paged" memories: memories that may only be read by first writing to a
18562  * specific address ("write address") and then reading from a specific address
18563  * ("read address"). There may be more than one write address per "page" and
18564  * more than one read address per write address.
18565  */
18566 static void
18567 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18568 {
18569     uint32_t i, j, k, n;
18570
18571     /* addresses of the paged registers */
18572     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18573     /* number of paged registers */
18574     int num_pages = __bxe_get_page_reg_num(sc);
18575     /* write addresses */
18576     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18577     /* number of write addresses */
18578     int write_num = __bxe_get_page_write_num(sc);
18579     /* read addresses info */
18580     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18581     /* number of read addresses */
18582     int read_num = __bxe_get_page_read_num(sc);
18583     uint32_t addr, size;
18584
18585     for (i = 0; i < num_pages; i++) {
18586         for (j = 0; j < write_num; j++) {
18587             REG_WR(sc, write_addr[j], page_addr[i]);
18588
18589             for (k = 0; k < read_num; k++) {
18590                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18591                     size = read_addr[k].size;
18592                     for (n = 0; n < size; n++) {
18593                         addr = read_addr[k].addr + n*4;
18594                         *p++ = REG_RD(sc, addr);
18595                     }
18596                 }
18597             }
18598         }
18599     }
18600     return;
18601 }
18602
18603
18604 static int
18605 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18606 {
18607     uint32_t i, j, addr;
18608     const struct wreg_addr *wreg_addr_p = NULL;
18609
18610     if (CHIP_IS_E1(sc))
18611         wreg_addr_p = &wreg_addr_e1;
18612     else if (CHIP_IS_E1H(sc))
18613         wreg_addr_p = &wreg_addr_e1h;
18614     else if (CHIP_IS_E2(sc))
18615         wreg_addr_p = &wreg_addr_e2;
18616     else if (CHIP_IS_E3A0(sc))
18617         wreg_addr_p = &wreg_addr_e3;
18618     else if (CHIP_IS_E3B0(sc))
18619         wreg_addr_p = &wreg_addr_e3b0;
18620     else
18621         return (-1);
18622
18623     /* Read the idle_chk registers */
18624     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18625         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18626             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18627             for (j = 0; j < idle_reg_addrs[i].size; j++)
18628                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18629         }
18630     }
18631
18632     /* Read the regular registers */
18633     for (i = 0; i < REGS_COUNT; i++) {
18634         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18635             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18636             for (j = 0; j < reg_addrs[i].size; j++)
18637                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18638         }
18639     }
18640
18641     /* Read the CAM registers */
18642     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18643         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18644         for (i = 0; i < wreg_addr_p->size; i++) {
18645             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18646
18647             /* In case of wreg_addr register, read additional
18648                registers from read_regs array
18649              */
18650             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18651                 addr = *(wreg_addr_p->read_regs);
18652                 *p++ = REG_RD(sc, addr + j*4);
18653             }
18654         }
18655     }
18656
18657     /* Paged registers are supported in E2 & E3 only */
18658     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18659         /* Read "paged" registers */
18660         bxe_read_pages_regs(sc, p, preset);
18661     }
18662
18663     return 0;
18664 }
18665
18666 int
18667 bxe_grc_dump(struct bxe_softc *sc)
18668 {
18669     int rval = 0;
18670     uint32_t preset_idx;
18671     uint8_t *buf;
18672     uint32_t size;
18673     struct  dump_header *d_hdr;
18674     uint32_t i;
18675     uint32_t reg_val;
18676     uint32_t reg_addr;
18677     uint32_t cmd_offset;
18678     int context_size;
18679     int allocated;
18680     struct ecore_ilt *ilt = SC_ILT(sc);
18681     struct bxe_fastpath *fp;
18682     struct ilt_client_info *ilt_cli;
18683     int grc_dump_size;
18684
18685
18686     if (sc->grcdump_done || sc->grcdump_started)
18687         return (rval);
18688     
18689     sc->grcdump_started = 1;
18690     BLOGI(sc, "Started collecting grcdump\n");
18691
18692     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18693                 sizeof(struct  dump_header);
18694
18695     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18696
18697     if (sc->grc_dump == NULL) {
18698         BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
18699         return(ENOMEM);
18700     }
18701
18702
18703
18704     /* Disable parity attentions as long as following dump may
18705      * cause false alarms by reading never written registers. We
18706      * will re-enable parity attentions right after the dump.
18707      */
18708
18709     /* Disable parity on path 0 */
18710     bxe_pretend_func(sc, 0);
18711
18712     ecore_disable_blocks_parity(sc);
18713
18714     /* Disable parity on path 1 */
18715     bxe_pretend_func(sc, 1);
18716     ecore_disable_blocks_parity(sc);
18717
18718     /* Return to current function */
18719     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18720
18721     buf = sc->grc_dump;
18722     d_hdr = sc->grc_dump;
18723
18724     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18725     d_hdr->version = BNX2X_DUMP_VERSION;
18726     d_hdr->preset = DUMP_ALL_PRESETS;
18727
18728     if (CHIP_IS_E1(sc)) {
18729         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18730     } else if (CHIP_IS_E1H(sc)) {
18731         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18732     } else if (CHIP_IS_E2(sc)) {
18733         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18734                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18735     } else if (CHIP_IS_E3A0(sc)) {
18736         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18737                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18738     } else if (CHIP_IS_E3B0(sc)) {
18739         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18740                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18741     }
18742
18743     buf += sizeof(struct  dump_header);
18744
18745     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18746
18747         /* Skip presets with IOR */
18748         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18749             (preset_idx == 11))
18750             continue;
18751
18752         rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
18753
18754         if (rval)
18755             break;
18756
18757         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18758
18759         buf += size;
18760     }
18761
18762     bxe_pretend_func(sc, 0);
18763     ecore_clear_blocks_parity(sc);
18764     ecore_enable_blocks_parity(sc);
18765
18766     bxe_pretend_func(sc, 1);
18767     ecore_clear_blocks_parity(sc);
18768     ecore_enable_blocks_parity(sc);
18769
18770     /* Return to current function */
18771     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18772
18773
18774     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
18775     for (i = 0, allocated = 0; allocated < context_size; i++) {
18776
18777         BLOGI(sc, "cdu_context i %d paddr %#jx vaddr %p size 0x%zx\n", i,
18778             (uintmax_t)sc->context[i].vcxt_dma.paddr,
18779             sc->context[i].vcxt_dma.vaddr,
18780             sc->context[i].size);
18781         allocated += sc->context[i].size;
18782     }
18783     BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
18784         (uintmax_t)sc->fw_stats_req_mapping,
18785         (uintmax_t)sc->fw_stats_data_mapping,
18786         sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
18787     BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
18788         (void *)sc->def_sb_dma.paddr, sc->def_sb,
18789         sizeof(struct host_sp_status_block));
18790     BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
18791         (uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
18792     BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
18793         (uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
18794         sizeof(struct bxe_slowpath));
18795     BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
18796         (uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
18797     BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
18798         (uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
18799         FW_BUF_SIZE);
18800     for (i = 0; i < sc->num_queues; i++) {
18801         fp = &sc->fp[i];
18802         BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18803             (uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
18804             sizeof(union bxe_host_hc_status_block));
18805         BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18806             (uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
18807             (BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
18808         BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18809             (uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
18810             (BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
18811         BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18812             (uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
18813             (BCM_PAGE_SIZE * RCQ_NUM_PAGES));
18814         BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18815             (uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
18816             (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
18817     }
18818
18819     ilt_cli = &ilt->clients[1];
18820     for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
18821         BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
18822             (uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
18823             ((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
18824     }
18825
18826
18827     cmd_offset = DMAE_REG_CMD_MEM;
18828     for (i = 0; i < 224; i++) {
18829         reg_addr = (cmd_offset +(i * 4));
18830         reg_val = REG_RD(sc, reg_addr);
18831         BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
18832             reg_addr, reg_val);
18833     }
18834
18835
18836     BLOGI(sc, "Collection of grcdump done\n");
18837     sc->grcdump_done = 1;
18838     return(rval);
18839 }
18840
18841 static int
18842 bxe_add_cdev(struct bxe_softc *sc)
18843 {
18844     sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
18845
18846     if (sc->eeprom == NULL) {
18847         BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
18848         return (-1);
18849     }
18850
18851     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18852                             sc->ifnet->if_dunit,
18853                             UID_ROOT,
18854                             GID_WHEEL,
18855                             0600,
18856                             "%s",
18857                             if_name(sc->ifnet));
18858
18859     if (sc->ioctl_dev == NULL) {
18860         free(sc->eeprom, M_DEVBUF);
18861         sc->eeprom = NULL;
18862         return (-1);
18863     }
18864
18865     sc->ioctl_dev->si_drv1 = sc;
18866
18867     return (0);
18868 }
18869
18870 static void
18871 bxe_del_cdev(struct bxe_softc *sc)
18872 {
18873     if (sc->ioctl_dev != NULL)
18874         destroy_dev(sc->ioctl_dev);
18875
18876     if (sc->eeprom != NULL) {
18877         free(sc->eeprom, M_DEVBUF);
18878         sc->eeprom = NULL;
18879     }
18880     sc->ioctl_dev = NULL;
18881
18882     return;
18883 }
18884
18885 static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
18886 {
18887
18888     if ((sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) == 0)
18889         return FALSE;
18890
18891     return TRUE;
18892 }
18893
18894
18895 static int
18896 bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18897 {
18898     int rval = 0;
18899
18900     if(!bxe_is_nvram_accessible(sc)) {
18901         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18902         return (-EAGAIN);
18903     }
18904     rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
18905
18906
18907    return (rval);
18908 }
18909
18910 static int
18911 bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18912 {
18913     int rval = 0;
18914
18915     if(!bxe_is_nvram_accessible(sc)) {
18916         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18917         return (-EAGAIN);
18918     }
18919     rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
18920
18921    return (rval);
18922 }
18923
18924 static int
18925 bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
18926 {
18927     int rval = 0;
18928
18929     switch (eeprom->eeprom_cmd) {
18930
18931     case BXE_EEPROM_CMD_SET_EEPROM:
18932
18933         rval = copyin(eeprom->eeprom_data, sc->eeprom,
18934                        eeprom->eeprom_data_len);
18935
18936         if (rval)
18937             break;
18938
18939         rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18940                        eeprom->eeprom_data_len);
18941         break;
18942
18943     case BXE_EEPROM_CMD_GET_EEPROM:
18944
18945         rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18946                        eeprom->eeprom_data_len);
18947
18948         if (rval) {
18949             break;
18950         }
18951
18952         rval = copyout(sc->eeprom, eeprom->eeprom_data,
18953                        eeprom->eeprom_data_len);
18954         break;
18955
18956     default:
18957             rval = EINVAL;
18958             break;
18959     }
18960
18961     if (rval) {
18962         BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
18963     }
18964
18965     return (rval);
18966 }
18967
18968 static int
18969 bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
18970 {
18971     uint32_t ext_phy_config;
18972     int port = SC_PORT(sc);
18973     int cfg_idx = bxe_get_link_cfg_idx(sc);
18974
18975     dev_p->supported = sc->port.supported[cfg_idx] |
18976             (sc->port.supported[cfg_idx ^ 1] &
18977             (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
18978     dev_p->advertising = sc->port.advertising[cfg_idx];
18979     if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
18980         ELINK_ETH_PHY_SFP_1G_FIBER) {
18981         dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
18982         dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
18983     }
18984     if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
18985         !(sc->flags & BXE_MF_FUNC_DIS)) {
18986         dev_p->duplex = sc->link_vars.duplex;
18987         if (IS_MF(sc) && !BXE_NOMCP(sc))
18988             dev_p->speed = bxe_get_mf_speed(sc);
18989         else
18990             dev_p->speed = sc->link_vars.line_speed;
18991     } else {
18992         dev_p->duplex = DUPLEX_UNKNOWN;
18993         dev_p->speed = SPEED_UNKNOWN;
18994     }
18995
18996     dev_p->port = bxe_media_detect(sc);
18997
18998     ext_phy_config = SHMEM_RD(sc,
18999                          dev_info.port_hw_config[port].external_phy_config);
19000     if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
19001         PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
19002         dev_p->phy_address =  sc->port.phy_addr;
19003     else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19004             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
19005         ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19006             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
19007         dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
19008     else
19009         dev_p->phy_address = 0;
19010
19011     if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
19012         dev_p->autoneg = AUTONEG_ENABLE;
19013     else
19014        dev_p->autoneg = AUTONEG_DISABLE;
19015
19016
19017     return 0;
19018 }
19019
19020 static int
19021 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
19022         struct thread *td)
19023 {
19024     struct bxe_softc    *sc;
19025     int                 rval = 0;
19026     device_t            pci_dev;
19027     bxe_grcdump_t       *dump = NULL;
19028     int grc_dump_size;
19029     bxe_drvinfo_t   *drv_infop = NULL;
19030     bxe_dev_setting_t  *dev_p;
19031     bxe_dev_setting_t  dev_set;
19032     bxe_get_regs_t  *reg_p;
19033     bxe_reg_rdw_t *reg_rdw_p;
19034     bxe_pcicfg_rdw_t *cfg_rdw_p;
19035     bxe_perm_mac_addr_t *mac_addr_p;
19036
19037
19038     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
19039         return ENXIO;
19040
19041     pci_dev= sc->dev;
19042
19043     dump = (bxe_grcdump_t *)data;
19044
19045     switch(cmd) {
19046
19047         case BXE_GRC_DUMP_SIZE:
19048             dump->pci_func = sc->pcie_func;
19049             dump->grcdump_size =
19050                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19051                      sizeof(struct  dump_header);
19052             break;
19053
19054         case BXE_GRC_DUMP:
19055             
19056             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19057                                 sizeof(struct  dump_header);
19058             if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
19059                 (dump->grcdump_size < grc_dump_size)) {
19060                 rval = EINVAL;
19061                 break;
19062             }
19063
19064             if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
19065                 (!sc->grcdump_started)) {
19066                 rval =  bxe_grc_dump(sc);
19067             }
19068
19069             if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
19070                 (sc->grc_dump != NULL))  {
19071                 dump->grcdump_dwords = grc_dump_size >> 2;
19072                 rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
19073                 free(sc->grc_dump, M_DEVBUF);
19074                 sc->grc_dump = NULL;
19075                 sc->grcdump_started = 0;
19076                 sc->grcdump_done = 0;
19077             }
19078
19079             break;
19080
19081         case BXE_DRV_INFO:
19082             drv_infop = (bxe_drvinfo_t *)data;
19083             snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
19084             snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
19085                 BXE_DRIVER_VERSION);
19086             snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
19087                 sc->devinfo.bc_ver_str);
19088             snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
19089                 "%s", sc->fw_ver_str);
19090             drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
19091             drv_infop->reg_dump_len =
19092                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
19093                     + sizeof(struct  dump_header);
19094             snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
19095                 sc->pcie_bus, sc->pcie_device, sc->pcie_func);
19096             break;
19097
19098         case BXE_DEV_SETTING:
19099             dev_p = (bxe_dev_setting_t *)data;
19100             bxe_get_settings(sc, &dev_set);
19101             dev_p->supported = dev_set.supported;
19102             dev_p->advertising = dev_set.advertising;
19103             dev_p->speed = dev_set.speed;
19104             dev_p->duplex = dev_set.duplex;
19105             dev_p->port = dev_set.port;
19106             dev_p->phy_address = dev_set.phy_address;
19107             dev_p->autoneg = dev_set.autoneg;
19108
19109             break;
19110
19111         case BXE_GET_REGS:
19112
19113             reg_p = (bxe_get_regs_t *)data;
19114             grc_dump_size = reg_p->reg_buf_len;
19115
19116             if((!sc->grcdump_done) && (!sc->grcdump_started)) {
19117                 bxe_grc_dump(sc);
19118             }
19119             if((sc->grcdump_done) && (sc->grcdump_started) &&
19120                 (sc->grc_dump != NULL))  {
19121                 rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
19122                 free(sc->grc_dump, M_DEVBUF);
19123                 sc->grc_dump = NULL;
19124                 sc->grcdump_started = 0;
19125                 sc->grcdump_done = 0;
19126             }
19127
19128             break;
19129
19130         case BXE_RDW_REG:
19131             reg_rdw_p = (bxe_reg_rdw_t *)data;
19132             if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
19133                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19134                 reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
19135
19136             if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
19137                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19138                 REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
19139
19140             break;
19141
19142         case BXE_RDW_PCICFG:
19143             cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
19144             if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
19145
19146                 cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
19147                                          cfg_rdw_p->cfg_width);
19148
19149             } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
19150                 pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
19151                             cfg_rdw_p->cfg_width);
19152             } else {
19153                 BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
19154             }
19155             break;
19156
19157         case BXE_MAC_ADDR:
19158             mac_addr_p = (bxe_perm_mac_addr_t *)data;
19159             snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
19160                 sc->mac_addr_str);
19161             break;
19162
19163         case BXE_EEPROM:
19164             rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
19165             break;
19166
19167
19168         default:
19169             break;
19170     }
19171
19172     return (rval);
19173 }