]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/dev/bxe/bxe.c
MFC r297155
[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 };
503
504 static const struct {
505     uint32_t offset;
506     uint32_t size;
507     char string[STAT_NAME_LEN];
508 } bxe_eth_q_stats_arr[] = {
509     { Q_STATS_OFFSET32(total_bytes_received_hi),
510                 8, "rx_bytes" },
511     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
512                 8, "rx_ucast_packets" },
513     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
514                 8, "rx_mcast_packets" },
515     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
516                 8, "rx_bcast_packets" },
517     { Q_STATS_OFFSET32(no_buff_discard_hi),
518                 8, "rx_discards" },
519     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
520                 8, "tx_bytes" },
521     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
522                 8, "tx_ucast_packets" },
523     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
524                 8, "tx_mcast_packets" },
525     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
526                 8, "tx_bcast_packets" },
527     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
528                 8, "tpa_aggregations" },
529     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
530                 8, "tpa_aggregated_frames"},
531     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
532                 8, "tpa_bytes"},
533     { Q_STATS_OFFSET32(rx_calls),
534                 4, "rx_calls"},
535     { Q_STATS_OFFSET32(rx_pkts),
536                 4, "rx_pkts"},
537     { Q_STATS_OFFSET32(rx_tpa_pkts),
538                 4, "rx_tpa_pkts"},
539     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
540                 4, "rx_erroneous_jumbo_sge_pkts"},
541     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
542                 4, "rx_bxe_service_rxsgl"},
543     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
544                 4, "rx_jumbo_sge_pkts"},
545     { Q_STATS_OFFSET32(rx_soft_errors),
546                 4, "rx_soft_errors"},
547     { Q_STATS_OFFSET32(rx_hw_csum_errors),
548                 4, "rx_hw_csum_errors"},
549     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
550                 4, "rx_ofld_frames_csum_ip"},
551     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
552                 4, "rx_ofld_frames_csum_tcp_udp"},
553     { Q_STATS_OFFSET32(rx_budget_reached),
554                 4, "rx_budget_reached"},
555     { Q_STATS_OFFSET32(tx_pkts),
556                 4, "tx_pkts"},
557     { Q_STATS_OFFSET32(tx_soft_errors),
558                 4, "tx_soft_errors"},
559     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
560                 4, "tx_ofld_frames_csum_ip"},
561     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
562                 4, "tx_ofld_frames_csum_tcp"},
563     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
564                 4, "tx_ofld_frames_csum_udp"},
565     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
566                 4, "tx_ofld_frames_lso"},
567     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
568                 4, "tx_ofld_frames_lso_hdr_splits"},
569     { Q_STATS_OFFSET32(tx_encap_failures),
570                 4, "tx_encap_failures"},
571     { Q_STATS_OFFSET32(tx_hw_queue_full),
572                 4, "tx_hw_queue_full"},
573     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
574                 4, "tx_hw_max_queue_depth"},
575     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
576                 4, "tx_dma_mapping_failure"},
577     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
578                 4, "tx_max_drbr_queue_depth"},
579     { Q_STATS_OFFSET32(tx_window_violation_std),
580                 4, "tx_window_violation_std"},
581     { Q_STATS_OFFSET32(tx_window_violation_tso),
582                 4, "tx_window_violation_tso"},
583     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
584                 4, "tx_chain_lost_mbuf"},
585     { Q_STATS_OFFSET32(tx_frames_deferred),
586                 4, "tx_frames_deferred"},
587     { Q_STATS_OFFSET32(tx_queue_xoff),
588                 4, "tx_queue_xoff"},
589     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
590                 4, "mbuf_defrag_attempts"},
591     { Q_STATS_OFFSET32(mbuf_defrag_failures),
592                 4, "mbuf_defrag_failures"},
593     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
594                 4, "mbuf_rx_bd_alloc_failed"},
595     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
596                 4, "mbuf_rx_bd_mapping_failed"},
597     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
598                 4, "mbuf_rx_tpa_alloc_failed"},
599     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
600                 4, "mbuf_rx_tpa_mapping_failed"},
601     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
602                 4, "mbuf_rx_sge_alloc_failed"},
603     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
604                 4, "mbuf_rx_sge_mapping_failed"},
605     { Q_STATS_OFFSET32(mbuf_alloc_tx),
606                 4, "mbuf_alloc_tx"},
607     { Q_STATS_OFFSET32(mbuf_alloc_rx),
608                 4, "mbuf_alloc_rx"},
609     { Q_STATS_OFFSET32(mbuf_alloc_sge),
610                 4, "mbuf_alloc_sge"},
611     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
612                 4, "mbuf_alloc_tpa"}
613 };
614
615 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
616 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
617
618
619 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
620                                  uint8_t          read_cfg,
621                                  uint8_t          cmng_type);
622 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
623 static void    storm_memset_cmng(struct bxe_softc *sc,
624                                  struct cmng_init *cmng,
625                                  uint8_t          port);
626 static void    bxe_set_reset_global(struct bxe_softc *sc);
627 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
628 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
629                                  int              engine);
630 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
631 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
632                                    uint8_t          *global,
633                                    uint8_t          print);
634 static void    bxe_int_disable(struct bxe_softc *sc);
635 static int     bxe_release_leader_lock(struct bxe_softc *sc);
636 static void    bxe_pf_disable(struct bxe_softc *sc);
637 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
638 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
639                                       struct bxe_fastpath *fp,
640                                       uint16_t            rx_bd_prod,
641                                       uint16_t            rx_cq_prod,
642                                       uint16_t            rx_sge_prod);
643 static void    bxe_link_report_locked(struct bxe_softc *sc);
644 static void    bxe_link_report(struct bxe_softc *sc);
645 static void    bxe_link_status_update(struct bxe_softc *sc);
646 static void    bxe_periodic_callout_func(void *xsc);
647 static void    bxe_periodic_start(struct bxe_softc *sc);
648 static void    bxe_periodic_stop(struct bxe_softc *sc);
649 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
650                                     uint16_t prev_index,
651                                     uint16_t index);
652 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
653                                      int                 queue);
654 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
655                                      uint16_t            index);
656 static uint8_t bxe_txeof(struct bxe_softc *sc,
657                          struct bxe_fastpath *fp);
658 static void    bxe_task_fp(struct bxe_fastpath *fp);
659 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
660                                      struct mbuf      *m,
661                                      uint8_t          contents);
662 static int     bxe_alloc_mem(struct bxe_softc *sc);
663 static void    bxe_free_mem(struct bxe_softc *sc);
664 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
665 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
666 static int     bxe_interrupt_attach(struct bxe_softc *sc);
667 static void    bxe_interrupt_detach(struct bxe_softc *sc);
668 static void    bxe_set_rx_mode(struct bxe_softc *sc);
669 static int     bxe_init_locked(struct bxe_softc *sc);
670 static int     bxe_stop_locked(struct bxe_softc *sc);
671 static __noinline int bxe_nic_load(struct bxe_softc *sc,
672                                    int              load_mode);
673 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
674                                      uint32_t         unload_mode,
675                                      uint8_t          keep_link);
676
677 static void bxe_handle_sp_tq(void *context, int pending);
678 static void bxe_handle_fp_tq(void *context, int pending);
679
680 static int bxe_add_cdev(struct bxe_softc *sc);
681 static void bxe_del_cdev(struct bxe_softc *sc);
682 static int bxe_grc_dump(struct bxe_softc *sc);
683 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
684 static void bxe_free_buf_rings(struct bxe_softc *sc);
685
686 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
687 uint32_t
688 calc_crc32(uint8_t  *crc32_packet,
689            uint32_t crc32_length,
690            uint32_t crc32_seed,
691            uint8_t  complement)
692 {
693    uint32_t byte         = 0;
694    uint32_t bit          = 0;
695    uint8_t  msb          = 0;
696    uint32_t temp         = 0;
697    uint32_t shft         = 0;
698    uint8_t  current_byte = 0;
699    uint32_t crc32_result = crc32_seed;
700    const uint32_t CRC32_POLY = 0x1edc6f41;
701
702    if ((crc32_packet == NULL) ||
703        (crc32_length == 0) ||
704        ((crc32_length % 8) != 0))
705     {
706         return (crc32_result);
707     }
708
709     for (byte = 0; byte < crc32_length; byte = byte + 1)
710     {
711         current_byte = crc32_packet[byte];
712         for (bit = 0; bit < 8; bit = bit + 1)
713         {
714             /* msb = crc32_result[31]; */
715             msb = (uint8_t)(crc32_result >> 31);
716
717             crc32_result = crc32_result << 1;
718
719             /* it (msb != current_byte[bit]) */
720             if (msb != (0x1 & (current_byte >> bit)))
721             {
722                 crc32_result = crc32_result ^ CRC32_POLY;
723                 /* crc32_result[0] = 1 */
724                 crc32_result |= 1;
725             }
726         }
727     }
728
729     /* Last step is to:
730      * 1. "mirror" every bit
731      * 2. swap the 4 bytes
732      * 3. complement each bit
733      */
734
735     /* Mirror */
736     temp = crc32_result;
737     shft = sizeof(crc32_result) * 8 - 1;
738
739     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
740     {
741         temp <<= 1;
742         temp |= crc32_result & 1;
743         shft-- ;
744     }
745
746     /* temp[31-bit] = crc32_result[bit] */
747     temp <<= shft;
748
749     /* Swap */
750     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
751     {
752         uint32_t t0, t1, t2, t3;
753         t0 = (0x000000ff & (temp >> 24));
754         t1 = (0x0000ff00 & (temp >> 8));
755         t2 = (0x00ff0000 & (temp << 8));
756         t3 = (0xff000000 & (temp << 24));
757         crc32_result = t0 | t1 | t2 | t3;
758     }
759
760     /* Complement */
761     if (complement)
762     {
763         crc32_result = ~crc32_result;
764     }
765
766     return (crc32_result);
767 }
768
769 int
770 bxe_test_bit(int                    nr,
771              volatile unsigned long *addr)
772 {
773     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
774 }
775
776 void
777 bxe_set_bit(unsigned int           nr,
778             volatile unsigned long *addr)
779 {
780     atomic_set_acq_long(addr, (1 << nr));
781 }
782
783 void
784 bxe_clear_bit(int                    nr,
785               volatile unsigned long *addr)
786 {
787     atomic_clear_acq_long(addr, (1 << nr));
788 }
789
790 int
791 bxe_test_and_set_bit(int                    nr,
792                        volatile unsigned long *addr)
793 {
794     unsigned long x;
795     nr = (1 << nr);
796     do {
797         x = *addr;
798     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
799     // if (x & nr) bit_was_set; else bit_was_not_set;
800     return (x & nr);
801 }
802
803 int
804 bxe_test_and_clear_bit(int                    nr,
805                        volatile unsigned long *addr)
806 {
807     unsigned long x;
808     nr = (1 << nr);
809     do {
810         x = *addr;
811     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
812     // if (x & nr) bit_was_set; else bit_was_not_set;
813     return (x & nr);
814 }
815
816 int
817 bxe_cmpxchg(volatile int *addr,
818             int          old,
819             int          new)
820 {
821     int x;
822     do {
823         x = *addr;
824     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
825     return (x);
826 }
827
828 /*
829  * Get DMA memory from the OS.
830  *
831  * Validates that the OS has provided DMA buffers in response to a
832  * bus_dmamap_load call and saves the physical address of those buffers.
833  * When the callback is used the OS will return 0 for the mapping function
834  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
835  * failures back to the caller.
836  *
837  * Returns:
838  *   Nothing.
839  */
840 static void
841 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
842 {
843     struct bxe_dma *dma = arg;
844
845     if (error) {
846         dma->paddr = 0;
847         dma->nseg  = 0;
848         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
849     } else {
850         dma->paddr = segs->ds_addr;
851         dma->nseg  = nseg;
852     }
853 }
854
855 /*
856  * Allocate a block of memory and map it for DMA. No partial completions
857  * allowed and release any resources acquired if we can't acquire all
858  * resources.
859  *
860  * Returns:
861  *   0 = Success, !0 = Failure
862  */
863 int
864 bxe_dma_alloc(struct bxe_softc *sc,
865               bus_size_t       size,
866               struct bxe_dma   *dma,
867               const char       *msg)
868 {
869     int rc;
870
871     if (dma->size > 0) {
872         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
873               (unsigned long)dma->size);
874         return (1);
875     }
876
877     memset(dma, 0, sizeof(*dma)); /* sanity */
878     dma->sc   = sc;
879     dma->size = size;
880     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
881
882     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
883                             BCM_PAGE_SIZE,      /* alignment */
884                             0,                  /* boundary limit */
885                             BUS_SPACE_MAXADDR,  /* restricted low */
886                             BUS_SPACE_MAXADDR,  /* restricted hi */
887                             NULL,               /* addr filter() */
888                             NULL,               /* addr filter() arg */
889                             size,               /* max map size */
890                             1,                  /* num discontinuous */
891                             size,               /* max seg size */
892                             BUS_DMA_ALLOCNOW,   /* flags */
893                             NULL,               /* lock() */
894                             NULL,               /* lock() arg */
895                             &dma->tag);         /* returned dma tag */
896     if (rc != 0) {
897         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
898         memset(dma, 0, sizeof(*dma));
899         return (1);
900     }
901
902     rc = bus_dmamem_alloc(dma->tag,
903                           (void **)&dma->vaddr,
904                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
905                           &dma->map);
906     if (rc != 0) {
907         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
908         bus_dma_tag_destroy(dma->tag);
909         memset(dma, 0, sizeof(*dma));
910         return (1);
911     }
912
913     rc = bus_dmamap_load(dma->tag,
914                          dma->map,
915                          dma->vaddr,
916                          size,
917                          bxe_dma_map_addr, /* BLOGD in here */
918                          dma,
919                          BUS_DMA_NOWAIT);
920     if (rc != 0) {
921         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
922         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
923         bus_dma_tag_destroy(dma->tag);
924         memset(dma, 0, sizeof(*dma));
925         return (1);
926     }
927
928     return (0);
929 }
930
931 void
932 bxe_dma_free(struct bxe_softc *sc,
933              struct bxe_dma   *dma)
934 {
935     if (dma->size > 0) {
936         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
937
938         bus_dmamap_sync(dma->tag, dma->map,
939                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
940         bus_dmamap_unload(dma->tag, dma->map);
941         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
942         bus_dma_tag_destroy(dma->tag);
943     }
944
945     memset(dma, 0, sizeof(*dma));
946 }
947
948 /*
949  * These indirect read and write routines are only during init.
950  * The locking is handled by the MCP.
951  */
952
953 void
954 bxe_reg_wr_ind(struct bxe_softc *sc,
955                uint32_t         addr,
956                uint32_t         val)
957 {
958     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
959     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
960     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
961 }
962
963 uint32_t
964 bxe_reg_rd_ind(struct bxe_softc *sc,
965                uint32_t         addr)
966 {
967     uint32_t val;
968
969     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
970     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
971     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
972
973     return (val);
974 }
975
976 static int
977 bxe_acquire_hw_lock(struct bxe_softc *sc,
978                     uint32_t         resource)
979 {
980     uint32_t lock_status;
981     uint32_t resource_bit = (1 << resource);
982     int func = SC_FUNC(sc);
983     uint32_t hw_lock_control_reg;
984     int cnt;
985
986     /* validate the resource is within range */
987     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
988         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
989             " resource_bit 0x%x\n", resource, resource_bit);
990         return (-1);
991     }
992
993     if (func <= 5) {
994         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
995     } else {
996         hw_lock_control_reg =
997                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
998     }
999
1000     /* validate the resource is not already taken */
1001     lock_status = REG_RD(sc, hw_lock_control_reg);
1002     if (lock_status & resource_bit) {
1003         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1004               resource, lock_status, resource_bit);
1005         return (-1);
1006     }
1007
1008     /* try every 5ms for 5 seconds */
1009     for (cnt = 0; cnt < 1000; cnt++) {
1010         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1011         lock_status = REG_RD(sc, hw_lock_control_reg);
1012         if (lock_status & resource_bit) {
1013             return (0);
1014         }
1015         DELAY(5000);
1016     }
1017
1018     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1019         resource, resource_bit);
1020     return (-1);
1021 }
1022
1023 static int
1024 bxe_release_hw_lock(struct bxe_softc *sc,
1025                     uint32_t         resource)
1026 {
1027     uint32_t lock_status;
1028     uint32_t resource_bit = (1 << resource);
1029     int func = SC_FUNC(sc);
1030     uint32_t hw_lock_control_reg;
1031
1032     /* validate the resource is within range */
1033     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1034         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1035             " resource_bit 0x%x\n", resource, resource_bit);
1036         return (-1);
1037     }
1038
1039     if (func <= 5) {
1040         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1041     } else {
1042         hw_lock_control_reg =
1043                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1044     }
1045
1046     /* validate the resource is currently taken */
1047     lock_status = REG_RD(sc, hw_lock_control_reg);
1048     if (!(lock_status & resource_bit)) {
1049         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1050               resource, lock_status, resource_bit);
1051         return (-1);
1052     }
1053
1054     REG_WR(sc, hw_lock_control_reg, resource_bit);
1055     return (0);
1056 }
1057 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1058 {
1059         BXE_PHY_LOCK(sc);
1060         bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1061 }
1062
1063 static void bxe_release_phy_lock(struct bxe_softc *sc)
1064 {
1065         bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1066         BXE_PHY_UNLOCK(sc);
1067 }
1068 /*
1069  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1070  * had we done things the other way around, if two pfs from the same port
1071  * would attempt to access nvram at the same time, we could run into a
1072  * scenario such as:
1073  * pf A takes the port lock.
1074  * pf B succeeds in taking the same lock since they are from the same port.
1075  * pf A takes the per pf misc lock. Performs eeprom access.
1076  * pf A finishes. Unlocks the per pf misc lock.
1077  * Pf B takes the lock and proceeds to perform it's own access.
1078  * pf A unlocks the per port lock, while pf B is still working (!).
1079  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1080  * access corrupted by pf B).*
1081  */
1082 static int
1083 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1084 {
1085     int port = SC_PORT(sc);
1086     int count, i;
1087     uint32_t val = 0;
1088
1089     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1090     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1091
1092     /* adjust timeout for emulation/FPGA */
1093     count = NVRAM_TIMEOUT_COUNT;
1094     if (CHIP_REV_IS_SLOW(sc)) {
1095         count *= 100;
1096     }
1097
1098     /* request access to nvram interface */
1099     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1100            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1101
1102     for (i = 0; i < count*10; i++) {
1103         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1104         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1105             break;
1106         }
1107
1108         DELAY(5);
1109     }
1110
1111     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1112         BLOGE(sc, "Cannot get access to nvram interface "
1113             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1114             port, val);
1115         return (-1);
1116     }
1117
1118     return (0);
1119 }
1120
1121 static int
1122 bxe_release_nvram_lock(struct bxe_softc *sc)
1123 {
1124     int port = SC_PORT(sc);
1125     int count, i;
1126     uint32_t val = 0;
1127
1128     /* adjust timeout for emulation/FPGA */
1129     count = NVRAM_TIMEOUT_COUNT;
1130     if (CHIP_REV_IS_SLOW(sc)) {
1131         count *= 100;
1132     }
1133
1134     /* relinquish nvram interface */
1135     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1136            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1137
1138     for (i = 0; i < count*10; i++) {
1139         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1140         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1141             break;
1142         }
1143
1144         DELAY(5);
1145     }
1146
1147     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1148         BLOGE(sc, "Cannot free access to nvram interface "
1149             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1150             port, val);
1151         return (-1);
1152     }
1153
1154     /* release HW lock: protect against other PFs in PF Direct Assignment */
1155     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1156
1157     return (0);
1158 }
1159
1160 static void
1161 bxe_enable_nvram_access(struct bxe_softc *sc)
1162 {
1163     uint32_t val;
1164
1165     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1166
1167     /* enable both bits, even on read */
1168     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1169            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1170 }
1171
1172 static void
1173 bxe_disable_nvram_access(struct bxe_softc *sc)
1174 {
1175     uint32_t val;
1176
1177     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1178
1179     /* disable both bits, even after read */
1180     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1181            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1182                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1183 }
1184
1185 static int
1186 bxe_nvram_read_dword(struct bxe_softc *sc,
1187                      uint32_t         offset,
1188                      uint32_t         *ret_val,
1189                      uint32_t         cmd_flags)
1190 {
1191     int count, i, rc;
1192     uint32_t val;
1193
1194     /* build the command word */
1195     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1196
1197     /* need to clear DONE bit separately */
1198     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1199
1200     /* address of the NVRAM to read from */
1201     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1202            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1203
1204     /* issue a read command */
1205     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1206
1207     /* adjust timeout for emulation/FPGA */
1208     count = NVRAM_TIMEOUT_COUNT;
1209     if (CHIP_REV_IS_SLOW(sc)) {
1210         count *= 100;
1211     }
1212
1213     /* wait for completion */
1214     *ret_val = 0;
1215     rc = -1;
1216     for (i = 0; i < count; i++) {
1217         DELAY(5);
1218         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1219
1220         if (val & MCPR_NVM_COMMAND_DONE) {
1221             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1222             /* we read nvram data in cpu order
1223              * but ethtool sees it as an array of bytes
1224              * converting to big-endian will do the work
1225              */
1226             *ret_val = htobe32(val);
1227             rc = 0;
1228             break;
1229         }
1230     }
1231
1232     if (rc == -1) {
1233         BLOGE(sc, "nvram read timeout expired "
1234             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1235             offset, cmd_flags, val);
1236     }
1237
1238     return (rc);
1239 }
1240
1241 static int
1242 bxe_nvram_read(struct bxe_softc *sc,
1243                uint32_t         offset,
1244                uint8_t          *ret_buf,
1245                int              buf_size)
1246 {
1247     uint32_t cmd_flags;
1248     uint32_t val;
1249     int rc;
1250
1251     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1252         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1253               offset, buf_size);
1254         return (-1);
1255     }
1256
1257     if ((offset + buf_size) > sc->devinfo.flash_size) {
1258         BLOGE(sc, "Invalid parameter, "
1259                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1260               offset, buf_size, sc->devinfo.flash_size);
1261         return (-1);
1262     }
1263
1264     /* request access to nvram interface */
1265     rc = bxe_acquire_nvram_lock(sc);
1266     if (rc) {
1267         return (rc);
1268     }
1269
1270     /* enable access to nvram interface */
1271     bxe_enable_nvram_access(sc);
1272
1273     /* read the first word(s) */
1274     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1275     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1276         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1277         memcpy(ret_buf, &val, 4);
1278
1279         /* advance to the next dword */
1280         offset += sizeof(uint32_t);
1281         ret_buf += sizeof(uint32_t);
1282         buf_size -= sizeof(uint32_t);
1283         cmd_flags = 0;
1284     }
1285
1286     if (rc == 0) {
1287         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1288         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1289         memcpy(ret_buf, &val, 4);
1290     }
1291
1292     /* disable access to nvram interface */
1293     bxe_disable_nvram_access(sc);
1294     bxe_release_nvram_lock(sc);
1295
1296     return (rc);
1297 }
1298
1299 static int
1300 bxe_nvram_write_dword(struct bxe_softc *sc,
1301                       uint32_t         offset,
1302                       uint32_t         val,
1303                       uint32_t         cmd_flags)
1304 {
1305     int count, i, rc;
1306
1307     /* build the command word */
1308     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1309
1310     /* need to clear DONE bit separately */
1311     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1312
1313     /* write the data */
1314     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1315
1316     /* address of the NVRAM to write to */
1317     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1318            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1319
1320     /* issue the write command */
1321     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1322
1323     /* adjust timeout for emulation/FPGA */
1324     count = NVRAM_TIMEOUT_COUNT;
1325     if (CHIP_REV_IS_SLOW(sc)) {
1326         count *= 100;
1327     }
1328
1329     /* wait for completion */
1330     rc = -1;
1331     for (i = 0; i < count; i++) {
1332         DELAY(5);
1333         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1334         if (val & MCPR_NVM_COMMAND_DONE) {
1335             rc = 0;
1336             break;
1337         }
1338     }
1339
1340     if (rc == -1) {
1341         BLOGE(sc, "nvram write timeout expired "
1342             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1343             offset, cmd_flags, val);
1344     }
1345
1346     return (rc);
1347 }
1348
1349 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1350
1351 static int
1352 bxe_nvram_write1(struct bxe_softc *sc,
1353                  uint32_t         offset,
1354                  uint8_t          *data_buf,
1355                  int              buf_size)
1356 {
1357     uint32_t cmd_flags;
1358     uint32_t align_offset;
1359     uint32_t val;
1360     int rc;
1361
1362     if ((offset + buf_size) > sc->devinfo.flash_size) {
1363         BLOGE(sc, "Invalid parameter, "
1364                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1365               offset, buf_size, sc->devinfo.flash_size);
1366         return (-1);
1367     }
1368
1369     /* request access to nvram interface */
1370     rc = bxe_acquire_nvram_lock(sc);
1371     if (rc) {
1372         return (rc);
1373     }
1374
1375     /* enable access to nvram interface */
1376     bxe_enable_nvram_access(sc);
1377
1378     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1379     align_offset = (offset & ~0x03);
1380     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1381
1382     if (rc == 0) {
1383         val &= ~(0xff << BYTE_OFFSET(offset));
1384         val |= (*data_buf << BYTE_OFFSET(offset));
1385
1386         /* nvram data is returned as an array of bytes
1387          * convert it back to cpu order
1388          */
1389         val = be32toh(val);
1390
1391         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1392     }
1393
1394     /* disable access to nvram interface */
1395     bxe_disable_nvram_access(sc);
1396     bxe_release_nvram_lock(sc);
1397
1398     return (rc);
1399 }
1400
1401 static int
1402 bxe_nvram_write(struct bxe_softc *sc,
1403                 uint32_t         offset,
1404                 uint8_t          *data_buf,
1405                 int              buf_size)
1406 {
1407     uint32_t cmd_flags;
1408     uint32_t val;
1409     uint32_t written_so_far;
1410     int rc;
1411
1412     if (buf_size == 1) {
1413         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1414     }
1415
1416     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1417         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1418               offset, buf_size);
1419         return (-1);
1420     }
1421
1422     if (buf_size == 0) {
1423         return (0); /* nothing to do */
1424     }
1425
1426     if ((offset + buf_size) > sc->devinfo.flash_size) {
1427         BLOGE(sc, "Invalid parameter, "
1428                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1429               offset, buf_size, sc->devinfo.flash_size);
1430         return (-1);
1431     }
1432
1433     /* request access to nvram interface */
1434     rc = bxe_acquire_nvram_lock(sc);
1435     if (rc) {
1436         return (rc);
1437     }
1438
1439     /* enable access to nvram interface */
1440     bxe_enable_nvram_access(sc);
1441
1442     written_so_far = 0;
1443     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1444     while ((written_so_far < buf_size) && (rc == 0)) {
1445         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1446             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1447         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1448             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1449         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1450             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1451         }
1452
1453         memcpy(&val, data_buf, 4);
1454
1455         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1456
1457         /* advance to the next dword */
1458         offset += sizeof(uint32_t);
1459         data_buf += sizeof(uint32_t);
1460         written_so_far += sizeof(uint32_t);
1461         cmd_flags = 0;
1462     }
1463
1464     /* disable access to nvram interface */
1465     bxe_disable_nvram_access(sc);
1466     bxe_release_nvram_lock(sc);
1467
1468     return (rc);
1469 }
1470
1471 /* copy command into DMAE command memory and set DMAE command Go */
1472 void
1473 bxe_post_dmae(struct bxe_softc    *sc,
1474               struct dmae_cmd *dmae,
1475               int                 idx)
1476 {
1477     uint32_t cmd_offset;
1478     int i;
1479
1480     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1481     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1482         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1483     }
1484
1485     REG_WR(sc, dmae_reg_go_c[idx], 1);
1486 }
1487
1488 uint32_t
1489 bxe_dmae_opcode_add_comp(uint32_t opcode,
1490                          uint8_t  comp_type)
1491 {
1492     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1493                       DMAE_CMD_C_TYPE_ENABLE));
1494 }
1495
1496 uint32_t
1497 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1498 {
1499     return (opcode & ~DMAE_CMD_SRC_RESET);
1500 }
1501
1502 uint32_t
1503 bxe_dmae_opcode(struct bxe_softc *sc,
1504                 uint8_t          src_type,
1505                 uint8_t          dst_type,
1506                 uint8_t          with_comp,
1507                 uint8_t          comp_type)
1508 {
1509     uint32_t opcode = 0;
1510
1511     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1512                (dst_type << DMAE_CMD_DST_SHIFT));
1513
1514     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1515
1516     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1517
1518     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1519                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1520
1521     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1522
1523 #ifdef __BIG_ENDIAN
1524     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1525 #else
1526     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1527 #endif
1528
1529     if (with_comp) {
1530         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1531     }
1532
1533     return (opcode);
1534 }
1535
1536 static void
1537 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1538                         struct dmae_cmd *dmae,
1539                         uint8_t             src_type,
1540                         uint8_t             dst_type)
1541 {
1542     memset(dmae, 0, sizeof(struct dmae_cmd));
1543
1544     /* set the opcode */
1545     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1546                                    TRUE, DMAE_COMP_PCI);
1547
1548     /* fill in the completion parameters */
1549     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1550     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1551     dmae->comp_val     = DMAE_COMP_VAL;
1552 }
1553
1554 /* issue a DMAE command over the init channel and wait for completion */
1555 static int
1556 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1557                          struct dmae_cmd *dmae)
1558 {
1559     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1560     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1561
1562     BXE_DMAE_LOCK(sc);
1563
1564     /* reset completion */
1565     *wb_comp = 0;
1566
1567     /* post the command on the channel used for initializations */
1568     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1569
1570     /* wait for completion */
1571     DELAY(5);
1572
1573     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1574         if (!timeout ||
1575             (sc->recovery_state != BXE_RECOVERY_DONE &&
1576              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1577             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1578                 *wb_comp, sc->recovery_state);
1579             BXE_DMAE_UNLOCK(sc);
1580             return (DMAE_TIMEOUT);
1581         }
1582
1583         timeout--;
1584         DELAY(50);
1585     }
1586
1587     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1588         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1589                 *wb_comp, sc->recovery_state);
1590         BXE_DMAE_UNLOCK(sc);
1591         return (DMAE_PCI_ERROR);
1592     }
1593
1594     BXE_DMAE_UNLOCK(sc);
1595     return (0);
1596 }
1597
1598 void
1599 bxe_read_dmae(struct bxe_softc *sc,
1600               uint32_t         src_addr,
1601               uint32_t         len32)
1602 {
1603     struct dmae_cmd dmae;
1604     uint32_t *data;
1605     int i, rc;
1606
1607     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1608
1609     if (!sc->dmae_ready) {
1610         data = BXE_SP(sc, wb_data[0]);
1611
1612         for (i = 0; i < len32; i++) {
1613             data[i] = (CHIP_IS_E1(sc)) ?
1614                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1615                           REG_RD(sc, (src_addr + (i * 4)));
1616         }
1617
1618         return;
1619     }
1620
1621     /* set opcode and fixed command fields */
1622     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1623
1624     /* fill in addresses and len */
1625     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1626     dmae.src_addr_hi = 0;
1627     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1628     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1629     dmae.len         = len32;
1630
1631     /* issue the command and wait for completion */
1632     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1633         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1634     };
1635 }
1636
1637 void
1638 bxe_write_dmae(struct bxe_softc *sc,
1639                bus_addr_t       dma_addr,
1640                uint32_t         dst_addr,
1641                uint32_t         len32)
1642 {
1643     struct dmae_cmd dmae;
1644     int rc;
1645
1646     if (!sc->dmae_ready) {
1647         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1648
1649         if (CHIP_IS_E1(sc)) {
1650             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1651         } else {
1652             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1653         }
1654
1655         return;
1656     }
1657
1658     /* set opcode and fixed command fields */
1659     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1660
1661     /* fill in addresses and len */
1662     dmae.src_addr_lo = U64_LO(dma_addr);
1663     dmae.src_addr_hi = U64_HI(dma_addr);
1664     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1665     dmae.dst_addr_hi = 0;
1666     dmae.len         = len32;
1667
1668     /* issue the command and wait for completion */
1669     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1670         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1671     }
1672 }
1673
1674 void
1675 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1676                         bus_addr_t       phys_addr,
1677                         uint32_t         addr,
1678                         uint32_t         len)
1679 {
1680     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1681     int offset = 0;
1682
1683     while (len > dmae_wr_max) {
1684         bxe_write_dmae(sc,
1685                        (phys_addr + offset), /* src DMA address */
1686                        (addr + offset),      /* dst GRC address */
1687                        dmae_wr_max);
1688         offset += (dmae_wr_max * 4);
1689         len -= dmae_wr_max;
1690     }
1691
1692     bxe_write_dmae(sc,
1693                    (phys_addr + offset), /* src DMA address */
1694                    (addr + offset),      /* dst GRC address */
1695                    len);
1696 }
1697
1698 void
1699 bxe_set_ctx_validation(struct bxe_softc   *sc,
1700                        struct eth_context *cxt,
1701                        uint32_t           cid)
1702 {
1703     /* ustorm cxt validation */
1704     cxt->ustorm_ag_context.cdu_usage =
1705         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1706             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1707     /* xcontext validation */
1708     cxt->xstorm_ag_context.cdu_reserved =
1709         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1710             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1711 }
1712
1713 static void
1714 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1715                             uint8_t          port,
1716                             uint8_t          fw_sb_id,
1717                             uint8_t          sb_index,
1718                             uint8_t          ticks)
1719 {
1720     uint32_t addr =
1721         (BAR_CSTRORM_INTMEM +
1722          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1723
1724     REG_WR8(sc, addr, ticks);
1725
1726     BLOGD(sc, DBG_LOAD,
1727           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1728           port, fw_sb_id, sb_index, ticks);
1729 }
1730
1731 static void
1732 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1733                             uint8_t          port,
1734                             uint16_t         fw_sb_id,
1735                             uint8_t          sb_index,
1736                             uint8_t          disable)
1737 {
1738     uint32_t enable_flag =
1739         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1740     uint32_t addr =
1741         (BAR_CSTRORM_INTMEM +
1742          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1743     uint8_t flags;
1744
1745     /* clear and set */
1746     flags = REG_RD8(sc, addr);
1747     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1748     flags |= enable_flag;
1749     REG_WR8(sc, addr, flags);
1750
1751     BLOGD(sc, DBG_LOAD,
1752           "port %d fw_sb_id %d sb_index %d disable %d\n",
1753           port, fw_sb_id, sb_index, disable);
1754 }
1755
1756 void
1757 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1758                              uint8_t          fw_sb_id,
1759                              uint8_t          sb_index,
1760                              uint8_t          disable,
1761                              uint16_t         usec)
1762 {
1763     int port = SC_PORT(sc);
1764     uint8_t ticks = (usec / 4); /* XXX ??? */
1765
1766     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1767
1768     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1769     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1770 }
1771
1772 void
1773 elink_cb_udelay(struct bxe_softc *sc,
1774                 uint32_t         usecs)
1775 {
1776     DELAY(usecs);
1777 }
1778
1779 uint32_t
1780 elink_cb_reg_read(struct bxe_softc *sc,
1781                   uint32_t         reg_addr)
1782 {
1783     return (REG_RD(sc, reg_addr));
1784 }
1785
1786 void
1787 elink_cb_reg_write(struct bxe_softc *sc,
1788                    uint32_t         reg_addr,
1789                    uint32_t         val)
1790 {
1791     REG_WR(sc, reg_addr, val);
1792 }
1793
1794 void
1795 elink_cb_reg_wb_write(struct bxe_softc *sc,
1796                       uint32_t         offset,
1797                       uint32_t         *wb_write,
1798                       uint16_t         len)
1799 {
1800     REG_WR_DMAE(sc, offset, wb_write, len);
1801 }
1802
1803 void
1804 elink_cb_reg_wb_read(struct bxe_softc *sc,
1805                      uint32_t         offset,
1806                      uint32_t         *wb_write,
1807                      uint16_t         len)
1808 {
1809     REG_RD_DMAE(sc, offset, wb_write, len);
1810 }
1811
1812 uint8_t
1813 elink_cb_path_id(struct bxe_softc *sc)
1814 {
1815     return (SC_PATH(sc));
1816 }
1817
1818 void
1819 elink_cb_event_log(struct bxe_softc     *sc,
1820                    const elink_log_id_t elink_log_id,
1821                    ...)
1822 {
1823     /* XXX */
1824     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1825 }
1826
1827 static int
1828 bxe_set_spio(struct bxe_softc *sc,
1829              int              spio,
1830              uint32_t         mode)
1831 {
1832     uint32_t spio_reg;
1833
1834     /* Only 2 SPIOs are configurable */
1835     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1836         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1837         return (-1);
1838     }
1839
1840     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1841
1842     /* read SPIO and mask except the float bits */
1843     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1844
1845     switch (mode) {
1846     case MISC_SPIO_OUTPUT_LOW:
1847         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1848         /* clear FLOAT and set CLR */
1849         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1850         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1851         break;
1852
1853     case MISC_SPIO_OUTPUT_HIGH:
1854         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1855         /* clear FLOAT and set SET */
1856         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1857         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1858         break;
1859
1860     case MISC_SPIO_INPUT_HI_Z:
1861         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1862         /* set FLOAT */
1863         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1864         break;
1865
1866     default:
1867         break;
1868     }
1869
1870     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1871     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1872
1873     return (0);
1874 }
1875
1876 static int
1877 bxe_gpio_read(struct bxe_softc *sc,
1878               int              gpio_num,
1879               uint8_t          port)
1880 {
1881     /* The GPIO should be swapped if swap register is set and active */
1882     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1883                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1884     int gpio_shift = (gpio_num +
1885                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1886     uint32_t gpio_mask = (1 << gpio_shift);
1887     uint32_t gpio_reg;
1888
1889     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1890         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1891             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1892             gpio_mask);
1893         return (-1);
1894     }
1895
1896     /* read GPIO value */
1897     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1898
1899     /* get the requested pin value */
1900     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1901 }
1902
1903 static int
1904 bxe_gpio_write(struct bxe_softc *sc,
1905                int              gpio_num,
1906                uint32_t         mode,
1907                uint8_t          port)
1908 {
1909     /* The GPIO should be swapped if swap register is set and active */
1910     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1911                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1912     int gpio_shift = (gpio_num +
1913                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1914     uint32_t gpio_mask = (1 << gpio_shift);
1915     uint32_t gpio_reg;
1916
1917     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1918         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1919             " gpio_shift %d gpio_mask 0x%x\n",
1920             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1921         return (-1);
1922     }
1923
1924     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1925
1926     /* read GPIO and mask except the float bits */
1927     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1928
1929     switch (mode) {
1930     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1931         BLOGD(sc, DBG_PHY,
1932               "Set GPIO %d (shift %d) -> output low\n",
1933               gpio_num, gpio_shift);
1934         /* clear FLOAT and set CLR */
1935         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1936         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1937         break;
1938
1939     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1940         BLOGD(sc, DBG_PHY,
1941               "Set GPIO %d (shift %d) -> output high\n",
1942               gpio_num, gpio_shift);
1943         /* clear FLOAT and set SET */
1944         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1945         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1946         break;
1947
1948     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1949         BLOGD(sc, DBG_PHY,
1950               "Set GPIO %d (shift %d) -> input\n",
1951               gpio_num, gpio_shift);
1952         /* set FLOAT */
1953         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1954         break;
1955
1956     default:
1957         break;
1958     }
1959
1960     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1961     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1962
1963     return (0);
1964 }
1965
1966 static int
1967 bxe_gpio_mult_write(struct bxe_softc *sc,
1968                     uint8_t          pins,
1969                     uint32_t         mode)
1970 {
1971     uint32_t gpio_reg;
1972
1973     /* any port swapping should be handled by caller */
1974
1975     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1976
1977     /* read GPIO and mask except the float bits */
1978     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1979     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1980     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
1981     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
1982
1983     switch (mode) {
1984     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1985         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
1986         /* set CLR */
1987         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
1988         break;
1989
1990     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1991         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
1992         /* set SET */
1993         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
1994         break;
1995
1996     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1997         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
1998         /* set FLOAT */
1999         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2000         break;
2001
2002     default:
2003         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2004             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2005         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2006         return (-1);
2007     }
2008
2009     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2010     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2011
2012     return (0);
2013 }
2014
2015 static int
2016 bxe_gpio_int_write(struct bxe_softc *sc,
2017                    int              gpio_num,
2018                    uint32_t         mode,
2019                    uint8_t          port)
2020 {
2021     /* The GPIO should be swapped if swap register is set and active */
2022     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2023                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2024     int gpio_shift = (gpio_num +
2025                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2026     uint32_t gpio_mask = (1 << gpio_shift);
2027     uint32_t gpio_reg;
2028
2029     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2030         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2031             " gpio_shift %d gpio_mask 0x%x\n",
2032             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2033         return (-1);
2034     }
2035
2036     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2037
2038     /* read GPIO int */
2039     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2040
2041     switch (mode) {
2042     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2043         BLOGD(sc, DBG_PHY,
2044               "Clear GPIO INT %d (shift %d) -> output low\n",
2045               gpio_num, gpio_shift);
2046         /* clear SET and set CLR */
2047         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2048         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2049         break;
2050
2051     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2052         BLOGD(sc, DBG_PHY,
2053               "Set GPIO INT %d (shift %d) -> output high\n",
2054               gpio_num, gpio_shift);
2055         /* clear CLR and set SET */
2056         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2057         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2058         break;
2059
2060     default:
2061         break;
2062     }
2063
2064     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2065     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2066
2067     return (0);
2068 }
2069
2070 uint32_t
2071 elink_cb_gpio_read(struct bxe_softc *sc,
2072                    uint16_t         gpio_num,
2073                    uint8_t          port)
2074 {
2075     return (bxe_gpio_read(sc, gpio_num, port));
2076 }
2077
2078 uint8_t
2079 elink_cb_gpio_write(struct bxe_softc *sc,
2080                     uint16_t         gpio_num,
2081                     uint8_t          mode, /* 0=low 1=high */
2082                     uint8_t          port)
2083 {
2084     return (bxe_gpio_write(sc, gpio_num, mode, port));
2085 }
2086
2087 uint8_t
2088 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2089                          uint8_t          pins,
2090                          uint8_t          mode) /* 0=low 1=high */
2091 {
2092     return (bxe_gpio_mult_write(sc, pins, mode));
2093 }
2094
2095 uint8_t
2096 elink_cb_gpio_int_write(struct bxe_softc *sc,
2097                         uint16_t         gpio_num,
2098                         uint8_t          mode, /* 0=low 1=high */
2099                         uint8_t          port)
2100 {
2101     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2102 }
2103
2104 void
2105 elink_cb_notify_link_changed(struct bxe_softc *sc)
2106 {
2107     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2108                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2109 }
2110
2111 /* send the MCP a request, block until there is a reply */
2112 uint32_t
2113 elink_cb_fw_command(struct bxe_softc *sc,
2114                     uint32_t         command,
2115                     uint32_t         param)
2116 {
2117     int mb_idx = SC_FW_MB_IDX(sc);
2118     uint32_t seq;
2119     uint32_t rc = 0;
2120     uint32_t cnt = 1;
2121     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2122
2123     BXE_FWMB_LOCK(sc);
2124
2125     seq = ++sc->fw_seq;
2126     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2127     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2128
2129     BLOGD(sc, DBG_PHY,
2130           "wrote command 0x%08x to FW MB param 0x%08x\n",
2131           (command | seq), param);
2132
2133     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2134     do {
2135         DELAY(delay * 1000);
2136         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2137     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2138
2139     BLOGD(sc, DBG_PHY,
2140           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2141           cnt*delay, rc, seq);
2142
2143     /* is this a reply to our command? */
2144     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2145         rc &= FW_MSG_CODE_MASK;
2146     } else {
2147         /* Ruh-roh! */
2148         BLOGE(sc, "FW failed to respond!\n");
2149         // XXX bxe_fw_dump(sc);
2150         rc = 0;
2151     }
2152
2153     BXE_FWMB_UNLOCK(sc);
2154     return (rc);
2155 }
2156
2157 static uint32_t
2158 bxe_fw_command(struct bxe_softc *sc,
2159                uint32_t         command,
2160                uint32_t         param)
2161 {
2162     return (elink_cb_fw_command(sc, command, param));
2163 }
2164
2165 static void
2166 __storm_memset_dma_mapping(struct bxe_softc *sc,
2167                            uint32_t         addr,
2168                            bus_addr_t       mapping)
2169 {
2170     REG_WR(sc, addr, U64_LO(mapping));
2171     REG_WR(sc, (addr + 4), U64_HI(mapping));
2172 }
2173
2174 static void
2175 storm_memset_spq_addr(struct bxe_softc *sc,
2176                       bus_addr_t       mapping,
2177                       uint16_t         abs_fid)
2178 {
2179     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2180                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2181     __storm_memset_dma_mapping(sc, addr, mapping);
2182 }
2183
2184 static void
2185 storm_memset_vf_to_pf(struct bxe_softc *sc,
2186                       uint16_t         abs_fid,
2187                       uint16_t         pf_id)
2188 {
2189     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2190     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2191     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2192     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2193 }
2194
2195 static void
2196 storm_memset_func_en(struct bxe_softc *sc,
2197                      uint16_t         abs_fid,
2198                      uint8_t          enable)
2199 {
2200     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2201     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2202     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2203     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2204 }
2205
2206 static void
2207 storm_memset_eq_data(struct bxe_softc       *sc,
2208                      struct event_ring_data *eq_data,
2209                      uint16_t               pfid)
2210 {
2211     uint32_t addr;
2212     size_t size;
2213
2214     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2215     size = sizeof(struct event_ring_data);
2216     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2217 }
2218
2219 static void
2220 storm_memset_eq_prod(struct bxe_softc *sc,
2221                      uint16_t         eq_prod,
2222                      uint16_t         pfid)
2223 {
2224     uint32_t addr = (BAR_CSTRORM_INTMEM +
2225                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2226     REG_WR16(sc, addr, eq_prod);
2227 }
2228
2229 /*
2230  * Post a slowpath command.
2231  *
2232  * A slowpath command is used to propogate a configuration change through
2233  * the controller in a controlled manner, allowing each STORM processor and
2234  * other H/W blocks to phase in the change.  The commands sent on the
2235  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2236  * completion of the ramrod will occur in different ways.  Here's a
2237  * breakdown of ramrods and how they complete:
2238  *
2239  * RAMROD_CMD_ID_ETH_PORT_SETUP
2240  *   Used to setup the leading connection on a port.  Completes on the
2241  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2242  *
2243  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2244  *   Used to setup an additional connection on a port.  Completes on the
2245  *   RCQ of the multi-queue/RSS connection being initialized.
2246  *
2247  * RAMROD_CMD_ID_ETH_STAT_QUERY
2248  *   Used to force the storm processors to update the statistics database
2249  *   in host memory.  This ramrod is send on the leading connection CID and
2250  *   completes as an index increment of the CSTORM on the default status
2251  *   block.
2252  *
2253  * RAMROD_CMD_ID_ETH_UPDATE
2254  *   Used to update the state of the leading connection, usually to udpate
2255  *   the RSS indirection table.  Completes on the RCQ of the leading
2256  *   connection. (Not currently used under FreeBSD until OS support becomes
2257  *   available.)
2258  *
2259  * RAMROD_CMD_ID_ETH_HALT
2260  *   Used when tearing down a connection prior to driver unload.  Completes
2261  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2262  *   use this on the leading connection.
2263  *
2264  * RAMROD_CMD_ID_ETH_SET_MAC
2265  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2266  *   the RCQ of the leading connection.
2267  *
2268  * RAMROD_CMD_ID_ETH_CFC_DEL
2269  *   Used when tearing down a conneciton prior to driver unload.  Completes
2270  *   on the RCQ of the leading connection (since the current connection
2271  *   has been completely removed from controller memory).
2272  *
2273  * RAMROD_CMD_ID_ETH_PORT_DEL
2274  *   Used to tear down the leading connection prior to driver unload,
2275  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2276  *   default status block.
2277  *
2278  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2279  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2280  *   RSS connection that is being offloaded.  (Not currently used under
2281  *   FreeBSD.)
2282  *
2283  * There can only be one command pending per function.
2284  *
2285  * Returns:
2286  *   0 = Success, !0 = Failure.
2287  */
2288
2289 /* must be called under the spq lock */
2290 static inline
2291 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2292 {
2293     struct eth_spe *next_spe = sc->spq_prod_bd;
2294
2295     if (sc->spq_prod_bd == sc->spq_last_bd) {
2296         /* wrap back to the first eth_spq */
2297         sc->spq_prod_bd = sc->spq;
2298         sc->spq_prod_idx = 0;
2299     } else {
2300         sc->spq_prod_bd++;
2301         sc->spq_prod_idx++;
2302     }
2303
2304     return (next_spe);
2305 }
2306
2307 /* must be called under the spq lock */
2308 static inline
2309 void bxe_sp_prod_update(struct bxe_softc *sc)
2310 {
2311     int func = SC_FUNC(sc);
2312
2313     /*
2314      * Make sure that BD data is updated before writing the producer.
2315      * BD data is written to the memory, the producer is read from the
2316      * memory, thus we need a full memory barrier to ensure the ordering.
2317      */
2318     mb();
2319
2320     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2321              sc->spq_prod_idx);
2322
2323     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2324                       BUS_SPACE_BARRIER_WRITE);
2325 }
2326
2327 /**
2328  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2329  *
2330  * @cmd:      command to check
2331  * @cmd_type: command type
2332  */
2333 static inline
2334 int bxe_is_contextless_ramrod(int cmd,
2335                               int cmd_type)
2336 {
2337     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2338         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2339         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2340         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2341         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2342         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2343         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2344         return (TRUE);
2345     } else {
2346         return (FALSE);
2347     }
2348 }
2349
2350 /**
2351  * bxe_sp_post - place a single command on an SP ring
2352  *
2353  * @sc:         driver handle
2354  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2355  * @cid:        SW CID the command is related to
2356  * @data_hi:    command private data address (high 32 bits)
2357  * @data_lo:    command private data address (low 32 bits)
2358  * @cmd_type:   command type (e.g. NONE, ETH)
2359  *
2360  * SP data is handled as if it's always an address pair, thus data fields are
2361  * not swapped to little endian in upper functions. Instead this function swaps
2362  * data as if it's two uint32 fields.
2363  */
2364 int
2365 bxe_sp_post(struct bxe_softc *sc,
2366             int              command,
2367             int              cid,
2368             uint32_t         data_hi,
2369             uint32_t         data_lo,
2370             int              cmd_type)
2371 {
2372     struct eth_spe *spe;
2373     uint16_t type;
2374     int common;
2375
2376     common = bxe_is_contextless_ramrod(command, cmd_type);
2377
2378     BXE_SP_LOCK(sc);
2379
2380     if (common) {
2381         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2382             BLOGE(sc, "EQ ring is full!\n");
2383             BXE_SP_UNLOCK(sc);
2384             return (-1);
2385         }
2386     } else {
2387         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2388             BLOGE(sc, "SPQ ring is full!\n");
2389             BXE_SP_UNLOCK(sc);
2390             return (-1);
2391         }
2392     }
2393
2394     spe = bxe_sp_get_next(sc);
2395
2396     /* CID needs port number to be encoded int it */
2397     spe->hdr.conn_and_cmd_data =
2398         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2399
2400     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2401
2402     /* TBD: Check if it works for VFs */
2403     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2404              SPE_HDR_T_FUNCTION_ID);
2405
2406     spe->hdr.type = htole16(type);
2407
2408     spe->data.update_data_addr.hi = htole32(data_hi);
2409     spe->data.update_data_addr.lo = htole32(data_lo);
2410
2411     /*
2412      * It's ok if the actual decrement is issued towards the memory
2413      * somewhere between the lock and unlock. Thus no more explict
2414      * memory barrier is needed.
2415      */
2416     if (common) {
2417         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2418     } else {
2419         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2420     }
2421
2422     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2423     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2424           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2425     BLOGD(sc, DBG_SP,
2426           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2427           sc->spq_prod_idx,
2428           (uint32_t)U64_HI(sc->spq_dma.paddr),
2429           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2430           command,
2431           common,
2432           HW_CID(sc, cid),
2433           data_hi,
2434           data_lo,
2435           type,
2436           atomic_load_acq_long(&sc->cq_spq_left),
2437           atomic_load_acq_long(&sc->eq_spq_left));
2438
2439     bxe_sp_prod_update(sc);
2440
2441     BXE_SP_UNLOCK(sc);
2442     return (0);
2443 }
2444
2445 /**
2446  * bxe_debug_print_ind_table - prints the indirection table configuration.
2447  *
2448  * @sc: driver hanlde
2449  * @p:  pointer to rss configuration
2450  */
2451
2452 /*
2453  * FreeBSD Device probe function.
2454  *
2455  * Compares the device found to the driver's list of supported devices and
2456  * reports back to the bsd loader whether this is the right driver for the device.
2457  * This is the driver entry function called from the "kldload" command.
2458  *
2459  * Returns:
2460  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2461  */
2462 static int
2463 bxe_probe(device_t dev)
2464 {
2465     struct bxe_softc *sc;
2466     struct bxe_device_type *t;
2467     char *descbuf;
2468     uint16_t did, sdid, svid, vid;
2469
2470     /* Find our device structure */
2471     sc = device_get_softc(dev);
2472     sc->dev = dev;
2473     t = bxe_devs;
2474
2475     /* Get the data for the device to be probed. */
2476     vid  = pci_get_vendor(dev);
2477     did  = pci_get_device(dev);
2478     svid = pci_get_subvendor(dev);
2479     sdid = pci_get_subdevice(dev);
2480
2481     BLOGD(sc, DBG_LOAD,
2482           "%s(); VID = 0x%04X, DID = 0x%04X, SVID = 0x%04X, "
2483           "SDID = 0x%04X\n", __FUNCTION__, vid, did, svid, sdid);
2484
2485     /* Look through the list of known devices for a match. */
2486     while (t->bxe_name != NULL) {
2487         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2488             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2489             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2490             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2491             if (descbuf == NULL)
2492                 return (ENOMEM);
2493
2494             /* Print out the device identity. */
2495             snprintf(descbuf, BXE_DEVDESC_MAX,
2496                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2497                      (((pci_read_config(dev, PCIR_REVID, 4) &
2498                         0xf0) >> 4) + 'A'),
2499                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2500                      BXE_DRIVER_VERSION);
2501
2502             device_set_desc_copy(dev, descbuf);
2503             free(descbuf, M_TEMP);
2504             return (BUS_PROBE_DEFAULT);
2505         }
2506         t++;
2507     }
2508
2509     return (ENXIO);
2510 }
2511
2512 static void
2513 bxe_init_mutexes(struct bxe_softc *sc)
2514 {
2515 #ifdef BXE_CORE_LOCK_SX
2516     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2517              "bxe%d_core_lock", sc->unit);
2518     sx_init(&sc->core_sx, sc->core_sx_name);
2519 #else
2520     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2521              "bxe%d_core_lock", sc->unit);
2522     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2523 #endif
2524
2525     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2526              "bxe%d_sp_lock", sc->unit);
2527     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2528
2529     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2530              "bxe%d_dmae_lock", sc->unit);
2531     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2532
2533     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2534              "bxe%d_phy_lock", sc->unit);
2535     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2536
2537     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2538              "bxe%d_fwmb_lock", sc->unit);
2539     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2540
2541     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2542              "bxe%d_print_lock", sc->unit);
2543     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2544
2545     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2546              "bxe%d_stats_lock", sc->unit);
2547     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2548
2549     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2550              "bxe%d_mcast_lock", sc->unit);
2551     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2552 }
2553
2554 static void
2555 bxe_release_mutexes(struct bxe_softc *sc)
2556 {
2557 #ifdef BXE_CORE_LOCK_SX
2558     sx_destroy(&sc->core_sx);
2559 #else
2560     if (mtx_initialized(&sc->core_mtx)) {
2561         mtx_destroy(&sc->core_mtx);
2562     }
2563 #endif
2564
2565     if (mtx_initialized(&sc->sp_mtx)) {
2566         mtx_destroy(&sc->sp_mtx);
2567     }
2568
2569     if (mtx_initialized(&sc->dmae_mtx)) {
2570         mtx_destroy(&sc->dmae_mtx);
2571     }
2572
2573     if (mtx_initialized(&sc->port.phy_mtx)) {
2574         mtx_destroy(&sc->port.phy_mtx);
2575     }
2576
2577     if (mtx_initialized(&sc->fwmb_mtx)) {
2578         mtx_destroy(&sc->fwmb_mtx);
2579     }
2580
2581     if (mtx_initialized(&sc->print_mtx)) {
2582         mtx_destroy(&sc->print_mtx);
2583     }
2584
2585     if (mtx_initialized(&sc->stats_mtx)) {
2586         mtx_destroy(&sc->stats_mtx);
2587     }
2588
2589     if (mtx_initialized(&sc->mcast_mtx)) {
2590         mtx_destroy(&sc->mcast_mtx);
2591     }
2592 }
2593
2594 static void
2595 bxe_tx_disable(struct bxe_softc* sc)
2596 {
2597     struct ifnet *ifp = sc->ifnet;
2598
2599     /* tell the stack the driver is stopped and TX queue is full */
2600     if (ifp != NULL) {
2601         ifp->if_drv_flags = 0;
2602     }
2603 }
2604
2605 static void
2606 bxe_drv_pulse(struct bxe_softc *sc)
2607 {
2608     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2609              sc->fw_drv_pulse_wr_seq);
2610 }
2611
2612 static inline uint16_t
2613 bxe_tx_avail(struct bxe_softc *sc,
2614              struct bxe_fastpath *fp)
2615 {
2616     int16_t  used;
2617     uint16_t prod;
2618     uint16_t cons;
2619
2620     prod = fp->tx_bd_prod;
2621     cons = fp->tx_bd_cons;
2622
2623     used = SUB_S16(prod, cons);
2624
2625     return (int16_t)(sc->tx_ring_size) - used;
2626 }
2627
2628 static inline int
2629 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2630 {
2631     uint16_t hw_cons;
2632
2633     mb(); /* status block fields can change */
2634     hw_cons = le16toh(*fp->tx_cons_sb);
2635     return (hw_cons != fp->tx_pkt_cons);
2636 }
2637
2638 static inline uint8_t
2639 bxe_has_tx_work(struct bxe_fastpath *fp)
2640 {
2641     /* expand this for multi-cos if ever supported */
2642     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2643 }
2644
2645 static inline int
2646 bxe_has_rx_work(struct bxe_fastpath *fp)
2647 {
2648     uint16_t rx_cq_cons_sb;
2649
2650     mb(); /* status block fields can change */
2651     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2652     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2653         rx_cq_cons_sb++;
2654     return (fp->rx_cq_cons != rx_cq_cons_sb);
2655 }
2656
2657 static void
2658 bxe_sp_event(struct bxe_softc    *sc,
2659              struct bxe_fastpath *fp,
2660              union eth_rx_cqe    *rr_cqe)
2661 {
2662     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2663     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2664     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2665     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2666
2667     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2668           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2669
2670     switch (command) {
2671     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2672         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2673         drv_cmd = ECORE_Q_CMD_UPDATE;
2674         break;
2675
2676     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2677         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2678         drv_cmd = ECORE_Q_CMD_SETUP;
2679         break;
2680
2681     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2682         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2683         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2684         break;
2685
2686     case (RAMROD_CMD_ID_ETH_HALT):
2687         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2688         drv_cmd = ECORE_Q_CMD_HALT;
2689         break;
2690
2691     case (RAMROD_CMD_ID_ETH_TERMINATE):
2692         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2693         drv_cmd = ECORE_Q_CMD_TERMINATE;
2694         break;
2695
2696     case (RAMROD_CMD_ID_ETH_EMPTY):
2697         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2698         drv_cmd = ECORE_Q_CMD_EMPTY;
2699         break;
2700
2701     default:
2702         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2703               command, fp->index);
2704         return;
2705     }
2706
2707     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2708         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2709         /*
2710          * q_obj->complete_cmd() failure means that this was
2711          * an unexpected completion.
2712          *
2713          * In this case we don't want to increase the sc->spq_left
2714          * because apparently we haven't sent this command the first
2715          * place.
2716          */
2717         // bxe_panic(sc, ("Unexpected SP completion\n"));
2718         return;
2719     }
2720
2721     atomic_add_acq_long(&sc->cq_spq_left, 1);
2722
2723     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2724           atomic_load_acq_long(&sc->cq_spq_left));
2725 }
2726
2727 /*
2728  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2729  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2730  * the current aggregation queue as in-progress.
2731  */
2732 static void
2733 bxe_tpa_start(struct bxe_softc            *sc,
2734               struct bxe_fastpath         *fp,
2735               uint16_t                    queue,
2736               uint16_t                    cons,
2737               uint16_t                    prod,
2738               struct eth_fast_path_rx_cqe *cqe)
2739 {
2740     struct bxe_sw_rx_bd tmp_bd;
2741     struct bxe_sw_rx_bd *rx_buf;
2742     struct eth_rx_bd *rx_bd;
2743     int max_agg_queues;
2744     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2745     uint16_t index;
2746
2747     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2748                        "cons=%d prod=%d\n",
2749           fp->index, queue, cons, prod);
2750
2751     max_agg_queues = MAX_AGG_QS(sc);
2752
2753     KASSERT((queue < max_agg_queues),
2754             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2755              fp->index, queue, max_agg_queues));
2756
2757     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2758             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2759              fp->index, queue));
2760
2761     /* copy the existing mbuf and mapping from the TPA pool */
2762     tmp_bd = tpa_info->bd;
2763
2764     if (tmp_bd.m == NULL) {
2765         uint32_t *tmp;
2766
2767         tmp = (uint32_t *)cqe;
2768
2769         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2770               fp->index, queue, cons, prod);
2771         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2772             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2773             
2774         /* XXX Error handling? */
2775         return;
2776     }
2777
2778     /* change the TPA queue to the start state */
2779     tpa_info->state            = BXE_TPA_STATE_START;
2780     tpa_info->placement_offset = cqe->placement_offset;
2781     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2782     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2783     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2784
2785     fp->rx_tpa_queue_used |= (1 << queue);
2786
2787     /*
2788      * If all the buffer descriptors are filled with mbufs then fill in
2789      * the current consumer index with a new BD. Else if a maximum Rx
2790      * buffer limit is imposed then fill in the next producer index.
2791      */
2792     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2793                 prod : cons;
2794
2795     /* move the received mbuf and mapping to TPA pool */
2796     tpa_info->bd = fp->rx_mbuf_chain[cons];
2797
2798     /* release any existing RX BD mbuf mappings */
2799     if (cons != index) {
2800         rx_buf = &fp->rx_mbuf_chain[cons];
2801
2802         if (rx_buf->m_map != NULL) {
2803             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2804                             BUS_DMASYNC_POSTREAD);
2805             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2806         }
2807
2808         /*
2809          * We get here when the maximum number of rx buffers is less than
2810          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2811          * it out here without concern of a memory leak.
2812          */
2813         fp->rx_mbuf_chain[cons].m = NULL;
2814     }
2815
2816     /* update the Rx SW BD with the mbuf info from the TPA pool */
2817     fp->rx_mbuf_chain[index] = tmp_bd;
2818
2819     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2820     rx_bd = &fp->rx_chain[index];
2821     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2822     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2823 }
2824
2825 /*
2826  * When a TPA aggregation is completed, loop through the individual mbufs
2827  * of the aggregation, combining them into a single mbuf which will be sent
2828  * up the stack. Refill all freed SGEs with mbufs as we go along.
2829  */
2830 static int
2831 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2832                    struct bxe_fastpath       *fp,
2833                    struct bxe_sw_tpa_info    *tpa_info,
2834                    uint16_t                  queue,
2835                    uint16_t                  pages,
2836                    struct mbuf               *m,
2837                                struct eth_end_agg_rx_cqe *cqe,
2838                    uint16_t                  cqe_idx)
2839 {
2840     struct mbuf *m_frag;
2841     uint32_t frag_len, frag_size, i;
2842     uint16_t sge_idx;
2843     int rc = 0;
2844     int j;
2845
2846     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2847
2848     BLOGD(sc, DBG_LRO,
2849           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2850           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2851
2852     /* make sure the aggregated frame is not too big to handle */
2853     if (pages > 8 * PAGES_PER_SGE) {
2854
2855         uint32_t *tmp = (uint32_t *)cqe;
2856
2857         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2858                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2859               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2860               tpa_info->len_on_bd, frag_size);
2861
2862         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2863             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2864
2865         bxe_panic(sc, ("sge page count error\n"));
2866         return (EINVAL);
2867     }
2868
2869     /*
2870      * Scan through the scatter gather list pulling individual mbufs into a
2871      * single mbuf for the host stack.
2872      */
2873     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2874         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2875
2876         /*
2877          * Firmware gives the indices of the SGE as if the ring is an array
2878          * (meaning that the "next" element will consume 2 indices).
2879          */
2880         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2881
2882         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2883                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2884               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2885
2886         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2887
2888         /* allocate a new mbuf for the SGE */
2889         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2890         if (rc) {
2891             /* Leave all remaining SGEs in the ring! */
2892             return (rc);
2893         }
2894
2895         /* update the fragment length */
2896         m_frag->m_len = frag_len;
2897
2898         /* concatenate the fragment to the head mbuf */
2899         m_cat(m, m_frag);
2900         fp->eth_q_stats.mbuf_alloc_sge--;
2901
2902         /* update the TPA mbuf size and remaining fragment size */
2903         m->m_pkthdr.len += frag_len;
2904         frag_size -= frag_len;
2905     }
2906
2907     BLOGD(sc, DBG_LRO,
2908           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2909           fp->index, queue, frag_size);
2910
2911     return (rc);
2912 }
2913
2914 static inline void
2915 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2916 {
2917     int i, j;
2918
2919     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2920         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2921
2922         for (j = 0; j < 2; j++) {
2923             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2924             idx--;
2925         }
2926     }
2927 }
2928
2929 static inline void
2930 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2931 {
2932     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2933     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2934
2935     /*
2936      * Clear the two last indices in the page to 1. These are the indices that
2937      * correspond to the "next" element, hence will never be indicated and
2938      * should be removed from the calculations.
2939      */
2940     bxe_clear_sge_mask_next_elems(fp);
2941 }
2942
2943 static inline void
2944 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2945                         uint16_t            idx)
2946 {
2947     uint16_t last_max = fp->last_max_sge;
2948
2949     if (SUB_S16(idx, last_max) > 0) {
2950         fp->last_max_sge = idx;
2951     }
2952 }
2953
2954 static inline void
2955 bxe_update_sge_prod(struct bxe_softc          *sc,
2956                     struct bxe_fastpath       *fp,
2957                     uint16_t                  sge_len,
2958                     union eth_sgl_or_raw_data *cqe)
2959 {
2960     uint16_t last_max, last_elem, first_elem;
2961     uint16_t delta = 0;
2962     uint16_t i;
2963
2964     if (!sge_len) {
2965         return;
2966     }
2967
2968     /* first mark all used pages */
2969     for (i = 0; i < sge_len; i++) {
2970         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
2971                             RX_SGE(le16toh(cqe->sgl[i])));
2972     }
2973
2974     BLOGD(sc, DBG_LRO,
2975           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
2976           fp->index, sge_len - 1,
2977           le16toh(cqe->sgl[sge_len - 1]));
2978
2979     /* assume that the last SGE index is the biggest */
2980     bxe_update_last_max_sge(fp,
2981                             le16toh(cqe->sgl[sge_len - 1]));
2982
2983     last_max = RX_SGE(fp->last_max_sge);
2984     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
2985     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
2986
2987     /* if ring is not full */
2988     if (last_elem + 1 != first_elem) {
2989         last_elem++;
2990     }
2991
2992     /* now update the prod */
2993     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
2994         if (__predict_true(fp->sge_mask[i])) {
2995             break;
2996         }
2997
2998         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
2999         delta += BIT_VEC64_ELEM_SZ;
3000     }
3001
3002     if (delta > 0) {
3003         fp->rx_sge_prod += delta;
3004         /* clear page-end entries */
3005         bxe_clear_sge_mask_next_elems(fp);
3006     }
3007
3008     BLOGD(sc, DBG_LRO,
3009           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3010           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3011 }
3012
3013 /*
3014  * The aggregation on the current TPA queue has completed. Pull the individual
3015  * mbuf fragments together into a single mbuf, perform all necessary checksum
3016  * calculations, and send the resuting mbuf to the stack.
3017  */
3018 static void
3019 bxe_tpa_stop(struct bxe_softc          *sc,
3020              struct bxe_fastpath       *fp,
3021              struct bxe_sw_tpa_info    *tpa_info,
3022              uint16_t                  queue,
3023              uint16_t                  pages,
3024                          struct eth_end_agg_rx_cqe *cqe,
3025              uint16_t                  cqe_idx)
3026 {
3027     struct ifnet *ifp = sc->ifnet;
3028     struct mbuf *m;
3029     int rc = 0;
3030
3031     BLOGD(sc, DBG_LRO,
3032           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3033           fp->index, queue, tpa_info->placement_offset,
3034           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3035
3036     m = tpa_info->bd.m;
3037
3038     /* allocate a replacement before modifying existing mbuf */
3039     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3040     if (rc) {
3041         /* drop the frame and log an error */
3042         fp->eth_q_stats.rx_soft_errors++;
3043         goto bxe_tpa_stop_exit;
3044     }
3045
3046     /* we have a replacement, fixup the current mbuf */
3047     m_adj(m, tpa_info->placement_offset);
3048     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3049
3050     /* mark the checksums valid (taken care of by the firmware) */
3051     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3052     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3053     m->m_pkthdr.csum_data = 0xffff;
3054     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3055                                CSUM_IP_VALID   |
3056                                CSUM_DATA_VALID |
3057                                CSUM_PSEUDO_HDR);
3058
3059     /* aggregate all of the SGEs into a single mbuf */
3060     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3061     if (rc) {
3062         /* drop the packet and log an error */
3063         fp->eth_q_stats.rx_soft_errors++;
3064         m_freem(m);
3065     } else {
3066         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3067             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3068             m->m_flags |= M_VLANTAG;
3069         }
3070
3071         /* assign packet to this interface interface */
3072         m->m_pkthdr.rcvif = ifp;
3073
3074 #if __FreeBSD_version >= 800000
3075         /* specify what RSS queue was used for this flow */
3076         m->m_pkthdr.flowid = fp->index;
3077         BXE_SET_FLOWID(m);
3078 #endif
3079
3080         ifp->if_ipackets++;
3081         fp->eth_q_stats.rx_tpa_pkts++;
3082
3083         /* pass the frame to the stack */
3084         (*ifp->if_input)(ifp, m);
3085     }
3086
3087     /* we passed an mbuf up the stack or dropped the frame */
3088     fp->eth_q_stats.mbuf_alloc_tpa--;
3089
3090 bxe_tpa_stop_exit:
3091
3092     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3093     fp->rx_tpa_queue_used &= ~(1 << queue);
3094 }
3095
3096 static uint8_t
3097 bxe_service_rxsgl(
3098                  struct bxe_fastpath *fp,
3099                  uint16_t len,
3100                  uint16_t lenonbd,
3101                  struct mbuf *m,
3102                  struct eth_fast_path_rx_cqe *cqe_fp)
3103 {
3104     struct mbuf *m_frag;
3105     uint16_t frags, frag_len;
3106     uint16_t sge_idx = 0;
3107     uint16_t j;
3108     uint8_t i, rc = 0;
3109     uint32_t frag_size;
3110
3111     /* adjust the mbuf */
3112     m->m_len = lenonbd;
3113
3114     frag_size =  len - lenonbd;
3115     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3116
3117     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3118         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3119
3120         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3121         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3122         m_frag->m_len = frag_len;
3123
3124        /* allocate a new mbuf for the SGE */
3125         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3126         if (rc) {
3127             /* Leave all remaining SGEs in the ring! */
3128             return (rc);
3129         }
3130         fp->eth_q_stats.mbuf_alloc_sge--;
3131
3132         /* concatenate the fragment to the head mbuf */
3133         m_cat(m, m_frag);
3134
3135         frag_size -= frag_len;
3136     }
3137
3138     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3139
3140     return rc;
3141 }
3142
3143 static uint8_t
3144 bxe_rxeof(struct bxe_softc    *sc,
3145           struct bxe_fastpath *fp)
3146 {
3147     struct ifnet *ifp = sc->ifnet;
3148     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3149     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3150     int rx_pkts = 0;
3151     int rc = 0;
3152
3153     BXE_FP_RX_LOCK(fp);
3154
3155     /* CQ "next element" is of the size of the regular element */
3156     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3157     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3158         hw_cq_cons++;
3159     }
3160
3161     bd_cons = fp->rx_bd_cons;
3162     bd_prod = fp->rx_bd_prod;
3163     bd_prod_fw = bd_prod;
3164     sw_cq_cons = fp->rx_cq_cons;
3165     sw_cq_prod = fp->rx_cq_prod;
3166
3167     /*
3168      * Memory barrier necessary as speculative reads of the rx
3169      * buffer can be ahead of the index in the status block
3170      */
3171     rmb();
3172
3173     BLOGD(sc, DBG_RX,
3174           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3175           fp->index, hw_cq_cons, sw_cq_cons);
3176
3177     while (sw_cq_cons != hw_cq_cons) {
3178         struct bxe_sw_rx_bd *rx_buf = NULL;
3179         union eth_rx_cqe *cqe;
3180         struct eth_fast_path_rx_cqe *cqe_fp;
3181         uint8_t cqe_fp_flags;
3182         enum eth_rx_cqe_type cqe_fp_type;
3183         uint16_t len, lenonbd,  pad;
3184         struct mbuf *m = NULL;
3185
3186         comp_ring_cons = RCQ(sw_cq_cons);
3187         bd_prod = RX_BD(bd_prod);
3188         bd_cons = RX_BD(bd_cons);
3189
3190         cqe          = &fp->rcq_chain[comp_ring_cons];
3191         cqe_fp       = &cqe->fast_path_cqe;
3192         cqe_fp_flags = cqe_fp->type_error_flags;
3193         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3194
3195         BLOGD(sc, DBG_RX,
3196               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3197               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3198               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3199               fp->index,
3200               hw_cq_cons,
3201               sw_cq_cons,
3202               bd_prod,
3203               bd_cons,
3204               CQE_TYPE(cqe_fp_flags),
3205               cqe_fp_flags,
3206               cqe_fp->status_flags,
3207               le32toh(cqe_fp->rss_hash_result),
3208               le16toh(cqe_fp->vlan_tag),
3209               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3210               le16toh(cqe_fp->len_on_bd));
3211
3212         /* is this a slowpath msg? */
3213         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3214             bxe_sp_event(sc, fp, cqe);
3215             goto next_cqe;
3216         }
3217
3218         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3219
3220         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3221             struct bxe_sw_tpa_info *tpa_info;
3222             uint16_t frag_size, pages;
3223             uint8_t queue;
3224
3225             if (CQE_TYPE_START(cqe_fp_type)) {
3226                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3227                               bd_cons, bd_prod, cqe_fp);
3228                 m = NULL; /* packet not ready yet */
3229                 goto next_rx;
3230             }
3231
3232             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3233                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3234
3235             queue = cqe->end_agg_cqe.queue_index;
3236             tpa_info = &fp->rx_tpa_info[queue];
3237
3238             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3239                   fp->index, queue);
3240
3241             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3242                          tpa_info->len_on_bd);
3243             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3244
3245             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3246                          &cqe->end_agg_cqe, comp_ring_cons);
3247
3248             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3249
3250             goto next_cqe;
3251         }
3252
3253         /* non TPA */
3254
3255         /* is this an error packet? */
3256         if (__predict_false(cqe_fp_flags &
3257                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3258             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3259             fp->eth_q_stats.rx_soft_errors++;
3260             goto next_rx;
3261         }
3262
3263         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3264         lenonbd = le16toh(cqe_fp->len_on_bd);
3265         pad = cqe_fp->placement_offset;
3266
3267         m = rx_buf->m;
3268
3269         if (__predict_false(m == NULL)) {
3270             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3271                   bd_cons, fp->index);
3272             goto next_rx;
3273         }
3274
3275         /* XXX double copy if packet length under a threshold */
3276
3277         /*
3278          * If all the buffer descriptors are filled with mbufs then fill in
3279          * the current consumer index with a new BD. Else if a maximum Rx
3280          * buffer limit is imposed then fill in the next producer index.
3281          */
3282         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3283                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3284                                       bd_prod : bd_cons);
3285         if (rc != 0) {
3286
3287             /* we simply reuse the received mbuf and don't post it to the stack */
3288             m = NULL;
3289
3290             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3291                   fp->index, rc);
3292             fp->eth_q_stats.rx_soft_errors++;
3293
3294             if (sc->max_rx_bufs != RX_BD_USABLE) {
3295                 /* copy this consumer index to the producer index */
3296                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3297                        sizeof(struct bxe_sw_rx_bd));
3298                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3299             }
3300
3301             goto next_rx;
3302         }
3303
3304         /* current mbuf was detached from the bd */
3305         fp->eth_q_stats.mbuf_alloc_rx--;
3306
3307         /* we allocated a replacement mbuf, fixup the current one */
3308         m_adj(m, pad);
3309         m->m_pkthdr.len = m->m_len = len;
3310
3311         if ((len > 60) && (len > lenonbd)) {
3312             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3313             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3314             if (rc)
3315                 break;
3316             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3317         } else if (lenonbd < len) {
3318             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3319         }
3320
3321         /* assign packet to this interface interface */
3322         m->m_pkthdr.rcvif = ifp;
3323
3324         /* assume no hardware checksum has complated */
3325         m->m_pkthdr.csum_flags = 0;
3326
3327         /* validate checksum if offload enabled */
3328         if (ifp->if_capenable & IFCAP_RXCSUM) {
3329             /* check for a valid IP frame */
3330             if (!(cqe->fast_path_cqe.status_flags &
3331                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3332                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3333                 if (__predict_false(cqe_fp_flags &
3334                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3335                     fp->eth_q_stats.rx_hw_csum_errors++;
3336                 } else {
3337                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3338                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3339                 }
3340             }
3341
3342             /* check for a valid TCP/UDP frame */
3343             if (!(cqe->fast_path_cqe.status_flags &
3344                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3345                 if (__predict_false(cqe_fp_flags &
3346                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3347                     fp->eth_q_stats.rx_hw_csum_errors++;
3348                 } else {
3349                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3350                     m->m_pkthdr.csum_data = 0xFFFF;
3351                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3352                                                CSUM_PSEUDO_HDR);
3353                 }
3354             }
3355         }
3356
3357         /* if there is a VLAN tag then flag that info */
3358         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3359             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3360             m->m_flags |= M_VLANTAG;
3361         }
3362
3363 #if __FreeBSD_version >= 800000
3364         /* specify what RSS queue was used for this flow */
3365         m->m_pkthdr.flowid = fp->index;
3366         BXE_SET_FLOWID(m);
3367 #endif
3368
3369 next_rx:
3370
3371         bd_cons    = RX_BD_NEXT(bd_cons);
3372         bd_prod    = RX_BD_NEXT(bd_prod);
3373         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3374
3375         /* pass the frame to the stack */
3376         if (__predict_true(m != NULL)) {
3377             ifp->if_ipackets++;
3378             rx_pkts++;
3379             (*ifp->if_input)(ifp, m);
3380         }
3381
3382 next_cqe:
3383
3384         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3385         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3386
3387         /* limit spinning on the queue */
3388         if (rc != 0)
3389             break;
3390
3391         if (rx_pkts == sc->rx_budget) {
3392             fp->eth_q_stats.rx_budget_reached++;
3393             break;
3394         }
3395     } /* while work to do */
3396
3397     fp->rx_bd_cons = bd_cons;
3398     fp->rx_bd_prod = bd_prod_fw;
3399     fp->rx_cq_cons = sw_cq_cons;
3400     fp->rx_cq_prod = sw_cq_prod;
3401
3402     /* Update producers */
3403     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3404
3405     fp->eth_q_stats.rx_pkts += rx_pkts;
3406     fp->eth_q_stats.rx_calls++;
3407
3408     BXE_FP_RX_UNLOCK(fp);
3409
3410     return (sw_cq_cons != hw_cq_cons);
3411 }
3412
3413 static uint16_t
3414 bxe_free_tx_pkt(struct bxe_softc    *sc,
3415                 struct bxe_fastpath *fp,
3416                 uint16_t            idx)
3417 {
3418     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3419     struct eth_tx_start_bd *tx_start_bd;
3420     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3421     uint16_t new_cons;
3422     int nbd;
3423
3424     /* unmap the mbuf from non-paged memory */
3425     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3426
3427     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3428     nbd = le16toh(tx_start_bd->nbd) - 1;
3429
3430     new_cons = (tx_buf->first_bd + nbd);
3431
3432     /* free the mbuf */
3433     if (__predict_true(tx_buf->m != NULL)) {
3434         m_freem(tx_buf->m);
3435         fp->eth_q_stats.mbuf_alloc_tx--;
3436     } else {
3437         fp->eth_q_stats.tx_chain_lost_mbuf++;
3438     }
3439
3440     tx_buf->m = NULL;
3441     tx_buf->first_bd = 0;
3442
3443     return (new_cons);
3444 }
3445
3446 /* transmit timeout watchdog */
3447 static int
3448 bxe_watchdog(struct bxe_softc    *sc,
3449              struct bxe_fastpath *fp)
3450 {
3451     BXE_FP_TX_LOCK(fp);
3452
3453     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3454         BXE_FP_TX_UNLOCK(fp);
3455         return (0);
3456     }
3457
3458     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3459
3460     BXE_FP_TX_UNLOCK(fp);
3461
3462     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3463     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3464
3465     return (-1);
3466 }
3467
3468 /* processes transmit completions */
3469 static uint8_t
3470 bxe_txeof(struct bxe_softc    *sc,
3471           struct bxe_fastpath *fp)
3472 {
3473     struct ifnet *ifp = sc->ifnet;
3474     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3475     uint16_t tx_bd_avail;
3476
3477     BXE_FP_TX_LOCK_ASSERT(fp);
3478
3479     bd_cons = fp->tx_bd_cons;
3480     hw_cons = le16toh(*fp->tx_cons_sb);
3481     sw_cons = fp->tx_pkt_cons;
3482
3483     while (sw_cons != hw_cons) {
3484         pkt_cons = TX_BD(sw_cons);
3485
3486         BLOGD(sc, DBG_TX,
3487               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3488               fp->index, hw_cons, sw_cons, pkt_cons);
3489
3490         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3491
3492         sw_cons++;
3493     }
3494
3495     fp->tx_pkt_cons = sw_cons;
3496     fp->tx_bd_cons  = bd_cons;
3497
3498     BLOGD(sc, DBG_TX,
3499           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3500           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3501
3502     mb();
3503
3504     tx_bd_avail = bxe_tx_avail(sc, fp);
3505
3506     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3507         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3508     } else {
3509         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3510     }
3511
3512     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3513         /* reset the watchdog timer if there are pending transmits */
3514         fp->watchdog_timer = BXE_TX_TIMEOUT;
3515         return (TRUE);
3516     } else {
3517         /* clear watchdog when there are no pending transmits */
3518         fp->watchdog_timer = 0;
3519         return (FALSE);
3520     }
3521 }
3522
3523 static void
3524 bxe_drain_tx_queues(struct bxe_softc *sc)
3525 {
3526     struct bxe_fastpath *fp;
3527     int i, count;
3528
3529     /* wait until all TX fastpath tasks have completed */
3530     for (i = 0; i < sc->num_queues; i++) {
3531         fp = &sc->fp[i];
3532
3533         count = 1000;
3534
3535         while (bxe_has_tx_work(fp)) {
3536
3537             BXE_FP_TX_LOCK(fp);
3538             bxe_txeof(sc, fp);
3539             BXE_FP_TX_UNLOCK(fp);
3540
3541             if (count == 0) {
3542                 BLOGE(sc, "Timeout waiting for fp[%d] "
3543                           "transmits to complete!\n", i);
3544                 bxe_panic(sc, ("tx drain failure\n"));
3545                 return;
3546             }
3547
3548             count--;
3549             DELAY(1000);
3550             rmb();
3551         }
3552     }
3553
3554     return;
3555 }
3556
3557 static int
3558 bxe_del_all_macs(struct bxe_softc          *sc,
3559                  struct ecore_vlan_mac_obj *mac_obj,
3560                  int                       mac_type,
3561                  uint8_t                   wait_for_comp)
3562 {
3563     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3564     int rc;
3565
3566     /* wait for completion of requested */
3567     if (wait_for_comp) {
3568         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3569     }
3570
3571     /* Set the mac type of addresses we want to clear */
3572     bxe_set_bit(mac_type, &vlan_mac_flags);
3573
3574     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3575     if (rc < 0) {
3576         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3577             rc, mac_type, wait_for_comp);
3578     }
3579
3580     return (rc);
3581 }
3582
3583 static int
3584 bxe_fill_accept_flags(struct bxe_softc *sc,
3585                       uint32_t         rx_mode,
3586                       unsigned long    *rx_accept_flags,
3587                       unsigned long    *tx_accept_flags)
3588 {
3589     /* Clear the flags first */
3590     *rx_accept_flags = 0;
3591     *tx_accept_flags = 0;
3592
3593     switch (rx_mode) {
3594     case BXE_RX_MODE_NONE:
3595         /*
3596          * 'drop all' supersedes any accept flags that may have been
3597          * passed to the function.
3598          */
3599         break;
3600
3601     case BXE_RX_MODE_NORMAL:
3602         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3603         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3604         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3605
3606         /* internal switching mode */
3607         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3608         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3609         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3610
3611         break;
3612
3613     case BXE_RX_MODE_ALLMULTI:
3614         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3615         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3616         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3617
3618         /* internal switching mode */
3619         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3620         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3621         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3622
3623         break;
3624
3625     case BXE_RX_MODE_PROMISC:
3626         /*
3627          * According to deffinition of SI mode, iface in promisc mode
3628          * should receive matched and unmatched (in resolution of port)
3629          * unicast packets.
3630          */
3631         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3632         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3633         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3634         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3635
3636         /* internal switching mode */
3637         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3638         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3639
3640         if (IS_MF_SI(sc)) {
3641             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3642         } else {
3643             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3644         }
3645
3646         break;
3647
3648     default:
3649         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3650         return (-1);
3651     }
3652
3653     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3654     if (rx_mode != BXE_RX_MODE_NONE) {
3655         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3656         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3657     }
3658
3659     return (0);
3660 }
3661
3662 static int
3663 bxe_set_q_rx_mode(struct bxe_softc *sc,
3664                   uint8_t          cl_id,
3665                   unsigned long    rx_mode_flags,
3666                   unsigned long    rx_accept_flags,
3667                   unsigned long    tx_accept_flags,
3668                   unsigned long    ramrod_flags)
3669 {
3670     struct ecore_rx_mode_ramrod_params ramrod_param;
3671     int rc;
3672
3673     memset(&ramrod_param, 0, sizeof(ramrod_param));
3674
3675     /* Prepare ramrod parameters */
3676     ramrod_param.cid = 0;
3677     ramrod_param.cl_id = cl_id;
3678     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3679     ramrod_param.func_id = SC_FUNC(sc);
3680
3681     ramrod_param.pstate = &sc->sp_state;
3682     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3683
3684     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3685     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3686
3687     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3688
3689     ramrod_param.ramrod_flags = ramrod_flags;
3690     ramrod_param.rx_mode_flags = rx_mode_flags;
3691
3692     ramrod_param.rx_accept_flags = rx_accept_flags;
3693     ramrod_param.tx_accept_flags = tx_accept_flags;
3694
3695     rc = ecore_config_rx_mode(sc, &ramrod_param);
3696     if (rc < 0) {
3697         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3698             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3699             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3700             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3701             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3702         return (rc);
3703     }
3704
3705     return (0);
3706 }
3707
3708 static int
3709 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3710 {
3711     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3712     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3713     int rc;
3714
3715     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3716                                &tx_accept_flags);
3717     if (rc) {
3718         return (rc);
3719     }
3720
3721     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3722     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3723
3724     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3725     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3726                               rx_accept_flags, tx_accept_flags,
3727                               ramrod_flags));
3728 }
3729
3730 /* returns the "mcp load_code" according to global load_count array */
3731 static int
3732 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3733 {
3734     int path = SC_PATH(sc);
3735     int port = SC_PORT(sc);
3736
3737     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3738           path, load_count[path][0], load_count[path][1],
3739           load_count[path][2]);
3740     load_count[path][0]++;
3741     load_count[path][1 + port]++;
3742     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3743           path, load_count[path][0], load_count[path][1],
3744           load_count[path][2]);
3745     if (load_count[path][0] == 1) {
3746         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3747     } else if (load_count[path][1 + port] == 1) {
3748         return (FW_MSG_CODE_DRV_LOAD_PORT);
3749     } else {
3750         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3751     }
3752 }
3753
3754 /* returns the "mcp load_code" according to global load_count array */
3755 static int
3756 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3757 {
3758     int port = SC_PORT(sc);
3759     int path = SC_PATH(sc);
3760
3761     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3762           path, load_count[path][0], load_count[path][1],
3763           load_count[path][2]);
3764     load_count[path][0]--;
3765     load_count[path][1 + port]--;
3766     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3767           path, load_count[path][0], load_count[path][1],
3768           load_count[path][2]);
3769     if (load_count[path][0] == 0) {
3770         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3771     } else if (load_count[path][1 + port] == 0) {
3772         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3773     } else {
3774         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3775     }
3776 }
3777
3778 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3779 static uint32_t
3780 bxe_send_unload_req(struct bxe_softc *sc,
3781                     int              unload_mode)
3782 {
3783     uint32_t reset_code = 0;
3784
3785     /* Select the UNLOAD request mode */
3786     if (unload_mode == UNLOAD_NORMAL) {
3787         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3788     } else {
3789         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3790     }
3791
3792     /* Send the request to the MCP */
3793     if (!BXE_NOMCP(sc)) {
3794         reset_code = bxe_fw_command(sc, reset_code, 0);
3795     } else {
3796         reset_code = bxe_nic_unload_no_mcp(sc);
3797     }
3798
3799     return (reset_code);
3800 }
3801
3802 /* send UNLOAD_DONE command to the MCP */
3803 static void
3804 bxe_send_unload_done(struct bxe_softc *sc,
3805                      uint8_t          keep_link)
3806 {
3807     uint32_t reset_param =
3808         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3809
3810     /* Report UNLOAD_DONE to MCP */
3811     if (!BXE_NOMCP(sc)) {
3812         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3813     }
3814 }
3815
3816 static int
3817 bxe_func_wait_started(struct bxe_softc *sc)
3818 {
3819     int tout = 50;
3820
3821     if (!sc->port.pmf) {
3822         return (0);
3823     }
3824
3825     /*
3826      * (assumption: No Attention from MCP at this stage)
3827      * PMF probably in the middle of TX disable/enable transaction
3828      * 1. Sync IRS for default SB
3829      * 2. Sync SP queue - this guarantees us that attention handling started
3830      * 3. Wait, that TX disable/enable transaction completes
3831      *
3832      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3833      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3834      * received completion for the transaction the state is TX_STOPPED.
3835      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3836      * transaction.
3837      */
3838
3839     /* XXX make sure default SB ISR is done */
3840     /* need a way to synchronize an irq (intr_mtx?) */
3841
3842     /* XXX flush any work queues */
3843
3844     while (ecore_func_get_state(sc, &sc->func_obj) !=
3845            ECORE_F_STATE_STARTED && tout--) {
3846         DELAY(20000);
3847     }
3848
3849     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3850         /*
3851          * Failed to complete the transaction in a "good way"
3852          * Force both transactions with CLR bit.
3853          */
3854         struct ecore_func_state_params func_params = { NULL };
3855
3856         BLOGE(sc, "Unexpected function state! "
3857                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3858
3859         func_params.f_obj = &sc->func_obj;
3860         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3861
3862         /* STARTED-->TX_STOPPED */
3863         func_params.cmd = ECORE_F_CMD_TX_STOP;
3864         ecore_func_state_change(sc, &func_params);
3865
3866         /* TX_STOPPED-->STARTED */
3867         func_params.cmd = ECORE_F_CMD_TX_START;
3868         return (ecore_func_state_change(sc, &func_params));
3869     }
3870
3871     return (0);
3872 }
3873
3874 static int
3875 bxe_stop_queue(struct bxe_softc *sc,
3876                int              index)
3877 {
3878     struct bxe_fastpath *fp = &sc->fp[index];
3879     struct ecore_queue_state_params q_params = { NULL };
3880     int rc;
3881
3882     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3883
3884     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3885     /* We want to wait for completion in this context */
3886     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3887
3888     /* Stop the primary connection: */
3889
3890     /* ...halt the connection */
3891     q_params.cmd = ECORE_Q_CMD_HALT;
3892     rc = ecore_queue_state_change(sc, &q_params);
3893     if (rc) {
3894         return (rc);
3895     }
3896
3897     /* ...terminate the connection */
3898     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3899     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3900     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3901     rc = ecore_queue_state_change(sc, &q_params);
3902     if (rc) {
3903         return (rc);
3904     }
3905
3906     /* ...delete cfc entry */
3907     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3908     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3909     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3910     return (ecore_queue_state_change(sc, &q_params));
3911 }
3912
3913 /* wait for the outstanding SP commands */
3914 static inline uint8_t
3915 bxe_wait_sp_comp(struct bxe_softc *sc,
3916                  unsigned long    mask)
3917 {
3918     unsigned long tmp;
3919     int tout = 5000; /* wait for 5 secs tops */
3920
3921     while (tout--) {
3922         mb();
3923         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3924             return (TRUE);
3925         }
3926
3927         DELAY(1000);
3928     }
3929
3930     mb();
3931
3932     tmp = atomic_load_acq_long(&sc->sp_state);
3933     if (tmp & mask) {
3934         BLOGE(sc, "Filtering completion timed out: "
3935                   "sp_state 0x%lx, mask 0x%lx\n",
3936               tmp, mask);
3937         return (FALSE);
3938     }
3939
3940     return (FALSE);
3941 }
3942
3943 static int
3944 bxe_func_stop(struct bxe_softc *sc)
3945 {
3946     struct ecore_func_state_params func_params = { NULL };
3947     int rc;
3948
3949     /* prepare parameters for function state transitions */
3950     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3951     func_params.f_obj = &sc->func_obj;
3952     func_params.cmd = ECORE_F_CMD_STOP;
3953
3954     /*
3955      * Try to stop the function the 'good way'. If it fails (in case
3956      * of a parity error during bxe_chip_cleanup()) and we are
3957      * not in a debug mode, perform a state transaction in order to
3958      * enable further HW_RESET transaction.
3959      */
3960     rc = ecore_func_state_change(sc, &func_params);
3961     if (rc) {
3962         BLOGE(sc, "FUNC_STOP ramrod failed. "
3963                   "Running a dry transaction (%d)\n", rc);
3964         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3965         return (ecore_func_state_change(sc, &func_params));
3966     }
3967
3968     return (0);
3969 }
3970
3971 static int
3972 bxe_reset_hw(struct bxe_softc *sc,
3973              uint32_t         load_code)
3974 {
3975     struct ecore_func_state_params func_params = { NULL };
3976
3977     /* Prepare parameters for function state transitions */
3978     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3979
3980     func_params.f_obj = &sc->func_obj;
3981     func_params.cmd = ECORE_F_CMD_HW_RESET;
3982
3983     func_params.params.hw_init.load_phase = load_code;
3984
3985     return (ecore_func_state_change(sc, &func_params));
3986 }
3987
3988 static void
3989 bxe_int_disable_sync(struct bxe_softc *sc,
3990                      int              disable_hw)
3991 {
3992     if (disable_hw) {
3993         /* prevent the HW from sending interrupts */
3994         bxe_int_disable(sc);
3995     }
3996
3997     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
3998     /* make sure all ISRs are done */
3999
4000     /* XXX make sure sp_task is not running */
4001     /* cancel and flush work queues */
4002 }
4003
4004 static void
4005 bxe_chip_cleanup(struct bxe_softc *sc,
4006                  uint32_t         unload_mode,
4007                  uint8_t          keep_link)
4008 {
4009     int port = SC_PORT(sc);
4010     struct ecore_mcast_ramrod_params rparam = { NULL };
4011     uint32_t reset_code;
4012     int i, rc = 0;
4013
4014     bxe_drain_tx_queues(sc);
4015
4016     /* give HW time to discard old tx messages */
4017     DELAY(1000);
4018
4019     /* Clean all ETH MACs */
4020     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4021     if (rc < 0) {
4022         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4023     }
4024
4025     /* Clean up UC list  */
4026     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4027     if (rc < 0) {
4028         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4029     }
4030
4031     /* Disable LLH */
4032     if (!CHIP_IS_E1(sc)) {
4033         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4034     }
4035
4036     /* Set "drop all" to stop Rx */
4037
4038     /*
4039      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4040      * a race between the completion code and this code.
4041      */
4042     BXE_MCAST_LOCK(sc);
4043
4044     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4045         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4046     } else {
4047         bxe_set_storm_rx_mode(sc);
4048     }
4049
4050     /* Clean up multicast configuration */
4051     rparam.mcast_obj = &sc->mcast_obj;
4052     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4053     if (rc < 0) {
4054         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4055     }
4056
4057     BXE_MCAST_UNLOCK(sc);
4058
4059     // XXX bxe_iov_chip_cleanup(sc);
4060
4061     /*
4062      * Send the UNLOAD_REQUEST to the MCP. This will return if
4063      * this function should perform FUNCTION, PORT, or COMMON HW
4064      * reset.
4065      */
4066     reset_code = bxe_send_unload_req(sc, unload_mode);
4067
4068     /*
4069      * (assumption: No Attention from MCP at this stage)
4070      * PMF probably in the middle of TX disable/enable transaction
4071      */
4072     rc = bxe_func_wait_started(sc);
4073     if (rc) {
4074         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4075     }
4076
4077     /*
4078      * Close multi and leading connections
4079      * Completions for ramrods are collected in a synchronous way
4080      */
4081     for (i = 0; i < sc->num_queues; i++) {
4082         if (bxe_stop_queue(sc, i)) {
4083             goto unload_error;
4084         }
4085     }
4086
4087     /*
4088      * If SP settings didn't get completed so far - something
4089      * very wrong has happen.
4090      */
4091     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4092         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4093     }
4094
4095 unload_error:
4096
4097     rc = bxe_func_stop(sc);
4098     if (rc) {
4099         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4100     }
4101
4102     /* disable HW interrupts */
4103     bxe_int_disable_sync(sc, TRUE);
4104
4105     /* detach interrupts */
4106     bxe_interrupt_detach(sc);
4107
4108     /* Reset the chip */
4109     rc = bxe_reset_hw(sc, reset_code);
4110     if (rc) {
4111         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4112     }
4113
4114     /* Report UNLOAD_DONE to MCP */
4115     bxe_send_unload_done(sc, keep_link);
4116 }
4117
4118 static void
4119 bxe_disable_close_the_gate(struct bxe_softc *sc)
4120 {
4121     uint32_t val;
4122     int port = SC_PORT(sc);
4123
4124     BLOGD(sc, DBG_LOAD,
4125           "Disabling 'close the gates'\n");
4126
4127     if (CHIP_IS_E1(sc)) {
4128         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4129                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4130         val = REG_RD(sc, addr);
4131         val &= ~(0x300);
4132         REG_WR(sc, addr, val);
4133     } else {
4134         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4135         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4136                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4137         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4138     }
4139 }
4140
4141 /*
4142  * Cleans the object that have internal lists without sending
4143  * ramrods. Should be run when interrutps are disabled.
4144  */
4145 static void
4146 bxe_squeeze_objects(struct bxe_softc *sc)
4147 {
4148     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4149     struct ecore_mcast_ramrod_params rparam = { NULL };
4150     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4151     int rc;
4152
4153     /* Cleanup MACs' object first... */
4154
4155     /* Wait for completion of requested */
4156     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4157     /* Perform a dry cleanup */
4158     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4159
4160     /* Clean ETH primary MAC */
4161     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4162     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4163                              &ramrod_flags);
4164     if (rc != 0) {
4165         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4166     }
4167
4168     /* Cleanup UC list */
4169     vlan_mac_flags = 0;
4170     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4171     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4172                              &ramrod_flags);
4173     if (rc != 0) {
4174         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4175     }
4176
4177     /* Now clean mcast object... */
4178
4179     rparam.mcast_obj = &sc->mcast_obj;
4180     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4181
4182     /* Add a DEL command... */
4183     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4184     if (rc < 0) {
4185         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4186     }
4187
4188     /* now wait until all pending commands are cleared */
4189
4190     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4191     while (rc != 0) {
4192         if (rc < 0) {
4193             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4194             return;
4195         }
4196
4197         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4198     }
4199 }
4200
4201 /* stop the controller */
4202 static __noinline int
4203 bxe_nic_unload(struct bxe_softc *sc,
4204                uint32_t         unload_mode,
4205                uint8_t          keep_link)
4206 {
4207     uint8_t global = FALSE;
4208     uint32_t val;
4209     int i;
4210
4211     BXE_CORE_LOCK_ASSERT(sc);
4212
4213     sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
4214
4215     for (i = 0; i < sc->num_queues; i++) {
4216         struct bxe_fastpath *fp;
4217
4218         fp = &sc->fp[i];
4219         BXE_FP_TX_LOCK(fp);
4220         BXE_FP_TX_UNLOCK(fp);
4221     }
4222
4223     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4224
4225     /* mark driver as unloaded in shmem2 */
4226     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4227         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4228         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4229                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4230     }
4231
4232     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4233         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4234         /*
4235          * We can get here if the driver has been unloaded
4236          * during parity error recovery and is either waiting for a
4237          * leader to complete or for other functions to unload and
4238          * then ifconfig down has been issued. In this case we want to
4239          * unload and let other functions to complete a recovery
4240          * process.
4241          */
4242         sc->recovery_state = BXE_RECOVERY_DONE;
4243         sc->is_leader = 0;
4244         bxe_release_leader_lock(sc);
4245         mb();
4246
4247         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4248         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4249             " state = 0x%x\n", sc->recovery_state, sc->state);
4250         return (-1);
4251     }
4252
4253     /*
4254      * Nothing to do during unload if previous bxe_nic_load()
4255      * did not completed succesfully - all resourses are released.
4256      */
4257     if ((sc->state == BXE_STATE_CLOSED) ||
4258         (sc->state == BXE_STATE_ERROR)) {
4259         return (0);
4260     }
4261
4262     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4263     mb();
4264
4265     /* stop tx */
4266     bxe_tx_disable(sc);
4267
4268     sc->rx_mode = BXE_RX_MODE_NONE;
4269     /* XXX set rx mode ??? */
4270
4271     if (IS_PF(sc) && !sc->grcdump_done) {
4272         /* set ALWAYS_ALIVE bit in shmem */
4273         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4274
4275         bxe_drv_pulse(sc);
4276
4277         bxe_stats_handle(sc, STATS_EVENT_STOP);
4278         bxe_save_statistics(sc);
4279     }
4280
4281     /* wait till consumers catch up with producers in all queues */
4282     bxe_drain_tx_queues(sc);
4283
4284     /* if VF indicate to PF this function is going down (PF will delete sp
4285      * elements and clear initializations
4286      */
4287     if (IS_VF(sc)) {
4288         ; /* bxe_vfpf_close_vf(sc); */
4289     } else if (unload_mode != UNLOAD_RECOVERY) {
4290         /* if this is a normal/close unload need to clean up chip */
4291         if (!sc->grcdump_done)
4292             bxe_chip_cleanup(sc, unload_mode, keep_link);
4293     } else {
4294         /* Send the UNLOAD_REQUEST to the MCP */
4295         bxe_send_unload_req(sc, unload_mode);
4296
4297         /*
4298          * Prevent transactions to host from the functions on the
4299          * engine that doesn't reset global blocks in case of global
4300          * attention once gloabl blocks are reset and gates are opened
4301          * (the engine which leader will perform the recovery
4302          * last).
4303          */
4304         if (!CHIP_IS_E1x(sc)) {
4305             bxe_pf_disable(sc);
4306         }
4307
4308         /* disable HW interrupts */
4309         bxe_int_disable_sync(sc, TRUE);
4310
4311         /* detach interrupts */
4312         bxe_interrupt_detach(sc);
4313
4314         /* Report UNLOAD_DONE to MCP */
4315         bxe_send_unload_done(sc, FALSE);
4316     }
4317
4318     /*
4319      * At this stage no more interrupts will arrive so we may safely clean
4320      * the queue'able objects here in case they failed to get cleaned so far.
4321      */
4322     if (IS_PF(sc)) {
4323         bxe_squeeze_objects(sc);
4324     }
4325
4326     /* There should be no more pending SP commands at this stage */
4327     sc->sp_state = 0;
4328
4329     sc->port.pmf = 0;
4330
4331     bxe_free_fp_buffers(sc);
4332
4333     if (IS_PF(sc)) {
4334         bxe_free_mem(sc);
4335     }
4336
4337     bxe_free_fw_stats_mem(sc);
4338
4339     sc->state = BXE_STATE_CLOSED;
4340
4341     /*
4342      * Check if there are pending parity attentions. If there are - set
4343      * RECOVERY_IN_PROGRESS.
4344      */
4345     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4346         bxe_set_reset_in_progress(sc);
4347
4348         /* Set RESET_IS_GLOBAL if needed */
4349         if (global) {
4350             bxe_set_reset_global(sc);
4351         }
4352     }
4353
4354     /*
4355      * The last driver must disable a "close the gate" if there is no
4356      * parity attention or "process kill" pending.
4357      */
4358     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4359         bxe_reset_is_done(sc, SC_PATH(sc))) {
4360         bxe_disable_close_the_gate(sc);
4361     }
4362
4363     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4364
4365     return (0);
4366 }
4367
4368 /*
4369  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4370  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4371  */
4372 static int
4373 bxe_ifmedia_update(struct ifnet *ifp)
4374 {
4375     struct bxe_softc *sc = (struct bxe_softc *)ifp->if_softc;
4376     struct ifmedia *ifm;
4377
4378     ifm = &sc->ifmedia;
4379
4380     /* We only support Ethernet media type. */
4381     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4382         return (EINVAL);
4383     }
4384
4385     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4386     case IFM_AUTO:
4387          break;
4388     case IFM_10G_CX4:
4389     case IFM_10G_SR:
4390     case IFM_10G_T:
4391     case IFM_10G_TWINAX:
4392     default:
4393         /* We don't support changing the media type. */
4394         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4395               IFM_SUBTYPE(ifm->ifm_media));
4396         return (EINVAL);
4397     }
4398
4399     return (0);
4400 }
4401
4402 /*
4403  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4404  */
4405 static void
4406 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4407 {
4408     struct bxe_softc *sc = ifp->if_softc;
4409
4410     /* Report link down if the driver isn't running. */
4411     if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4412         ifmr->ifm_active |= IFM_NONE;
4413         return;
4414     }
4415
4416     /* Setup the default interface info. */
4417     ifmr->ifm_status = IFM_AVALID;
4418     ifmr->ifm_active = IFM_ETHER;
4419
4420     if (sc->link_vars.link_up) {
4421         ifmr->ifm_status |= IFM_ACTIVE;
4422     } else {
4423         ifmr->ifm_active |= IFM_NONE;
4424         return;
4425     }
4426
4427     ifmr->ifm_active |= sc->media;
4428
4429     if (sc->link_vars.duplex == DUPLEX_FULL) {
4430         ifmr->ifm_active |= IFM_FDX;
4431     } else {
4432         ifmr->ifm_active |= IFM_HDX;
4433     }
4434 }
4435
4436 static int
4437 bxe_ioctl_nvram(struct bxe_softc *sc,
4438                 uint32_t         priv_op,
4439                 struct ifreq     *ifr)
4440 {
4441     struct bxe_nvram_data nvdata_base;
4442     struct bxe_nvram_data *nvdata;
4443     int len;
4444     int error = 0;
4445
4446     copyin(ifr->ifr_data, &nvdata_base, sizeof(nvdata_base));
4447
4448     len = (sizeof(struct bxe_nvram_data) +
4449            nvdata_base.len -
4450            sizeof(uint32_t));
4451
4452     if (len > sizeof(struct bxe_nvram_data)) {
4453         if ((nvdata = (struct bxe_nvram_data *)
4454                  malloc(len, M_DEVBUF,
4455                         (M_NOWAIT | M_ZERO))) == NULL) {
4456             BLOGE(sc, "BXE_IOC_RD_NVRAM malloc failed priv_op 0x%x "
4457                 " len = 0x%x\n", priv_op, len);
4458             return (1);
4459         }
4460         memcpy(nvdata, &nvdata_base, sizeof(struct bxe_nvram_data));
4461     } else {
4462         nvdata = &nvdata_base;
4463     }
4464
4465     if (priv_op == BXE_IOC_RD_NVRAM) {
4466         BLOGD(sc, DBG_IOCTL, "IOC_RD_NVRAM 0x%x %d\n",
4467               nvdata->offset, nvdata->len);
4468         error = bxe_nvram_read(sc,
4469                                nvdata->offset,
4470                                (uint8_t *)nvdata->value,
4471                                nvdata->len);
4472         copyout(nvdata, ifr->ifr_data, len);
4473     } else { /* BXE_IOC_WR_NVRAM */
4474         BLOGD(sc, DBG_IOCTL, "IOC_WR_NVRAM 0x%x %d\n",
4475               nvdata->offset, nvdata->len);
4476         copyin(ifr->ifr_data, nvdata, len);
4477         error = bxe_nvram_write(sc,
4478                                 nvdata->offset,
4479                                 (uint8_t *)nvdata->value,
4480                                 nvdata->len);
4481     }
4482
4483     if (len > sizeof(struct bxe_nvram_data)) {
4484         free(nvdata, M_DEVBUF);
4485     }
4486
4487     return (error);
4488 }
4489
4490 static int
4491 bxe_ioctl_stats_show(struct bxe_softc *sc,
4492                      uint32_t         priv_op,
4493                      struct ifreq     *ifr)
4494 {
4495     const size_t str_size   = (BXE_NUM_ETH_STATS * STAT_NAME_LEN);
4496     const size_t stats_size = (BXE_NUM_ETH_STATS * sizeof(uint64_t));
4497     caddr_t p_tmp;
4498     uint32_t *offset;
4499     int i;
4500
4501     switch (priv_op)
4502     {
4503     case BXE_IOC_STATS_SHOW_NUM:
4504         memset(ifr->ifr_data, 0, sizeof(union bxe_stats_show_data));
4505         ((union bxe_stats_show_data *)ifr->ifr_data)->desc.num =
4506             BXE_NUM_ETH_STATS;
4507         ((union bxe_stats_show_data *)ifr->ifr_data)->desc.len =
4508             STAT_NAME_LEN;
4509         return (0);
4510
4511     case BXE_IOC_STATS_SHOW_STR:
4512         memset(ifr->ifr_data, 0, str_size);
4513         p_tmp = ifr->ifr_data;
4514         for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4515             strcpy(p_tmp, bxe_eth_stats_arr[i].string);
4516             p_tmp += STAT_NAME_LEN;
4517         }
4518         return (0);
4519
4520     case BXE_IOC_STATS_SHOW_CNT:
4521         memset(ifr->ifr_data, 0, stats_size);
4522         p_tmp = ifr->ifr_data;
4523         for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4524             offset = ((uint32_t *)&sc->eth_stats +
4525                       bxe_eth_stats_arr[i].offset);
4526             switch (bxe_eth_stats_arr[i].size) {
4527             case 4:
4528                 *((uint64_t *)p_tmp) = (uint64_t)*offset;
4529                 break;
4530             case 8:
4531                 *((uint64_t *)p_tmp) = HILO_U64(*offset, *(offset + 1));
4532                 break;
4533             default:
4534                 *((uint64_t *)p_tmp) = 0;
4535             }
4536             p_tmp += sizeof(uint64_t);
4537         }
4538         return (0);
4539
4540     default:
4541         return (-1);
4542     }
4543 }
4544
4545 static void
4546 bxe_handle_chip_tq(void *context,
4547                    int  pending)
4548 {
4549     struct bxe_softc *sc = (struct bxe_softc *)context;
4550     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4551
4552     switch (work)
4553     {
4554     case CHIP_TQ_REINIT:
4555         if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
4556             /* restart the interface */
4557             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4558             bxe_periodic_stop(sc);
4559             BXE_CORE_LOCK(sc);
4560             bxe_stop_locked(sc);
4561             bxe_init_locked(sc);
4562             BXE_CORE_UNLOCK(sc);
4563         }
4564         break;
4565
4566     default:
4567         break;
4568     }
4569 }
4570
4571 /*
4572  * Handles any IOCTL calls from the operating system.
4573  *
4574  * Returns:
4575  *   0 = Success, >0 Failure
4576  */
4577 static int
4578 bxe_ioctl(struct ifnet *ifp,
4579           u_long       command,
4580           caddr_t      data)
4581 {
4582     struct bxe_softc *sc = ifp->if_softc;
4583     struct ifreq *ifr = (struct ifreq *)data;
4584     struct bxe_nvram_data *nvdata;
4585     uint32_t priv_op;
4586     int mask = 0;
4587     int reinit = 0;
4588     int error = 0;
4589
4590     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4591     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4592
4593     switch (command)
4594     {
4595     case SIOCSIFMTU:
4596         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4597               ifr->ifr_mtu);
4598
4599         if (sc->mtu == ifr->ifr_mtu) {
4600             /* nothing to change */
4601             break;
4602         }
4603
4604         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4605             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4606                   ifr->ifr_mtu, mtu_min, mtu_max);
4607             error = EINVAL;
4608             break;
4609         }
4610
4611         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4612                              (unsigned long)ifr->ifr_mtu);
4613         atomic_store_rel_long((volatile unsigned long *)&ifp->if_mtu,
4614                               (unsigned long)ifr->ifr_mtu);
4615
4616         reinit = 1;
4617         break;
4618
4619     case SIOCSIFFLAGS:
4620         /* toggle the interface state up or down */
4621         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4622
4623         BXE_CORE_LOCK(sc);
4624         /* check if the interface is up */
4625         if (ifp->if_flags & IFF_UP) {
4626             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4627                 /* set the receive mode flags */
4628                 bxe_set_rx_mode(sc);
4629             } else {
4630                 bxe_init_locked(sc);
4631             }
4632         } else {
4633             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4634                 bxe_periodic_stop(sc);
4635                 bxe_stop_locked(sc);
4636             }
4637         }
4638         BXE_CORE_UNLOCK(sc);
4639
4640         break;
4641
4642     case SIOCADDMULTI:
4643     case SIOCDELMULTI:
4644         /* add/delete multicast addresses */
4645         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4646
4647         /* check if the interface is up */
4648         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4649             /* set the receive mode flags */
4650             BXE_CORE_LOCK(sc);
4651             bxe_set_rx_mode(sc);
4652             BXE_CORE_UNLOCK(sc); 
4653         }
4654
4655         break;
4656
4657     case SIOCSIFCAP:
4658         /* find out which capabilities have changed */
4659         mask = (ifr->ifr_reqcap ^ ifp->if_capenable);
4660
4661         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4662               mask);
4663
4664         /* toggle the LRO capabilites enable flag */
4665         if (mask & IFCAP_LRO) {
4666             ifp->if_capenable ^= IFCAP_LRO;
4667             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4668                   (ifp->if_capenable & IFCAP_LRO) ? "ON" : "OFF");
4669             reinit = 1;
4670         }
4671
4672         /* toggle the TXCSUM checksum capabilites enable flag */
4673         if (mask & IFCAP_TXCSUM) {
4674             ifp->if_capenable ^= IFCAP_TXCSUM;
4675             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4676                   (ifp->if_capenable & IFCAP_TXCSUM) ? "ON" : "OFF");
4677             if (ifp->if_capenable & IFCAP_TXCSUM) {
4678                 ifp->if_hwassist = (CSUM_IP       |
4679                                     CSUM_TCP      |
4680                                     CSUM_UDP      |
4681                                     CSUM_TSO      |
4682                                     CSUM_TCP_IPV6 |
4683                                     CSUM_UDP_IPV6);
4684             } else {
4685                 ifp->if_hwassist = 0;
4686             }
4687         }
4688
4689         /* toggle the RXCSUM checksum capabilities enable flag */
4690         if (mask & IFCAP_RXCSUM) {
4691             ifp->if_capenable ^= IFCAP_RXCSUM;
4692             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4693                   (ifp->if_capenable & IFCAP_RXCSUM) ? "ON" : "OFF");
4694             if (ifp->if_capenable & IFCAP_RXCSUM) {
4695                 ifp->if_hwassist = (CSUM_IP       |
4696                                     CSUM_TCP      |
4697                                     CSUM_UDP      |
4698                                     CSUM_TSO      |
4699                                     CSUM_TCP_IPV6 |
4700                                     CSUM_UDP_IPV6);
4701             } else {
4702                 ifp->if_hwassist = 0;
4703             }
4704         }
4705
4706         /* toggle TSO4 capabilities enabled flag */
4707         if (mask & IFCAP_TSO4) {
4708             ifp->if_capenable ^= IFCAP_TSO4;
4709             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4710                   (ifp->if_capenable & IFCAP_TSO4) ? "ON" : "OFF");
4711         }
4712
4713         /* toggle TSO6 capabilities enabled flag */
4714         if (mask & IFCAP_TSO6) {
4715             ifp->if_capenable ^= IFCAP_TSO6;
4716             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4717                   (ifp->if_capenable & IFCAP_TSO6) ? "ON" : "OFF");
4718         }
4719
4720         /* toggle VLAN_HWTSO capabilities enabled flag */
4721         if (mask & IFCAP_VLAN_HWTSO) {
4722             ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
4723             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4724                   (ifp->if_capenable & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4725         }
4726
4727         /* toggle VLAN_HWCSUM capabilities enabled flag */
4728         if (mask & IFCAP_VLAN_HWCSUM) {
4729             /* XXX investigate this... */
4730             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4731             error = EINVAL;
4732         }
4733
4734         /* toggle VLAN_MTU capabilities enable flag */
4735         if (mask & IFCAP_VLAN_MTU) {
4736             /* XXX investigate this... */
4737             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4738             error = EINVAL;
4739         }
4740
4741         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4742         if (mask & IFCAP_VLAN_HWTAGGING) {
4743             /* XXX investigate this... */
4744             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4745             error = EINVAL;
4746         }
4747
4748         /* toggle VLAN_HWFILTER capabilities enabled flag */
4749         if (mask & IFCAP_VLAN_HWFILTER) {
4750             /* XXX investigate this... */
4751             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4752             error = EINVAL;
4753         }
4754
4755         /* XXX not yet...
4756          * IFCAP_WOL_MAGIC
4757          */
4758
4759         break;
4760
4761     case SIOCSIFMEDIA:
4762     case SIOCGIFMEDIA:
4763         /* set/get interface media */
4764         BLOGD(sc, DBG_IOCTL,
4765               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4766               (command & 0xff));
4767         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4768         break;
4769
4770     case SIOCGPRIVATE_0:
4771         copyin(ifr->ifr_data, &priv_op, sizeof(priv_op));
4772
4773         switch (priv_op)
4774         {
4775         case BXE_IOC_RD_NVRAM:
4776         case BXE_IOC_WR_NVRAM:
4777             nvdata = (struct bxe_nvram_data *)ifr->ifr_data;
4778             BLOGD(sc, DBG_IOCTL,
4779                   "Received Private NVRAM ioctl addr=0x%x size=%u\n",
4780                   nvdata->offset, nvdata->len);
4781             error = bxe_ioctl_nvram(sc, priv_op, ifr);
4782             break;
4783
4784         case BXE_IOC_STATS_SHOW_NUM:
4785         case BXE_IOC_STATS_SHOW_STR:
4786         case BXE_IOC_STATS_SHOW_CNT:
4787             BLOGD(sc, DBG_IOCTL, "Received Private Stats ioctl (%d)\n",
4788                   priv_op);
4789             error = bxe_ioctl_stats_show(sc, priv_op, ifr);
4790             break;
4791
4792         default:
4793             BLOGW(sc, "Received Private Unknown ioctl (%d)\n", priv_op);
4794             error = EINVAL;
4795             break;
4796         }
4797
4798         break;
4799
4800     default:
4801         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4802               (command & 0xff));
4803         error = ether_ioctl(ifp, command, data);
4804         break;
4805     }
4806
4807     if (reinit && (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
4808         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4809               "Re-initializing hardware from IOCTL change\n");
4810         bxe_periodic_stop(sc);
4811         BXE_CORE_LOCK(sc);
4812         bxe_stop_locked(sc);
4813         bxe_init_locked(sc);
4814         BXE_CORE_UNLOCK(sc);
4815     }
4816
4817     return (error);
4818 }
4819
4820 static __noinline void
4821 bxe_dump_mbuf(struct bxe_softc *sc,
4822               struct mbuf      *m,
4823               uint8_t          contents)
4824 {
4825     char * type;
4826     int i = 0;
4827
4828     if (!(sc->debug & DBG_MBUF)) {
4829         return;
4830     }
4831
4832     if (m == NULL) {
4833         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4834         return;
4835     }
4836
4837     while (m) {
4838
4839 #if __FreeBSD_version >= 1000000
4840         BLOGD(sc, DBG_MBUF,
4841               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4842               i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4843
4844         if (m->m_flags & M_PKTHDR) {
4845              BLOGD(sc, DBG_MBUF,
4846                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4847                    i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4848                    (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4849         }
4850 #else
4851         BLOGD(sc, DBG_MBUF,
4852               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4853               i, m, m->m_len, m->m_flags,
4854               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4855
4856         if (m->m_flags & M_PKTHDR) {
4857              BLOGD(sc, DBG_MBUF,
4858                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4859                    i, m->m_pkthdr.len, m->m_flags,
4860                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4861                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4862                    "\22M_PROMISC\23M_NOFREE",
4863                    (int)m->m_pkthdr.csum_flags,
4864                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4865                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4866                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4867                    "\14CSUM_PSEUDO_HDR");
4868         }
4869 #endif /* #if __FreeBSD_version >= 1000000 */
4870
4871         if (m->m_flags & M_EXT) {
4872             switch (m->m_ext.ext_type) {
4873             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4874             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4875             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4876             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4877             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4878             case EXT_PACKET:     type = "EXT_PACKET";     break;
4879             case EXT_MBUF:       type = "EXT_MBUF";       break;
4880             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4881             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4882             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4883             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4884             default:             type = "UNKNOWN";        break;
4885             }
4886
4887             BLOGD(sc, DBG_MBUF,
4888                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4889                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4890         }
4891
4892         if (contents) {
4893             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4894         }
4895
4896         m = m->m_next;
4897         i++;
4898     }
4899 }
4900
4901 /*
4902  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4903  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4904  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4905  * The headers comes in a seperate bd in FreeBSD so 13-3=10.
4906  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4907  */
4908 static int
4909 bxe_chktso_window(struct bxe_softc  *sc,
4910                   int               nsegs,
4911                   bus_dma_segment_t *segs,
4912                   struct mbuf       *m)
4913 {
4914     uint32_t num_wnds, wnd_size, wnd_sum;
4915     int32_t frag_idx, wnd_idx;
4916     unsigned short lso_mss;
4917     int defrag;
4918
4919     defrag = 0;
4920     wnd_sum = 0;
4921     wnd_size = 10;
4922     num_wnds = nsegs - wnd_size;
4923     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4924
4925     /*
4926      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4927      * first window sum of data while skipping the first assuming it is the
4928      * header in FreeBSD.
4929      */
4930     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4931         wnd_sum += htole16(segs[frag_idx].ds_len);
4932     }
4933
4934     /* check the first 10 bd window size */
4935     if (wnd_sum < lso_mss) {
4936         return (1);
4937     }
4938
4939     /* run through the windows */
4940     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4941         /* subtract the first mbuf->m_len of the last wndw(-header) */
4942         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4943         /* add the next mbuf len to the len of our new window */
4944         wnd_sum += htole16(segs[frag_idx].ds_len);
4945         if (wnd_sum < lso_mss) {
4946             return (1);
4947         }
4948     }
4949
4950     return (0);
4951 }
4952
4953 static uint8_t
4954 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4955                     struct mbuf         *m,
4956                     uint32_t            *parsing_data)
4957 {
4958     struct ether_vlan_header *eh = NULL;
4959     struct ip *ip4 = NULL;
4960     struct ip6_hdr *ip6 = NULL;
4961     caddr_t ip = NULL;
4962     struct tcphdr *th = NULL;
4963     int e_hlen, ip_hlen, l4_off;
4964     uint16_t proto;
4965
4966     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4967         /* no L4 checksum offload needed */
4968         return (0);
4969     }
4970
4971     /* get the Ethernet header */
4972     eh = mtod(m, struct ether_vlan_header *);
4973
4974     /* handle VLAN encapsulation if present */
4975     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4976         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4977         proto  = ntohs(eh->evl_proto);
4978     } else {
4979         e_hlen = ETHER_HDR_LEN;
4980         proto  = ntohs(eh->evl_encap_proto);
4981     }
4982
4983     switch (proto) {
4984     case ETHERTYPE_IP:
4985         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4986         ip4 = (m->m_len < sizeof(struct ip)) ?
4987                   (struct ip *)m->m_next->m_data :
4988                   (struct ip *)(m->m_data + e_hlen);
4989         /* ip_hl is number of 32-bit words */
4990         ip_hlen = (ip4->ip_hl << 2);
4991         ip = (caddr_t)ip4;
4992         break;
4993     case ETHERTYPE_IPV6:
4994         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4995         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4996                   (struct ip6_hdr *)m->m_next->m_data :
4997                   (struct ip6_hdr *)(m->m_data + e_hlen);
4998         /* XXX cannot support offload with IPv6 extensions */
4999         ip_hlen = sizeof(struct ip6_hdr);
5000         ip = (caddr_t)ip6;
5001         break;
5002     default:
5003         /* We can't offload in this case... */
5004         /* XXX error stat ??? */
5005         return (0);
5006     }
5007
5008     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5009     l4_off = (e_hlen + ip_hlen);
5010
5011     *parsing_data |=
5012         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
5013          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
5014
5015     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5016                                   CSUM_TSO |
5017                                   CSUM_TCP_IPV6)) {
5018         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5019         th = (struct tcphdr *)(ip + ip_hlen);
5020         /* th_off is number of 32-bit words */
5021         *parsing_data |= ((th->th_off <<
5022                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
5023                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
5024         return (l4_off + (th->th_off << 2)); /* entire header length */
5025     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5026                                          CSUM_UDP_IPV6)) {
5027         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5028         return (l4_off + sizeof(struct udphdr)); /* entire header length */
5029     } else {
5030         /* XXX error stat ??? */
5031         return (0);
5032     }
5033 }
5034
5035 static uint8_t
5036 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
5037                  struct mbuf                *m,
5038                  struct eth_tx_parse_bd_e1x *pbd)
5039 {
5040     struct ether_vlan_header *eh = NULL;
5041     struct ip *ip4 = NULL;
5042     struct ip6_hdr *ip6 = NULL;
5043     caddr_t ip = NULL;
5044     struct tcphdr *th = NULL;
5045     struct udphdr *uh = NULL;
5046     int e_hlen, ip_hlen;
5047     uint16_t proto;
5048     uint8_t hlen;
5049     uint16_t tmp_csum;
5050     uint32_t *tmp_uh;
5051
5052     /* get the Ethernet header */
5053     eh = mtod(m, struct ether_vlan_header *);
5054
5055     /* handle VLAN encapsulation if present */
5056     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
5057         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
5058         proto  = ntohs(eh->evl_proto);
5059     } else {
5060         e_hlen = ETHER_HDR_LEN;
5061         proto  = ntohs(eh->evl_encap_proto);
5062     }
5063
5064     switch (proto) {
5065     case ETHERTYPE_IP:
5066         /* get the IP header, if mbuf len < 20 then header in next mbuf */
5067         ip4 = (m->m_len < sizeof(struct ip)) ?
5068                   (struct ip *)m->m_next->m_data :
5069                   (struct ip *)(m->m_data + e_hlen);
5070         /* ip_hl is number of 32-bit words */
5071         ip_hlen = (ip4->ip_hl << 1);
5072         ip = (caddr_t)ip4;
5073         break;
5074     case ETHERTYPE_IPV6:
5075         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
5076         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
5077                   (struct ip6_hdr *)m->m_next->m_data :
5078                   (struct ip6_hdr *)(m->m_data + e_hlen);
5079         /* XXX cannot support offload with IPv6 extensions */
5080         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
5081         ip = (caddr_t)ip6;
5082         break;
5083     default:
5084         /* We can't offload in this case... */
5085         /* XXX error stat ??? */
5086         return (0);
5087     }
5088
5089     hlen = (e_hlen >> 1);
5090
5091     /* note that rest of global_data is indirectly zeroed here */
5092     if (m->m_flags & M_VLANTAG) {
5093         pbd->global_data =
5094             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
5095     } else {
5096         pbd->global_data = htole16(hlen);
5097     }
5098
5099     pbd->ip_hlen_w = ip_hlen;
5100
5101     hlen += pbd->ip_hlen_w;
5102
5103     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5104
5105     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5106                                   CSUM_TSO |
5107                                   CSUM_TCP_IPV6)) {
5108         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5109         /* th_off is number of 32-bit words */
5110         hlen += (uint16_t)(th->th_off << 1);
5111     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5112                                          CSUM_UDP_IPV6)) {
5113         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5114         hlen += (sizeof(struct udphdr) / 2);
5115     } else {
5116         /* valid case as only CSUM_IP was set */
5117         return (0);
5118     }
5119
5120     pbd->total_hlen_w = htole16(hlen);
5121
5122     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5123                                   CSUM_TSO |
5124                                   CSUM_TCP_IPV6)) {
5125         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5126         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5127     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5128                                          CSUM_UDP_IPV6)) {
5129         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5130
5131         /*
5132          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5133          * checksums and does not know anything about the UDP header and where
5134          * the checksum field is located. It only knows about TCP. Therefore
5135          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5136          * offload. Since the checksum field offset for TCP is 16 bytes and
5137          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5138          * bytes less than the start of the UDP header. This allows the
5139          * hardware to write the checksum in the correct spot. But the
5140          * hardware will compute a checksum which includes the last 10 bytes
5141          * of the IP header. To correct this we tweak the stack computed
5142          * pseudo checksum by folding in the calculation of the inverse
5143          * checksum for those final 10 bytes of the IP header. This allows
5144          * the correct checksum to be computed by the hardware.
5145          */
5146
5147         /* set pointer 10 bytes before UDP header */
5148         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5149
5150         /* calculate a pseudo header checksum over the first 10 bytes */
5151         tmp_csum = in_pseudo(*tmp_uh,
5152                              *(tmp_uh + 1),
5153                              *(uint16_t *)(tmp_uh + 2));
5154
5155         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5156     }
5157
5158     return (hlen * 2); /* entire header length, number of bytes */
5159 }
5160
5161 static void
5162 bxe_set_pbd_lso_e2(struct mbuf *m,
5163                    uint32_t    *parsing_data)
5164 {
5165     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5166                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5167                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5168
5169     /* XXX test for IPv6 with extension header... */
5170 }
5171
5172 static void
5173 bxe_set_pbd_lso(struct mbuf                *m,
5174                 struct eth_tx_parse_bd_e1x *pbd)
5175 {
5176     struct ether_vlan_header *eh = NULL;
5177     struct ip *ip = NULL;
5178     struct tcphdr *th = NULL;
5179     int e_hlen;
5180
5181     /* get the Ethernet header */
5182     eh = mtod(m, struct ether_vlan_header *);
5183
5184     /* handle VLAN encapsulation if present */
5185     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5186                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5187
5188     /* get the IP and TCP header, with LSO entire header in first mbuf */
5189     /* XXX assuming IPv4 */
5190     ip = (struct ip *)(m->m_data + e_hlen);
5191     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5192
5193     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5194     pbd->tcp_send_seq = ntohl(th->th_seq);
5195     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5196
5197 #if 1
5198         /* XXX IPv4 */
5199         pbd->ip_id = ntohs(ip->ip_id);
5200         pbd->tcp_pseudo_csum =
5201             ntohs(in_pseudo(ip->ip_src.s_addr,
5202                             ip->ip_dst.s_addr,
5203                             htons(IPPROTO_TCP)));
5204 #else
5205         /* XXX IPv6 */
5206         pbd->tcp_pseudo_csum =
5207             ntohs(in_pseudo(&ip6->ip6_src,
5208                             &ip6->ip6_dst,
5209                             htons(IPPROTO_TCP)));
5210 #endif
5211
5212     pbd->global_data |=
5213         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5214 }
5215
5216 /*
5217  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5218  * visible to the controller.
5219  *
5220  * If an mbuf is submitted to this routine and cannot be given to the
5221  * controller (e.g. it has too many fragments) then the function may free
5222  * the mbuf and return to the caller.
5223  *
5224  * Returns:
5225  *   0 = Success, !0 = Failure
5226  *   Note the side effect that an mbuf may be freed if it causes a problem.
5227  */
5228 static int
5229 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5230 {
5231     bus_dma_segment_t segs[32];
5232     struct mbuf *m0;
5233     struct bxe_sw_tx_bd *tx_buf;
5234     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5235     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5236     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5237     struct eth_tx_bd *tx_data_bd;
5238     struct eth_tx_bd *tx_total_pkt_size_bd;
5239     struct eth_tx_start_bd *tx_start_bd;
5240     uint16_t bd_prod, pkt_prod, total_pkt_size;
5241     uint8_t mac_type;
5242     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5243     struct bxe_softc *sc;
5244     uint16_t tx_bd_avail;
5245     struct ether_vlan_header *eh;
5246     uint32_t pbd_e2_parsing_data = 0;
5247     uint8_t hlen = 0;
5248     int tmp_bd;
5249     int i;
5250
5251     sc = fp->sc;
5252
5253 #if __FreeBSD_version >= 800000
5254     M_ASSERTPKTHDR(*m_head);
5255 #endif /* #if __FreeBSD_version >= 800000 */
5256
5257     m0 = *m_head;
5258     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5259     tx_start_bd = NULL;
5260     tx_data_bd = NULL;
5261     tx_total_pkt_size_bd = NULL;
5262
5263     /* get the H/W pointer for packets and BDs */
5264     pkt_prod = fp->tx_pkt_prod;
5265     bd_prod = fp->tx_bd_prod;
5266
5267     mac_type = UNICAST_ADDRESS;
5268
5269     /* map the mbuf into the next open DMAable memory */
5270     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5271     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5272                                     tx_buf->m_map, m0,
5273                                     segs, &nsegs, BUS_DMA_NOWAIT);
5274
5275     /* mapping errors */
5276     if(__predict_false(error != 0)) {
5277         fp->eth_q_stats.tx_dma_mapping_failure++;
5278         if (error == ENOMEM) {
5279             /* resource issue, try again later */
5280             rc = ENOMEM;
5281         } else if (error == EFBIG) {
5282             /* possibly recoverable with defragmentation */
5283             fp->eth_q_stats.mbuf_defrag_attempts++;
5284             m0 = m_defrag(*m_head, M_DONTWAIT);
5285             if (m0 == NULL) {
5286                 fp->eth_q_stats.mbuf_defrag_failures++;
5287                 rc = ENOBUFS;
5288             } else {
5289                 /* defrag successful, try mapping again */
5290                 *m_head = m0;
5291                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5292                                                 tx_buf->m_map, m0,
5293                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5294                 if (error) {
5295                     fp->eth_q_stats.tx_dma_mapping_failure++;
5296                     rc = error;
5297                 }
5298             }
5299         } else {
5300             /* unknown, unrecoverable mapping error */
5301             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5302             bxe_dump_mbuf(sc, m0, FALSE);
5303             rc = error;
5304         }
5305
5306         goto bxe_tx_encap_continue;
5307     }
5308
5309     tx_bd_avail = bxe_tx_avail(sc, fp);
5310
5311     /* make sure there is enough room in the send queue */
5312     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5313         /* Recoverable, try again later. */
5314         fp->eth_q_stats.tx_hw_queue_full++;
5315         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5316         rc = ENOMEM;
5317         goto bxe_tx_encap_continue;
5318     }
5319
5320     /* capture the current H/W TX chain high watermark */
5321     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5322                         (TX_BD_USABLE - tx_bd_avail))) {
5323         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5324     }
5325
5326     /* make sure it fits in the packet window */
5327     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5328         /*
5329          * The mbuf may be to big for the controller to handle. If the frame
5330          * is a TSO frame we'll need to do an additional check.
5331          */
5332         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5333             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5334                 goto bxe_tx_encap_continue; /* OK to send */
5335             } else {
5336                 fp->eth_q_stats.tx_window_violation_tso++;
5337             }
5338         } else {
5339             fp->eth_q_stats.tx_window_violation_std++;
5340         }
5341
5342         /* lets try to defragment this mbuf and remap it */
5343         fp->eth_q_stats.mbuf_defrag_attempts++;
5344         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5345
5346         m0 = m_defrag(*m_head, M_DONTWAIT);
5347         if (m0 == NULL) {
5348             fp->eth_q_stats.mbuf_defrag_failures++;
5349             /* Ugh, just drop the frame... :( */
5350             rc = ENOBUFS;
5351         } else {
5352             /* defrag successful, try mapping again */
5353             *m_head = m0;
5354             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5355                                             tx_buf->m_map, m0,
5356                                             segs, &nsegs, BUS_DMA_NOWAIT);
5357             if (error) {
5358                 fp->eth_q_stats.tx_dma_mapping_failure++;
5359                 /* No sense in trying to defrag/copy chain, drop it. :( */
5360                 rc = error;
5361             }
5362             else {
5363                 /* if the chain is still too long then drop it */
5364                 if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5365                     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5366                     rc = ENODEV;
5367                 }
5368             }
5369         }
5370     }
5371
5372 bxe_tx_encap_continue:
5373
5374     /* Check for errors */
5375     if (rc) {
5376         if (rc == ENOMEM) {
5377             /* recoverable try again later  */
5378         } else {
5379             fp->eth_q_stats.tx_soft_errors++;
5380             fp->eth_q_stats.mbuf_alloc_tx--;
5381             m_freem(*m_head);
5382             *m_head = NULL;
5383         }
5384
5385         return (rc);
5386     }
5387
5388     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5389     if (m0->m_flags & M_BCAST) {
5390         mac_type = BROADCAST_ADDRESS;
5391     } else if (m0->m_flags & M_MCAST) {
5392         mac_type = MULTICAST_ADDRESS;
5393     }
5394
5395     /* store the mbuf into the mbuf ring */
5396     tx_buf->m        = m0;
5397     tx_buf->first_bd = fp->tx_bd_prod;
5398     tx_buf->flags    = 0;
5399
5400     /* prepare the first transmit (start) BD for the mbuf */
5401     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5402
5403     BLOGD(sc, DBG_TX,
5404           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5405           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5406
5407     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5408     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5409     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5410     total_pkt_size += tx_start_bd->nbytes;
5411     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5412
5413     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5414
5415     /* all frames have at least Start BD + Parsing BD */
5416     nbds = nsegs + 1;
5417     tx_start_bd->nbd = htole16(nbds);
5418
5419     if (m0->m_flags & M_VLANTAG) {
5420         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5421         tx_start_bd->bd_flags.as_bitfield |=
5422             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5423     } else {
5424         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5425         if (IS_VF(sc)) {
5426             /* map ethernet header to find type and header length */
5427             eh = mtod(m0, struct ether_vlan_header *);
5428             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5429         } else {
5430             /* used by FW for packet accounting */
5431             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5432         }
5433     }
5434
5435     /*
5436      * add a parsing BD from the chain. The parsing BD is always added
5437      * though it is only used for TSO and chksum
5438      */
5439     bd_prod = TX_BD_NEXT(bd_prod);
5440
5441     if (m0->m_pkthdr.csum_flags) {
5442         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5443             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5444             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5445         }
5446
5447         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5448             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5449                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5450         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5451             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5452                                                   ETH_TX_BD_FLAGS_IS_UDP |
5453                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5454         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5455                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5456             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5457         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5458             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5459                                                   ETH_TX_BD_FLAGS_IS_UDP);
5460         }
5461     }
5462
5463     if (!CHIP_IS_E1x(sc)) {
5464         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5465         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5466
5467         if (m0->m_pkthdr.csum_flags) {
5468             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5469         }
5470
5471         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5472                  mac_type);
5473     } else {
5474         uint16_t global_data = 0;
5475
5476         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5477         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5478
5479         if (m0->m_pkthdr.csum_flags) {
5480             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5481         }
5482
5483         SET_FLAG(global_data,
5484                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5485         pbd_e1x->global_data |= htole16(global_data);
5486     }
5487
5488     /* setup the parsing BD with TSO specific info */
5489     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5490         fp->eth_q_stats.tx_ofld_frames_lso++;
5491         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5492
5493         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5494             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5495
5496             /* split the first BD into header/data making the fw job easy */
5497             nbds++;
5498             tx_start_bd->nbd = htole16(nbds);
5499             tx_start_bd->nbytes = htole16(hlen);
5500
5501             bd_prod = TX_BD_NEXT(bd_prod);
5502
5503             /* new transmit BD after the tx_parse_bd */
5504             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5505             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5506             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5507             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5508             if (tx_total_pkt_size_bd == NULL) {
5509                 tx_total_pkt_size_bd = tx_data_bd;
5510             }
5511
5512             BLOGD(sc, DBG_TX,
5513                   "TSO split header size is %d (%x:%x) nbds %d\n",
5514                   le16toh(tx_start_bd->nbytes),
5515                   le32toh(tx_start_bd->addr_hi),
5516                   le32toh(tx_start_bd->addr_lo),
5517                   nbds);
5518         }
5519
5520         if (!CHIP_IS_E1x(sc)) {
5521             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5522         } else {
5523             bxe_set_pbd_lso(m0, pbd_e1x);
5524         }
5525     }
5526
5527     if (pbd_e2_parsing_data) {
5528         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5529     }
5530
5531     /* prepare remaining BDs, start tx bd contains first seg/frag */
5532     for (i = 1; i < nsegs ; i++) {
5533         bd_prod = TX_BD_NEXT(bd_prod);
5534         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5535         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5536         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5537         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5538         if (tx_total_pkt_size_bd == NULL) {
5539             tx_total_pkt_size_bd = tx_data_bd;
5540         }
5541         total_pkt_size += tx_data_bd->nbytes;
5542     }
5543
5544     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5545
5546     if (tx_total_pkt_size_bd != NULL) {
5547         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5548     }
5549
5550     if (__predict_false(sc->debug & DBG_TX)) {
5551         tmp_bd = tx_buf->first_bd;
5552         for (i = 0; i < nbds; i++)
5553         {
5554             if (i == 0) {
5555                 BLOGD(sc, DBG_TX,
5556                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5557                       "bd_flags=0x%x hdr_nbds=%d\n",
5558                       tx_start_bd,
5559                       tmp_bd,
5560                       le16toh(tx_start_bd->nbd),
5561                       le16toh(tx_start_bd->vlan_or_ethertype),
5562                       tx_start_bd->bd_flags.as_bitfield,
5563                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5564             } else if (i == 1) {
5565                 if (pbd_e1x) {
5566                     BLOGD(sc, DBG_TX,
5567                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5568                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5569                           "tcp_seq=%u total_hlen_w=%u\n",
5570                           pbd_e1x,
5571                           tmp_bd,
5572                           pbd_e1x->global_data,
5573                           pbd_e1x->ip_hlen_w,
5574                           pbd_e1x->ip_id,
5575                           pbd_e1x->lso_mss,
5576                           pbd_e1x->tcp_flags,
5577                           pbd_e1x->tcp_pseudo_csum,
5578                           pbd_e1x->tcp_send_seq,
5579                           le16toh(pbd_e1x->total_hlen_w));
5580                 } else { /* if (pbd_e2) */
5581                     BLOGD(sc, DBG_TX,
5582                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5583                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5584                           pbd_e2,
5585                           tmp_bd,
5586                           pbd_e2->data.mac_addr.dst_hi,
5587                           pbd_e2->data.mac_addr.dst_mid,
5588                           pbd_e2->data.mac_addr.dst_lo,
5589                           pbd_e2->data.mac_addr.src_hi,
5590                           pbd_e2->data.mac_addr.src_mid,
5591                           pbd_e2->data.mac_addr.src_lo,
5592                           pbd_e2->parsing_data);
5593                 }
5594             }
5595
5596             if (i != 1) { /* skip parse db as it doesn't hold data */
5597                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5598                 BLOGD(sc, DBG_TX,
5599                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5600                       tx_data_bd,
5601                       tmp_bd,
5602                       le16toh(tx_data_bd->nbytes),
5603                       le32toh(tx_data_bd->addr_hi),
5604                       le32toh(tx_data_bd->addr_lo));
5605             }
5606
5607             tmp_bd = TX_BD_NEXT(tmp_bd);
5608         }
5609     }
5610
5611     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5612
5613     /* update TX BD producer index value for next TX */
5614     bd_prod = TX_BD_NEXT(bd_prod);
5615
5616     /*
5617      * If the chain of tx_bd's describing this frame is adjacent to or spans
5618      * an eth_tx_next_bd element then we need to increment the nbds value.
5619      */
5620     if (TX_BD_IDX(bd_prod) < nbds) {
5621         nbds++;
5622     }
5623
5624     /* don't allow reordering of writes for nbd and packets */
5625     mb();
5626
5627     fp->tx_db.data.prod += nbds;
5628
5629     /* producer points to the next free tx_bd at this point */
5630     fp->tx_pkt_prod++;
5631     fp->tx_bd_prod = bd_prod;
5632
5633     DOORBELL(sc, fp->index, fp->tx_db.raw);
5634
5635     fp->eth_q_stats.tx_pkts++;
5636
5637     /* Prevent speculative reads from getting ahead of the status block. */
5638     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5639                       0, 0, BUS_SPACE_BARRIER_READ);
5640
5641     /* Prevent speculative reads from getting ahead of the doorbell. */
5642     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5643                       0, 0, BUS_SPACE_BARRIER_READ);
5644
5645     return (0);
5646 }
5647
5648 static void
5649 bxe_tx_start_locked(struct bxe_softc    *sc,
5650                     struct ifnet        *ifp,
5651                     struct bxe_fastpath *fp)
5652 {
5653     struct mbuf *m = NULL;
5654     int tx_count = 0;
5655     uint16_t tx_bd_avail;
5656
5657     BXE_FP_TX_LOCK_ASSERT(fp);
5658
5659     /* keep adding entries while there are frames to send */
5660     while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
5661
5662         /*
5663          * check for any frames to send
5664          * dequeue can still be NULL even if queue is not empty
5665          */
5666         IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
5667         if (__predict_false(m == NULL)) {
5668             break;
5669         }
5670
5671         /* the mbuf now belongs to us */
5672         fp->eth_q_stats.mbuf_alloc_tx++;
5673
5674         /*
5675          * Put the frame into the transmit ring. If we don't have room,
5676          * place the mbuf back at the head of the TX queue, set the
5677          * OACTIVE flag, and wait for the NIC to drain the chain.
5678          */
5679         if (__predict_false(bxe_tx_encap(fp, &m))) {
5680             fp->eth_q_stats.tx_encap_failures++;
5681             if (m != NULL) {
5682                 /* mark the TX queue as full and return the frame */
5683                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5684                 IFQ_DRV_PREPEND(&ifp->if_snd, m);
5685                 fp->eth_q_stats.mbuf_alloc_tx--;
5686                 fp->eth_q_stats.tx_queue_xoff++;
5687             }
5688
5689             /* stop looking for more work */
5690             break;
5691         }
5692
5693         /* the frame was enqueued successfully */
5694         tx_count++;
5695
5696         /* send a copy of the frame to any BPF listeners. */
5697         BPF_MTAP(ifp, m);
5698
5699         tx_bd_avail = bxe_tx_avail(sc, fp);
5700
5701         /* handle any completions if we're running low */
5702         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5703             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5704             bxe_txeof(sc, fp);
5705             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5706                 break;
5707             }
5708         }
5709     }
5710
5711     /* all TX packets were dequeued and/or the tx ring is full */
5712     if (tx_count > 0) {
5713         /* reset the TX watchdog timeout timer */
5714         fp->watchdog_timer = BXE_TX_TIMEOUT;
5715     }
5716 }
5717
5718 /* Legacy (non-RSS) dispatch routine */
5719 static void
5720 bxe_tx_start(struct ifnet *ifp)
5721 {
5722     struct bxe_softc *sc;
5723     struct bxe_fastpath *fp;
5724
5725     sc = ifp->if_softc;
5726
5727     if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5728         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5729         return;
5730     }
5731
5732     if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5733         BLOGW(sc, "Interface TX queue is full, ignoring transmit request\n");
5734         return;
5735     }
5736
5737     if (!sc->link_vars.link_up) {
5738         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5739         return;
5740     }
5741
5742     fp = &sc->fp[0];
5743
5744     BXE_FP_TX_LOCK(fp);
5745     bxe_tx_start_locked(sc, ifp, fp);
5746     BXE_FP_TX_UNLOCK(fp);
5747 }
5748
5749 #if __FreeBSD_version >= 800000
5750
5751 static int
5752 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5753                        struct ifnet        *ifp,
5754                        struct bxe_fastpath *fp,
5755                        struct mbuf         *m)
5756 {
5757     struct buf_ring *tx_br = fp->tx_br;
5758     struct mbuf *next;
5759     int depth, rc, tx_count;
5760     uint16_t tx_bd_avail;
5761
5762     rc = tx_count = 0;
5763
5764     BXE_FP_TX_LOCK_ASSERT(fp);
5765
5766     if (!tx_br) {
5767         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5768         return (EINVAL);
5769     }
5770
5771     if (!sc->link_vars.link_up ||
5772         (ifp->if_drv_flags &
5773         (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) != IFF_DRV_RUNNING) {
5774         rc = drbr_enqueue(ifp, tx_br, m);
5775         goto bxe_tx_mq_start_locked_exit;
5776     }
5777
5778     /* fetch the depth of the driver queue */
5779     depth = drbr_inuse(ifp, tx_br);
5780     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5781         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5782     }
5783
5784     if (m == NULL) {
5785         /* no new work, check for pending frames */
5786         next = drbr_dequeue(ifp, tx_br);
5787     } else if (drbr_needs_enqueue(ifp, tx_br)) {
5788         /* have both new and pending work, maintain packet order */
5789         rc = drbr_enqueue(ifp, tx_br, m);
5790         if (rc != 0) {
5791             fp->eth_q_stats.tx_soft_errors++;
5792             goto bxe_tx_mq_start_locked_exit;
5793         }
5794         next = drbr_dequeue(ifp, tx_br);
5795     } else {
5796         /* new work only and nothing pending */
5797         next = m;
5798     }
5799
5800     /* keep adding entries while there are frames to send */
5801     while (next != NULL) {
5802
5803         /* the mbuf now belongs to us */
5804         fp->eth_q_stats.mbuf_alloc_tx++;
5805
5806         /*
5807          * Put the frame into the transmit ring. If we don't have room,
5808          * place the mbuf back at the head of the TX queue, set the
5809          * OACTIVE flag, and wait for the NIC to drain the chain.
5810          */
5811         rc = bxe_tx_encap(fp, &next);
5812         if (__predict_false(rc != 0)) {
5813             fp->eth_q_stats.tx_encap_failures++;
5814             if (next != NULL) {
5815                 /* mark the TX queue as full and save the frame */
5816                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5817                 /* XXX this may reorder the frame */
5818                 rc = drbr_enqueue(ifp, tx_br, next);
5819                 fp->eth_q_stats.mbuf_alloc_tx--;
5820                 fp->eth_q_stats.tx_frames_deferred++;
5821             }
5822
5823             /* stop looking for more work */
5824             break;
5825         }
5826
5827         /* the transmit frame was enqueued successfully */
5828         tx_count++;
5829
5830         /* send a copy of the frame to any BPF listeners */
5831         BPF_MTAP(ifp, next);
5832
5833         tx_bd_avail = bxe_tx_avail(sc, fp);
5834
5835         /* handle any completions if we're running low */
5836         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5837             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5838             bxe_txeof(sc, fp);
5839             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5840                 break;
5841             }
5842         }
5843
5844         next = drbr_dequeue(ifp, tx_br);
5845     }
5846
5847     /* all TX packets were dequeued and/or the tx ring is full */
5848     if (tx_count > 0) {
5849         /* reset the TX watchdog timeout timer */
5850         fp->watchdog_timer = BXE_TX_TIMEOUT;
5851     }
5852
5853 bxe_tx_mq_start_locked_exit:
5854
5855     return (rc);
5856 }
5857
5858 /* Multiqueue (TSS) dispatch routine. */
5859 static int
5860 bxe_tx_mq_start(struct ifnet *ifp,
5861                 struct mbuf  *m)
5862 {
5863     struct bxe_softc *sc = ifp->if_softc;
5864     struct bxe_fastpath *fp;
5865     int fp_index, rc;
5866
5867     fp_index = 0; /* default is the first queue */
5868
5869     /* check if flowid is set */
5870
5871     if (BXE_VALID_FLOWID(m))
5872         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5873
5874     fp = &sc->fp[fp_index];
5875
5876     if (BXE_FP_TX_TRYLOCK(fp)) {
5877         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5878         BXE_FP_TX_UNLOCK(fp);
5879     } else
5880         rc = drbr_enqueue(ifp, fp->tx_br, m);
5881
5882     return (rc);
5883 }
5884
5885 static void
5886 bxe_mq_flush(struct ifnet *ifp)
5887 {
5888     struct bxe_softc *sc = ifp->if_softc;
5889     struct bxe_fastpath *fp;
5890     struct mbuf *m;
5891     int i;
5892
5893     for (i = 0; i < sc->num_queues; i++) {
5894         fp = &sc->fp[i];
5895
5896         if (fp->state != BXE_FP_STATE_OPEN) {
5897             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5898                   fp->index, fp->state);
5899             continue;
5900         }
5901
5902         if (fp->tx_br != NULL) {
5903             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5904             BXE_FP_TX_LOCK(fp);
5905             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5906                 m_freem(m);
5907             }
5908             BXE_FP_TX_UNLOCK(fp);
5909         }
5910     }
5911
5912     if_qflush(ifp);
5913 }
5914
5915 #endif /* FreeBSD_version >= 800000 */
5916
5917 static uint16_t
5918 bxe_cid_ilt_lines(struct bxe_softc *sc)
5919 {
5920     if (IS_SRIOV(sc)) {
5921         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5922     }
5923     return (L2_ILT_LINES(sc));
5924 }
5925
5926 static void
5927 bxe_ilt_set_info(struct bxe_softc *sc)
5928 {
5929     struct ilt_client_info *ilt_client;
5930     struct ecore_ilt *ilt = sc->ilt;
5931     uint16_t line = 0;
5932
5933     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5934     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5935
5936     /* CDU */
5937     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5938     ilt_client->client_num = ILT_CLIENT_CDU;
5939     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5940     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5941     ilt_client->start = line;
5942     line += bxe_cid_ilt_lines(sc);
5943
5944     if (CNIC_SUPPORT(sc)) {
5945         line += CNIC_ILT_LINES;
5946     }
5947
5948     ilt_client->end = (line - 1);
5949
5950     BLOGD(sc, DBG_LOAD,
5951           "ilt client[CDU]: start %d, end %d, "
5952           "psz 0x%x, flags 0x%x, hw psz %d\n",
5953           ilt_client->start, ilt_client->end,
5954           ilt_client->page_size,
5955           ilt_client->flags,
5956           ilog2(ilt_client->page_size >> 12));
5957
5958     /* QM */
5959     if (QM_INIT(sc->qm_cid_count)) {
5960         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5961         ilt_client->client_num = ILT_CLIENT_QM;
5962         ilt_client->page_size = QM_ILT_PAGE_SZ;
5963         ilt_client->flags = 0;
5964         ilt_client->start = line;
5965
5966         /* 4 bytes for each cid */
5967         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5968                              QM_ILT_PAGE_SZ);
5969
5970         ilt_client->end = (line - 1);
5971
5972         BLOGD(sc, DBG_LOAD,
5973               "ilt client[QM]: start %d, end %d, "
5974               "psz 0x%x, flags 0x%x, hw psz %d\n",
5975               ilt_client->start, ilt_client->end,
5976               ilt_client->page_size, ilt_client->flags,
5977               ilog2(ilt_client->page_size >> 12));
5978     }
5979
5980     if (CNIC_SUPPORT(sc)) {
5981         /* SRC */
5982         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5983         ilt_client->client_num = ILT_CLIENT_SRC;
5984         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5985         ilt_client->flags = 0;
5986         ilt_client->start = line;
5987         line += SRC_ILT_LINES;
5988         ilt_client->end = (line - 1);
5989
5990         BLOGD(sc, DBG_LOAD,
5991               "ilt client[SRC]: start %d, end %d, "
5992               "psz 0x%x, flags 0x%x, hw psz %d\n",
5993               ilt_client->start, ilt_client->end,
5994               ilt_client->page_size, ilt_client->flags,
5995               ilog2(ilt_client->page_size >> 12));
5996
5997         /* TM */
5998         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5999         ilt_client->client_num = ILT_CLIENT_TM;
6000         ilt_client->page_size = TM_ILT_PAGE_SZ;
6001         ilt_client->flags = 0;
6002         ilt_client->start = line;
6003         line += TM_ILT_LINES;
6004         ilt_client->end = (line - 1);
6005
6006         BLOGD(sc, DBG_LOAD,
6007               "ilt client[TM]: start %d, end %d, "
6008               "psz 0x%x, flags 0x%x, hw psz %d\n",
6009               ilt_client->start, ilt_client->end,
6010               ilt_client->page_size, ilt_client->flags,
6011               ilog2(ilt_client->page_size >> 12));
6012     }
6013
6014     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
6015 }
6016
6017 static void
6018 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
6019 {
6020     int i;
6021     uint32_t rx_buf_size;
6022
6023     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
6024
6025     for (i = 0; i < sc->num_queues; i++) {
6026         if(rx_buf_size <= MCLBYTES){
6027             sc->fp[i].rx_buf_size = rx_buf_size;
6028             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6029         }else if (rx_buf_size <= MJUMPAGESIZE){
6030             sc->fp[i].rx_buf_size = rx_buf_size;
6031             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
6032         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
6033             sc->fp[i].rx_buf_size = MCLBYTES;
6034             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6035         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
6036             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
6037             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
6038         }else {
6039             sc->fp[i].rx_buf_size = MCLBYTES;
6040             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6041         }
6042     }
6043 }
6044
6045 static int
6046 bxe_alloc_ilt_mem(struct bxe_softc *sc)
6047 {
6048     int rc = 0;
6049
6050     if ((sc->ilt =
6051          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
6052                                     M_BXE_ILT,
6053                                     (M_NOWAIT | M_ZERO))) == NULL) {
6054         rc = 1;
6055     }
6056
6057     return (rc);
6058 }
6059
6060 static int
6061 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
6062 {
6063     int rc = 0;
6064
6065     if ((sc->ilt->lines =
6066          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6067                                     M_BXE_ILT,
6068                                     (M_NOWAIT | M_ZERO))) == NULL) {
6069         rc = 1;
6070     }
6071
6072     return (rc);
6073 }
6074
6075 static void
6076 bxe_free_ilt_mem(struct bxe_softc *sc)
6077 {
6078     if (sc->ilt != NULL) {
6079         free(sc->ilt, M_BXE_ILT);
6080         sc->ilt = NULL;
6081     }
6082 }
6083
6084 static void
6085 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6086 {
6087     if (sc->ilt->lines != NULL) {
6088         free(sc->ilt->lines, M_BXE_ILT);
6089         sc->ilt->lines = NULL;
6090     }
6091 }
6092
6093 static void
6094 bxe_free_mem(struct bxe_softc *sc)
6095 {
6096     int i;
6097
6098     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6099         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6100         sc->context[i].vcxt = NULL;
6101         sc->context[i].size = 0;
6102     }
6103
6104     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6105
6106     bxe_free_ilt_lines_mem(sc);
6107
6108 }
6109
6110 static int
6111 bxe_alloc_mem(struct bxe_softc *sc)
6112 {
6113     int context_size;
6114     int allocated;
6115     int i;
6116
6117     /*
6118      * Allocate memory for CDU context:
6119      * This memory is allocated separately and not in the generic ILT
6120      * functions because CDU differs in few aspects:
6121      * 1. There can be multiple entities allocating memory for context -
6122      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6123      * its own ILT lines.
6124      * 2. Since CDU page-size is not a single 4KB page (which is the case
6125      * for the other ILT clients), to be efficient we want to support
6126      * allocation of sub-page-size in the last entry.
6127      * 3. Context pointers are used by the driver to pass to FW / update
6128      * the context (for the other ILT clients the pointers are used just to
6129      * free the memory during unload).
6130      */
6131     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6132     for (i = 0, allocated = 0; allocated < context_size; i++) {
6133         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6134                                   (context_size - allocated));
6135
6136         if (bxe_dma_alloc(sc, sc->context[i].size,
6137                           &sc->context[i].vcxt_dma,
6138                           "cdu context") != 0) {
6139             bxe_free_mem(sc);
6140             return (-1);
6141         }
6142
6143         sc->context[i].vcxt =
6144             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6145
6146         allocated += sc->context[i].size;
6147     }
6148
6149     bxe_alloc_ilt_lines_mem(sc);
6150
6151     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6152           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6153     {
6154         for (i = 0; i < 4; i++) {
6155             BLOGD(sc, DBG_LOAD,
6156                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6157                   i,
6158                   sc->ilt->clients[i].page_size,
6159                   sc->ilt->clients[i].start,
6160                   sc->ilt->clients[i].end,
6161                   sc->ilt->clients[i].client_num,
6162                   sc->ilt->clients[i].flags);
6163         }
6164     }
6165     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6166         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6167         bxe_free_mem(sc);
6168         return (-1);
6169     }
6170
6171     return (0);
6172 }
6173
6174 static void
6175 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6176 {
6177     struct bxe_softc *sc;
6178     int i;
6179
6180     sc = fp->sc;
6181
6182     if (fp->rx_mbuf_tag == NULL) {
6183         return;
6184     }
6185
6186     /* free all mbufs and unload all maps */
6187     for (i = 0; i < RX_BD_TOTAL; i++) {
6188         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6189             bus_dmamap_sync(fp->rx_mbuf_tag,
6190                             fp->rx_mbuf_chain[i].m_map,
6191                             BUS_DMASYNC_POSTREAD);
6192             bus_dmamap_unload(fp->rx_mbuf_tag,
6193                               fp->rx_mbuf_chain[i].m_map);
6194         }
6195
6196         if (fp->rx_mbuf_chain[i].m != NULL) {
6197             m_freem(fp->rx_mbuf_chain[i].m);
6198             fp->rx_mbuf_chain[i].m = NULL;
6199             fp->eth_q_stats.mbuf_alloc_rx--;
6200         }
6201     }
6202 }
6203
6204 static void
6205 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6206 {
6207     struct bxe_softc *sc;
6208     int i, max_agg_queues;
6209
6210     sc = fp->sc;
6211
6212     if (fp->rx_mbuf_tag == NULL) {
6213         return;
6214     }
6215
6216     max_agg_queues = MAX_AGG_QS(sc);
6217
6218     /* release all mbufs and unload all DMA maps in the TPA pool */
6219     for (i = 0; i < max_agg_queues; i++) {
6220         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6221             bus_dmamap_sync(fp->rx_mbuf_tag,
6222                             fp->rx_tpa_info[i].bd.m_map,
6223                             BUS_DMASYNC_POSTREAD);
6224             bus_dmamap_unload(fp->rx_mbuf_tag,
6225                               fp->rx_tpa_info[i].bd.m_map);
6226         }
6227
6228         if (fp->rx_tpa_info[i].bd.m != NULL) {
6229             m_freem(fp->rx_tpa_info[i].bd.m);
6230             fp->rx_tpa_info[i].bd.m = NULL;
6231             fp->eth_q_stats.mbuf_alloc_tpa--;
6232         }
6233     }
6234 }
6235
6236 static void
6237 bxe_free_sge_chain(struct bxe_fastpath *fp)
6238 {
6239     struct bxe_softc *sc;
6240     int i;
6241
6242     sc = fp->sc;
6243
6244     if (fp->rx_sge_mbuf_tag == NULL) {
6245         return;
6246     }
6247
6248     /* rree all mbufs and unload all maps */
6249     for (i = 0; i < RX_SGE_TOTAL; i++) {
6250         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6251             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6252                             fp->rx_sge_mbuf_chain[i].m_map,
6253                             BUS_DMASYNC_POSTREAD);
6254             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6255                               fp->rx_sge_mbuf_chain[i].m_map);
6256         }
6257
6258         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6259             m_freem(fp->rx_sge_mbuf_chain[i].m);
6260             fp->rx_sge_mbuf_chain[i].m = NULL;
6261             fp->eth_q_stats.mbuf_alloc_sge--;
6262         }
6263     }
6264 }
6265
6266 static void
6267 bxe_free_fp_buffers(struct bxe_softc *sc)
6268 {
6269     struct bxe_fastpath *fp;
6270     int i;
6271
6272     for (i = 0; i < sc->num_queues; i++) {
6273         fp = &sc->fp[i];
6274
6275 #if __FreeBSD_version >= 800000
6276         if (fp->tx_br != NULL) {
6277             /* just in case bxe_mq_flush() wasn't called */
6278             if (mtx_initialized(&fp->tx_mtx)) {
6279                 struct mbuf *m;
6280
6281                 BXE_FP_TX_LOCK(fp);
6282                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6283                     m_freem(m);
6284                 BXE_FP_TX_UNLOCK(fp);
6285             }
6286         }
6287 #endif
6288
6289         /* free all RX buffers */
6290         bxe_free_rx_bd_chain(fp);
6291         bxe_free_tpa_pool(fp);
6292         bxe_free_sge_chain(fp);
6293
6294         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6295             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6296                   fp->eth_q_stats.mbuf_alloc_rx);
6297         }
6298
6299         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6300             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6301                   fp->eth_q_stats.mbuf_alloc_sge);
6302         }
6303
6304         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6305             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6306                   fp->eth_q_stats.mbuf_alloc_tpa);
6307         }
6308
6309         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6310             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6311                   fp->eth_q_stats.mbuf_alloc_tx);
6312         }
6313
6314         /* XXX verify all mbufs were reclaimed */
6315     }
6316 }
6317
6318 static int
6319 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6320                      uint16_t            prev_index,
6321                      uint16_t            index)
6322 {
6323     struct bxe_sw_rx_bd *rx_buf;
6324     struct eth_rx_bd *rx_bd;
6325     bus_dma_segment_t segs[1];
6326     bus_dmamap_t map;
6327     struct mbuf *m;
6328     int nsegs, rc;
6329
6330     rc = 0;
6331
6332     /* allocate the new RX BD mbuf */
6333     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6334     if (__predict_false(m == NULL)) {
6335         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6336         return (ENOBUFS);
6337     }
6338
6339     fp->eth_q_stats.mbuf_alloc_rx++;
6340
6341     /* initialize the mbuf buffer length */
6342     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6343
6344     /* map the mbuf into non-paged pool */
6345     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6346                                  fp->rx_mbuf_spare_map,
6347                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6348     if (__predict_false(rc != 0)) {
6349         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6350         m_freem(m);
6351         fp->eth_q_stats.mbuf_alloc_rx--;
6352         return (rc);
6353     }
6354
6355     /* all mbufs must map to a single segment */
6356     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6357
6358     /* release any existing RX BD mbuf mappings */
6359
6360     if (prev_index != index) {
6361         rx_buf = &fp->rx_mbuf_chain[prev_index];
6362
6363         if (rx_buf->m_map != NULL) {
6364             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6365                             BUS_DMASYNC_POSTREAD);
6366             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6367         }
6368
6369         /*
6370          * We only get here from bxe_rxeof() when the maximum number
6371          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6372          * holds the mbuf in the prev_index so it's OK to NULL it out
6373          * here without concern of a memory leak.
6374          */
6375         fp->rx_mbuf_chain[prev_index].m = NULL;
6376     }
6377
6378     rx_buf = &fp->rx_mbuf_chain[index];
6379
6380     if (rx_buf->m_map != NULL) {
6381         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6382                         BUS_DMASYNC_POSTREAD);
6383         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6384     }
6385
6386     /* save the mbuf and mapping info for a future packet */
6387     map = (prev_index != index) ?
6388               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6389     rx_buf->m_map = fp->rx_mbuf_spare_map;
6390     fp->rx_mbuf_spare_map = map;
6391     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6392                     BUS_DMASYNC_PREREAD);
6393     rx_buf->m = m;
6394
6395     rx_bd = &fp->rx_chain[index];
6396     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6397     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6398
6399     return (rc);
6400 }
6401
6402 static int
6403 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6404                       int                 queue)
6405 {
6406     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6407     bus_dma_segment_t segs[1];
6408     bus_dmamap_t map;
6409     struct mbuf *m;
6410     int nsegs;
6411     int rc = 0;
6412
6413     /* allocate the new TPA mbuf */
6414     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6415     if (__predict_false(m == NULL)) {
6416         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6417         return (ENOBUFS);
6418     }
6419
6420     fp->eth_q_stats.mbuf_alloc_tpa++;
6421
6422     /* initialize the mbuf buffer length */
6423     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6424
6425     /* map the mbuf into non-paged pool */
6426     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6427                                  fp->rx_tpa_info_mbuf_spare_map,
6428                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6429     if (__predict_false(rc != 0)) {
6430         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6431         m_free(m);
6432         fp->eth_q_stats.mbuf_alloc_tpa--;
6433         return (rc);
6434     }
6435
6436     /* all mbufs must map to a single segment */
6437     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6438
6439     /* release any existing TPA mbuf mapping */
6440     if (tpa_info->bd.m_map != NULL) {
6441         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6442                         BUS_DMASYNC_POSTREAD);
6443         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6444     }
6445
6446     /* save the mbuf and mapping info for the TPA mbuf */
6447     map = tpa_info->bd.m_map;
6448     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6449     fp->rx_tpa_info_mbuf_spare_map = map;
6450     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6451                     BUS_DMASYNC_PREREAD);
6452     tpa_info->bd.m = m;
6453     tpa_info->seg = segs[0];
6454
6455     return (rc);
6456 }
6457
6458 /*
6459  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6460  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6461  * chain.
6462  */
6463 static int
6464 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6465                       uint16_t            index)
6466 {
6467     struct bxe_sw_rx_bd *sge_buf;
6468     struct eth_rx_sge *sge;
6469     bus_dma_segment_t segs[1];
6470     bus_dmamap_t map;
6471     struct mbuf *m;
6472     int nsegs;
6473     int rc = 0;
6474
6475     /* allocate a new SGE mbuf */
6476     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6477     if (__predict_false(m == NULL)) {
6478         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6479         return (ENOMEM);
6480     }
6481
6482     fp->eth_q_stats.mbuf_alloc_sge++;
6483
6484     /* initialize the mbuf buffer length */
6485     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6486
6487     /* map the SGE mbuf into non-paged pool */
6488     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6489                                  fp->rx_sge_mbuf_spare_map,
6490                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6491     if (__predict_false(rc != 0)) {
6492         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6493         m_freem(m);
6494         fp->eth_q_stats.mbuf_alloc_sge--;
6495         return (rc);
6496     }
6497
6498     /* all mbufs must map to a single segment */
6499     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6500
6501     sge_buf = &fp->rx_sge_mbuf_chain[index];
6502
6503     /* release any existing SGE mbuf mapping */
6504     if (sge_buf->m_map != NULL) {
6505         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6506                         BUS_DMASYNC_POSTREAD);
6507         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6508     }
6509
6510     /* save the mbuf and mapping info for a future packet */
6511     map = sge_buf->m_map;
6512     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6513     fp->rx_sge_mbuf_spare_map = map;
6514     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6515                     BUS_DMASYNC_PREREAD);
6516     sge_buf->m = m;
6517
6518     sge = &fp->rx_sge_chain[index];
6519     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6520     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6521
6522     return (rc);
6523 }
6524
6525 static __noinline int
6526 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6527 {
6528     struct bxe_fastpath *fp;
6529     int i, j, rc = 0;
6530     int ring_prod, cqe_ring_prod;
6531     int max_agg_queues;
6532
6533     for (i = 0; i < sc->num_queues; i++) {
6534         fp = &sc->fp[i];
6535
6536         ring_prod = cqe_ring_prod = 0;
6537         fp->rx_bd_cons = 0;
6538         fp->rx_cq_cons = 0;
6539
6540         /* allocate buffers for the RX BDs in RX BD chain */
6541         for (j = 0; j < sc->max_rx_bufs; j++) {
6542             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6543             if (rc != 0) {
6544                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6545                       i, rc);
6546                 goto bxe_alloc_fp_buffers_error;
6547             }
6548
6549             ring_prod     = RX_BD_NEXT(ring_prod);
6550             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6551         }
6552
6553         fp->rx_bd_prod = ring_prod;
6554         fp->rx_cq_prod = cqe_ring_prod;
6555         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6556
6557         max_agg_queues = MAX_AGG_QS(sc);
6558
6559         fp->tpa_enable = TRUE;
6560
6561         /* fill the TPA pool */
6562         for (j = 0; j < max_agg_queues; j++) {
6563             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6564             if (rc != 0) {
6565                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6566                           i, j);
6567                 fp->tpa_enable = FALSE;
6568                 goto bxe_alloc_fp_buffers_error;
6569             }
6570
6571             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6572         }
6573
6574         if (fp->tpa_enable) {
6575             /* fill the RX SGE chain */
6576             ring_prod = 0;
6577             for (j = 0; j < RX_SGE_USABLE; j++) {
6578                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6579                 if (rc != 0) {
6580                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6581                               i, ring_prod);
6582                     fp->tpa_enable = FALSE;
6583                     ring_prod = 0;
6584                     goto bxe_alloc_fp_buffers_error;
6585                 }
6586
6587                 ring_prod = RX_SGE_NEXT(ring_prod);
6588             }
6589
6590             fp->rx_sge_prod = ring_prod;
6591         }
6592     }
6593
6594     return (0);
6595
6596 bxe_alloc_fp_buffers_error:
6597
6598     /* unwind what was already allocated */
6599     bxe_free_rx_bd_chain(fp);
6600     bxe_free_tpa_pool(fp);
6601     bxe_free_sge_chain(fp);
6602
6603     return (ENOBUFS);
6604 }
6605
6606 static void
6607 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6608 {
6609     bxe_dma_free(sc, &sc->fw_stats_dma);
6610
6611     sc->fw_stats_num = 0;
6612
6613     sc->fw_stats_req_size = 0;
6614     sc->fw_stats_req = NULL;
6615     sc->fw_stats_req_mapping = 0;
6616
6617     sc->fw_stats_data_size = 0;
6618     sc->fw_stats_data = NULL;
6619     sc->fw_stats_data_mapping = 0;
6620 }
6621
6622 static int
6623 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6624 {
6625     uint8_t num_queue_stats;
6626     int num_groups;
6627
6628     /* number of queues for statistics is number of eth queues */
6629     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6630
6631     /*
6632      * Total number of FW statistics requests =
6633      *   1 for port stats + 1 for PF stats + num of queues
6634      */
6635     sc->fw_stats_num = (2 + num_queue_stats);
6636
6637     /*
6638      * Request is built from stats_query_header and an array of
6639      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6640      * rules. The real number or requests is configured in the
6641      * stats_query_header.
6642      */
6643     num_groups =
6644         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6645          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6646
6647     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6648           sc->fw_stats_num, num_groups);
6649
6650     sc->fw_stats_req_size =
6651         (sizeof(struct stats_query_header) +
6652          (num_groups * sizeof(struct stats_query_cmd_group)));
6653
6654     /*
6655      * Data for statistics requests + stats_counter.
6656      * stats_counter holds per-STORM counters that are incremented when
6657      * STORM has finished with the current request. Memory for FCoE
6658      * offloaded statistics are counted anyway, even if they will not be sent.
6659      * VF stats are not accounted for here as the data of VF stats is stored
6660      * in memory allocated by the VF, not here.
6661      */
6662     sc->fw_stats_data_size =
6663         (sizeof(struct stats_counter) +
6664          sizeof(struct per_port_stats) +
6665          sizeof(struct per_pf_stats) +
6666          /* sizeof(struct fcoe_statistics_params) + */
6667          (sizeof(struct per_queue_stats) * num_queue_stats));
6668
6669     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6670                       &sc->fw_stats_dma, "fw stats") != 0) {
6671         bxe_free_fw_stats_mem(sc);
6672         return (-1);
6673     }
6674
6675     /* set up the shortcuts */
6676
6677     sc->fw_stats_req =
6678         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6679     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6680
6681     sc->fw_stats_data =
6682         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6683                                      sc->fw_stats_req_size);
6684     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6685                                  sc->fw_stats_req_size);
6686
6687     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6688           (uintmax_t)sc->fw_stats_req_mapping);
6689
6690     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6691           (uintmax_t)sc->fw_stats_data_mapping);
6692
6693     return (0);
6694 }
6695
6696 /*
6697  * Bits map:
6698  * 0-7  - Engine0 load counter.
6699  * 8-15 - Engine1 load counter.
6700  * 16   - Engine0 RESET_IN_PROGRESS bit.
6701  * 17   - Engine1 RESET_IN_PROGRESS bit.
6702  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6703  *        function on the engine
6704  * 19   - Engine1 ONE_IS_LOADED.
6705  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6706  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6707  *        for just the one belonging to its engine).
6708  */
6709 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6710 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6711 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6712 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6713 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6714 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6715 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6716 #define BXE_GLOBAL_RESET_BIT      0x00040000
6717
6718 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6719 static void
6720 bxe_set_reset_global(struct bxe_softc *sc)
6721 {
6722     uint32_t val;
6723     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6724     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6725     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6726     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6727 }
6728
6729 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6730 static void
6731 bxe_clear_reset_global(struct bxe_softc *sc)
6732 {
6733     uint32_t val;
6734     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6735     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6736     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6737     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6738 }
6739
6740 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6741 static uint8_t
6742 bxe_reset_is_global(struct bxe_softc *sc)
6743 {
6744     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6745     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6746     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6747 }
6748
6749 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6750 static void
6751 bxe_set_reset_done(struct bxe_softc *sc)
6752 {
6753     uint32_t val;
6754     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6755                                  BXE_PATH0_RST_IN_PROG_BIT;
6756
6757     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6758
6759     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6760     /* Clear the bit */
6761     val &= ~bit;
6762     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6763
6764     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6765 }
6766
6767 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6768 static void
6769 bxe_set_reset_in_progress(struct bxe_softc *sc)
6770 {
6771     uint32_t val;
6772     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6773                                  BXE_PATH0_RST_IN_PROG_BIT;
6774
6775     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6776
6777     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6778     /* Set the bit */
6779     val |= bit;
6780     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6781
6782     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6783 }
6784
6785 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6786 static uint8_t
6787 bxe_reset_is_done(struct bxe_softc *sc,
6788                   int              engine)
6789 {
6790     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6791     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6792                             BXE_PATH0_RST_IN_PROG_BIT;
6793
6794     /* return false if bit is set */
6795     return (val & bit) ? FALSE : TRUE;
6796 }
6797
6798 /* get the load status for an engine, should be run under rtnl lock */
6799 static uint8_t
6800 bxe_get_load_status(struct bxe_softc *sc,
6801                     int              engine)
6802 {
6803     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6804                              BXE_PATH0_LOAD_CNT_MASK;
6805     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6806                               BXE_PATH0_LOAD_CNT_SHIFT;
6807     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6808
6809     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6810
6811     val = ((val & mask) >> shift);
6812
6813     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6814
6815     return (val != 0);
6816 }
6817
6818 /* set pf load mark */
6819 /* XXX needs to be under rtnl lock */
6820 static void
6821 bxe_set_pf_load(struct bxe_softc *sc)
6822 {
6823     uint32_t val;
6824     uint32_t val1;
6825     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6826                                   BXE_PATH0_LOAD_CNT_MASK;
6827     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6828                                    BXE_PATH0_LOAD_CNT_SHIFT;
6829
6830     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6831
6832     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6833     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6834
6835     /* get the current counter value */
6836     val1 = ((val & mask) >> shift);
6837
6838     /* set bit of this PF */
6839     val1 |= (1 << SC_ABS_FUNC(sc));
6840
6841     /* clear the old value */
6842     val &= ~mask;
6843
6844     /* set the new one */
6845     val |= ((val1 << shift) & mask);
6846
6847     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6848
6849     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6850 }
6851
6852 /* clear pf load mark */
6853 /* XXX needs to be under rtnl lock */
6854 static uint8_t
6855 bxe_clear_pf_load(struct bxe_softc *sc)
6856 {
6857     uint32_t val1, val;
6858     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6859                                   BXE_PATH0_LOAD_CNT_MASK;
6860     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6861                                    BXE_PATH0_LOAD_CNT_SHIFT;
6862
6863     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6864     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6865     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6866
6867     /* get the current counter value */
6868     val1 = (val & mask) >> shift;
6869
6870     /* clear bit of that PF */
6871     val1 &= ~(1 << SC_ABS_FUNC(sc));
6872
6873     /* clear the old value */
6874     val &= ~mask;
6875
6876     /* set the new one */
6877     val |= ((val1 << shift) & mask);
6878
6879     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6880     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6881     return (val1 != 0);
6882 }
6883
6884 /* send load requrest to mcp and analyze response */
6885 static int
6886 bxe_nic_load_request(struct bxe_softc *sc,
6887                      uint32_t         *load_code)
6888 {
6889     /* init fw_seq */
6890     sc->fw_seq =
6891         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6892          DRV_MSG_SEQ_NUMBER_MASK);
6893
6894     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6895
6896     /* get the current FW pulse sequence */
6897     sc->fw_drv_pulse_wr_seq =
6898         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6899          DRV_PULSE_SEQ_MASK);
6900
6901     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6902           sc->fw_drv_pulse_wr_seq);
6903
6904     /* load request */
6905     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6906                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6907
6908     /* if the MCP fails to respond we must abort */
6909     if (!(*load_code)) {
6910         BLOGE(sc, "MCP response failure!\n");
6911         return (-1);
6912     }
6913
6914     /* if MCP refused then must abort */
6915     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6916         BLOGE(sc, "MCP refused load request\n");
6917         return (-1);
6918     }
6919
6920     return (0);
6921 }
6922
6923 /*
6924  * Check whether another PF has already loaded FW to chip. In virtualized
6925  * environments a pf from anoth VM may have already initialized the device
6926  * including loading FW.
6927  */
6928 static int
6929 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6930                          uint32_t         load_code)
6931 {
6932     uint32_t my_fw, loaded_fw;
6933
6934     /* is another pf loaded on this engine? */
6935     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6936         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6937         /* build my FW version dword */
6938         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6939                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6940                  (BCM_5710_FW_REVISION_VERSION << 16) +
6941                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6942
6943         /* read loaded FW from chip */
6944         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6945         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6946               loaded_fw, my_fw);
6947
6948         /* abort nic load if version mismatch */
6949         if (my_fw != loaded_fw) {
6950             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6951                   loaded_fw, my_fw);
6952             return (-1);
6953         }
6954     }
6955
6956     return (0);
6957 }
6958
6959 /* mark PMF if applicable */
6960 static void
6961 bxe_nic_load_pmf(struct bxe_softc *sc,
6962                  uint32_t         load_code)
6963 {
6964     uint32_t ncsi_oem_data_addr;
6965
6966     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6967         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6968         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6969         /*
6970          * Barrier here for ordering between the writing to sc->port.pmf here
6971          * and reading it from the periodic task.
6972          */
6973         sc->port.pmf = 1;
6974         mb();
6975     } else {
6976         sc->port.pmf = 0;
6977     }
6978
6979     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6980
6981     /* XXX needed? */
6982     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6983         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6984             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6985             if (ncsi_oem_data_addr) {
6986                 REG_WR(sc,
6987                        (ncsi_oem_data_addr +
6988                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6989                        0);
6990             }
6991         }
6992     }
6993 }
6994
6995 static void
6996 bxe_read_mf_cfg(struct bxe_softc *sc)
6997 {
6998     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6999     int abs_func;
7000     int vn;
7001
7002     if (BXE_NOMCP(sc)) {
7003         return; /* what should be the default bvalue in this case */
7004     }
7005
7006     /*
7007      * The formula for computing the absolute function number is...
7008      * For 2 port configuration (4 functions per port):
7009      *   abs_func = 2 * vn + SC_PORT + SC_PATH
7010      * For 4 port configuration (2 functions per port):
7011      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
7012      */
7013     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
7014         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
7015         if (abs_func >= E1H_FUNC_MAX) {
7016             break;
7017         }
7018         sc->devinfo.mf_info.mf_config[vn] =
7019             MFCFG_RD(sc, func_mf_config[abs_func].config);
7020     }
7021
7022     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
7023         FUNC_MF_CFG_FUNC_DISABLED) {
7024         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
7025         sc->flags |= BXE_MF_FUNC_DIS;
7026     } else {
7027         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
7028         sc->flags &= ~BXE_MF_FUNC_DIS;
7029     }
7030 }
7031
7032 /* acquire split MCP access lock register */
7033 static int bxe_acquire_alr(struct bxe_softc *sc)
7034 {
7035     uint32_t j, val;
7036
7037     for (j = 0; j < 1000; j++) {
7038         val = (1UL << 31);
7039         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
7040         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
7041         if (val & (1L << 31))
7042             break;
7043
7044         DELAY(5000);
7045     }
7046
7047     if (!(val & (1L << 31))) {
7048         BLOGE(sc, "Cannot acquire MCP access lock register\n");
7049         return (-1);
7050     }
7051
7052     return (0);
7053 }
7054
7055 /* release split MCP access lock register */
7056 static void bxe_release_alr(struct bxe_softc *sc)
7057 {
7058     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
7059 }
7060
7061 static void
7062 bxe_fan_failure(struct bxe_softc *sc)
7063 {
7064     int port = SC_PORT(sc);
7065     uint32_t ext_phy_config;
7066
7067     /* mark the failure */
7068     ext_phy_config =
7069         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7070
7071     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7072     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7073     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7074              ext_phy_config);
7075
7076     /* log the failure */
7077     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7078               "the card to prevent permanent damage. "
7079               "Please contact OEM Support for assistance\n");
7080
7081     /* XXX */
7082 #if 1
7083     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7084 #else
7085     /*
7086      * Schedule device reset (unload)
7087      * This is due to some boards consuming sufficient power when driver is
7088      * up to overheat if fan fails.
7089      */
7090     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7091     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7092 #endif
7093 }
7094
7095 /* this function is called upon a link interrupt */
7096 static void
7097 bxe_link_attn(struct bxe_softc *sc)
7098 {
7099     uint32_t pause_enabled = 0;
7100     struct host_port_stats *pstats;
7101     int cmng_fns;
7102
7103     /* Make sure that we are synced with the current statistics */
7104     bxe_stats_handle(sc, STATS_EVENT_STOP);
7105
7106     elink_link_update(&sc->link_params, &sc->link_vars);
7107
7108     if (sc->link_vars.link_up) {
7109
7110         /* dropless flow control */
7111         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7112             pause_enabled = 0;
7113
7114             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7115                 pause_enabled = 1;
7116             }
7117
7118             REG_WR(sc,
7119                    (BAR_USTRORM_INTMEM +
7120                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7121                    pause_enabled);
7122         }
7123
7124         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7125             pstats = BXE_SP(sc, port_stats);
7126             /* reset old mac stats */
7127             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7128         }
7129
7130         if (sc->state == BXE_STATE_OPEN) {
7131             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7132         }
7133     }
7134
7135     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7136         cmng_fns = bxe_get_cmng_fns_mode(sc);
7137
7138         if (cmng_fns != CMNG_FNS_NONE) {
7139             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7140             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7141         } else {
7142             /* rate shaping and fairness are disabled */
7143             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7144         }
7145     }
7146
7147     bxe_link_report_locked(sc);
7148
7149     if (IS_MF(sc)) {
7150         ; // XXX bxe_link_sync_notify(sc);
7151     }
7152 }
7153
7154 static void
7155 bxe_attn_int_asserted(struct bxe_softc *sc,
7156                       uint32_t         asserted)
7157 {
7158     int port = SC_PORT(sc);
7159     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7160                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7161     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7162                                         NIG_REG_MASK_INTERRUPT_PORT0;
7163     uint32_t aeu_mask;
7164     uint32_t nig_mask = 0;
7165     uint32_t reg_addr;
7166     uint32_t igu_acked;
7167     uint32_t cnt;
7168
7169     if (sc->attn_state & asserted) {
7170         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7171     }
7172
7173     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7174
7175     aeu_mask = REG_RD(sc, aeu_addr);
7176
7177     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7178           aeu_mask, asserted);
7179
7180     aeu_mask &= ~(asserted & 0x3ff);
7181
7182     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7183
7184     REG_WR(sc, aeu_addr, aeu_mask);
7185
7186     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7187
7188     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7189     sc->attn_state |= asserted;
7190     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7191
7192     if (asserted & ATTN_HARD_WIRED_MASK) {
7193         if (asserted & ATTN_NIG_FOR_FUNC) {
7194
7195             bxe_acquire_phy_lock(sc);
7196             /* save nig interrupt mask */
7197             nig_mask = REG_RD(sc, nig_int_mask_addr);
7198
7199             /* If nig_mask is not set, no need to call the update function */
7200             if (nig_mask) {
7201                 REG_WR(sc, nig_int_mask_addr, 0);
7202
7203                 bxe_link_attn(sc);
7204             }
7205
7206             /* handle unicore attn? */
7207         }
7208
7209         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7210             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7211         }
7212
7213         if (asserted & GPIO_2_FUNC) {
7214             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7215         }
7216
7217         if (asserted & GPIO_3_FUNC) {
7218             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7219         }
7220
7221         if (asserted & GPIO_4_FUNC) {
7222             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7223         }
7224
7225         if (port == 0) {
7226             if (asserted & ATTN_GENERAL_ATTN_1) {
7227                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7228                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7229             }
7230             if (asserted & ATTN_GENERAL_ATTN_2) {
7231                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7232                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7233             }
7234             if (asserted & ATTN_GENERAL_ATTN_3) {
7235                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7236                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7237             }
7238         } else {
7239             if (asserted & ATTN_GENERAL_ATTN_4) {
7240                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7241                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7242             }
7243             if (asserted & ATTN_GENERAL_ATTN_5) {
7244                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7245                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7246             }
7247             if (asserted & ATTN_GENERAL_ATTN_6) {
7248                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7249                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7250             }
7251         }
7252     } /* hardwired */
7253
7254     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7255         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7256     } else {
7257         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7258     }
7259
7260     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7261           asserted,
7262           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7263     REG_WR(sc, reg_addr, asserted);
7264
7265     /* now set back the mask */
7266     if (asserted & ATTN_NIG_FOR_FUNC) {
7267         /*
7268          * Verify that IGU ack through BAR was written before restoring
7269          * NIG mask. This loop should exit after 2-3 iterations max.
7270          */
7271         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7272             cnt = 0;
7273
7274             do {
7275                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7276             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7277                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7278
7279             if (!igu_acked) {
7280                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7281             }
7282
7283             mb();
7284         }
7285
7286         REG_WR(sc, nig_int_mask_addr, nig_mask);
7287
7288         bxe_release_phy_lock(sc);
7289     }
7290 }
7291
7292 static void
7293 bxe_print_next_block(struct bxe_softc *sc,
7294                      int              idx,
7295                      const char       *blk)
7296 {
7297     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7298 }
7299
7300 static int
7301 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7302                               uint32_t         sig,
7303                               int              par_num,
7304                               uint8_t          print)
7305 {
7306     uint32_t cur_bit = 0;
7307     int i = 0;
7308
7309     for (i = 0; sig; i++) {
7310         cur_bit = ((uint32_t)0x1 << i);
7311         if (sig & cur_bit) {
7312             switch (cur_bit) {
7313             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7314                 if (print)
7315                     bxe_print_next_block(sc, par_num++, "BRB");
7316                 break;
7317             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7318                 if (print)
7319                     bxe_print_next_block(sc, par_num++, "PARSER");
7320                 break;
7321             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7322                 if (print)
7323                     bxe_print_next_block(sc, par_num++, "TSDM");
7324                 break;
7325             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7326                 if (print)
7327                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7328                 break;
7329             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7330                 if (print)
7331                     bxe_print_next_block(sc, par_num++, "TCM");
7332                 break;
7333             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7334                 if (print)
7335                     bxe_print_next_block(sc, par_num++, "TSEMI");
7336                 break;
7337             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7338                 if (print)
7339                     bxe_print_next_block(sc, par_num++, "XPB");
7340                 break;
7341             }
7342
7343             /* Clear the bit */
7344             sig &= ~cur_bit;
7345         }
7346     }
7347
7348     return (par_num);
7349 }
7350
7351 static int
7352 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7353                               uint32_t         sig,
7354                               int              par_num,
7355                               uint8_t          *global,
7356                               uint8_t          print)
7357 {
7358     int i = 0;
7359     uint32_t cur_bit = 0;
7360     for (i = 0; sig; i++) {
7361         cur_bit = ((uint32_t)0x1 << i);
7362         if (sig & cur_bit) {
7363             switch (cur_bit) {
7364             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7365                 if (print)
7366                     bxe_print_next_block(sc, par_num++, "PBF");
7367                 break;
7368             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7369                 if (print)
7370                     bxe_print_next_block(sc, par_num++, "QM");
7371                 break;
7372             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7373                 if (print)
7374                     bxe_print_next_block(sc, par_num++, "TM");
7375                 break;
7376             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7377                 if (print)
7378                     bxe_print_next_block(sc, par_num++, "XSDM");
7379                 break;
7380             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7381                 if (print)
7382                     bxe_print_next_block(sc, par_num++, "XCM");
7383                 break;
7384             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7385                 if (print)
7386                     bxe_print_next_block(sc, par_num++, "XSEMI");
7387                 break;
7388             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7389                 if (print)
7390                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7391                 break;
7392             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7393                 if (print)
7394                     bxe_print_next_block(sc, par_num++, "NIG");
7395                 break;
7396             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7397                 if (print)
7398                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7399                 *global = TRUE;
7400                 break;
7401             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7402                 if (print)
7403                     bxe_print_next_block(sc, par_num++, "DEBUG");
7404                 break;
7405             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7406                 if (print)
7407                     bxe_print_next_block(sc, par_num++, "USDM");
7408                 break;
7409             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7410                 if (print)
7411                     bxe_print_next_block(sc, par_num++, "UCM");
7412                 break;
7413             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7414                 if (print)
7415                     bxe_print_next_block(sc, par_num++, "USEMI");
7416                 break;
7417             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7418                 if (print)
7419                     bxe_print_next_block(sc, par_num++, "UPB");
7420                 break;
7421             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7422                 if (print)
7423                     bxe_print_next_block(sc, par_num++, "CSDM");
7424                 break;
7425             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7426                 if (print)
7427                     bxe_print_next_block(sc, par_num++, "CCM");
7428                 break;
7429             }
7430
7431             /* Clear the bit */
7432             sig &= ~cur_bit;
7433         }
7434     }
7435
7436     return (par_num);
7437 }
7438
7439 static int
7440 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7441                               uint32_t         sig,
7442                               int              par_num,
7443                               uint8_t          print)
7444 {
7445     uint32_t cur_bit = 0;
7446     int i = 0;
7447
7448     for (i = 0; sig; i++) {
7449         cur_bit = ((uint32_t)0x1 << i);
7450         if (sig & cur_bit) {
7451             switch (cur_bit) {
7452             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7453                 if (print)
7454                     bxe_print_next_block(sc, par_num++, "CSEMI");
7455                 break;
7456             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7457                 if (print)
7458                     bxe_print_next_block(sc, par_num++, "PXP");
7459                 break;
7460             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7461                 if (print)
7462                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7463                 break;
7464             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7465                 if (print)
7466                     bxe_print_next_block(sc, par_num++, "CFC");
7467                 break;
7468             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7469                 if (print)
7470                     bxe_print_next_block(sc, par_num++, "CDU");
7471                 break;
7472             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7473                 if (print)
7474                     bxe_print_next_block(sc, par_num++, "DMAE");
7475                 break;
7476             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7477                 if (print)
7478                     bxe_print_next_block(sc, par_num++, "IGU");
7479                 break;
7480             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7481                 if (print)
7482                     bxe_print_next_block(sc, par_num++, "MISC");
7483                 break;
7484             }
7485
7486             /* Clear the bit */
7487             sig &= ~cur_bit;
7488         }
7489     }
7490
7491     return (par_num);
7492 }
7493
7494 static int
7495 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7496                               uint32_t         sig,
7497                               int              par_num,
7498                               uint8_t          *global,
7499                               uint8_t          print)
7500 {
7501     uint32_t cur_bit = 0;
7502     int i = 0;
7503
7504     for (i = 0; sig; i++) {
7505         cur_bit = ((uint32_t)0x1 << i);
7506         if (sig & cur_bit) {
7507             switch (cur_bit) {
7508             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7509                 if (print)
7510                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7511                 *global = TRUE;
7512                 break;
7513             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7514                 if (print)
7515                     bxe_print_next_block(sc, par_num++,
7516                               "MCP UMP RX");
7517                 *global = TRUE;
7518                 break;
7519             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7520                 if (print)
7521                     bxe_print_next_block(sc, par_num++,
7522                               "MCP UMP TX");
7523                 *global = TRUE;
7524                 break;
7525             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7526                 if (print)
7527                     bxe_print_next_block(sc, par_num++,
7528                               "MCP SCPAD");
7529                 *global = TRUE;
7530                 break;
7531             }
7532
7533             /* Clear the bit */
7534             sig &= ~cur_bit;
7535         }
7536     }
7537
7538     return (par_num);
7539 }
7540
7541 static int
7542 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7543                               uint32_t         sig,
7544                               int              par_num,
7545                               uint8_t          print)
7546 {
7547     uint32_t cur_bit = 0;
7548     int i = 0;
7549
7550     for (i = 0; sig; i++) {
7551         cur_bit = ((uint32_t)0x1 << i);
7552         if (sig & cur_bit) {
7553             switch (cur_bit) {
7554             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7555                 if (print)
7556                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7557                 break;
7558             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7559                 if (print)
7560                     bxe_print_next_block(sc, par_num++, "ATC");
7561                 break;
7562             }
7563
7564             /* Clear the bit */
7565             sig &= ~cur_bit;
7566         }
7567     }
7568
7569     return (par_num);
7570 }
7571
7572 static uint8_t
7573 bxe_parity_attn(struct bxe_softc *sc,
7574                 uint8_t          *global,
7575                 uint8_t          print,
7576                 uint32_t         *sig)
7577 {
7578     int par_num = 0;
7579
7580     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7581         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7582         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7583         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7584         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7585         BLOGE(sc, "Parity error: HW block parity attention:\n"
7586                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7587               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7588               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7589               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7590               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7591               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7592
7593         if (print)
7594             BLOGI(sc, "Parity errors detected in blocks: ");
7595
7596         par_num =
7597             bxe_check_blocks_with_parity0(sc, sig[0] &
7598                                           HW_PRTY_ASSERT_SET_0,
7599                                           par_num, print);
7600         par_num =
7601             bxe_check_blocks_with_parity1(sc, sig[1] &
7602                                           HW_PRTY_ASSERT_SET_1,
7603                                           par_num, global, print);
7604         par_num =
7605             bxe_check_blocks_with_parity2(sc, sig[2] &
7606                                           HW_PRTY_ASSERT_SET_2,
7607                                           par_num, print);
7608         par_num =
7609             bxe_check_blocks_with_parity3(sc, sig[3] &
7610                                           HW_PRTY_ASSERT_SET_3,
7611                                           par_num, global, print);
7612         par_num =
7613             bxe_check_blocks_with_parity4(sc, sig[4] &
7614                                           HW_PRTY_ASSERT_SET_4,
7615                                           par_num, print);
7616
7617         if (print)
7618             BLOGI(sc, "\n");
7619
7620         return (TRUE);
7621     }
7622
7623     return (FALSE);
7624 }
7625
7626 static uint8_t
7627 bxe_chk_parity_attn(struct bxe_softc *sc,
7628                     uint8_t          *global,
7629                     uint8_t          print)
7630 {
7631     struct attn_route attn = { {0} };
7632     int port = SC_PORT(sc);
7633
7634     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7635     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7636     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7637     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7638
7639     /*
7640      * Since MCP attentions can't be disabled inside the block, we need to
7641      * read AEU registers to see whether they're currently disabled
7642      */
7643     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7644                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7645                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7646                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7647
7648
7649     if (!CHIP_IS_E1x(sc))
7650         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7651
7652     return (bxe_parity_attn(sc, global, print, attn.sig));
7653 }
7654
7655 static void
7656 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7657                          uint32_t         attn)
7658 {
7659     uint32_t val;
7660
7661     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7662         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7663         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7664         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7665             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7666         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7667             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7668         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7669             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7670         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7671             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7672         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7673             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7674         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7675             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7676         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7677             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7678         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7679             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7680         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7681             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7682     }
7683
7684     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7685         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7686         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7687         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7688             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7689         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7690             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7691         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7692             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7693         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7694             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7695         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7696             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7697         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7698             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7699     }
7700
7701     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7702                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7703         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7704               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7705                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7706     }
7707 }
7708
7709 static void
7710 bxe_e1h_disable(struct bxe_softc *sc)
7711 {
7712     int port = SC_PORT(sc);
7713
7714     bxe_tx_disable(sc);
7715
7716     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7717 }
7718
7719 static void
7720 bxe_e1h_enable(struct bxe_softc *sc)
7721 {
7722     int port = SC_PORT(sc);
7723
7724     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7725
7726     // XXX bxe_tx_enable(sc);
7727 }
7728
7729 /*
7730  * called due to MCP event (on pmf):
7731  *   reread new bandwidth configuration
7732  *   configure FW
7733  *   notify others function about the change
7734  */
7735 static void
7736 bxe_config_mf_bw(struct bxe_softc *sc)
7737 {
7738     if (sc->link_vars.link_up) {
7739         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7740         // XXX bxe_link_sync_notify(sc);
7741     }
7742
7743     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7744 }
7745
7746 static void
7747 bxe_set_mf_bw(struct bxe_softc *sc)
7748 {
7749     bxe_config_mf_bw(sc);
7750     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7751 }
7752
7753 static void
7754 bxe_handle_eee_event(struct bxe_softc *sc)
7755 {
7756     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7757     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7758 }
7759
7760 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7761
7762 static void
7763 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7764 {
7765     struct eth_stats_info *ether_stat =
7766         &sc->sp->drv_info_to_mcp.ether_stat;
7767
7768     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7769             ETH_STAT_INFO_VERSION_LEN);
7770
7771     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7772     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7773                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7774                                           ether_stat->mac_local + MAC_PAD,
7775                                           MAC_PAD, ETH_ALEN);
7776
7777     ether_stat->mtu_size = sc->mtu;
7778
7779     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7780     if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
7781         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7782     }
7783
7784     // XXX ether_stat->feature_flags |= ???;
7785
7786     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7787
7788     ether_stat->txq_size = sc->tx_ring_size;
7789     ether_stat->rxq_size = sc->rx_ring_size;
7790 }
7791
7792 static void
7793 bxe_handle_drv_info_req(struct bxe_softc *sc)
7794 {
7795     enum drv_info_opcode op_code;
7796     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7797
7798     /* if drv_info version supported by MFW doesn't match - send NACK */
7799     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7800         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7801         return;
7802     }
7803
7804     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7805                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7806
7807     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7808
7809     switch (op_code) {
7810     case ETH_STATS_OPCODE:
7811         bxe_drv_info_ether_stat(sc);
7812         break;
7813     case FCOE_STATS_OPCODE:
7814     case ISCSI_STATS_OPCODE:
7815     default:
7816         /* if op code isn't supported - send NACK */
7817         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7818         return;
7819     }
7820
7821     /*
7822      * If we got drv_info attn from MFW then these fields are defined in
7823      * shmem2 for sure
7824      */
7825     SHMEM2_WR(sc, drv_info_host_addr_lo,
7826               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7827     SHMEM2_WR(sc, drv_info_host_addr_hi,
7828               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7829
7830     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7831 }
7832
7833 static void
7834 bxe_dcc_event(struct bxe_softc *sc,
7835               uint32_t         dcc_event)
7836 {
7837     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7838
7839     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7840         /*
7841          * This is the only place besides the function initialization
7842          * where the sc->flags can change so it is done without any
7843          * locks
7844          */
7845         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7846             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7847             sc->flags |= BXE_MF_FUNC_DIS;
7848             bxe_e1h_disable(sc);
7849         } else {
7850             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7851             sc->flags &= ~BXE_MF_FUNC_DIS;
7852             bxe_e1h_enable(sc);
7853         }
7854         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7855     }
7856
7857     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7858         bxe_config_mf_bw(sc);
7859         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7860     }
7861
7862     /* Report results to MCP */
7863     if (dcc_event)
7864         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7865     else
7866         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7867 }
7868
7869 static void
7870 bxe_pmf_update(struct bxe_softc *sc)
7871 {
7872     int port = SC_PORT(sc);
7873     uint32_t val;
7874
7875     sc->port.pmf = 1;
7876     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7877
7878     /*
7879      * We need the mb() to ensure the ordering between the writing to
7880      * sc->port.pmf here and reading it from the bxe_periodic_task().
7881      */
7882     mb();
7883
7884     /* queue a periodic task */
7885     // XXX schedule task...
7886
7887     // XXX bxe_dcbx_pmf_update(sc);
7888
7889     /* enable nig attention */
7890     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7891     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7892         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7893         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7894     } else if (!CHIP_IS_E1x(sc)) {
7895         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7896         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7897     }
7898
7899     bxe_stats_handle(sc, STATS_EVENT_PMF);
7900 }
7901
7902 static int
7903 bxe_mc_assert(struct bxe_softc *sc)
7904 {
7905     char last_idx;
7906     int i, rc = 0;
7907     uint32_t row0, row1, row2, row3;
7908
7909     /* XSTORM */
7910     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7911     if (last_idx)
7912         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7913
7914     /* print the asserts */
7915     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7916
7917         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7918         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7919         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7920         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7921
7922         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7923             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7924                   i, row3, row2, row1, row0);
7925             rc++;
7926         } else {
7927             break;
7928         }
7929     }
7930
7931     /* TSTORM */
7932     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7933     if (last_idx) {
7934         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7935     }
7936
7937     /* print the asserts */
7938     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7939
7940         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7941         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7942         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7943         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7944
7945         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7946             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7947                   i, row3, row2, row1, row0);
7948             rc++;
7949         } else {
7950             break;
7951         }
7952     }
7953
7954     /* CSTORM */
7955     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7956     if (last_idx) {
7957         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7958     }
7959
7960     /* print the asserts */
7961     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7962
7963         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7964         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7965         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7966         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7967
7968         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7969             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7970                   i, row3, row2, row1, row0);
7971             rc++;
7972         } else {
7973             break;
7974         }
7975     }
7976
7977     /* USTORM */
7978     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7979     if (last_idx) {
7980         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7981     }
7982
7983     /* print the asserts */
7984     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7985
7986         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7987         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7988         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7989         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7990
7991         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7992             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7993                   i, row3, row2, row1, row0);
7994             rc++;
7995         } else {
7996             break;
7997         }
7998     }
7999
8000     return (rc);
8001 }
8002
8003 static void
8004 bxe_attn_int_deasserted3(struct bxe_softc *sc,
8005                          uint32_t         attn)
8006 {
8007     int func = SC_FUNC(sc);
8008     uint32_t val;
8009
8010     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
8011
8012         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
8013
8014             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
8015             bxe_read_mf_cfg(sc);
8016             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
8017                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
8018             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
8019
8020             if (val & DRV_STATUS_DCC_EVENT_MASK)
8021                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
8022
8023             if (val & DRV_STATUS_SET_MF_BW)
8024                 bxe_set_mf_bw(sc);
8025
8026             if (val & DRV_STATUS_DRV_INFO_REQ)
8027                 bxe_handle_drv_info_req(sc);
8028
8029             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
8030                 bxe_pmf_update(sc);
8031
8032             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
8033                 bxe_handle_eee_event(sc);
8034
8035             if (sc->link_vars.periodic_flags &
8036                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
8037                 /* sync with link */
8038                 bxe_acquire_phy_lock(sc);
8039                 sc->link_vars.periodic_flags &=
8040                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
8041                 bxe_release_phy_lock(sc);
8042                 if (IS_MF(sc))
8043                     ; // XXX bxe_link_sync_notify(sc);
8044                 bxe_link_report(sc);
8045             }
8046
8047             /*
8048              * Always call it here: bxe_link_report() will
8049              * prevent the link indication duplication.
8050              */
8051             bxe_link_status_update(sc);
8052
8053         } else if (attn & BXE_MC_ASSERT_BITS) {
8054
8055             BLOGE(sc, "MC assert!\n");
8056             bxe_mc_assert(sc);
8057             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8058             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8059             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8060             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8061             bxe_panic(sc, ("MC assert!\n"));
8062
8063         } else if (attn & BXE_MCP_ASSERT) {
8064
8065             BLOGE(sc, "MCP assert!\n");
8066             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8067             // XXX bxe_fw_dump(sc);
8068
8069         } else {
8070             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8071         }
8072     }
8073
8074     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8075         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8076         if (attn & BXE_GRC_TIMEOUT) {
8077             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8078             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8079         }
8080         if (attn & BXE_GRC_RSV) {
8081             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8082             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8083         }
8084         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8085     }
8086 }
8087
8088 static void
8089 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8090                          uint32_t         attn)
8091 {
8092     int port = SC_PORT(sc);
8093     int reg_offset;
8094     uint32_t val0, mask0, val1, mask1;
8095     uint32_t val;
8096
8097     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8098         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8099         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8100         /* CFC error attention */
8101         if (val & 0x2) {
8102             BLOGE(sc, "FATAL error from CFC\n");
8103         }
8104     }
8105
8106     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8107         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8108         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8109         /* RQ_USDMDP_FIFO_OVERFLOW */
8110         if (val & 0x18000) {
8111             BLOGE(sc, "FATAL error from PXP\n");
8112         }
8113
8114         if (!CHIP_IS_E1x(sc)) {
8115             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8116             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8117         }
8118     }
8119
8120 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8121 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8122
8123     if (attn & AEU_PXP2_HW_INT_BIT) {
8124         /*  CQ47854 workaround do not panic on
8125          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8126          */
8127         if (!CHIP_IS_E1x(sc)) {
8128             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8129             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8130             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8131             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8132             /*
8133              * If the olny PXP2_EOP_ERROR_BIT is set in
8134              * STS0 and STS1 - clear it
8135              *
8136              * probably we lose additional attentions between
8137              * STS0 and STS_CLR0, in this case user will not
8138              * be notified about them
8139              */
8140             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8141                 !(val1 & mask1))
8142                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8143
8144             /* print the register, since no one can restore it */
8145             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8146
8147             /*
8148              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8149              * then notify
8150              */
8151             if (val0 & PXP2_EOP_ERROR_BIT) {
8152                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8153
8154                 /*
8155                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8156                  * set then clear attention from PXP2 block without panic
8157                  */
8158                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8159                     ((val1 & mask1) == 0))
8160                     attn &= ~AEU_PXP2_HW_INT_BIT;
8161             }
8162         }
8163     }
8164
8165     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8166         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8167                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8168
8169         val = REG_RD(sc, reg_offset);
8170         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8171         REG_WR(sc, reg_offset, val);
8172
8173         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8174               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8175         bxe_panic(sc, ("HW block attention set2\n"));
8176     }
8177 }
8178
8179 static void
8180 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8181                          uint32_t         attn)
8182 {
8183     int port = SC_PORT(sc);
8184     int reg_offset;
8185     uint32_t val;
8186
8187     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8188         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8189         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8190         /* DORQ discard attention */
8191         if (val & 0x2) {
8192             BLOGE(sc, "FATAL error from DORQ\n");
8193         }
8194     }
8195
8196     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8197         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8198                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8199
8200         val = REG_RD(sc, reg_offset);
8201         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8202         REG_WR(sc, reg_offset, val);
8203
8204         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8205               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8206         bxe_panic(sc, ("HW block attention set1\n"));
8207     }
8208 }
8209
8210 static void
8211 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8212                          uint32_t         attn)
8213 {
8214     int port = SC_PORT(sc);
8215     int reg_offset;
8216     uint32_t val;
8217
8218     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8219                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8220
8221     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8222         val = REG_RD(sc, reg_offset);
8223         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8224         REG_WR(sc, reg_offset, val);
8225
8226         BLOGW(sc, "SPIO5 hw attention\n");
8227
8228         /* Fan failure attention */
8229         elink_hw_reset_phy(&sc->link_params);
8230         bxe_fan_failure(sc);
8231     }
8232
8233     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8234         bxe_acquire_phy_lock(sc);
8235         elink_handle_module_detect_int(&sc->link_params);
8236         bxe_release_phy_lock(sc);
8237     }
8238
8239     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8240         val = REG_RD(sc, reg_offset);
8241         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8242         REG_WR(sc, reg_offset, val);
8243
8244         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8245                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8246     }
8247 }
8248
8249 static void
8250 bxe_attn_int_deasserted(struct bxe_softc *sc,
8251                         uint32_t         deasserted)
8252 {
8253     struct attn_route attn;
8254     struct attn_route *group_mask;
8255     int port = SC_PORT(sc);
8256     int index;
8257     uint32_t reg_addr;
8258     uint32_t val;
8259     uint32_t aeu_mask;
8260     uint8_t global = FALSE;
8261
8262     /*
8263      * Need to take HW lock because MCP or other port might also
8264      * try to handle this event.
8265      */
8266     bxe_acquire_alr(sc);
8267
8268     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8269         /* XXX
8270          * In case of parity errors don't handle attentions so that
8271          * other function would "see" parity errors.
8272          */
8273         sc->recovery_state = BXE_RECOVERY_INIT;
8274         // XXX schedule a recovery task...
8275         /* disable HW interrupts */
8276         bxe_int_disable(sc);
8277         bxe_release_alr(sc);
8278         return;
8279     }
8280
8281     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8282     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8283     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8284     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8285     if (!CHIP_IS_E1x(sc)) {
8286         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8287     } else {
8288         attn.sig[4] = 0;
8289     }
8290
8291     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8292           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8293
8294     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8295         if (deasserted & (1 << index)) {
8296             group_mask = &sc->attn_group[index];
8297
8298             BLOGD(sc, DBG_INTR,
8299                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8300                   group_mask->sig[0], group_mask->sig[1],
8301                   group_mask->sig[2], group_mask->sig[3],
8302                   group_mask->sig[4]);
8303
8304             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8305             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8306             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8307             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8308             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8309         }
8310     }
8311
8312     bxe_release_alr(sc);
8313
8314     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8315         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8316                     COMMAND_REG_ATTN_BITS_CLR);
8317     } else {
8318         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8319     }
8320
8321     val = ~deasserted;
8322     BLOGD(sc, DBG_INTR,
8323           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8324           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8325     REG_WR(sc, reg_addr, val);
8326
8327     if (~sc->attn_state & deasserted) {
8328         BLOGE(sc, "IGU error\n");
8329     }
8330
8331     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8332                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8333
8334     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8335
8336     aeu_mask = REG_RD(sc, reg_addr);
8337
8338     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8339           aeu_mask, deasserted);
8340     aeu_mask |= (deasserted & 0x3ff);
8341     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8342
8343     REG_WR(sc, reg_addr, aeu_mask);
8344     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8345
8346     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8347     sc->attn_state &= ~deasserted;
8348     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8349 }
8350
8351 static void
8352 bxe_attn_int(struct bxe_softc *sc)
8353 {
8354     /* read local copy of bits */
8355     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8356     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8357     uint32_t attn_state = sc->attn_state;
8358
8359     /* look for changed bits */
8360     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8361     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8362
8363     BLOGD(sc, DBG_INTR,
8364           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8365           attn_bits, attn_ack, asserted, deasserted);
8366
8367     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8368         BLOGE(sc, "BAD attention state\n");
8369     }
8370
8371     /* handle bits that were raised */
8372     if (asserted) {
8373         bxe_attn_int_asserted(sc, asserted);
8374     }
8375
8376     if (deasserted) {
8377         bxe_attn_int_deasserted(sc, deasserted);
8378     }
8379 }
8380
8381 static uint16_t
8382 bxe_update_dsb_idx(struct bxe_softc *sc)
8383 {
8384     struct host_sp_status_block *def_sb = sc->def_sb;
8385     uint16_t rc = 0;
8386
8387     mb(); /* status block is written to by the chip */
8388
8389     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8390         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8391         rc |= BXE_DEF_SB_ATT_IDX;
8392     }
8393
8394     if (sc->def_idx != def_sb->sp_sb.running_index) {
8395         sc->def_idx = def_sb->sp_sb.running_index;
8396         rc |= BXE_DEF_SB_IDX;
8397     }
8398
8399     mb();
8400
8401     return (rc);
8402 }
8403
8404 static inline struct ecore_queue_sp_obj *
8405 bxe_cid_to_q_obj(struct bxe_softc *sc,
8406                  uint32_t         cid)
8407 {
8408     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8409     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8410 }
8411
8412 static void
8413 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8414 {
8415     struct ecore_mcast_ramrod_params rparam;
8416     int rc;
8417
8418     memset(&rparam, 0, sizeof(rparam));
8419
8420     rparam.mcast_obj = &sc->mcast_obj;
8421
8422     BXE_MCAST_LOCK(sc);
8423
8424     /* clear pending state for the last command */
8425     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8426
8427     /* if there are pending mcast commands - send them */
8428     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8429         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8430         if (rc < 0) {
8431             BLOGD(sc, DBG_SP,
8432                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8433         }
8434     }
8435
8436     BXE_MCAST_UNLOCK(sc);
8437 }
8438
8439 static void
8440 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8441                               union event_ring_elem *elem)
8442 {
8443     unsigned long ramrod_flags = 0;
8444     int rc = 0;
8445     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8446     struct ecore_vlan_mac_obj *vlan_mac_obj;
8447
8448     /* always push next commands out, don't wait here */
8449     bit_set(&ramrod_flags, RAMROD_CONT);
8450
8451     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8452     case ECORE_FILTER_MAC_PENDING:
8453         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8454         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8455         break;
8456
8457     case ECORE_FILTER_MCAST_PENDING:
8458         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8459         /*
8460          * This is only relevant for 57710 where multicast MACs are
8461          * configured as unicast MACs using the same ramrod.
8462          */
8463         bxe_handle_mcast_eqe(sc);
8464         return;
8465
8466     default:
8467         BLOGE(sc, "Unsupported classification command: %d\n",
8468               elem->message.data.eth_event.echo);
8469         return;
8470     }
8471
8472     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8473
8474     if (rc < 0) {
8475         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8476     } else if (rc > 0) {
8477         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8478     }
8479 }
8480
8481 static void
8482 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8483                        union event_ring_elem *elem)
8484 {
8485     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8486
8487     /* send rx_mode command again if was requested */
8488     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8489                                &sc->sp_state)) {
8490         bxe_set_storm_rx_mode(sc);
8491     }
8492 }
8493
8494 static void
8495 bxe_update_eq_prod(struct bxe_softc *sc,
8496                    uint16_t         prod)
8497 {
8498     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8499     wmb(); /* keep prod updates ordered */
8500 }
8501
8502 static void
8503 bxe_eq_int(struct bxe_softc *sc)
8504 {
8505     uint16_t hw_cons, sw_cons, sw_prod;
8506     union event_ring_elem *elem;
8507     uint8_t echo;
8508     uint32_t cid;
8509     uint8_t opcode;
8510     int spqe_cnt = 0;
8511     struct ecore_queue_sp_obj *q_obj;
8512     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8513     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8514
8515     hw_cons = le16toh(*sc->eq_cons_sb);
8516
8517     /*
8518      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8519      * when we get to the next-page we need to adjust so the loop
8520      * condition below will be met. The next element is the size of a
8521      * regular element and hence incrementing by 1
8522      */
8523     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8524         hw_cons++;
8525     }
8526
8527     /*
8528      * This function may never run in parallel with itself for a
8529      * specific sc and no need for a read memory barrier here.
8530      */
8531     sw_cons = sc->eq_cons;
8532     sw_prod = sc->eq_prod;
8533
8534     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8535           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8536
8537     for (;
8538          sw_cons != hw_cons;
8539          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8540
8541         elem = &sc->eq[EQ_DESC(sw_cons)];
8542
8543         /* elem CID originates from FW, actually LE */
8544         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8545         opcode = elem->message.opcode;
8546
8547         /* handle eq element */
8548         switch (opcode) {
8549
8550         case EVENT_RING_OPCODE_STAT_QUERY:
8551             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8552                   sc->stats_comp++);
8553             /* nothing to do with stats comp */
8554             goto next_spqe;
8555
8556         case EVENT_RING_OPCODE_CFC_DEL:
8557             /* handle according to cid range */
8558             /* we may want to verify here that the sc state is HALTING */
8559             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8560             q_obj = bxe_cid_to_q_obj(sc, cid);
8561             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8562                 break;
8563             }
8564             goto next_spqe;
8565
8566         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8567             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8568             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8569                 break;
8570             }
8571             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8572             goto next_spqe;
8573
8574         case EVENT_RING_OPCODE_START_TRAFFIC:
8575             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8576             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8577                 break;
8578             }
8579             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8580             goto next_spqe;
8581
8582         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8583             echo = elem->message.data.function_update_event.echo;
8584             if (echo == SWITCH_UPDATE) {
8585                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8586                 if (f_obj->complete_cmd(sc, f_obj,
8587                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8588                     break;
8589                 }
8590             }
8591             else {
8592                 BLOGD(sc, DBG_SP,
8593                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8594             }
8595             goto next_spqe;
8596
8597         case EVENT_RING_OPCODE_FORWARD_SETUP:
8598             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8599             if (q_obj->complete_cmd(sc, q_obj,
8600                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8601                 break;
8602             }
8603             goto next_spqe;
8604
8605         case EVENT_RING_OPCODE_FUNCTION_START:
8606             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8607             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8608                 break;
8609             }
8610             goto next_spqe;
8611
8612         case EVENT_RING_OPCODE_FUNCTION_STOP:
8613             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8614             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8615                 break;
8616             }
8617             goto next_spqe;
8618         }
8619
8620         switch (opcode | sc->state) {
8621         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8622         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8623             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8624             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8625             rss_raw->clear_pending(rss_raw);
8626             break;
8627
8628         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8629         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8630         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8631         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8632         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8633         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8634             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8635             bxe_handle_classification_eqe(sc, elem);
8636             break;
8637
8638         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8639         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8640         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8641             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8642             bxe_handle_mcast_eqe(sc);
8643             break;
8644
8645         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8646         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8647         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8648             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8649             bxe_handle_rx_mode_eqe(sc, elem);
8650             break;
8651
8652         default:
8653             /* unknown event log error and continue */
8654             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8655                   elem->message.opcode, sc->state);
8656         }
8657
8658 next_spqe:
8659         spqe_cnt++;
8660     } /* for */
8661
8662     mb();
8663     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8664
8665     sc->eq_cons = sw_cons;
8666     sc->eq_prod = sw_prod;
8667
8668     /* make sure that above mem writes were issued towards the memory */
8669     wmb();
8670
8671     /* update producer */
8672     bxe_update_eq_prod(sc, sc->eq_prod);
8673 }
8674
8675 static void
8676 bxe_handle_sp_tq(void *context,
8677                  int  pending)
8678 {
8679     struct bxe_softc *sc = (struct bxe_softc *)context;
8680     uint16_t status;
8681
8682     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8683
8684     /* what work needs to be performed? */
8685     status = bxe_update_dsb_idx(sc);
8686
8687     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8688
8689     /* HW attentions */
8690     if (status & BXE_DEF_SB_ATT_IDX) {
8691         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8692         bxe_attn_int(sc);
8693         status &= ~BXE_DEF_SB_ATT_IDX;
8694     }
8695
8696     /* SP events: STAT_QUERY and others */
8697     if (status & BXE_DEF_SB_IDX) {
8698         /* handle EQ completions */
8699         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8700         bxe_eq_int(sc);
8701         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8702                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8703         status &= ~BXE_DEF_SB_IDX;
8704     }
8705
8706     /* if status is non zero then something went wrong */
8707     if (__predict_false(status)) {
8708         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8709     }
8710
8711     /* ack status block only if something was actually handled */
8712     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8713                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8714
8715     /*
8716      * Must be called after the EQ processing (since eq leads to sriov
8717      * ramrod completion flows).
8718      * This flow may have been scheduled by the arrival of a ramrod
8719      * completion, or by the sriov code rescheduling itself.
8720      */
8721     // XXX bxe_iov_sp_task(sc);
8722
8723 }
8724
8725 static void
8726 bxe_handle_fp_tq(void *context,
8727                  int  pending)
8728 {
8729     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8730     struct bxe_softc *sc = fp->sc;
8731     uint8_t more_tx = FALSE;
8732     uint8_t more_rx = FALSE;
8733
8734     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8735
8736     /* XXX
8737      * IFF_DRV_RUNNING state can't be checked here since we process
8738      * slowpath events on a client queue during setup. Instead
8739      * we need to add a "process/continue" flag here that the driver
8740      * can use to tell the task here not to do anything.
8741      */
8742 #if 0
8743     if (!(sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
8744         return;
8745     }
8746 #endif
8747
8748     /* update the fastpath index */
8749     bxe_update_fp_sb_idx(fp);
8750
8751     /* XXX add loop here if ever support multiple tx CoS */
8752     /* fp->txdata[cos] */
8753     if (bxe_has_tx_work(fp)) {
8754         BXE_FP_TX_LOCK(fp);
8755         more_tx = bxe_txeof(sc, fp);
8756         BXE_FP_TX_UNLOCK(fp);
8757     }
8758
8759     if (bxe_has_rx_work(fp)) {
8760         more_rx = bxe_rxeof(sc, fp);
8761     }
8762
8763     if (more_rx /*|| more_tx*/) {
8764         /* still more work to do */
8765         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8766         return;
8767     }
8768
8769     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8770                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8771 }
8772
8773 static void
8774 bxe_task_fp(struct bxe_fastpath *fp)
8775 {
8776     struct bxe_softc *sc = fp->sc;
8777     uint8_t more_tx = FALSE;
8778     uint8_t more_rx = FALSE;
8779
8780     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8781
8782     /* update the fastpath index */
8783     bxe_update_fp_sb_idx(fp);
8784
8785     /* XXX add loop here if ever support multiple tx CoS */
8786     /* fp->txdata[cos] */
8787     if (bxe_has_tx_work(fp)) {
8788         BXE_FP_TX_LOCK(fp);
8789         more_tx = bxe_txeof(sc, fp);
8790         BXE_FP_TX_UNLOCK(fp);
8791     }
8792
8793     if (bxe_has_rx_work(fp)) {
8794         more_rx = bxe_rxeof(sc, fp);
8795     }
8796
8797     if (more_rx /*|| more_tx*/) {
8798         /* still more work to do, bail out if this ISR and process later */
8799         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8800         return;
8801     }
8802
8803     /*
8804      * Here we write the fastpath index taken before doing any tx or rx work.
8805      * It is very well possible other hw events occurred up to this point and
8806      * they were actually processed accordingly above. Since we're going to
8807      * write an older fastpath index, an interrupt is coming which we might
8808      * not do any work in.
8809      */
8810     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8811                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8812 }
8813
8814 /*
8815  * Legacy interrupt entry point.
8816  *
8817  * Verifies that the controller generated the interrupt and
8818  * then calls a separate routine to handle the various
8819  * interrupt causes: link, RX, and TX.
8820  */
8821 static void
8822 bxe_intr_legacy(void *xsc)
8823 {
8824     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8825     struct bxe_fastpath *fp;
8826     uint16_t status, mask;
8827     int i;
8828
8829     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8830
8831     /*
8832      * 0 for ustorm, 1 for cstorm
8833      * the bits returned from ack_int() are 0-15
8834      * bit 0 = attention status block
8835      * bit 1 = fast path status block
8836      * a mask of 0x2 or more = tx/rx event
8837      * a mask of 1 = slow path event
8838      */
8839
8840     status = bxe_ack_int(sc);
8841
8842     /* the interrupt is not for us */
8843     if (__predict_false(status == 0)) {
8844         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8845         return;
8846     }
8847
8848     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8849
8850     FOR_EACH_ETH_QUEUE(sc, i) {
8851         fp = &sc->fp[i];
8852         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8853         if (status & mask) {
8854             /* acknowledge and disable further fastpath interrupts */
8855             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8856             bxe_task_fp(fp);
8857             status &= ~mask;
8858         }
8859     }
8860
8861     if (__predict_false(status & 0x1)) {
8862         /* acknowledge and disable further slowpath interrupts */
8863         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8864
8865         /* schedule slowpath handler */
8866         taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8867
8868         status &= ~0x1;
8869     }
8870
8871     if (__predict_false(status)) {
8872         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8873     }
8874 }
8875
8876 /* slowpath interrupt entry point */
8877 static void
8878 bxe_intr_sp(void *xsc)
8879 {
8880     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8881
8882     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8883
8884     /* acknowledge and disable further slowpath interrupts */
8885     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8886
8887     /* schedule slowpath handler */
8888     taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8889 }
8890
8891 /* fastpath interrupt entry point */
8892 static void
8893 bxe_intr_fp(void *xfp)
8894 {
8895     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8896     struct bxe_softc *sc = fp->sc;
8897
8898     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8899
8900     BLOGD(sc, DBG_INTR,
8901           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8902           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8903
8904     /* acknowledge and disable further fastpath interrupts */
8905     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8906
8907     bxe_task_fp(fp);
8908 }
8909
8910 /* Release all interrupts allocated by the driver. */
8911 static void
8912 bxe_interrupt_free(struct bxe_softc *sc)
8913 {
8914     int i;
8915
8916     switch (sc->interrupt_mode) {
8917     case INTR_MODE_INTX:
8918         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8919         if (sc->intr[0].resource != NULL) {
8920             bus_release_resource(sc->dev,
8921                                  SYS_RES_IRQ,
8922                                  sc->intr[0].rid,
8923                                  sc->intr[0].resource);
8924         }
8925         break;
8926     case INTR_MODE_MSI:
8927         for (i = 0; i < sc->intr_count; i++) {
8928             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8929             if (sc->intr[i].resource && sc->intr[i].rid) {
8930                 bus_release_resource(sc->dev,
8931                                      SYS_RES_IRQ,
8932                                      sc->intr[i].rid,
8933                                      sc->intr[i].resource);
8934             }
8935         }
8936         pci_release_msi(sc->dev);
8937         break;
8938     case INTR_MODE_MSIX:
8939         for (i = 0; i < sc->intr_count; i++) {
8940             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8941             if (sc->intr[i].resource && sc->intr[i].rid) {
8942                 bus_release_resource(sc->dev,
8943                                      SYS_RES_IRQ,
8944                                      sc->intr[i].rid,
8945                                      sc->intr[i].resource);
8946             }
8947         }
8948         pci_release_msi(sc->dev);
8949         break;
8950     default:
8951         /* nothing to do as initial allocation failed */
8952         break;
8953     }
8954 }
8955
8956 /*
8957  * This function determines and allocates the appropriate
8958  * interrupt based on system capabilites and user request.
8959  *
8960  * The user may force a particular interrupt mode, specify
8961  * the number of receive queues, specify the method for
8962  * distribuitng received frames to receive queues, or use
8963  * the default settings which will automatically select the
8964  * best supported combination.  In addition, the OS may or
8965  * may not support certain combinations of these settings.
8966  * This routine attempts to reconcile the settings requested
8967  * by the user with the capabilites available from the system
8968  * to select the optimal combination of features.
8969  *
8970  * Returns:
8971  *   0 = Success, !0 = Failure.
8972  */
8973 static int
8974 bxe_interrupt_alloc(struct bxe_softc *sc)
8975 {
8976     int msix_count = 0;
8977     int msi_count = 0;
8978     int num_requested = 0;
8979     int num_allocated = 0;
8980     int rid, i, j;
8981     int rc;
8982
8983     /* get the number of available MSI/MSI-X interrupts from the OS */
8984     if (sc->interrupt_mode > 0) {
8985         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8986             msix_count = pci_msix_count(sc->dev);
8987         }
8988
8989         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8990             msi_count = pci_msi_count(sc->dev);
8991         }
8992
8993         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8994               msi_count, msix_count);
8995     }
8996
8997     do { /* try allocating MSI-X interrupt resources (at least 2) */
8998         if (sc->interrupt_mode != INTR_MODE_MSIX) {
8999             break;
9000         }
9001
9002         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
9003             (msix_count < 2)) {
9004             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9005             break;
9006         }
9007
9008         /* ask for the necessary number of MSI-X vectors */
9009         num_requested = min((sc->num_queues + 1), msix_count);
9010
9011         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
9012
9013         num_allocated = num_requested;
9014         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
9015             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
9016             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9017             break;
9018         }
9019
9020         if (num_allocated < 2) { /* possible? */
9021             BLOGE(sc, "MSI-X allocation less than 2!\n");
9022             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9023             pci_release_msi(sc->dev);
9024             break;
9025         }
9026
9027         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
9028               num_requested, num_allocated);
9029
9030         /* best effort so use the number of vectors allocated to us */
9031         sc->intr_count = num_allocated;
9032         sc->num_queues = num_allocated - 1;
9033
9034         rid = 1; /* initial resource identifier */
9035
9036         /* allocate the MSI-X vectors */
9037         for (i = 0; i < num_allocated; i++) {
9038             sc->intr[i].rid = (rid + i);
9039
9040             if ((sc->intr[i].resource =
9041                  bus_alloc_resource_any(sc->dev,
9042                                         SYS_RES_IRQ,
9043                                         &sc->intr[i].rid,
9044                                         RF_ACTIVE)) == NULL) {
9045                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
9046                       i, (rid + i));
9047
9048                 for (j = (i - 1); j >= 0; j--) {
9049                     bus_release_resource(sc->dev,
9050                                          SYS_RES_IRQ,
9051                                          sc->intr[j].rid,
9052                                          sc->intr[j].resource);
9053                 }
9054
9055                 sc->intr_count = 0;
9056                 sc->num_queues = 0;
9057                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9058                 pci_release_msi(sc->dev);
9059                 break;
9060             }
9061
9062             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9063         }
9064     } while (0);
9065
9066     do { /* try allocating MSI vector resources (at least 2) */
9067         if (sc->interrupt_mode != INTR_MODE_MSI) {
9068             break;
9069         }
9070
9071         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9072             (msi_count < 1)) {
9073             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9074             break;
9075         }
9076
9077         /* ask for a single MSI vector */
9078         num_requested = 1;
9079
9080         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9081
9082         num_allocated = num_requested;
9083         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9084             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9085             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9086             break;
9087         }
9088
9089         if (num_allocated != 1) { /* possible? */
9090             BLOGE(sc, "MSI allocation is not 1!\n");
9091             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9092             pci_release_msi(sc->dev);
9093             break;
9094         }
9095
9096         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9097               num_requested, num_allocated);
9098
9099         /* best effort so use the number of vectors allocated to us */
9100         sc->intr_count = num_allocated;
9101         sc->num_queues = num_allocated;
9102
9103         rid = 1; /* initial resource identifier */
9104
9105         sc->intr[0].rid = rid;
9106
9107         if ((sc->intr[0].resource =
9108              bus_alloc_resource_any(sc->dev,
9109                                     SYS_RES_IRQ,
9110                                     &sc->intr[0].rid,
9111                                     RF_ACTIVE)) == NULL) {
9112             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9113             sc->intr_count = 0;
9114             sc->num_queues = 0;
9115             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9116             pci_release_msi(sc->dev);
9117             break;
9118         }
9119
9120         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9121     } while (0);
9122
9123     do { /* try allocating INTx vector resources */
9124         if (sc->interrupt_mode != INTR_MODE_INTX) {
9125             break;
9126         }
9127
9128         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9129
9130         /* only one vector for INTx */
9131         sc->intr_count = 1;
9132         sc->num_queues = 1;
9133
9134         rid = 0; /* initial resource identifier */
9135
9136         sc->intr[0].rid = rid;
9137
9138         if ((sc->intr[0].resource =
9139              bus_alloc_resource_any(sc->dev,
9140                                     SYS_RES_IRQ,
9141                                     &sc->intr[0].rid,
9142                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9143             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9144             sc->intr_count = 0;
9145             sc->num_queues = 0;
9146             sc->interrupt_mode = -1; /* Failed! */
9147             break;
9148         }
9149
9150         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9151     } while (0);
9152
9153     if (sc->interrupt_mode == -1) {
9154         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9155         rc = 1;
9156     } else {
9157         BLOGD(sc, DBG_LOAD,
9158               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9159               sc->interrupt_mode, sc->num_queues);
9160         rc = 0;
9161     }
9162
9163     return (rc);
9164 }
9165
9166 static void
9167 bxe_interrupt_detach(struct bxe_softc *sc)
9168 {
9169     struct bxe_fastpath *fp;
9170     int i;
9171
9172     /* release interrupt resources */
9173     for (i = 0; i < sc->intr_count; i++) {
9174         if (sc->intr[i].resource && sc->intr[i].tag) {
9175             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9176             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9177         }
9178     }
9179
9180     for (i = 0; i < sc->num_queues; i++) {
9181         fp = &sc->fp[i];
9182         if (fp->tq) {
9183             taskqueue_drain(fp->tq, &fp->tq_task);
9184             taskqueue_free(fp->tq);
9185             fp->tq = NULL;
9186         }
9187     }
9188
9189
9190     if (sc->sp_tq) {
9191         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9192         taskqueue_free(sc->sp_tq);
9193         sc->sp_tq = NULL;
9194     }
9195 }
9196
9197 /*
9198  * Enables interrupts and attach to the ISR.
9199  *
9200  * When using multiple MSI/MSI-X vectors the first vector
9201  * is used for slowpath operations while all remaining
9202  * vectors are used for fastpath operations.  If only a
9203  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9204  * ISR must look for both slowpath and fastpath completions.
9205  */
9206 static int
9207 bxe_interrupt_attach(struct bxe_softc *sc)
9208 {
9209     struct bxe_fastpath *fp;
9210     int rc = 0;
9211     int i;
9212
9213     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9214              "bxe%d_sp_tq", sc->unit);
9215     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9216     sc->sp_tq = taskqueue_create_fast(sc->sp_tq_name, M_NOWAIT,
9217                                       taskqueue_thread_enqueue,
9218                                       &sc->sp_tq);
9219     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9220                             "%s", sc->sp_tq_name);
9221
9222
9223     for (i = 0; i < sc->num_queues; i++) {
9224         fp = &sc->fp[i];
9225         snprintf(fp->tq_name, sizeof(fp->tq_name),
9226                  "bxe%d_fp%d_tq", sc->unit, i);
9227         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9228         fp->tq = taskqueue_create_fast(fp->tq_name, M_NOWAIT,
9229                                        taskqueue_thread_enqueue,
9230                                        &fp->tq);
9231         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9232                                 "%s", fp->tq_name);
9233     }
9234
9235     /* setup interrupt handlers */
9236     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9237         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9238
9239         /*
9240          * Setup the interrupt handler. Note that we pass the driver instance
9241          * to the interrupt handler for the slowpath.
9242          */
9243         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9244                                  (INTR_TYPE_NET | INTR_MPSAFE),
9245                                  NULL, bxe_intr_sp, sc,
9246                                  &sc->intr[0].tag)) != 0) {
9247             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9248             goto bxe_interrupt_attach_exit;
9249         }
9250
9251         bus_describe_intr(sc->dev, sc->intr[0].resource,
9252                           sc->intr[0].tag, "sp");
9253
9254         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9255
9256         /* initialize the fastpath vectors (note the first was used for sp) */
9257         for (i = 0; i < sc->num_queues; i++) {
9258             fp = &sc->fp[i];
9259             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9260
9261             /*
9262              * Setup the interrupt handler. Note that we pass the
9263              * fastpath context to the interrupt handler in this
9264              * case.
9265              */
9266             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9267                                      (INTR_TYPE_NET | INTR_MPSAFE),
9268                                      NULL, bxe_intr_fp, fp,
9269                                      &sc->intr[i + 1].tag)) != 0) {
9270                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9271                       (i + 1), rc);
9272                 goto bxe_interrupt_attach_exit;
9273             }
9274
9275             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9276                               sc->intr[i + 1].tag, "fp%02d", i);
9277
9278             /* bind the fastpath instance to a cpu */
9279             if (sc->num_queues > 1) {
9280                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9281             }
9282
9283             fp->state = BXE_FP_STATE_IRQ;
9284         }
9285     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9286         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9287
9288         /*
9289          * Setup the interrupt handler. Note that we pass the
9290          * driver instance to the interrupt handler which
9291          * will handle both the slowpath and fastpath.
9292          */
9293         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9294                                  (INTR_TYPE_NET | INTR_MPSAFE),
9295                                  NULL, bxe_intr_legacy, sc,
9296                                  &sc->intr[0].tag)) != 0) {
9297             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9298             goto bxe_interrupt_attach_exit;
9299         }
9300
9301     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9302         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9303
9304         /*
9305          * Setup the interrupt handler. Note that we pass the
9306          * driver instance to the interrupt handler which
9307          * will handle both the slowpath and fastpath.
9308          */
9309         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9310                                  (INTR_TYPE_NET | INTR_MPSAFE),
9311                                  NULL, bxe_intr_legacy, sc,
9312                                  &sc->intr[0].tag)) != 0) {
9313             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9314             goto bxe_interrupt_attach_exit;
9315         }
9316     }
9317
9318 bxe_interrupt_attach_exit:
9319
9320     return (rc);
9321 }
9322
9323 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9324 static int  bxe_init_hw_common(struct bxe_softc *sc);
9325 static int  bxe_init_hw_port(struct bxe_softc *sc);
9326 static int  bxe_init_hw_func(struct bxe_softc *sc);
9327 static void bxe_reset_common(struct bxe_softc *sc);
9328 static void bxe_reset_port(struct bxe_softc *sc);
9329 static void bxe_reset_func(struct bxe_softc *sc);
9330 static int  bxe_gunzip_init(struct bxe_softc *sc);
9331 static void bxe_gunzip_end(struct bxe_softc *sc);
9332 static int  bxe_init_firmware(struct bxe_softc *sc);
9333 static void bxe_release_firmware(struct bxe_softc *sc);
9334
9335 static struct
9336 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9337     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9338     .init_hw_cmn      = bxe_init_hw_common,
9339     .init_hw_port     = bxe_init_hw_port,
9340     .init_hw_func     = bxe_init_hw_func,
9341
9342     .reset_hw_cmn     = bxe_reset_common,
9343     .reset_hw_port    = bxe_reset_port,
9344     .reset_hw_func    = bxe_reset_func,
9345
9346     .gunzip_init      = bxe_gunzip_init,
9347     .gunzip_end       = bxe_gunzip_end,
9348
9349     .init_fw          = bxe_init_firmware,
9350     .release_fw       = bxe_release_firmware,
9351 };
9352
9353 static void
9354 bxe_init_func_obj(struct bxe_softc *sc)
9355 {
9356     sc->dmae_ready = 0;
9357
9358     ecore_init_func_obj(sc,
9359                         &sc->func_obj,
9360                         BXE_SP(sc, func_rdata),
9361                         BXE_SP_MAPPING(sc, func_rdata),
9362                         BXE_SP(sc, func_afex_rdata),
9363                         BXE_SP_MAPPING(sc, func_afex_rdata),
9364                         &bxe_func_sp_drv);
9365 }
9366
9367 static int
9368 bxe_init_hw(struct bxe_softc *sc,
9369             uint32_t         load_code)
9370 {
9371     struct ecore_func_state_params func_params = { NULL };
9372     int rc;
9373
9374     /* prepare the parameters for function state transitions */
9375     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9376
9377     func_params.f_obj = &sc->func_obj;
9378     func_params.cmd = ECORE_F_CMD_HW_INIT;
9379
9380     func_params.params.hw_init.load_phase = load_code;
9381
9382     /*
9383      * Via a plethora of function pointers, we will eventually reach
9384      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9385      */
9386     rc = ecore_func_state_change(sc, &func_params);
9387
9388     return (rc);
9389 }
9390
9391 static void
9392 bxe_fill(struct bxe_softc *sc,
9393          uint32_t         addr,
9394          int              fill,
9395          uint32_t         len)
9396 {
9397     uint32_t i;
9398
9399     if (!(len % 4) && !(addr % 4)) {
9400         for (i = 0; i < len; i += 4) {
9401             REG_WR(sc, (addr + i), fill);
9402         }
9403     } else {
9404         for (i = 0; i < len; i++) {
9405             REG_WR8(sc, (addr + i), fill);
9406         }
9407     }
9408 }
9409
9410 /* writes FP SP data to FW - data_size in dwords */
9411 static void
9412 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9413                   int              fw_sb_id,
9414                   uint32_t         *sb_data_p,
9415                   uint32_t         data_size)
9416 {
9417     int index;
9418
9419     for (index = 0; index < data_size; index++) {
9420         REG_WR(sc,
9421                (BAR_CSTRORM_INTMEM +
9422                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9423                 (sizeof(uint32_t) * index)),
9424                *(sb_data_p + index));
9425     }
9426 }
9427
9428 static void
9429 bxe_zero_fp_sb(struct bxe_softc *sc,
9430                int              fw_sb_id)
9431 {
9432     struct hc_status_block_data_e2 sb_data_e2;
9433     struct hc_status_block_data_e1x sb_data_e1x;
9434     uint32_t *sb_data_p;
9435     uint32_t data_size = 0;
9436
9437     if (!CHIP_IS_E1x(sc)) {
9438         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9439         sb_data_e2.common.state = SB_DISABLED;
9440         sb_data_e2.common.p_func.vf_valid = FALSE;
9441         sb_data_p = (uint32_t *)&sb_data_e2;
9442         data_size = (sizeof(struct hc_status_block_data_e2) /
9443                      sizeof(uint32_t));
9444     } else {
9445         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9446         sb_data_e1x.common.state = SB_DISABLED;
9447         sb_data_e1x.common.p_func.vf_valid = FALSE;
9448         sb_data_p = (uint32_t *)&sb_data_e1x;
9449         data_size = (sizeof(struct hc_status_block_data_e1x) /
9450                      sizeof(uint32_t));
9451     }
9452
9453     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9454
9455     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9456              0, CSTORM_STATUS_BLOCK_SIZE);
9457     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9458              0, CSTORM_SYNC_BLOCK_SIZE);
9459 }
9460
9461 static void
9462 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9463                   struct hc_sp_status_block_data *sp_sb_data)
9464 {
9465     int i;
9466
9467     for (i = 0;
9468          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9469          i++) {
9470         REG_WR(sc,
9471                (BAR_CSTRORM_INTMEM +
9472                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9473                 (i * sizeof(uint32_t))),
9474                *((uint32_t *)sp_sb_data + i));
9475     }
9476 }
9477
9478 static void
9479 bxe_zero_sp_sb(struct bxe_softc *sc)
9480 {
9481     struct hc_sp_status_block_data sp_sb_data;
9482
9483     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9484
9485     sp_sb_data.state           = SB_DISABLED;
9486     sp_sb_data.p_func.vf_valid = FALSE;
9487
9488     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9489
9490     bxe_fill(sc,
9491              (BAR_CSTRORM_INTMEM +
9492               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9493               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9494     bxe_fill(sc,
9495              (BAR_CSTRORM_INTMEM +
9496               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9497               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9498 }
9499
9500 static void
9501 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9502                              int                       igu_sb_id,
9503                              int                       igu_seg_id)
9504 {
9505     hc_sm->igu_sb_id      = igu_sb_id;
9506     hc_sm->igu_seg_id     = igu_seg_id;
9507     hc_sm->timer_value    = 0xFF;
9508     hc_sm->time_to_expire = 0xFFFFFFFF;
9509 }
9510
9511 static void
9512 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9513 {
9514     /* zero out state machine indices */
9515
9516     /* rx indices */
9517     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9518
9519     /* tx indices */
9520     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9521     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9522     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9523     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9524
9525     /* map indices */
9526
9527     /* rx indices */
9528     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9529         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9530
9531     /* tx indices */
9532     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9533         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9534     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9535         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9536     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9537         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9538     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9539         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9540 }
9541
9542 static void
9543 bxe_init_sb(struct bxe_softc *sc,
9544             bus_addr_t       busaddr,
9545             int              vfid,
9546             uint8_t          vf_valid,
9547             int              fw_sb_id,
9548             int              igu_sb_id)
9549 {
9550     struct hc_status_block_data_e2  sb_data_e2;
9551     struct hc_status_block_data_e1x sb_data_e1x;
9552     struct hc_status_block_sm       *hc_sm_p;
9553     uint32_t *sb_data_p;
9554     int igu_seg_id;
9555     int data_size;
9556
9557     if (CHIP_INT_MODE_IS_BC(sc)) {
9558         igu_seg_id = HC_SEG_ACCESS_NORM;
9559     } else {
9560         igu_seg_id = IGU_SEG_ACCESS_NORM;
9561     }
9562
9563     bxe_zero_fp_sb(sc, fw_sb_id);
9564
9565     if (!CHIP_IS_E1x(sc)) {
9566         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9567         sb_data_e2.common.state = SB_ENABLED;
9568         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9569         sb_data_e2.common.p_func.vf_id = vfid;
9570         sb_data_e2.common.p_func.vf_valid = vf_valid;
9571         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9572         sb_data_e2.common.same_igu_sb_1b = TRUE;
9573         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9574         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9575         hc_sm_p = sb_data_e2.common.state_machine;
9576         sb_data_p = (uint32_t *)&sb_data_e2;
9577         data_size = (sizeof(struct hc_status_block_data_e2) /
9578                      sizeof(uint32_t));
9579         bxe_map_sb_state_machines(sb_data_e2.index_data);
9580     } else {
9581         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9582         sb_data_e1x.common.state = SB_ENABLED;
9583         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9584         sb_data_e1x.common.p_func.vf_id = 0xff;
9585         sb_data_e1x.common.p_func.vf_valid = FALSE;
9586         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9587         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9588         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9589         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9590         hc_sm_p = sb_data_e1x.common.state_machine;
9591         sb_data_p = (uint32_t *)&sb_data_e1x;
9592         data_size = (sizeof(struct hc_status_block_data_e1x) /
9593                      sizeof(uint32_t));
9594         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9595     }
9596
9597     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9598     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9599
9600     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9601
9602     /* write indices to HW - PCI guarantees endianity of regpairs */
9603     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9604 }
9605
9606 static inline uint8_t
9607 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9608 {
9609     if (CHIP_IS_E1x(fp->sc)) {
9610         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9611     } else {
9612         return (fp->cl_id);
9613     }
9614 }
9615
9616 static inline uint32_t
9617 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9618                            struct bxe_fastpath *fp)
9619 {
9620     uint32_t offset = BAR_USTRORM_INTMEM;
9621
9622     if (!CHIP_IS_E1x(sc)) {
9623         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9624     } else {
9625         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9626     }
9627
9628     return (offset);
9629 }
9630
9631 static void
9632 bxe_init_eth_fp(struct bxe_softc *sc,
9633                 int              idx)
9634 {
9635     struct bxe_fastpath *fp = &sc->fp[idx];
9636     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9637     unsigned long q_type = 0;
9638     int cos;
9639
9640     fp->sc    = sc;
9641     fp->index = idx;
9642
9643     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9644     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9645
9646     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9647                     (SC_L_ID(sc) + idx) :
9648                     /* want client ID same as IGU SB ID for non-E1 */
9649                     fp->igu_sb_id;
9650     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9651
9652     /* setup sb indices */
9653     if (!CHIP_IS_E1x(sc)) {
9654         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9655         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9656     } else {
9657         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9658         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9659     }
9660
9661     /* init shortcut */
9662     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9663
9664     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9665
9666     /*
9667      * XXX If multiple CoS is ever supported then each fastpath structure
9668      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9669      */
9670     for (cos = 0; cos < sc->max_cos; cos++) {
9671         cids[cos] = idx;
9672     }
9673     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9674
9675     /* nothing more for a VF to do */
9676     if (IS_VF(sc)) {
9677         return;
9678     }
9679
9680     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9681                 fp->fw_sb_id, fp->igu_sb_id);
9682
9683     bxe_update_fp_sb_idx(fp);
9684
9685     /* Configure Queue State object */
9686     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9687     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9688
9689     ecore_init_queue_obj(sc,
9690                          &sc->sp_objs[idx].q_obj,
9691                          fp->cl_id,
9692                          cids,
9693                          sc->max_cos,
9694                          SC_FUNC(sc),
9695                          BXE_SP(sc, q_rdata),
9696                          BXE_SP_MAPPING(sc, q_rdata),
9697                          q_type);
9698
9699     /* configure classification DBs */
9700     ecore_init_mac_obj(sc,
9701                        &sc->sp_objs[idx].mac_obj,
9702                        fp->cl_id,
9703                        idx,
9704                        SC_FUNC(sc),
9705                        BXE_SP(sc, mac_rdata),
9706                        BXE_SP_MAPPING(sc, mac_rdata),
9707                        ECORE_FILTER_MAC_PENDING,
9708                        &sc->sp_state,
9709                        ECORE_OBJ_TYPE_RX_TX,
9710                        &sc->macs_pool);
9711
9712     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9713           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9714 }
9715
9716 static inline void
9717 bxe_update_rx_prod(struct bxe_softc    *sc,
9718                    struct bxe_fastpath *fp,
9719                    uint16_t            rx_bd_prod,
9720                    uint16_t            rx_cq_prod,
9721                    uint16_t            rx_sge_prod)
9722 {
9723     struct ustorm_eth_rx_producers rx_prods = { 0 };
9724     uint32_t i;
9725
9726     /* update producers */
9727     rx_prods.bd_prod  = rx_bd_prod;
9728     rx_prods.cqe_prod = rx_cq_prod;
9729     rx_prods.sge_prod = rx_sge_prod;
9730
9731     /*
9732      * Make sure that the BD and SGE data is updated before updating the
9733      * producers since FW might read the BD/SGE right after the producer
9734      * is updated.
9735      * This is only applicable for weak-ordered memory model archs such
9736      * as IA-64. The following barrier is also mandatory since FW will
9737      * assumes BDs must have buffers.
9738      */
9739     wmb();
9740
9741     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9742         REG_WR(sc,
9743                (fp->ustorm_rx_prods_offset + (i * 4)),
9744                ((uint32_t *)&rx_prods)[i]);
9745     }
9746
9747     wmb(); /* keep prod updates ordered */
9748
9749     BLOGD(sc, DBG_RX,
9750           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9751           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9752 }
9753
9754 static void
9755 bxe_init_rx_rings(struct bxe_softc *sc)
9756 {
9757     struct bxe_fastpath *fp;
9758     int i;
9759
9760     for (i = 0; i < sc->num_queues; i++) {
9761         fp = &sc->fp[i];
9762
9763         fp->rx_bd_cons = 0;
9764
9765         /*
9766          * Activate the BD ring...
9767          * Warning, this will generate an interrupt (to the TSTORM)
9768          * so this can only be done after the chip is initialized
9769          */
9770         bxe_update_rx_prod(sc, fp,
9771                            fp->rx_bd_prod,
9772                            fp->rx_cq_prod,
9773                            fp->rx_sge_prod);
9774
9775         if (i != 0) {
9776             continue;
9777         }
9778
9779         if (CHIP_IS_E1(sc)) {
9780             REG_WR(sc,
9781                    (BAR_USTRORM_INTMEM +
9782                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9783                    U64_LO(fp->rcq_dma.paddr));
9784             REG_WR(sc,
9785                    (BAR_USTRORM_INTMEM +
9786                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9787                    U64_HI(fp->rcq_dma.paddr));
9788         }
9789     }
9790 }
9791
9792 static void
9793 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9794 {
9795     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9796     fp->tx_db.data.zero_fill1 = 0;
9797     fp->tx_db.data.prod = 0;
9798
9799     fp->tx_pkt_prod = 0;
9800     fp->tx_pkt_cons = 0;
9801     fp->tx_bd_prod = 0;
9802     fp->tx_bd_cons = 0;
9803     fp->eth_q_stats.tx_pkts = 0;
9804 }
9805
9806 static inline void
9807 bxe_init_tx_rings(struct bxe_softc *sc)
9808 {
9809     int i;
9810
9811     for (i = 0; i < sc->num_queues; i++) {
9812         bxe_init_tx_ring_one(&sc->fp[i]);
9813     }
9814 }
9815
9816 static void
9817 bxe_init_def_sb(struct bxe_softc *sc)
9818 {
9819     struct host_sp_status_block *def_sb = sc->def_sb;
9820     bus_addr_t mapping = sc->def_sb_dma.paddr;
9821     int igu_sp_sb_index;
9822     int igu_seg_id;
9823     int port = SC_PORT(sc);
9824     int func = SC_FUNC(sc);
9825     int reg_offset, reg_offset_en5;
9826     uint64_t section;
9827     int index, sindex;
9828     struct hc_sp_status_block_data sp_sb_data;
9829
9830     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9831
9832     if (CHIP_INT_MODE_IS_BC(sc)) {
9833         igu_sp_sb_index = DEF_SB_IGU_ID;
9834         igu_seg_id = HC_SEG_ACCESS_DEF;
9835     } else {
9836         igu_sp_sb_index = sc->igu_dsb_id;
9837         igu_seg_id = IGU_SEG_ACCESS_DEF;
9838     }
9839
9840     /* attentions */
9841     section = ((uint64_t)mapping +
9842                offsetof(struct host_sp_status_block, atten_status_block));
9843     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9844     sc->attn_state = 0;
9845
9846     reg_offset = (port) ?
9847                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9848                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9849     reg_offset_en5 = (port) ?
9850                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9851                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9852
9853     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9854         /* take care of sig[0]..sig[4] */
9855         for (sindex = 0; sindex < 4; sindex++) {
9856             sc->attn_group[index].sig[sindex] =
9857                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9858         }
9859
9860         if (!CHIP_IS_E1x(sc)) {
9861             /*
9862              * enable5 is separate from the rest of the registers,
9863              * and the address skip is 4 and not 16 between the
9864              * different groups
9865              */
9866             sc->attn_group[index].sig[4] =
9867                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9868         } else {
9869             sc->attn_group[index].sig[4] = 0;
9870         }
9871     }
9872
9873     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9874         reg_offset = (port) ?
9875                          HC_REG_ATTN_MSG1_ADDR_L :
9876                          HC_REG_ATTN_MSG0_ADDR_L;
9877         REG_WR(sc, reg_offset, U64_LO(section));
9878         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9879     } else if (!CHIP_IS_E1x(sc)) {
9880         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9881         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9882     }
9883
9884     section = ((uint64_t)mapping +
9885                offsetof(struct host_sp_status_block, sp_sb));
9886
9887     bxe_zero_sp_sb(sc);
9888
9889     /* PCI guarantees endianity of regpair */
9890     sp_sb_data.state           = SB_ENABLED;
9891     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9892     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9893     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9894     sp_sb_data.igu_seg_id      = igu_seg_id;
9895     sp_sb_data.p_func.pf_id    = func;
9896     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9897     sp_sb_data.p_func.vf_id    = 0xff;
9898
9899     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9900
9901     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9902 }
9903
9904 static void
9905 bxe_init_sp_ring(struct bxe_softc *sc)
9906 {
9907     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9908     sc->spq_prod_idx = 0;
9909     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9910     sc->spq_prod_bd = sc->spq;
9911     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9912 }
9913
9914 static void
9915 bxe_init_eq_ring(struct bxe_softc *sc)
9916 {
9917     union event_ring_elem *elem;
9918     int i;
9919
9920     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9921         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9922
9923         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9924                                                  BCM_PAGE_SIZE *
9925                                                  (i % NUM_EQ_PAGES)));
9926         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9927                                                  BCM_PAGE_SIZE *
9928                                                  (i % NUM_EQ_PAGES)));
9929     }
9930
9931     sc->eq_cons    = 0;
9932     sc->eq_prod    = NUM_EQ_DESC;
9933     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9934
9935     atomic_store_rel_long(&sc->eq_spq_left,
9936                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9937                                NUM_EQ_DESC) - 1));
9938 }
9939
9940 static void
9941 bxe_init_internal_common(struct bxe_softc *sc)
9942 {
9943     int i;
9944
9945     if (IS_MF_SI(sc)) {
9946         /*
9947          * In switch independent mode, the TSTORM needs to accept
9948          * packets that failed classification, since approximate match
9949          * mac addresses aren't written to NIG LLH.
9950          */
9951         REG_WR8(sc,
9952                 (BAR_TSTRORM_INTMEM + TSTORM_ACCEPT_CLASSIFY_FAILED_OFFSET),
9953                 2);
9954     } else if (!CHIP_IS_E1(sc)) { /* 57710 doesn't support MF */
9955         REG_WR8(sc,
9956                 (BAR_TSTRORM_INTMEM + TSTORM_ACCEPT_CLASSIFY_FAILED_OFFSET),
9957                 0);
9958     }
9959
9960     /*
9961      * Zero this manually as its initialization is currently missing
9962      * in the initTool.
9963      */
9964     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9965         REG_WR(sc,
9966                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9967                0);
9968     }
9969
9970     if (!CHIP_IS_E1x(sc)) {
9971         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9972                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9973     }
9974 }
9975
9976 static void
9977 bxe_init_internal(struct bxe_softc *sc,
9978                   uint32_t         load_code)
9979 {
9980     switch (load_code) {
9981     case FW_MSG_CODE_DRV_LOAD_COMMON:
9982     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9983         bxe_init_internal_common(sc);
9984         /* no break */
9985
9986     case FW_MSG_CODE_DRV_LOAD_PORT:
9987         /* nothing to do */
9988         /* no break */
9989
9990     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9991         /* internal memory per function is initialized inside bxe_pf_init */
9992         break;
9993
9994     default:
9995         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9996         break;
9997     }
9998 }
9999
10000 static void
10001 storm_memset_func_cfg(struct bxe_softc                         *sc,
10002                       struct tstorm_eth_function_common_config *tcfg,
10003                       uint16_t                                  abs_fid)
10004 {
10005     uint32_t addr;
10006     size_t size;
10007
10008     addr = (BAR_TSTRORM_INTMEM +
10009             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
10010     size = sizeof(struct tstorm_eth_function_common_config);
10011     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
10012 }
10013
10014 static void
10015 bxe_func_init(struct bxe_softc            *sc,
10016               struct bxe_func_init_params *p)
10017 {
10018     struct tstorm_eth_function_common_config tcfg = { 0 };
10019
10020     if (CHIP_IS_E1x(sc)) {
10021         storm_memset_func_cfg(sc, &tcfg, p->func_id);
10022     }
10023
10024     /* Enable the function in the FW */
10025     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
10026     storm_memset_func_en(sc, p->func_id, 1);
10027
10028     /* spq */
10029     if (p->func_flgs & FUNC_FLG_SPQ) {
10030         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
10031         REG_WR(sc,
10032                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
10033                p->spq_prod);
10034     }
10035 }
10036
10037 /*
10038  * Calculates the sum of vn_min_rates.
10039  * It's needed for further normalizing of the min_rates.
10040  * Returns:
10041  *   sum of vn_min_rates.
10042  *     or
10043  *   0 - if all the min_rates are 0.
10044  * In the later case fainess algorithm should be deactivated.
10045  * If all min rates are not zero then those that are zeroes will be set to 1.
10046  */
10047 static void
10048 bxe_calc_vn_min(struct bxe_softc       *sc,
10049                 struct cmng_init_input *input)
10050 {
10051     uint32_t vn_cfg;
10052     uint32_t vn_min_rate;
10053     int all_zero = 1;
10054     int vn;
10055
10056     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10057         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10058         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
10059                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
10060
10061         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10062             /* skip hidden VNs */
10063             vn_min_rate = 0;
10064         } else if (!vn_min_rate) {
10065             /* If min rate is zero - set it to 100 */
10066             vn_min_rate = DEF_MIN_RATE;
10067         } else {
10068             all_zero = 0;
10069         }
10070
10071         input->vnic_min_rate[vn] = vn_min_rate;
10072     }
10073
10074     /* if ETS or all min rates are zeros - disable fairness */
10075     if (BXE_IS_ETS_ENABLED(sc)) {
10076         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10077         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10078     } else if (all_zero) {
10079         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10080         BLOGD(sc, DBG_LOAD,
10081               "Fariness disabled (all MIN values are zeroes)\n");
10082     } else {
10083         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10084     }
10085 }
10086
10087 static inline uint16_t
10088 bxe_extract_max_cfg(struct bxe_softc *sc,
10089                     uint32_t         mf_cfg)
10090 {
10091     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10092                         FUNC_MF_CFG_MAX_BW_SHIFT);
10093
10094     if (!max_cfg) {
10095         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10096         max_cfg = 100;
10097     }
10098
10099     return (max_cfg);
10100 }
10101
10102 static void
10103 bxe_calc_vn_max(struct bxe_softc       *sc,
10104                 int                    vn,
10105                 struct cmng_init_input *input)
10106 {
10107     uint16_t vn_max_rate;
10108     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10109     uint32_t max_cfg;
10110
10111     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10112         vn_max_rate = 0;
10113     } else {
10114         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10115
10116         if (IS_MF_SI(sc)) {
10117             /* max_cfg in percents of linkspeed */
10118             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10119         } else { /* SD modes */
10120             /* max_cfg is absolute in 100Mb units */
10121             vn_max_rate = (max_cfg * 100);
10122         }
10123     }
10124
10125     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10126
10127     input->vnic_max_rate[vn] = vn_max_rate;
10128 }
10129
10130 static void
10131 bxe_cmng_fns_init(struct bxe_softc *sc,
10132                   uint8_t          read_cfg,
10133                   uint8_t          cmng_type)
10134 {
10135     struct cmng_init_input input;
10136     int vn;
10137
10138     memset(&input, 0, sizeof(struct cmng_init_input));
10139
10140     input.port_rate = sc->link_vars.line_speed;
10141
10142     if (cmng_type == CMNG_FNS_MINMAX) {
10143         /* read mf conf from shmem */
10144         if (read_cfg) {
10145             bxe_read_mf_cfg(sc);
10146         }
10147
10148         /* get VN min rate and enable fairness if not 0 */
10149         bxe_calc_vn_min(sc, &input);
10150
10151         /* get VN max rate */
10152         if (sc->port.pmf) {
10153             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10154                 bxe_calc_vn_max(sc, vn, &input);
10155             }
10156         }
10157
10158         /* always enable rate shaping and fairness */
10159         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10160
10161         ecore_init_cmng(&input, &sc->cmng);
10162         return;
10163     }
10164
10165     /* rate shaping and fairness are disabled */
10166     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10167 }
10168
10169 static int
10170 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10171 {
10172     if (CHIP_REV_IS_SLOW(sc)) {
10173         return (CMNG_FNS_NONE);
10174     }
10175
10176     if (IS_MF(sc)) {
10177         return (CMNG_FNS_MINMAX);
10178     }
10179
10180     return (CMNG_FNS_NONE);
10181 }
10182
10183 static void
10184 storm_memset_cmng(struct bxe_softc *sc,
10185                   struct cmng_init *cmng,
10186                   uint8_t          port)
10187 {
10188     int vn;
10189     int func;
10190     uint32_t addr;
10191     size_t size;
10192
10193     addr = (BAR_XSTRORM_INTMEM +
10194             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10195     size = sizeof(struct cmng_struct_per_port);
10196     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10197
10198     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10199         func = func_by_vn(sc, vn);
10200
10201         addr = (BAR_XSTRORM_INTMEM +
10202                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10203         size = sizeof(struct rate_shaping_vars_per_vn);
10204         ecore_storm_memset_struct(sc, addr, size,
10205                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10206
10207         addr = (BAR_XSTRORM_INTMEM +
10208                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10209         size = sizeof(struct fairness_vars_per_vn);
10210         ecore_storm_memset_struct(sc, addr, size,
10211                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10212     }
10213 }
10214
10215 static void
10216 bxe_pf_init(struct bxe_softc *sc)
10217 {
10218     struct bxe_func_init_params func_init = { 0 };
10219     struct event_ring_data eq_data = { { 0 } };
10220     uint16_t flags;
10221
10222     if (!CHIP_IS_E1x(sc)) {
10223         /* reset IGU PF statistics: MSIX + ATTN */
10224         /* PF */
10225         REG_WR(sc,
10226                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10227                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10228                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10229                0);
10230         /* ATTN */
10231         REG_WR(sc,
10232                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10233                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10234                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10235                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10236                0);
10237     }
10238
10239     /* function setup flags */
10240     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10241
10242     /*
10243      * This flag is relevant for E1x only.
10244      * E2 doesn't have a TPA configuration in a function level.
10245      */
10246     flags |= (sc->ifnet->if_capenable & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10247
10248     func_init.func_flgs = flags;
10249     func_init.pf_id     = SC_FUNC(sc);
10250     func_init.func_id   = SC_FUNC(sc);
10251     func_init.spq_map   = sc->spq_dma.paddr;
10252     func_init.spq_prod  = sc->spq_prod_idx;
10253
10254     bxe_func_init(sc, &func_init);
10255
10256     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10257
10258     /*
10259      * Congestion management values depend on the link rate.
10260      * There is no active link so initial link rate is set to 10Gbps.
10261      * When the link comes up the congestion management values are
10262      * re-calculated according to the actual link rate.
10263      */
10264     sc->link_vars.line_speed = SPEED_10000;
10265     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10266
10267     /* Only the PMF sets the HW */
10268     if (sc->port.pmf) {
10269         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10270     }
10271
10272     /* init Event Queue - PCI bus guarantees correct endainity */
10273     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10274     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10275     eq_data.producer     = sc->eq_prod;
10276     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10277     eq_data.sb_id        = DEF_SB_ID;
10278     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10279 }
10280
10281 static void
10282 bxe_hc_int_enable(struct bxe_softc *sc)
10283 {
10284     int port = SC_PORT(sc);
10285     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10286     uint32_t val = REG_RD(sc, addr);
10287     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10288     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10289                            (sc->intr_count == 1)) ? TRUE : FALSE;
10290     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10291
10292     if (msix) {
10293         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10294                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10295         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10296                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10297         if (single_msix) {
10298             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10299         }
10300     } else if (msi) {
10301         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10302         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10303                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10304                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10305     } else {
10306         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10307                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10308                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10309                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10310
10311         if (!CHIP_IS_E1(sc)) {
10312             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10313                   val, port, addr);
10314
10315             REG_WR(sc, addr, val);
10316
10317             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10318         }
10319     }
10320
10321     if (CHIP_IS_E1(sc)) {
10322         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10323     }
10324
10325     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10326           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10327
10328     REG_WR(sc, addr, val);
10329
10330     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10331     mb();
10332
10333     if (!CHIP_IS_E1(sc)) {
10334         /* init leading/trailing edge */
10335         if (IS_MF(sc)) {
10336             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10337             if (sc->port.pmf) {
10338                 /* enable nig and gpio3 attention */
10339                 val |= 0x1100;
10340             }
10341         } else {
10342             val = 0xffff;
10343         }
10344
10345         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10346         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10347     }
10348
10349     /* make sure that interrupts are indeed enabled from here on */
10350     mb();
10351 }
10352
10353 static void
10354 bxe_igu_int_enable(struct bxe_softc *sc)
10355 {
10356     uint32_t val;
10357     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10358     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10359                            (sc->intr_count == 1)) ? TRUE : FALSE;
10360     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10361
10362     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10363
10364     if (msix) {
10365         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10366                  IGU_PF_CONF_SINGLE_ISR_EN);
10367         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10368                 IGU_PF_CONF_ATTN_BIT_EN);
10369         if (single_msix) {
10370             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10371         }
10372     } else if (msi) {
10373         val &= ~IGU_PF_CONF_INT_LINE_EN;
10374         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10375                 IGU_PF_CONF_ATTN_BIT_EN |
10376                 IGU_PF_CONF_SINGLE_ISR_EN);
10377     } else {
10378         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10379         val |= (IGU_PF_CONF_INT_LINE_EN |
10380                 IGU_PF_CONF_ATTN_BIT_EN |
10381                 IGU_PF_CONF_SINGLE_ISR_EN);
10382     }
10383
10384     /* clean previous status - need to configure igu prior to ack*/
10385     if ((!msix) || single_msix) {
10386         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10387         bxe_ack_int(sc);
10388     }
10389
10390     val |= IGU_PF_CONF_FUNC_EN;
10391
10392     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10393           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10394
10395     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10396
10397     mb();
10398
10399     /* init leading/trailing edge */
10400     if (IS_MF(sc)) {
10401         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10402         if (sc->port.pmf) {
10403             /* enable nig and gpio3 attention */
10404             val |= 0x1100;
10405         }
10406     } else {
10407         val = 0xffff;
10408     }
10409
10410     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10411     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10412
10413     /* make sure that interrupts are indeed enabled from here on */
10414     mb();
10415 }
10416
10417 static void
10418 bxe_int_enable(struct bxe_softc *sc)
10419 {
10420     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10421         bxe_hc_int_enable(sc);
10422     } else {
10423         bxe_igu_int_enable(sc);
10424     }
10425 }
10426
10427 static void
10428 bxe_hc_int_disable(struct bxe_softc *sc)
10429 {
10430     int port = SC_PORT(sc);
10431     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10432     uint32_t val = REG_RD(sc, addr);
10433
10434     /*
10435      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10436      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10437      * block
10438      */
10439     if (CHIP_IS_E1(sc)) {
10440         /*
10441          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10442          * to prevent from HC sending interrupts after we exit the function
10443          */
10444         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10445
10446         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10447                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10448                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10449     } else {
10450         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10451                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10452                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10453                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10454     }
10455
10456     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10457
10458     /* flush all outstanding writes */
10459     mb();
10460
10461     REG_WR(sc, addr, val);
10462     if (REG_RD(sc, addr) != val) {
10463         BLOGE(sc, "proper val not read from HC IGU!\n");
10464     }
10465 }
10466
10467 static void
10468 bxe_igu_int_disable(struct bxe_softc *sc)
10469 {
10470     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10471
10472     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10473              IGU_PF_CONF_INT_LINE_EN |
10474              IGU_PF_CONF_ATTN_BIT_EN);
10475
10476     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10477
10478     /* flush all outstanding writes */
10479     mb();
10480
10481     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10482     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10483         BLOGE(sc, "proper val not read from IGU!\n");
10484     }
10485 }
10486
10487 static void
10488 bxe_int_disable(struct bxe_softc *sc)
10489 {
10490     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10491         bxe_hc_int_disable(sc);
10492     } else {
10493         bxe_igu_int_disable(sc);
10494     }
10495 }
10496
10497 static void
10498 bxe_nic_init(struct bxe_softc *sc,
10499              int              load_code)
10500 {
10501     int i;
10502
10503     for (i = 0; i < sc->num_queues; i++) {
10504         bxe_init_eth_fp(sc, i);
10505     }
10506
10507     rmb(); /* ensure status block indices were read */
10508
10509     bxe_init_rx_rings(sc);
10510     bxe_init_tx_rings(sc);
10511
10512     if (IS_VF(sc)) {
10513         return;
10514     }
10515
10516     /* initialize MOD_ABS interrupts */
10517     elink_init_mod_abs_int(sc, &sc->link_vars,
10518                            sc->devinfo.chip_id,
10519                            sc->devinfo.shmem_base,
10520                            sc->devinfo.shmem2_base,
10521                            SC_PORT(sc));
10522
10523     bxe_init_def_sb(sc);
10524     bxe_update_dsb_idx(sc);
10525     bxe_init_sp_ring(sc);
10526     bxe_init_eq_ring(sc);
10527     bxe_init_internal(sc, load_code);
10528     bxe_pf_init(sc);
10529     bxe_stats_init(sc);
10530
10531     /* flush all before enabling interrupts */
10532     mb();
10533
10534     bxe_int_enable(sc);
10535
10536     /* check for SPIO5 */
10537     bxe_attn_int_deasserted0(sc,
10538                              REG_RD(sc,
10539                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10540                                      SC_PORT(sc)*4)) &
10541                              AEU_INPUTS_ATTN_BITS_SPIO5);
10542 }
10543
10544 static inline void
10545 bxe_init_objs(struct bxe_softc *sc)
10546 {
10547     /* mcast rules must be added to tx if tx switching is enabled */
10548     ecore_obj_type o_type =
10549         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10550                                          ECORE_OBJ_TYPE_RX;
10551
10552     /* RX_MODE controlling object */
10553     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10554
10555     /* multicast configuration controlling object */
10556     ecore_init_mcast_obj(sc,
10557                          &sc->mcast_obj,
10558                          sc->fp[0].cl_id,
10559                          sc->fp[0].index,
10560                          SC_FUNC(sc),
10561                          SC_FUNC(sc),
10562                          BXE_SP(sc, mcast_rdata),
10563                          BXE_SP_MAPPING(sc, mcast_rdata),
10564                          ECORE_FILTER_MCAST_PENDING,
10565                          &sc->sp_state,
10566                          o_type);
10567
10568     /* Setup CAM credit pools */
10569     ecore_init_mac_credit_pool(sc,
10570                                &sc->macs_pool,
10571                                SC_FUNC(sc),
10572                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10573                                                  VNICS_PER_PATH(sc));
10574
10575     ecore_init_vlan_credit_pool(sc,
10576                                 &sc->vlans_pool,
10577                                 SC_ABS_FUNC(sc) >> 1,
10578                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10579                                                   VNICS_PER_PATH(sc));
10580
10581     /* RSS configuration object */
10582     ecore_init_rss_config_obj(sc,
10583                               &sc->rss_conf_obj,
10584                               sc->fp[0].cl_id,
10585                               sc->fp[0].index,
10586                               SC_FUNC(sc),
10587                               SC_FUNC(sc),
10588                               BXE_SP(sc, rss_rdata),
10589                               BXE_SP_MAPPING(sc, rss_rdata),
10590                               ECORE_FILTER_RSS_CONF_PENDING,
10591                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10592 }
10593
10594 /*
10595  * Initialize the function. This must be called before sending CLIENT_SETUP
10596  * for the first client.
10597  */
10598 static inline int
10599 bxe_func_start(struct bxe_softc *sc)
10600 {
10601     struct ecore_func_state_params func_params = { NULL };
10602     struct ecore_func_start_params *start_params = &func_params.params.start;
10603
10604     /* Prepare parameters for function state transitions */
10605     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10606
10607     func_params.f_obj = &sc->func_obj;
10608     func_params.cmd = ECORE_F_CMD_START;
10609
10610     /* Function parameters */
10611     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10612     start_params->sd_vlan_tag = OVLAN(sc);
10613
10614     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10615         start_params->network_cos_mode = STATIC_COS;
10616     } else { /* CHIP_IS_E1X */
10617         start_params->network_cos_mode = FW_WRR;
10618     }
10619
10620     //start_params->gre_tunnel_mode = 0;
10621     //start_params->gre_tunnel_rss  = 0;
10622
10623     return (ecore_func_state_change(sc, &func_params));
10624 }
10625
10626 static int
10627 bxe_set_power_state(struct bxe_softc *sc,
10628                     uint8_t          state)
10629 {
10630     uint16_t pmcsr;
10631
10632     /* If there is no power capability, silently succeed */
10633     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10634         BLOGW(sc, "No power capability\n");
10635         return (0);
10636     }
10637
10638     pmcsr = pci_read_config(sc->dev,
10639                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10640                             2);
10641
10642     switch (state) {
10643     case PCI_PM_D0:
10644         pci_write_config(sc->dev,
10645                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10646                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10647
10648         if (pmcsr & PCIM_PSTAT_DMASK) {
10649             /* delay required during transition out of D3hot */
10650             DELAY(20000);
10651         }
10652
10653         break;
10654
10655     case PCI_PM_D3hot:
10656         /* XXX if there are other clients above don't shut down the power */
10657
10658         /* don't shut down the power for emulation and FPGA */
10659         if (CHIP_REV_IS_SLOW(sc)) {
10660             return (0);
10661         }
10662
10663         pmcsr &= ~PCIM_PSTAT_DMASK;
10664         pmcsr |= PCIM_PSTAT_D3;
10665
10666         if (sc->wol) {
10667             pmcsr |= PCIM_PSTAT_PMEENABLE;
10668         }
10669
10670         pci_write_config(sc->dev,
10671                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10672                          pmcsr, 4);
10673
10674         /*
10675          * No more memory access after this point until device is brought back
10676          * to D0 state.
10677          */
10678         break;
10679
10680     default:
10681         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10682             state, pmcsr);
10683         return (-1);
10684     }
10685
10686     return (0);
10687 }
10688
10689
10690 /* return true if succeeded to acquire the lock */
10691 static uint8_t
10692 bxe_trylock_hw_lock(struct bxe_softc *sc,
10693                     uint32_t         resource)
10694 {
10695     uint32_t lock_status;
10696     uint32_t resource_bit = (1 << resource);
10697     int func = SC_FUNC(sc);
10698     uint32_t hw_lock_control_reg;
10699
10700     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10701
10702     /* Validating that the resource is within range */
10703     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10704         BLOGD(sc, DBG_LOAD,
10705               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10706               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10707         return (FALSE);
10708     }
10709
10710     if (func <= 5) {
10711         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10712     } else {
10713         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10714     }
10715
10716     /* try to acquire the lock */
10717     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10718     lock_status = REG_RD(sc, hw_lock_control_reg);
10719     if (lock_status & resource_bit) {
10720         return (TRUE);
10721     }
10722
10723     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10724         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10725         lock_status, resource_bit);
10726
10727     return (FALSE);
10728 }
10729
10730 /*
10731  * Get the recovery leader resource id according to the engine this function
10732  * belongs to. Currently only only 2 engines is supported.
10733  */
10734 static int
10735 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10736 {
10737     if (SC_PATH(sc)) {
10738         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10739     } else {
10740         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10741     }
10742 }
10743
10744 /* try to acquire a leader lock for current engine */
10745 static uint8_t
10746 bxe_trylock_leader_lock(struct bxe_softc *sc)
10747 {
10748     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10749 }
10750
10751 static int
10752 bxe_release_leader_lock(struct bxe_softc *sc)
10753 {
10754     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10755 }
10756
10757 /* close gates #2, #3 and #4 */
10758 static void
10759 bxe_set_234_gates(struct bxe_softc *sc,
10760                   uint8_t          close)
10761 {
10762     uint32_t val;
10763
10764     /* gates #2 and #4a are closed/opened for "not E1" only */
10765     if (!CHIP_IS_E1(sc)) {
10766         /* #4 */
10767         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10768         /* #2 */
10769         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10770     }
10771
10772     /* #3 */
10773     if (CHIP_IS_E1x(sc)) {
10774         /* prevent interrupts from HC on both ports */
10775         val = REG_RD(sc, HC_REG_CONFIG_1);
10776         REG_WR(sc, HC_REG_CONFIG_1,
10777                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10778                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10779
10780         val = REG_RD(sc, HC_REG_CONFIG_0);
10781         REG_WR(sc, HC_REG_CONFIG_0,
10782                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10783                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10784     } else {
10785         /* Prevent incomming interrupts in IGU */
10786         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10787
10788         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10789                (!close) ?
10790                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10791                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10792     }
10793
10794     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10795           close ? "closing" : "opening");
10796
10797     wmb();
10798 }
10799
10800 /* poll for pending writes bit, it should get cleared in no more than 1s */
10801 static int
10802 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10803 {
10804     uint32_t cnt = 1000;
10805     uint32_t pend_bits = 0;
10806
10807     do {
10808         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10809
10810         if (pend_bits == 0) {
10811             break;
10812         }
10813
10814         DELAY(1000);
10815     } while (--cnt > 0);
10816
10817     if (cnt == 0) {
10818         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10819         return (-1);
10820     }
10821
10822     return (0);
10823 }
10824
10825 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10826
10827 static void
10828 bxe_clp_reset_prep(struct bxe_softc *sc,
10829                    uint32_t         *magic_val)
10830 {
10831     /* Do some magic... */
10832     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10833     *magic_val = val & SHARED_MF_CLP_MAGIC;
10834     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10835 }
10836
10837 /* restore the value of the 'magic' bit */
10838 static void
10839 bxe_clp_reset_done(struct bxe_softc *sc,
10840                    uint32_t         magic_val)
10841 {
10842     /* Restore the 'magic' bit value... */
10843     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10844     MFCFG_WR(sc, shared_mf_config.clp_mb,
10845               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10846 }
10847
10848 /* prepare for MCP reset, takes care of CLP configurations */
10849 static void
10850 bxe_reset_mcp_prep(struct bxe_softc *sc,
10851                    uint32_t         *magic_val)
10852 {
10853     uint32_t shmem;
10854     uint32_t validity_offset;
10855
10856     /* set `magic' bit in order to save MF config */
10857     if (!CHIP_IS_E1(sc)) {
10858         bxe_clp_reset_prep(sc, magic_val);
10859     }
10860
10861     /* get shmem offset */
10862     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10863     validity_offset =
10864         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10865
10866     /* Clear validity map flags */
10867     if (shmem > 0) {
10868         REG_WR(sc, shmem + validity_offset, 0);
10869     }
10870 }
10871
10872 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10873 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10874
10875 static void
10876 bxe_mcp_wait_one(struct bxe_softc *sc)
10877 {
10878     /* special handling for emulation and FPGA (10 times longer) */
10879     if (CHIP_REV_IS_SLOW(sc)) {
10880         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10881     } else {
10882         DELAY((MCP_ONE_TIMEOUT) * 1000);
10883     }
10884 }
10885
10886 /* initialize shmem_base and waits for validity signature to appear */
10887 static int
10888 bxe_init_shmem(struct bxe_softc *sc)
10889 {
10890     int cnt = 0;
10891     uint32_t val = 0;
10892
10893     do {
10894         sc->devinfo.shmem_base     =
10895         sc->link_params.shmem_base =
10896             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10897
10898         if (sc->devinfo.shmem_base) {
10899             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10900             if (val & SHR_MEM_VALIDITY_MB)
10901                 return (0);
10902         }
10903
10904         bxe_mcp_wait_one(sc);
10905
10906     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10907
10908     BLOGE(sc, "BAD MCP validity signature\n");
10909
10910     return (-1);
10911 }
10912
10913 static int
10914 bxe_reset_mcp_comp(struct bxe_softc *sc,
10915                    uint32_t         magic_val)
10916 {
10917     int rc = bxe_init_shmem(sc);
10918
10919     /* Restore the `magic' bit value */
10920     if (!CHIP_IS_E1(sc)) {
10921         bxe_clp_reset_done(sc, magic_val);
10922     }
10923
10924     return (rc);
10925 }
10926
10927 static void
10928 bxe_pxp_prep(struct bxe_softc *sc)
10929 {
10930     if (!CHIP_IS_E1(sc)) {
10931         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10932         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10933         wmb();
10934     }
10935 }
10936
10937 /*
10938  * Reset the whole chip except for:
10939  *      - PCIE core
10940  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10941  *      - IGU
10942  *      - MISC (including AEU)
10943  *      - GRC
10944  *      - RBCN, RBCP
10945  */
10946 static void
10947 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10948                             uint8_t          global)
10949 {
10950     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10951     uint32_t global_bits2, stay_reset2;
10952
10953     /*
10954      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10955      * (per chip) blocks.
10956      */
10957     global_bits2 =
10958         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10959         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10960
10961     /*
10962      * Don't reset the following blocks.
10963      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10964      *            reset, as in 4 port device they might still be owned
10965      *            by the MCP (there is only one leader per path).
10966      */
10967     not_reset_mask1 =
10968         MISC_REGISTERS_RESET_REG_1_RST_HC |
10969         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10970         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10971
10972     not_reset_mask2 =
10973         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10974         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10975         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10976         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10977         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10978         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10979         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10980         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10981         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10982         MISC_REGISTERS_RESET_REG_2_PGLC |
10983         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10984         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10985         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10986         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10987         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10988         MISC_REGISTERS_RESET_REG_2_UMAC1;
10989
10990     /*
10991      * Keep the following blocks in reset:
10992      *  - all xxMACs are handled by the elink code.
10993      */
10994     stay_reset2 =
10995         MISC_REGISTERS_RESET_REG_2_XMAC |
10996         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10997
10998     /* Full reset masks according to the chip */
10999     reset_mask1 = 0xffffffff;
11000
11001     if (CHIP_IS_E1(sc))
11002         reset_mask2 = 0xffff;
11003     else if (CHIP_IS_E1H(sc))
11004         reset_mask2 = 0x1ffff;
11005     else if (CHIP_IS_E2(sc))
11006         reset_mask2 = 0xfffff;
11007     else /* CHIP_IS_E3 */
11008         reset_mask2 = 0x3ffffff;
11009
11010     /* Don't reset global blocks unless we need to */
11011     if (!global)
11012         reset_mask2 &= ~global_bits2;
11013
11014     /*
11015      * In case of attention in the QM, we need to reset PXP
11016      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
11017      * because otherwise QM reset would release 'close the gates' shortly
11018      * before resetting the PXP, then the PSWRQ would send a write
11019      * request to PGLUE. Then when PXP is reset, PGLUE would try to
11020      * read the payload data from PSWWR, but PSWWR would not
11021      * respond. The write queue in PGLUE would stuck, dmae commands
11022      * would not return. Therefore it's important to reset the second
11023      * reset register (containing the
11024      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
11025      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
11026      * bit).
11027      */
11028     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
11029            reset_mask2 & (~not_reset_mask2));
11030
11031     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
11032            reset_mask1 & (~not_reset_mask1));
11033
11034     mb();
11035     wmb();
11036
11037     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
11038            reset_mask2 & (~stay_reset2));
11039
11040     mb();
11041     wmb();
11042
11043     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
11044     wmb();
11045 }
11046
11047 static int
11048 bxe_process_kill(struct bxe_softc *sc,
11049                  uint8_t          global)
11050 {
11051     int cnt = 1000;
11052     uint32_t val = 0;
11053     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
11054     uint32_t tags_63_32 = 0;
11055
11056     /* Empty the Tetris buffer, wait for 1s */
11057     do {
11058         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
11059         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
11060         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
11061         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
11062         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
11063         if (CHIP_IS_E3(sc)) {
11064             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
11065         }
11066
11067         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11068             ((port_is_idle_0 & 0x1) == 0x1) &&
11069             ((port_is_idle_1 & 0x1) == 0x1) &&
11070             (pgl_exp_rom2 == 0xffffffff) &&
11071             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11072             break;
11073         DELAY(1000);
11074     } while (cnt-- > 0);
11075
11076     if (cnt <= 0) {
11077         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11078                   "are still outstanding read requests after 1s! "
11079                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11080                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11081               sr_cnt, blk_cnt, port_is_idle_0,
11082               port_is_idle_1, pgl_exp_rom2);
11083         return (-1);
11084     }
11085
11086     mb();
11087
11088     /* Close gates #2, #3 and #4 */
11089     bxe_set_234_gates(sc, TRUE);
11090
11091     /* Poll for IGU VQs for 57712 and newer chips */
11092     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11093         return (-1);
11094     }
11095
11096     /* XXX indicate that "process kill" is in progress to MCP */
11097
11098     /* clear "unprepared" bit */
11099     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11100     mb();
11101
11102     /* Make sure all is written to the chip before the reset */
11103     wmb();
11104
11105     /*
11106      * Wait for 1ms to empty GLUE and PCI-E core queues,
11107      * PSWHST, GRC and PSWRD Tetris buffer.
11108      */
11109     DELAY(1000);
11110
11111     /* Prepare to chip reset: */
11112     /* MCP */
11113     if (global) {
11114         bxe_reset_mcp_prep(sc, &val);
11115     }
11116
11117     /* PXP */
11118     bxe_pxp_prep(sc);
11119     mb();
11120
11121     /* reset the chip */
11122     bxe_process_kill_chip_reset(sc, global);
11123     mb();
11124
11125     /* clear errors in PGB */
11126     if (!CHIP_IS_E1(sc))
11127         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11128
11129     /* Recover after reset: */
11130     /* MCP */
11131     if (global && bxe_reset_mcp_comp(sc, val)) {
11132         return (-1);
11133     }
11134
11135     /* XXX add resetting the NO_MCP mode DB here */
11136
11137     /* Open the gates #2, #3 and #4 */
11138     bxe_set_234_gates(sc, FALSE);
11139
11140     /* XXX
11141      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11142      * re-enable attentions
11143      */
11144
11145     return (0);
11146 }
11147
11148 static int
11149 bxe_leader_reset(struct bxe_softc *sc)
11150 {
11151     int rc = 0;
11152     uint8_t global = bxe_reset_is_global(sc);
11153     uint32_t load_code;
11154
11155     /*
11156      * If not going to reset MCP, load "fake" driver to reset HW while
11157      * driver is owner of the HW.
11158      */
11159     if (!global && !BXE_NOMCP(sc)) {
11160         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11161                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11162         if (!load_code) {
11163             BLOGE(sc, "MCP response failure, aborting\n");
11164             rc = -1;
11165             goto exit_leader_reset;
11166         }
11167
11168         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11169             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11170             BLOGE(sc, "MCP unexpected response, aborting\n");
11171             rc = -1;
11172             goto exit_leader_reset2;
11173         }
11174
11175         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11176         if (!load_code) {
11177             BLOGE(sc, "MCP response failure, aborting\n");
11178             rc = -1;
11179             goto exit_leader_reset2;
11180         }
11181     }
11182
11183     /* try to recover after the failure */
11184     if (bxe_process_kill(sc, global)) {
11185         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11186         rc = -1;
11187         goto exit_leader_reset2;
11188     }
11189
11190     /*
11191      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11192      * state.
11193      */
11194     bxe_set_reset_done(sc);
11195     if (global) {
11196         bxe_clear_reset_global(sc);
11197     }
11198
11199 exit_leader_reset2:
11200
11201     /* unload "fake driver" if it was loaded */
11202     if (!global && !BXE_NOMCP(sc)) {
11203         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11204         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11205     }
11206
11207 exit_leader_reset:
11208
11209     sc->is_leader = 0;
11210     bxe_release_leader_lock(sc);
11211
11212     mb();
11213     return (rc);
11214 }
11215
11216 /*
11217  * prepare INIT transition, parameters configured:
11218  *   - HC configuration
11219  *   - Queue's CDU context
11220  */
11221 static void
11222 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11223                    struct bxe_fastpath            *fp,
11224                    struct ecore_queue_init_params *init_params)
11225 {
11226     uint8_t cos;
11227     int cxt_index, cxt_offset;
11228
11229     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11230     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11231
11232     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11233     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11234
11235     /* HC rate */
11236     init_params->rx.hc_rate =
11237         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11238     init_params->tx.hc_rate =
11239         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11240
11241     /* FW SB ID */
11242     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11243
11244     /* CQ index among the SB indices */
11245     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11246     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11247
11248     /* set maximum number of COSs supported by this queue */
11249     init_params->max_cos = sc->max_cos;
11250
11251     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11252           fp->index, init_params->max_cos);
11253
11254     /* set the context pointers queue object */
11255     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11256         /* XXX change index/cid here if ever support multiple tx CoS */
11257         /* fp->txdata[cos]->cid */
11258         cxt_index = fp->index / ILT_PAGE_CIDS;
11259         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11260         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11261     }
11262 }
11263
11264 /* set flags that are common for the Tx-only and not normal connections */
11265 static unsigned long
11266 bxe_get_common_flags(struct bxe_softc    *sc,
11267                      struct bxe_fastpath *fp,
11268                      uint8_t             zero_stats)
11269 {
11270     unsigned long flags = 0;
11271
11272     /* PF driver will always initialize the Queue to an ACTIVE state */
11273     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11274
11275     /*
11276      * tx only connections collect statistics (on the same index as the
11277      * parent connection). The statistics are zeroed when the parent
11278      * connection is initialized.
11279      */
11280
11281     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11282     if (zero_stats) {
11283         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11284     }
11285
11286     /*
11287      * tx only connections can support tx-switching, though their
11288      * CoS-ness doesn't survive the loopback
11289      */
11290     if (sc->flags & BXE_TX_SWITCHING) {
11291         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11292     }
11293
11294     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11295
11296     return (flags);
11297 }
11298
11299 static unsigned long
11300 bxe_get_q_flags(struct bxe_softc    *sc,
11301                 struct bxe_fastpath *fp,
11302                 uint8_t             leading)
11303 {
11304     unsigned long flags = 0;
11305
11306     if (IS_MF_SD(sc)) {
11307         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11308     }
11309
11310     if (sc->ifnet->if_capenable & IFCAP_LRO) {
11311         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11312         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11313     }
11314
11315     if (leading) {
11316         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11317         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11318     }
11319
11320     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11321
11322     /* merge with common flags */
11323     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11324 }
11325
11326 static void
11327 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11328                       struct bxe_fastpath               *fp,
11329                       struct ecore_general_setup_params *gen_init,
11330                       uint8_t                           cos)
11331 {
11332     gen_init->stat_id = bxe_stats_id(fp);
11333     gen_init->spcl_id = fp->cl_id;
11334     gen_init->mtu = sc->mtu;
11335     gen_init->cos = cos;
11336 }
11337
11338 static void
11339 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11340                  struct bxe_fastpath           *fp,
11341                  struct rxq_pause_params       *pause,
11342                  struct ecore_rxq_setup_params *rxq_init)
11343 {
11344     uint8_t max_sge = 0;
11345     uint16_t sge_sz = 0;
11346     uint16_t tpa_agg_size = 0;
11347
11348     pause->sge_th_lo = SGE_TH_LO(sc);
11349     pause->sge_th_hi = SGE_TH_HI(sc);
11350
11351     /* validate SGE ring has enough to cross high threshold */
11352     if (sc->dropless_fc &&
11353             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11354             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11355         BLOGW(sc, "sge ring threshold limit\n");
11356     }
11357
11358     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11359     tpa_agg_size = (2 * sc->mtu);
11360     if (tpa_agg_size < sc->max_aggregation_size) {
11361         tpa_agg_size = sc->max_aggregation_size;
11362     }
11363
11364     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11365     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11366                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11367     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11368
11369     /* pause - not for e1 */
11370     if (!CHIP_IS_E1(sc)) {
11371         pause->bd_th_lo = BD_TH_LO(sc);
11372         pause->bd_th_hi = BD_TH_HI(sc);
11373
11374         pause->rcq_th_lo = RCQ_TH_LO(sc);
11375         pause->rcq_th_hi = RCQ_TH_HI(sc);
11376
11377         /* validate rings have enough entries to cross high thresholds */
11378         if (sc->dropless_fc &&
11379             pause->bd_th_hi + FW_PREFETCH_CNT >
11380             sc->rx_ring_size) {
11381             BLOGW(sc, "rx bd ring threshold limit\n");
11382         }
11383
11384         if (sc->dropless_fc &&
11385             pause->rcq_th_hi + FW_PREFETCH_CNT >
11386             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11387             BLOGW(sc, "rcq ring threshold limit\n");
11388         }
11389
11390         pause->pri_map = 1;
11391     }
11392
11393     /* rxq setup */
11394     rxq_init->dscr_map   = fp->rx_dma.paddr;
11395     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11396     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11397     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11398
11399     /*
11400      * This should be a maximum number of data bytes that may be
11401      * placed on the BD (not including paddings).
11402      */
11403     rxq_init->buf_sz = (fp->rx_buf_size -
11404                         IP_HEADER_ALIGNMENT_PADDING);
11405
11406     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11407     rxq_init->tpa_agg_sz      = tpa_agg_size;
11408     rxq_init->sge_buf_sz      = sge_sz;
11409     rxq_init->max_sges_pkt    = max_sge;
11410     rxq_init->rss_engine_id   = SC_FUNC(sc);
11411     rxq_init->mcast_engine_id = SC_FUNC(sc);
11412
11413     /*
11414      * Maximum number or simultaneous TPA aggregation for this Queue.
11415      * For PF Clients it should be the maximum available number.
11416      * VF driver(s) may want to define it to a smaller value.
11417      */
11418     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11419
11420     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11421     rxq_init->fw_sb_id = fp->fw_sb_id;
11422
11423     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11424
11425     /*
11426      * configure silent vlan removal
11427      * if multi function mode is afex, then mask default vlan
11428      */
11429     if (IS_MF_AFEX(sc)) {
11430         rxq_init->silent_removal_value =
11431             sc->devinfo.mf_info.afex_def_vlan_tag;
11432         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11433     }
11434 }
11435
11436 static void
11437 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11438                  struct bxe_fastpath           *fp,
11439                  struct ecore_txq_setup_params *txq_init,
11440                  uint8_t                       cos)
11441 {
11442     /*
11443      * XXX If multiple CoS is ever supported then each fastpath structure
11444      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11445      * fp->txdata[cos]->tx_dma.paddr;
11446      */
11447     txq_init->dscr_map     = fp->tx_dma.paddr;
11448     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11449     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11450     txq_init->fw_sb_id     = fp->fw_sb_id;
11451
11452     /*
11453      * set the TSS leading client id for TX classfication to the
11454      * leading RSS client id
11455      */
11456     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11457 }
11458
11459 /*
11460  * This function performs 2 steps in a queue state machine:
11461  *   1) RESET->INIT
11462  *   2) INIT->SETUP
11463  */
11464 static int
11465 bxe_setup_queue(struct bxe_softc    *sc,
11466                 struct bxe_fastpath *fp,
11467                 uint8_t             leading)
11468 {
11469     struct ecore_queue_state_params q_params = { NULL };
11470     struct ecore_queue_setup_params *setup_params =
11471                         &q_params.params.setup;
11472     int rc;
11473
11474     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11475
11476     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11477
11478     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11479
11480     /* we want to wait for completion in this context */
11481     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11482
11483     /* prepare the INIT parameters */
11484     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11485
11486     /* Set the command */
11487     q_params.cmd = ECORE_Q_CMD_INIT;
11488
11489     /* Change the state to INIT */
11490     rc = ecore_queue_state_change(sc, &q_params);
11491     if (rc) {
11492         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11493         return (rc);
11494     }
11495
11496     BLOGD(sc, DBG_LOAD, "init complete\n");
11497
11498     /* now move the Queue to the SETUP state */
11499     memset(setup_params, 0, sizeof(*setup_params));
11500
11501     /* set Queue flags */
11502     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11503
11504     /* set general SETUP parameters */
11505     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11506                           FIRST_TX_COS_INDEX);
11507
11508     bxe_pf_rx_q_prep(sc, fp,
11509                      &setup_params->pause_params,
11510                      &setup_params->rxq_params);
11511
11512     bxe_pf_tx_q_prep(sc, fp,
11513                      &setup_params->txq_params,
11514                      FIRST_TX_COS_INDEX);
11515
11516     /* Set the command */
11517     q_params.cmd = ECORE_Q_CMD_SETUP;
11518
11519     /* change the state to SETUP */
11520     rc = ecore_queue_state_change(sc, &q_params);
11521     if (rc) {
11522         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11523         return (rc);
11524     }
11525
11526     return (rc);
11527 }
11528
11529 static int
11530 bxe_setup_leading(struct bxe_softc *sc)
11531 {
11532     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11533 }
11534
11535 static int
11536 bxe_config_rss_pf(struct bxe_softc            *sc,
11537                   struct ecore_rss_config_obj *rss_obj,
11538                   uint8_t                     config_hash)
11539 {
11540     struct ecore_config_rss_params params = { NULL };
11541     int i;
11542
11543     /*
11544      * Although RSS is meaningless when there is a single HW queue we
11545      * still need it enabled in order to have HW Rx hash generated.
11546      */
11547
11548     params.rss_obj = rss_obj;
11549
11550     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11551
11552     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11553
11554     /* RSS configuration */
11555     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11556     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11557     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11558     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11559     if (rss_obj->udp_rss_v4) {
11560         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11561     }
11562     if (rss_obj->udp_rss_v6) {
11563         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11564     }
11565
11566     /* Hash bits */
11567     params.rss_result_mask = MULTI_MASK;
11568
11569     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11570
11571     if (config_hash) {
11572         /* RSS keys */
11573         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11574             params.rss_key[i] = arc4random();
11575         }
11576
11577         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11578     }
11579
11580     return (ecore_config_rss(sc, &params));
11581 }
11582
11583 static int
11584 bxe_config_rss_eth(struct bxe_softc *sc,
11585                    uint8_t          config_hash)
11586 {
11587     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11588 }
11589
11590 static int
11591 bxe_init_rss_pf(struct bxe_softc *sc)
11592 {
11593     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11594     int i;
11595
11596     /*
11597      * Prepare the initial contents of the indirection table if
11598      * RSS is enabled
11599      */
11600     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11601         sc->rss_conf_obj.ind_table[i] =
11602             (sc->fp->cl_id + (i % num_eth_queues));
11603     }
11604
11605     if (sc->udp_rss) {
11606         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11607     }
11608
11609     /*
11610      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11611      * per-port, so if explicit configuration is needed, do it only
11612      * for a PMF.
11613      *
11614      * For 57712 and newer it's a per-function configuration.
11615      */
11616     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11617 }
11618
11619 static int
11620 bxe_set_mac_one(struct bxe_softc          *sc,
11621                 uint8_t                   *mac,
11622                 struct ecore_vlan_mac_obj *obj,
11623                 uint8_t                   set,
11624                 int                       mac_type,
11625                 unsigned long             *ramrod_flags)
11626 {
11627     struct ecore_vlan_mac_ramrod_params ramrod_param;
11628     int rc;
11629
11630     memset(&ramrod_param, 0, sizeof(ramrod_param));
11631
11632     /* fill in general parameters */
11633     ramrod_param.vlan_mac_obj = obj;
11634     ramrod_param.ramrod_flags = *ramrod_flags;
11635
11636     /* fill a user request section if needed */
11637     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11638         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11639
11640         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11641
11642         /* Set the command: ADD or DEL */
11643         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11644                                             ECORE_VLAN_MAC_DEL;
11645     }
11646
11647     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11648
11649     if (rc == ECORE_EXISTS) {
11650         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11651         /* do not treat adding same MAC as error */
11652         rc = 0;
11653     } else if (rc < 0) {
11654         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11655     }
11656
11657     return (rc);
11658 }
11659
11660 static int
11661 bxe_set_eth_mac(struct bxe_softc *sc,
11662                 uint8_t          set)
11663 {
11664     unsigned long ramrod_flags = 0;
11665
11666     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11667
11668     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11669
11670     /* Eth MAC is set on RSS leading client (fp[0]) */
11671     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11672                             &sc->sp_objs->mac_obj,
11673                             set, ECORE_ETH_MAC, &ramrod_flags));
11674 }
11675
11676 static int
11677 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11678 {
11679     uint32_t sel_phy_idx = 0;
11680
11681     if (sc->link_params.num_phys <= 1) {
11682         return (ELINK_INT_PHY);
11683     }
11684
11685     if (sc->link_vars.link_up) {
11686         sel_phy_idx = ELINK_EXT_PHY1;
11687         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11688         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11689             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11690              ELINK_SUPPORTED_FIBRE))
11691             sel_phy_idx = ELINK_EXT_PHY2;
11692     } else {
11693         switch (elink_phy_selection(&sc->link_params)) {
11694         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11695         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11696         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11697                sel_phy_idx = ELINK_EXT_PHY1;
11698                break;
11699         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11700         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11701                sel_phy_idx = ELINK_EXT_PHY2;
11702                break;
11703         }
11704     }
11705
11706     return (sel_phy_idx);
11707 }
11708
11709 static int
11710 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11711 {
11712     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11713
11714     /*
11715      * The selected activated PHY is always after swapping (in case PHY
11716      * swapping is enabled). So when swapping is enabled, we need to reverse
11717      * the configuration
11718      */
11719
11720     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11721         if (sel_phy_idx == ELINK_EXT_PHY1)
11722             sel_phy_idx = ELINK_EXT_PHY2;
11723         else if (sel_phy_idx == ELINK_EXT_PHY2)
11724             sel_phy_idx = ELINK_EXT_PHY1;
11725     }
11726
11727     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11728 }
11729
11730 static void
11731 bxe_set_requested_fc(struct bxe_softc *sc)
11732 {
11733     /*
11734      * Initialize link parameters structure variables
11735      * It is recommended to turn off RX FC for jumbo frames
11736      * for better performance
11737      */
11738     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11739         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11740     } else {
11741         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11742     }
11743 }
11744
11745 static void
11746 bxe_calc_fc_adv(struct bxe_softc *sc)
11747 {
11748     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11749     switch (sc->link_vars.ieee_fc &
11750             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11751     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
11752     default:
11753         sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11754                                            ADVERTISED_Pause);
11755         break;
11756
11757     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11758         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11759                                           ADVERTISED_Pause);
11760         break;
11761
11762     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11763         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11764         break;
11765     }
11766 }
11767
11768 static uint16_t
11769 bxe_get_mf_speed(struct bxe_softc *sc)
11770 {
11771     uint16_t line_speed = sc->link_vars.line_speed;
11772     if (IS_MF(sc)) {
11773         uint16_t maxCfg =
11774             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11775
11776         /* calculate the current MAX line speed limit for the MF devices */
11777         if (IS_MF_SI(sc)) {
11778             line_speed = (line_speed * maxCfg) / 100;
11779         } else { /* SD mode */
11780             uint16_t vn_max_rate = maxCfg * 100;
11781
11782             if (vn_max_rate < line_speed) {
11783                 line_speed = vn_max_rate;
11784             }
11785         }
11786     }
11787
11788     return (line_speed);
11789 }
11790
11791 static void
11792 bxe_fill_report_data(struct bxe_softc            *sc,
11793                      struct bxe_link_report_data *data)
11794 {
11795     uint16_t line_speed = bxe_get_mf_speed(sc);
11796
11797     memset(data, 0, sizeof(*data));
11798
11799     /* fill the report data with the effective line speed */
11800     data->line_speed = line_speed;
11801
11802     /* Link is down */
11803     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11804         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11805     }
11806
11807     /* Full DUPLEX */
11808     if (sc->link_vars.duplex == DUPLEX_FULL) {
11809         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11810     }
11811
11812     /* Rx Flow Control is ON */
11813     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11814         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11815     }
11816
11817     /* Tx Flow Control is ON */
11818     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11819         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11820     }
11821 }
11822
11823 /* report link status to OS, should be called under phy_lock */
11824 static void
11825 bxe_link_report_locked(struct bxe_softc *sc)
11826 {
11827     struct bxe_link_report_data cur_data;
11828
11829     /* reread mf_cfg */
11830     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11831         bxe_read_mf_cfg(sc);
11832     }
11833
11834     /* Read the current link report info */
11835     bxe_fill_report_data(sc, &cur_data);
11836
11837     /* Don't report link down or exactly the same link status twice */
11838     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11839         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11840                       &sc->last_reported_link.link_report_flags) &&
11841          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11842                       &cur_data.link_report_flags))) {
11843         return;
11844     }
11845
11846     sc->link_cnt++;
11847
11848     /* report new link params and remember the state for the next time */
11849     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11850
11851     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11852                      &cur_data.link_report_flags)) {
11853         if_link_state_change(sc->ifnet, LINK_STATE_DOWN);
11854         BLOGI(sc, "NIC Link is Down\n");
11855     } else {
11856         const char *duplex;
11857         const char *flow;
11858
11859         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11860                                    &cur_data.link_report_flags)) {
11861             duplex = "full";
11862         } else {
11863             duplex = "half";
11864         }
11865
11866         /*
11867          * Handle the FC at the end so that only these flags would be
11868          * possibly set. This way we may easily check if there is no FC
11869          * enabled.
11870          */
11871         if (cur_data.link_report_flags) {
11872             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11873                              &cur_data.link_report_flags) &&
11874                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11875                              &cur_data.link_report_flags)) {
11876                 flow = "ON - receive & transmit";
11877             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11878                                     &cur_data.link_report_flags) &&
11879                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11880                                      &cur_data.link_report_flags)) {
11881                 flow = "ON - receive";
11882             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11883                                      &cur_data.link_report_flags) &&
11884                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11885                                     &cur_data.link_report_flags)) {
11886                 flow = "ON - transmit";
11887             } else {
11888                 flow = "none"; /* possible? */
11889             }
11890         } else {
11891             flow = "none";
11892         }
11893
11894         if_link_state_change(sc->ifnet, LINK_STATE_UP);
11895         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11896               cur_data.line_speed, duplex, flow);
11897     }
11898 }
11899
11900 static void
11901 bxe_link_report(struct bxe_softc *sc)
11902 {
11903     bxe_acquire_phy_lock(sc);
11904     bxe_link_report_locked(sc);
11905     bxe_release_phy_lock(sc);
11906 }
11907
11908 static void
11909 bxe_link_status_update(struct bxe_softc *sc)
11910 {
11911     if (sc->state != BXE_STATE_OPEN) {
11912         return;
11913     }
11914
11915     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11916         elink_link_status_update(&sc->link_params, &sc->link_vars);
11917     } else {
11918         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11919                                   ELINK_SUPPORTED_10baseT_Full |
11920                                   ELINK_SUPPORTED_100baseT_Half |
11921                                   ELINK_SUPPORTED_100baseT_Full |
11922                                   ELINK_SUPPORTED_1000baseT_Full |
11923                                   ELINK_SUPPORTED_2500baseX_Full |
11924                                   ELINK_SUPPORTED_10000baseT_Full |
11925                                   ELINK_SUPPORTED_TP |
11926                                   ELINK_SUPPORTED_FIBRE |
11927                                   ELINK_SUPPORTED_Autoneg |
11928                                   ELINK_SUPPORTED_Pause |
11929                                   ELINK_SUPPORTED_Asym_Pause);
11930         sc->port.advertising[0] = sc->port.supported[0];
11931
11932         sc->link_params.sc                = sc;
11933         sc->link_params.port              = SC_PORT(sc);
11934         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11935         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11936         sc->link_params.req_line_speed[0] = SPEED_10000;
11937         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11938         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11939
11940         if (CHIP_REV_IS_FPGA(sc)) {
11941             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11942             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11943             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11944                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11945         } else {
11946             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11947             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11948             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11949                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11950         }
11951
11952         sc->link_vars.link_up = 1;
11953
11954         sc->link_vars.duplex    = DUPLEX_FULL;
11955         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11956
11957         if (IS_PF(sc)) {
11958             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11959             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11960             bxe_link_report(sc);
11961         }
11962     }
11963
11964     if (IS_PF(sc)) {
11965         if (sc->link_vars.link_up) {
11966             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11967         } else {
11968             bxe_stats_handle(sc, STATS_EVENT_STOP);
11969         }
11970         bxe_link_report(sc);
11971     } else {
11972         bxe_link_report(sc);
11973         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11974     }
11975 }
11976
11977 static int
11978 bxe_initial_phy_init(struct bxe_softc *sc,
11979                      int              load_mode)
11980 {
11981     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11982     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11983     struct elink_params *lp = &sc->link_params;
11984
11985     bxe_set_requested_fc(sc);
11986
11987     if (CHIP_REV_IS_SLOW(sc)) {
11988         uint32_t bond = CHIP_BOND_ID(sc);
11989         uint32_t feat = 0;
11990
11991         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11992             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11993         } else if (bond & 0x4) {
11994             if (CHIP_IS_E3(sc)) {
11995                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11996             } else {
11997                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11998             }
11999         } else if (bond & 0x8) {
12000             if (CHIP_IS_E3(sc)) {
12001                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
12002             } else {
12003                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12004             }
12005         }
12006
12007         /* disable EMAC for E3 and above */
12008         if (bond & 0x2) {
12009             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12010         }
12011
12012         sc->link_params.feature_config_flags |= feat;
12013     }
12014
12015     bxe_acquire_phy_lock(sc);
12016
12017     if (load_mode == LOAD_DIAG) {
12018         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
12019         /* Prefer doing PHY loopback at 10G speed, if possible */
12020         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
12021             if (lp->speed_cap_mask[cfg_idx] &
12022                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
12023                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
12024             } else {
12025                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
12026             }
12027         }
12028     }
12029
12030     if (load_mode == LOAD_LOOPBACK_EXT) {
12031         lp->loopback_mode = ELINK_LOOPBACK_EXT;
12032     }
12033
12034     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
12035
12036     bxe_release_phy_lock(sc);
12037
12038     bxe_calc_fc_adv(sc);
12039
12040     if (sc->link_vars.link_up) {
12041         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12042         bxe_link_report(sc);
12043     }
12044
12045     if (!CHIP_REV_IS_SLOW(sc)) {
12046         bxe_periodic_start(sc);
12047     }
12048
12049     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
12050     return (rc);
12051 }
12052
12053 /* must be called under IF_ADDR_LOCK */
12054 static int
12055 bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
12056                          struct ecore_mcast_ramrod_params *p)
12057 {
12058     struct ifnet *ifp = sc->ifnet;
12059     int mc_count = 0;
12060     struct ifmultiaddr *ifma;
12061     struct ecore_mcast_list_elem *mc_mac;
12062
12063     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12064         if (ifma->ifma_addr->sa_family != AF_LINK) {
12065             continue;
12066         }
12067
12068         mc_count++;
12069     }
12070
12071     ECORE_LIST_INIT(&p->mcast_list);
12072     p->mcast_list_len = 0;
12073
12074     if (!mc_count) {
12075         return (0);
12076     }
12077
12078     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12079                     (M_NOWAIT | M_ZERO));
12080     if (!mc_mac) {
12081         BLOGE(sc, "Failed to allocate temp mcast list\n");
12082         return (-1);
12083     }
12084     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12085
12086     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12087         if (ifma->ifma_addr->sa_family != AF_LINK) {
12088             continue;
12089         }
12090
12091         mc_mac->mac = (uint8_t *)LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
12092         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &p->mcast_list);
12093
12094         BLOGD(sc, DBG_LOAD,
12095               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
12096               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12097               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
12098
12099         mc_mac++;
12100     }
12101
12102     p->mcast_list_len = mc_count;
12103
12104     return (0);
12105 }
12106
12107 static void
12108 bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12109 {
12110     struct ecore_mcast_list_elem *mc_mac =
12111         ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12112                                struct ecore_mcast_list_elem,
12113                                link);
12114
12115     if (mc_mac) {
12116         /* only a single free as all mc_macs are in the same heap array */
12117         free(mc_mac, M_DEVBUF);
12118     }
12119 }
12120
12121 static int
12122 bxe_set_mc_list(struct bxe_softc *sc)
12123 {
12124     struct ecore_mcast_ramrod_params rparam = { NULL };
12125     int rc = 0;
12126
12127     rparam.mcast_obj = &sc->mcast_obj;
12128
12129     BXE_MCAST_LOCK(sc);
12130
12131     /* first, clear all configured multicast MACs */
12132     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12133     if (rc < 0) {
12134         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12135         BXE_MCAST_UNLOCK(sc);
12136         return (rc);
12137     }
12138
12139     /* configure a new MACs list */
12140     rc = bxe_init_mcast_macs_list(sc, &rparam);
12141     if (rc) {
12142         BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12143         BXE_MCAST_UNLOCK(sc);
12144         return (rc);
12145     }
12146
12147     /* Now add the new MACs */
12148     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12149     if (rc < 0) {
12150         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12151     }
12152
12153     bxe_free_mcast_macs_list(&rparam);
12154
12155     BXE_MCAST_UNLOCK(sc);
12156
12157     return (rc);
12158 }
12159
12160 static int
12161 bxe_set_uc_list(struct bxe_softc *sc)
12162 {
12163     struct ifnet *ifp = sc->ifnet;
12164     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12165     struct ifaddr *ifa;
12166     unsigned long ramrod_flags = 0;
12167     int rc;
12168
12169 #if __FreeBSD_version < 800000
12170     IF_ADDR_LOCK(ifp);
12171 #else
12172     if_addr_rlock(ifp);
12173 #endif
12174
12175     /* first schedule a cleanup up of old configuration */
12176     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12177     if (rc < 0) {
12178         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12179 #if __FreeBSD_version < 800000
12180         IF_ADDR_UNLOCK(ifp);
12181 #else
12182         if_addr_runlock(ifp);
12183 #endif
12184         return (rc);
12185     }
12186
12187     ifa = ifp->if_addr;
12188     while (ifa) {
12189         if (ifa->ifa_addr->sa_family != AF_LINK) {
12190             ifa = TAILQ_NEXT(ifa, ifa_link);
12191             continue;
12192         }
12193
12194         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12195                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12196         if (rc == -EEXIST) {
12197             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12198             /* do not treat adding same MAC as an error */
12199             rc = 0;
12200         } else if (rc < 0) {
12201             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12202 #if __FreeBSD_version < 800000
12203             IF_ADDR_UNLOCK(ifp);
12204 #else
12205             if_addr_runlock(ifp);
12206 #endif
12207             return (rc);
12208         }
12209
12210         ifa = TAILQ_NEXT(ifa, ifa_link);
12211     }
12212
12213 #if __FreeBSD_version < 800000
12214     IF_ADDR_UNLOCK(ifp);
12215 #else
12216     if_addr_runlock(ifp);
12217 #endif
12218
12219     /* Execute the pending commands */
12220     bit_set(&ramrod_flags, RAMROD_CONT);
12221     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12222                             ECORE_UC_LIST_MAC, &ramrod_flags));
12223 }
12224
12225 static void
12226 bxe_set_rx_mode(struct bxe_softc *sc)
12227 {
12228     struct ifnet *ifp = sc->ifnet;
12229     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12230
12231     if (sc->state != BXE_STATE_OPEN) {
12232         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12233         return;
12234     }
12235
12236     BLOGD(sc, DBG_SP, "ifp->if_flags=0x%x\n", ifp->if_flags);
12237
12238     if (ifp->if_flags & IFF_PROMISC) {
12239         rx_mode = BXE_RX_MODE_PROMISC;
12240     } else if ((ifp->if_flags & IFF_ALLMULTI) ||
12241                ((ifp->if_amcount > BXE_MAX_MULTICAST) &&
12242                 CHIP_IS_E1(sc))) {
12243         rx_mode = BXE_RX_MODE_ALLMULTI;
12244     } else {
12245         if (IS_PF(sc)) {
12246             /* some multicasts */
12247             if (bxe_set_mc_list(sc) < 0) {
12248                 rx_mode = BXE_RX_MODE_ALLMULTI;
12249             }
12250             if (bxe_set_uc_list(sc) < 0) {
12251                 rx_mode = BXE_RX_MODE_PROMISC;
12252             }
12253         }
12254     }
12255
12256     sc->rx_mode = rx_mode;
12257
12258     /* schedule the rx_mode command */
12259     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12260         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12261         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12262         return;
12263     }
12264
12265     if (IS_PF(sc)) {
12266         bxe_set_storm_rx_mode(sc);
12267     }
12268 }
12269
12270
12271 /* update flags in shmem */
12272 static void
12273 bxe_update_drv_flags(struct bxe_softc *sc,
12274                      uint32_t         flags,
12275                      uint32_t         set)
12276 {
12277     uint32_t drv_flags;
12278
12279     if (SHMEM2_HAS(sc, drv_flags)) {
12280         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12281         drv_flags = SHMEM2_RD(sc, drv_flags);
12282
12283         if (set) {
12284             SET_FLAGS(drv_flags, flags);
12285         } else {
12286             RESET_FLAGS(drv_flags, flags);
12287         }
12288
12289         SHMEM2_WR(sc, drv_flags, drv_flags);
12290         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12291
12292         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12293     }
12294 }
12295
12296 /* periodic timer callout routine, only runs when the interface is up */
12297
12298 static void
12299 bxe_periodic_callout_func(void *xsc)
12300 {
12301     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12302     int i;
12303
12304     if (!BXE_CORE_TRYLOCK(sc)) {
12305         /* just bail and try again next time */
12306
12307         if ((sc->state == BXE_STATE_OPEN) &&
12308             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12309             /* schedule the next periodic callout */
12310             callout_reset(&sc->periodic_callout, hz,
12311                           bxe_periodic_callout_func, sc);
12312         }
12313
12314         return;
12315     }
12316
12317     if ((sc->state != BXE_STATE_OPEN) ||
12318         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12319         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12320         BXE_CORE_UNLOCK(sc);
12321         return;
12322     }
12323
12324     /* Check for TX timeouts on any fastpath. */
12325     FOR_EACH_QUEUE(sc, i) {
12326         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12327             /* Ruh-Roh, chip was reset! */
12328             break;
12329         }
12330     }
12331
12332     if (!CHIP_REV_IS_SLOW(sc)) {
12333         /*
12334          * This barrier is needed to ensure the ordering between the writing
12335          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12336          * the reading here.
12337          */
12338         mb();
12339         if (sc->port.pmf) {
12340             bxe_acquire_phy_lock(sc);
12341             elink_period_func(&sc->link_params, &sc->link_vars);
12342             bxe_release_phy_lock(sc);
12343         }
12344     }
12345
12346     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12347         int mb_idx = SC_FW_MB_IDX(sc);
12348         uint32_t drv_pulse;
12349         uint32_t mcp_pulse;
12350
12351         ++sc->fw_drv_pulse_wr_seq;
12352         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12353
12354         drv_pulse = sc->fw_drv_pulse_wr_seq;
12355         bxe_drv_pulse(sc);
12356
12357         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12358                      MCP_PULSE_SEQ_MASK);
12359
12360         /*
12361          * The delta between driver pulse and mcp response should
12362          * be 1 (before mcp response) or 0 (after mcp response).
12363          */
12364         if ((drv_pulse != mcp_pulse) &&
12365             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12366             /* someone lost a heartbeat... */
12367             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12368                   drv_pulse, mcp_pulse);
12369         }
12370     }
12371
12372     /* state is BXE_STATE_OPEN */
12373     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12374
12375     BXE_CORE_UNLOCK(sc);
12376
12377     if ((sc->state == BXE_STATE_OPEN) &&
12378         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12379         /* schedule the next periodic callout */
12380         callout_reset(&sc->periodic_callout, hz,
12381                       bxe_periodic_callout_func, sc);
12382     }
12383 }
12384
12385 static void
12386 bxe_periodic_start(struct bxe_softc *sc)
12387 {
12388     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12389     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12390 }
12391
12392 static void
12393 bxe_periodic_stop(struct bxe_softc *sc)
12394 {
12395     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12396     callout_drain(&sc->periodic_callout);
12397 }
12398
12399 /* start the controller */
12400 static __noinline int
12401 bxe_nic_load(struct bxe_softc *sc,
12402              int              load_mode)
12403 {
12404     uint32_t val;
12405     int load_code = 0;
12406     int i, rc = 0;
12407
12408     BXE_CORE_LOCK_ASSERT(sc);
12409
12410     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12411
12412     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12413
12414     if (IS_PF(sc)) {
12415         /* must be called before memory allocation and HW init */
12416         bxe_ilt_set_info(sc);
12417     }
12418
12419     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12420
12421     bxe_set_fp_rx_buf_size(sc);
12422
12423     if (bxe_alloc_fp_buffers(sc) != 0) {
12424         BLOGE(sc, "Failed to allocate fastpath memory\n");
12425         sc->state = BXE_STATE_CLOSED;
12426         rc = ENOMEM;
12427         goto bxe_nic_load_error0;
12428     }
12429
12430     if (bxe_alloc_mem(sc) != 0) {
12431         sc->state = BXE_STATE_CLOSED;
12432         rc = ENOMEM;
12433         goto bxe_nic_load_error0;
12434     }
12435
12436     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12437         sc->state = BXE_STATE_CLOSED;
12438         rc = ENOMEM;
12439         goto bxe_nic_load_error0;
12440     }
12441
12442     if (IS_PF(sc)) {
12443         /* set pf load just before approaching the MCP */
12444         bxe_set_pf_load(sc);
12445
12446         /* if MCP exists send load request and analyze response */
12447         if (!BXE_NOMCP(sc)) {
12448             /* attempt to load pf */
12449             if (bxe_nic_load_request(sc, &load_code) != 0) {
12450                 sc->state = BXE_STATE_CLOSED;
12451                 rc = ENXIO;
12452                 goto bxe_nic_load_error1;
12453             }
12454
12455             /* what did the MCP say? */
12456             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12457                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12458                 sc->state = BXE_STATE_CLOSED;
12459                 rc = ENXIO;
12460                 goto bxe_nic_load_error2;
12461             }
12462         } else {
12463             BLOGI(sc, "Device has no MCP!\n");
12464             load_code = bxe_nic_load_no_mcp(sc);
12465         }
12466
12467         /* mark PMF if applicable */
12468         bxe_nic_load_pmf(sc, load_code);
12469
12470         /* Init Function state controlling object */
12471         bxe_init_func_obj(sc);
12472
12473         /* Initialize HW */
12474         if (bxe_init_hw(sc, load_code) != 0) {
12475             BLOGE(sc, "HW init failed\n");
12476             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12477             sc->state = BXE_STATE_CLOSED;
12478             rc = ENXIO;
12479             goto bxe_nic_load_error2;
12480         }
12481     }
12482
12483     /* set ALWAYS_ALIVE bit in shmem */
12484     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12485     bxe_drv_pulse(sc);
12486     sc->flags |= BXE_NO_PULSE;
12487
12488     /* attach interrupts */
12489     if (bxe_interrupt_attach(sc) != 0) {
12490         sc->state = BXE_STATE_CLOSED;
12491         rc = ENXIO;
12492         goto bxe_nic_load_error2;
12493     }
12494
12495     bxe_nic_init(sc, load_code);
12496
12497     /* Init per-function objects */
12498     if (IS_PF(sc)) {
12499         bxe_init_objs(sc);
12500         // XXX bxe_iov_nic_init(sc);
12501
12502         /* set AFEX default VLAN tag to an invalid value */
12503         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12504         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12505
12506         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12507         rc = bxe_func_start(sc);
12508         if (rc) {
12509             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12510             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12511             sc->state = BXE_STATE_ERROR;
12512             goto bxe_nic_load_error3;
12513         }
12514
12515         /* send LOAD_DONE command to MCP */
12516         if (!BXE_NOMCP(sc)) {
12517             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12518             if (!load_code) {
12519                 BLOGE(sc, "MCP response failure, aborting\n");
12520                 sc->state = BXE_STATE_ERROR;
12521                 rc = ENXIO;
12522                 goto bxe_nic_load_error3;
12523             }
12524         }
12525
12526         rc = bxe_setup_leading(sc);
12527         if (rc) {
12528             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12529             sc->state = BXE_STATE_ERROR;
12530             goto bxe_nic_load_error3;
12531         }
12532
12533         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12534             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12535             if (rc) {
12536                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12537                 sc->state = BXE_STATE_ERROR;
12538                 goto bxe_nic_load_error3;
12539             }
12540         }
12541
12542         rc = bxe_init_rss_pf(sc);
12543         if (rc) {
12544             BLOGE(sc, "PF RSS init failed\n");
12545             sc->state = BXE_STATE_ERROR;
12546             goto bxe_nic_load_error3;
12547         }
12548     }
12549     /* XXX VF */
12550
12551     /* now when Clients are configured we are ready to work */
12552     sc->state = BXE_STATE_OPEN;
12553
12554     /* Configure a ucast MAC */
12555     if (IS_PF(sc)) {
12556         rc = bxe_set_eth_mac(sc, TRUE);
12557     }
12558     if (rc) {
12559         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12560         sc->state = BXE_STATE_ERROR;
12561         goto bxe_nic_load_error3;
12562     }
12563
12564     if (sc->port.pmf) {
12565         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12566         if (rc) {
12567             sc->state = BXE_STATE_ERROR;
12568             goto bxe_nic_load_error3;
12569         }
12570     }
12571
12572     sc->link_params.feature_config_flags &=
12573         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12574
12575     /* start fast path */
12576
12577     /* Initialize Rx filter */
12578     bxe_set_rx_mode(sc);
12579
12580     /* start the Tx */
12581     switch (/* XXX load_mode */LOAD_OPEN) {
12582     case LOAD_NORMAL:
12583     case LOAD_OPEN:
12584         break;
12585
12586     case LOAD_DIAG:
12587     case LOAD_LOOPBACK_EXT:
12588         sc->state = BXE_STATE_DIAG;
12589         break;
12590
12591     default:
12592         break;
12593     }
12594
12595     if (sc->port.pmf) {
12596         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12597     } else {
12598         bxe_link_status_update(sc);
12599     }
12600
12601     /* start the periodic timer callout */
12602     bxe_periodic_start(sc);
12603
12604     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12605         /* mark driver is loaded in shmem2 */
12606         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12607         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12608                   (val |
12609                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12610                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12611     }
12612
12613     /* wait for all pending SP commands to complete */
12614     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12615         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12616         bxe_periodic_stop(sc);
12617         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12618         return (ENXIO);
12619     }
12620
12621     /* Tell the stack the driver is running! */
12622     sc->ifnet->if_drv_flags = IFF_DRV_RUNNING;
12623
12624     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12625
12626     return (0);
12627
12628 bxe_nic_load_error3:
12629
12630     if (IS_PF(sc)) {
12631         bxe_int_disable_sync(sc, 1);
12632
12633         /* clean out queued objects */
12634         bxe_squeeze_objects(sc);
12635     }
12636
12637     bxe_interrupt_detach(sc);
12638
12639 bxe_nic_load_error2:
12640
12641     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12642         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12643         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12644     }
12645
12646     sc->port.pmf = 0;
12647
12648 bxe_nic_load_error1:
12649
12650     /* clear pf_load status, as it was already set */
12651     if (IS_PF(sc)) {
12652         bxe_clear_pf_load(sc);
12653     }
12654
12655 bxe_nic_load_error0:
12656
12657     bxe_free_fw_stats_mem(sc);
12658     bxe_free_fp_buffers(sc);
12659     bxe_free_mem(sc);
12660
12661     return (rc);
12662 }
12663
12664 static int
12665 bxe_init_locked(struct bxe_softc *sc)
12666 {
12667     int other_engine = SC_PATH(sc) ? 0 : 1;
12668     uint8_t other_load_status, load_status;
12669     uint8_t global = FALSE;
12670     int rc;
12671
12672     BXE_CORE_LOCK_ASSERT(sc);
12673
12674     /* check if the driver is already running */
12675     if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
12676         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12677         return (0);
12678     }
12679
12680     bxe_set_power_state(sc, PCI_PM_D0);
12681
12682     /*
12683      * If parity occurred during the unload, then attentions and/or
12684      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12685      * loaded on the current engine to complete the recovery. Parity recovery
12686      * is only relevant for PF driver.
12687      */
12688     if (IS_PF(sc)) {
12689         other_load_status = bxe_get_load_status(sc, other_engine);
12690         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12691
12692         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12693             bxe_chk_parity_attn(sc, &global, TRUE)) {
12694             do {
12695                 /*
12696                  * If there are attentions and they are in global blocks, set
12697                  * the GLOBAL_RESET bit regardless whether it will be this
12698                  * function that will complete the recovery or not.
12699                  */
12700                 if (global) {
12701                     bxe_set_reset_global(sc);
12702                 }
12703
12704                 /*
12705                  * Only the first function on the current engine should try
12706                  * to recover in open. In case of attentions in global blocks
12707                  * only the first in the chip should try to recover.
12708                  */
12709                 if ((!load_status && (!global || !other_load_status)) &&
12710                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12711                     BLOGI(sc, "Recovered during init\n");
12712                     break;
12713                 }
12714
12715                 /* recovery has failed... */
12716                 bxe_set_power_state(sc, PCI_PM_D3hot);
12717                 sc->recovery_state = BXE_RECOVERY_FAILED;
12718
12719                 BLOGE(sc, "Recovery flow hasn't properly "
12720                           "completed yet, try again later. "
12721                           "If you still see this message after a "
12722                           "few retries then power cycle is required.\n");
12723
12724                 rc = ENXIO;
12725                 goto bxe_init_locked_done;
12726             } while (0);
12727         }
12728     }
12729
12730     sc->recovery_state = BXE_RECOVERY_DONE;
12731
12732     rc = bxe_nic_load(sc, LOAD_OPEN);
12733
12734 bxe_init_locked_done:
12735
12736     if (rc) {
12737         /* Tell the stack the driver is NOT running! */
12738         BLOGE(sc, "Initialization failed, "
12739                   "stack notified driver is NOT running!\n");
12740         sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
12741     }
12742
12743     return (rc);
12744 }
12745
12746 static int
12747 bxe_stop_locked(struct bxe_softc *sc)
12748 {
12749     BXE_CORE_LOCK_ASSERT(sc);
12750     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12751 }
12752
12753 /*
12754  * Handles controller initialization when called from an unlocked routine.
12755  * ifconfig calls this function.
12756  *
12757  * Returns:
12758  *   void
12759  */
12760 static void
12761 bxe_init(void *xsc)
12762 {
12763     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12764
12765     BXE_CORE_LOCK(sc);
12766     bxe_init_locked(sc);
12767     BXE_CORE_UNLOCK(sc);
12768 }
12769
12770 static int
12771 bxe_init_ifnet(struct bxe_softc *sc)
12772 {
12773     struct ifnet *ifp;
12774
12775     /* ifconfig entrypoint for media type/status reporting */
12776     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12777                  bxe_ifmedia_update,
12778                  bxe_ifmedia_status);
12779
12780     /* set the default interface values */
12781     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12782     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12783     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12784
12785     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12786
12787     /* allocate the ifnet structure */
12788     if ((ifp = if_alloc(IFT_ETHER)) == NULL) {
12789         BLOGE(sc, "Interface allocation failed!\n");
12790         return (ENXIO);
12791     }
12792
12793     ifp->if_softc = sc;
12794     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12795     ifp->if_flags = (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
12796     ifp->if_ioctl = bxe_ioctl;
12797     ifp->if_start = bxe_tx_start;
12798 #if __FreeBSD_version >= 800000
12799     ifp->if_transmit = bxe_tx_mq_start;
12800     ifp->if_qflush = bxe_mq_flush;
12801 #endif
12802 #ifdef FreeBSD8_0
12803     ifp->if_timer = 0;
12804 #endif
12805     ifp->if_init = bxe_init;
12806     ifp->if_mtu = sc->mtu;
12807     ifp->if_hwassist = (CSUM_IP       |
12808                         CSUM_TCP      |
12809                         CSUM_UDP      |
12810                         CSUM_TSO      |
12811                         CSUM_TCP_IPV6 |
12812                         CSUM_UDP_IPV6);
12813     ifp->if_capabilities =
12814 #if __FreeBSD_version < 700000
12815         (IFCAP_VLAN_MTU       |
12816          IFCAP_VLAN_HWTAGGING |
12817          IFCAP_HWCSUM         |
12818          IFCAP_JUMBO_MTU      |
12819          IFCAP_LRO);
12820 #else
12821         (IFCAP_VLAN_MTU       |
12822          IFCAP_VLAN_HWTAGGING |
12823          IFCAP_VLAN_HWTSO     |
12824          IFCAP_VLAN_HWFILTER  |
12825          IFCAP_VLAN_HWCSUM    |
12826          IFCAP_HWCSUM         |
12827          IFCAP_JUMBO_MTU      |
12828          IFCAP_LRO            |
12829          IFCAP_TSO4           |
12830          IFCAP_TSO6           |
12831          IFCAP_WOL_MAGIC);
12832 #endif
12833     ifp->if_capenable = ifp->if_capabilities;
12834     ifp->if_capenable &= ~IFCAP_WOL_MAGIC; /* XXX not yet... */
12835 #if __FreeBSD_version < 1000025
12836     ifp->if_baudrate = 1000000000;
12837 #else
12838     if_initbaudrate(ifp, IF_Gbps(10));
12839 #endif
12840     ifp->if_snd.ifq_drv_maxlen = sc->tx_ring_size;
12841
12842     IFQ_SET_MAXLEN(&ifp->if_snd, ifp->if_snd.ifq_drv_maxlen);
12843     IFQ_SET_READY(&ifp->if_snd);
12844
12845     sc->ifnet = ifp;
12846
12847     /* attach to the Ethernet interface list */
12848     ether_ifattach(ifp, sc->link_params.mac_addr);
12849
12850     return (0);
12851 }
12852
12853 static void
12854 bxe_deallocate_bars(struct bxe_softc *sc)
12855 {
12856     int i;
12857
12858     for (i = 0; i < MAX_BARS; i++) {
12859         if (sc->bar[i].resource != NULL) {
12860             bus_release_resource(sc->dev,
12861                                  SYS_RES_MEMORY,
12862                                  sc->bar[i].rid,
12863                                  sc->bar[i].resource);
12864             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12865                   i, PCIR_BAR(i));
12866         }
12867     }
12868 }
12869
12870 static int
12871 bxe_allocate_bars(struct bxe_softc *sc)
12872 {
12873     u_int flags;
12874     int i;
12875
12876     memset(sc->bar, 0, sizeof(sc->bar));
12877
12878     for (i = 0; i < MAX_BARS; i++) {
12879
12880         /* memory resources reside at BARs 0, 2, 4 */
12881         /* Run `pciconf -lb` to see mappings */
12882         if ((i != 0) && (i != 2) && (i != 4)) {
12883             continue;
12884         }
12885
12886         sc->bar[i].rid = PCIR_BAR(i);
12887
12888         flags = RF_ACTIVE;
12889         if (i == 0) {
12890             flags |= RF_SHAREABLE;
12891         }
12892
12893         if ((sc->bar[i].resource =
12894              bus_alloc_resource_any(sc->dev,
12895                                     SYS_RES_MEMORY,
12896                                     &sc->bar[i].rid,
12897                                     flags)) == NULL) {
12898             return (0);
12899         }
12900
12901         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12902         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12903         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12904
12905         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%ld) -> %p\n",
12906               i, PCIR_BAR(i),
12907               (void *)rman_get_start(sc->bar[i].resource),
12908               (void *)rman_get_end(sc->bar[i].resource),
12909               rman_get_size(sc->bar[i].resource),
12910               (void *)sc->bar[i].kva);
12911     }
12912
12913     return (0);
12914 }
12915
12916 static void
12917 bxe_get_function_num(struct bxe_softc *sc)
12918 {
12919     uint32_t val = 0;
12920
12921     /*
12922      * Read the ME register to get the function number. The ME register
12923      * holds the relative-function number and absolute-function number. The
12924      * absolute-function number appears only in E2 and above. Before that
12925      * these bits always contained zero, therefore we cannot blindly use them.
12926      */
12927
12928     val = REG_RD(sc, BAR_ME_REGISTER);
12929
12930     sc->pfunc_rel =
12931         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12932     sc->path_id =
12933         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12934
12935     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12936         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12937     } else {
12938         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12939     }
12940
12941     BLOGD(sc, DBG_LOAD,
12942           "Relative function %d, Absolute function %d, Path %d\n",
12943           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12944 }
12945
12946 static uint32_t
12947 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12948 {
12949     uint32_t shmem2_size;
12950     uint32_t offset;
12951     uint32_t mf_cfg_offset_value;
12952
12953     /* Non 57712 */
12954     offset = (SHMEM_RD(sc, func_mb) +
12955               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12956
12957     /* 57712 plus */
12958     if (sc->devinfo.shmem2_base != 0) {
12959         shmem2_size = SHMEM2_RD(sc, size);
12960         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12961             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12962             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12963                 offset = mf_cfg_offset_value;
12964             }
12965         }
12966     }
12967
12968     return (offset);
12969 }
12970
12971 static uint32_t
12972 bxe_pcie_capability_read(struct bxe_softc *sc,
12973                          int    reg,
12974                          int    width)
12975 {
12976     int pcie_reg;
12977
12978     /* ensure PCIe capability is enabled */
12979     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12980         if (pcie_reg != 0) {
12981             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12982             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12983         }
12984     }
12985
12986     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12987
12988     return (0);
12989 }
12990
12991 static uint8_t
12992 bxe_is_pcie_pending(struct bxe_softc *sc)
12993 {
12994     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12995             PCIM_EXP_STA_TRANSACTION_PND);
12996 }
12997
12998 /*
12999  * Walk the PCI capabiites list for the device to find what features are
13000  * supported. These capabilites may be enabled/disabled by firmware so it's
13001  * best to walk the list rather than make assumptions.
13002  */
13003 static void
13004 bxe_probe_pci_caps(struct bxe_softc *sc)
13005 {
13006     uint16_t link_status;
13007     int reg;
13008
13009     /* check if PCI Power Management is enabled */
13010     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
13011         if (reg != 0) {
13012             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
13013
13014             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
13015             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
13016         }
13017     }
13018
13019     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
13020
13021     /* handle PCIe 2.0 workarounds for 57710 */
13022     if (CHIP_IS_E1(sc)) {
13023         /* workaround for 57710 errata E4_57710_27462 */
13024         sc->devinfo.pcie_link_speed =
13025             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
13026
13027         /* workaround for 57710 errata E4_57710_27488 */
13028         sc->devinfo.pcie_link_width =
13029             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13030         if (sc->devinfo.pcie_link_speed > 1) {
13031             sc->devinfo.pcie_link_width =
13032                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
13033         }
13034     } else {
13035         sc->devinfo.pcie_link_speed =
13036             (link_status & PCIM_LINK_STA_SPEED);
13037         sc->devinfo.pcie_link_width =
13038             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13039     }
13040
13041     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
13042           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
13043
13044     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
13045     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
13046
13047     /* check if MSI capability is enabled */
13048     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
13049         if (reg != 0) {
13050             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13051
13052             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13053             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13054         }
13055     }
13056
13057     /* check if MSI-X capability is enabled */
13058     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13059         if (reg != 0) {
13060             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13061
13062             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13063             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13064         }
13065     }
13066 }
13067
13068 static int
13069 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13070 {
13071     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13072     uint32_t val;
13073
13074     /* get the outer vlan if we're in switch-dependent mode */
13075
13076     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13077     mf_info->ext_id = (uint16_t)val;
13078
13079     mf_info->multi_vnics_mode = 1;
13080
13081     if (!VALID_OVLAN(mf_info->ext_id)) {
13082         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13083         return (1);
13084     }
13085
13086     /* get the capabilities */
13087     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13088         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13089         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13090     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13091                FUNC_MF_CFG_PROTOCOL_FCOE) {
13092         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13093     } else {
13094         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13095     }
13096
13097     mf_info->vnics_per_port =
13098         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13099
13100     return (0);
13101 }
13102
13103 static uint32_t
13104 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13105 {
13106     uint32_t retval = 0;
13107     uint32_t val;
13108
13109     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13110
13111     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13112         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13113             retval |= MF_PROTO_SUPPORT_ETHERNET;
13114         }
13115         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13116             retval |= MF_PROTO_SUPPORT_ISCSI;
13117         }
13118         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13119             retval |= MF_PROTO_SUPPORT_FCOE;
13120         }
13121     }
13122
13123     return (retval);
13124 }
13125
13126 static int
13127 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13128 {
13129     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13130     uint32_t val;
13131
13132     /*
13133      * There is no outer vlan if we're in switch-independent mode.
13134      * If the mac is valid then assume multi-function.
13135      */
13136
13137     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13138
13139     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13140
13141     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13142
13143     mf_info->vnics_per_port =
13144         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13145
13146     return (0);
13147 }
13148
13149 static int
13150 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13151 {
13152     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13153     uint32_t e1hov_tag;
13154     uint32_t func_config;
13155     uint32_t niv_config;
13156
13157     mf_info->multi_vnics_mode = 1;
13158
13159     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13160     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13161     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13162
13163     mf_info->ext_id =
13164         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13165                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13166
13167     mf_info->default_vlan =
13168         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13169                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13170
13171     mf_info->niv_allowed_priorities =
13172         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13173                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13174
13175     mf_info->niv_default_cos =
13176         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13177                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13178
13179     mf_info->afex_vlan_mode =
13180         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13181          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13182
13183     mf_info->niv_mba_enabled =
13184         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13185          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13186
13187     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13188
13189     mf_info->vnics_per_port =
13190         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13191
13192     return (0);
13193 }
13194
13195 static int
13196 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13197 {
13198     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13199     uint32_t mf_cfg1;
13200     uint32_t mf_cfg2;
13201     uint32_t ovlan1;
13202     uint32_t ovlan2;
13203     uint8_t i, j;
13204
13205     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13206           SC_PORT(sc));
13207     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13208           mf_info->mf_config[SC_VN(sc)]);
13209     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13210           mf_info->multi_vnics_mode);
13211     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13212           mf_info->vnics_per_port);
13213     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13214           mf_info->ext_id);
13215     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13216           mf_info->min_bw[0], mf_info->min_bw[1],
13217           mf_info->min_bw[2], mf_info->min_bw[3]);
13218     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13219           mf_info->max_bw[0], mf_info->max_bw[1],
13220           mf_info->max_bw[2], mf_info->max_bw[3]);
13221     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13222           sc->mac_addr_str);
13223
13224     /* various MF mode sanity checks... */
13225
13226     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13227         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13228               SC_PORT(sc));
13229         return (1);
13230     }
13231
13232     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13233         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13234               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13235         return (1);
13236     }
13237
13238     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13239         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13240         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13241             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13242                   SC_VN(sc), OVLAN(sc));
13243             return (1);
13244         }
13245
13246         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13247             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13248                   mf_info->multi_vnics_mode, OVLAN(sc));
13249             return (1);
13250         }
13251
13252         /*
13253          * Verify all functions are either MF or SF mode. If MF, make sure
13254          * sure that all non-hidden functions have a valid ovlan. If SF,
13255          * make sure that all non-hidden functions have an invalid ovlan.
13256          */
13257         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13258             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13259             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13260             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13261                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13262                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13263                 BLOGE(sc, "mf_mode=SD function %d MF config "
13264                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13265                       i, mf_info->multi_vnics_mode, ovlan1);
13266                 return (1);
13267             }
13268         }
13269
13270         /* Verify all funcs on the same port each have a different ovlan. */
13271         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13272             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13273             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13274             /* iterate from the next function on the port to the max func */
13275             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13276                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13277                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13278                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13279                     VALID_OVLAN(ovlan1) &&
13280                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13281                     VALID_OVLAN(ovlan2) &&
13282                     (ovlan1 == ovlan2)) {
13283                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13284                               "have the same ovlan (%d)\n",
13285                           i, j, ovlan1);
13286                     return (1);
13287                 }
13288             }
13289         }
13290     } /* MULTI_FUNCTION_SD */
13291
13292     return (0);
13293 }
13294
13295 static int
13296 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13297 {
13298     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13299     uint32_t val, mac_upper;
13300     uint8_t i, vnic;
13301
13302     /* initialize mf_info defaults */
13303     mf_info->vnics_per_port   = 1;
13304     mf_info->multi_vnics_mode = FALSE;
13305     mf_info->path_has_ovlan   = FALSE;
13306     mf_info->mf_mode          = SINGLE_FUNCTION;
13307
13308     if (!CHIP_IS_MF_CAP(sc)) {
13309         return (0);
13310     }
13311
13312     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13313         BLOGE(sc, "Invalid mf_cfg_base!\n");
13314         return (1);
13315     }
13316
13317     /* get the MF mode (switch dependent / independent / single-function) */
13318
13319     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13320
13321     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13322     {
13323     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13324
13325         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13326
13327         /* check for legal upper mac bytes */
13328         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13329             mf_info->mf_mode = MULTI_FUNCTION_SI;
13330         } else {
13331             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13332         }
13333
13334         break;
13335
13336     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13337     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13338
13339         /* get outer vlan configuration */
13340         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13341
13342         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13343             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13344             mf_info->mf_mode = MULTI_FUNCTION_SD;
13345         } else {
13346             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13347         }
13348
13349         break;
13350
13351     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13352
13353         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13354         return (0);
13355
13356     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13357
13358         /*
13359          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13360          * and the MAC address is valid.
13361          */
13362         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13363
13364         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13365             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13366             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13367         } else {
13368             BLOGE(sc, "Invalid config for AFEX mode\n");
13369         }
13370
13371         break;
13372
13373     default:
13374
13375         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13376               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13377
13378         return (1);
13379     }
13380
13381     /* set path mf_mode (which could be different than function mf_mode) */
13382     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13383         mf_info->path_has_ovlan = TRUE;
13384     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13385         /*
13386          * Decide on path multi vnics mode. If we're not in MF mode and in
13387          * 4-port mode, this is good enough to check vnic-0 of the other port
13388          * on the same path
13389          */
13390         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13391             uint8_t other_port = !(PORT_ID(sc) & 1);
13392             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13393
13394             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13395
13396             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13397         }
13398     }
13399
13400     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13401         /* invalid MF config */
13402         if (SC_VN(sc) >= 1) {
13403             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13404             return (1);
13405         }
13406
13407         return (0);
13408     }
13409
13410     /* get the MF configuration */
13411     mf_info->mf_config[SC_VN(sc)] =
13412         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13413
13414     switch(mf_info->mf_mode)
13415     {
13416     case MULTI_FUNCTION_SD:
13417
13418         bxe_get_shmem_mf_cfg_info_sd(sc);
13419         break;
13420
13421     case MULTI_FUNCTION_SI:
13422
13423         bxe_get_shmem_mf_cfg_info_si(sc);
13424         break;
13425
13426     case MULTI_FUNCTION_AFEX:
13427
13428         bxe_get_shmem_mf_cfg_info_niv(sc);
13429         break;
13430
13431     default:
13432
13433         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13434               mf_info->mf_mode);
13435         return (1);
13436     }
13437
13438     /* get the congestion management parameters */
13439
13440     vnic = 0;
13441     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13442         /* get min/max bw */
13443         val = MFCFG_RD(sc, func_mf_config[i].config);
13444         mf_info->min_bw[vnic] =
13445             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13446         mf_info->max_bw[vnic] =
13447             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13448         vnic++;
13449     }
13450
13451     return (bxe_check_valid_mf_cfg(sc));
13452 }
13453
13454 static int
13455 bxe_get_shmem_info(struct bxe_softc *sc)
13456 {
13457     int port;
13458     uint32_t mac_hi, mac_lo, val;
13459
13460     port = SC_PORT(sc);
13461     mac_hi = mac_lo = 0;
13462
13463     sc->link_params.sc   = sc;
13464     sc->link_params.port = port;
13465
13466     /* get the hardware config info */
13467     sc->devinfo.hw_config =
13468         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13469     sc->devinfo.hw_config2 =
13470         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13471
13472     sc->link_params.hw_led_mode =
13473         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13474          SHARED_HW_CFG_LED_MODE_SHIFT);
13475
13476     /* get the port feature config */
13477     sc->port.config =
13478         SHMEM_RD(sc, dev_info.port_feature_config[port].config),
13479
13480     /* get the link params */
13481     sc->link_params.speed_cap_mask[0] =
13482         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13483     sc->link_params.speed_cap_mask[1] =
13484         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13485
13486     /* get the lane config */
13487     sc->link_params.lane_config =
13488         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13489
13490     /* get the link config */
13491     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13492     sc->port.link_config[ELINK_INT_PHY] = val;
13493     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13494     sc->port.link_config[ELINK_EXT_PHY1] =
13495         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13496
13497     /* get the override preemphasis flag and enable it or turn it off */
13498     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13499     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13500         sc->link_params.feature_config_flags |=
13501             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13502     } else {
13503         sc->link_params.feature_config_flags &=
13504             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13505     }
13506
13507     /* get the initial value of the link params */
13508     sc->link_params.multi_phy_config =
13509         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13510
13511     /* get external phy info */
13512     sc->port.ext_phy_config =
13513         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13514
13515     /* get the multifunction configuration */
13516     bxe_get_mf_cfg_info(sc);
13517
13518     /* get the mac address */
13519     if (IS_MF(sc)) {
13520         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13521         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13522     } else {
13523         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13524         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13525     }
13526
13527     if ((mac_lo == 0) && (mac_hi == 0)) {
13528         *sc->mac_addr_str = 0;
13529         BLOGE(sc, "No Ethernet address programmed!\n");
13530     } else {
13531         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13532         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13533         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13534         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13535         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13536         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13537         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13538                  "%02x:%02x:%02x:%02x:%02x:%02x",
13539                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13540                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13541                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13542         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13543     }
13544
13545     return (0);
13546 }
13547
13548 static void
13549 bxe_get_tunable_params(struct bxe_softc *sc)
13550 {
13551     /* sanity checks */
13552
13553     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13554         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13555         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13556         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13557         bxe_interrupt_mode = INTR_MODE_MSIX;
13558     }
13559
13560     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13561         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13562         bxe_queue_count = 0;
13563     }
13564
13565     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13566         if (bxe_max_rx_bufs == 0) {
13567             bxe_max_rx_bufs = RX_BD_USABLE;
13568         } else {
13569             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13570             bxe_max_rx_bufs = 2048;
13571         }
13572     }
13573
13574     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13575         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13576         bxe_hc_rx_ticks = 25;
13577     }
13578
13579     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13580         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13581         bxe_hc_tx_ticks = 50;
13582     }
13583
13584     if (bxe_max_aggregation_size == 0) {
13585         bxe_max_aggregation_size = TPA_AGG_SIZE;
13586     }
13587
13588     if (bxe_max_aggregation_size > 0xffff) {
13589         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13590               bxe_max_aggregation_size);
13591         bxe_max_aggregation_size = TPA_AGG_SIZE;
13592     }
13593
13594     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13595         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13596         bxe_mrrs = -1;
13597     }
13598
13599     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13600         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13601         bxe_autogreeen = 0;
13602     }
13603
13604     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13605         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13606         bxe_udp_rss = 0;
13607     }
13608
13609     /* pull in user settings */
13610
13611     sc->interrupt_mode       = bxe_interrupt_mode;
13612     sc->max_rx_bufs          = bxe_max_rx_bufs;
13613     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13614     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13615     sc->max_aggregation_size = bxe_max_aggregation_size;
13616     sc->mrrs                 = bxe_mrrs;
13617     sc->autogreeen           = bxe_autogreeen;
13618     sc->udp_rss              = bxe_udp_rss;
13619
13620     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13621         sc->num_queues = 1;
13622     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13623         sc->num_queues =
13624             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13625                 MAX_RSS_CHAINS);
13626         if (sc->num_queues > mp_ncpus) {
13627             sc->num_queues = mp_ncpus;
13628         }
13629     }
13630
13631     BLOGD(sc, DBG_LOAD,
13632           "User Config: "
13633           "debug=0x%lx "
13634           "interrupt_mode=%d "
13635           "queue_count=%d "
13636           "hc_rx_ticks=%d "
13637           "hc_tx_ticks=%d "
13638           "rx_budget=%d "
13639           "max_aggregation_size=%d "
13640           "mrrs=%d "
13641           "autogreeen=%d "
13642           "udp_rss=%d\n",
13643           bxe_debug,
13644           sc->interrupt_mode,
13645           sc->num_queues,
13646           sc->hc_rx_ticks,
13647           sc->hc_tx_ticks,
13648           bxe_rx_budget,
13649           sc->max_aggregation_size,
13650           sc->mrrs,
13651           sc->autogreeen,
13652           sc->udp_rss);
13653 }
13654
13655 static void
13656 bxe_media_detect(struct bxe_softc *sc)
13657 {
13658     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13659     switch (sc->link_params.phy[phy_idx].media_type) {
13660     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13661     case ELINK_ETH_PHY_XFP_FIBER:
13662         BLOGI(sc, "Found 10Gb Fiber media.\n");
13663         sc->media = IFM_10G_SR;
13664         break;
13665     case ELINK_ETH_PHY_SFP_1G_FIBER:
13666         BLOGI(sc, "Found 1Gb Fiber media.\n");
13667         sc->media = IFM_1000_SX;
13668         break;
13669     case ELINK_ETH_PHY_KR:
13670     case ELINK_ETH_PHY_CX4:
13671         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13672         sc->media = IFM_10G_CX4;
13673         break;
13674     case ELINK_ETH_PHY_DA_TWINAX:
13675         BLOGI(sc, "Found 10Gb Twinax media.\n");
13676         sc->media = IFM_10G_TWINAX;
13677         break;
13678     case ELINK_ETH_PHY_BASE_T:
13679         if (sc->link_params.speed_cap_mask[0] &
13680             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13681             BLOGI(sc, "Found 10GBase-T media.\n");
13682             sc->media = IFM_10G_T;
13683         } else {
13684             BLOGI(sc, "Found 1000Base-T media.\n");
13685             sc->media = IFM_1000_T;
13686         }
13687         break;
13688     case ELINK_ETH_PHY_NOT_PRESENT:
13689         BLOGI(sc, "Media not present.\n");
13690         sc->media = 0;
13691         break;
13692     case ELINK_ETH_PHY_UNSPECIFIED:
13693     default:
13694         BLOGI(sc, "Unknown media!\n");
13695         sc->media = 0;
13696         break;
13697     }
13698 }
13699
13700 #define GET_FIELD(value, fname)                     \
13701     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13702 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13703 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13704
13705 static int
13706 bxe_get_igu_cam_info(struct bxe_softc *sc)
13707 {
13708     int pfid = SC_FUNC(sc);
13709     int igu_sb_id;
13710     uint32_t val;
13711     uint8_t fid, igu_sb_cnt = 0;
13712
13713     sc->igu_base_sb = 0xff;
13714
13715     if (CHIP_INT_MODE_IS_BC(sc)) {
13716         int vn = SC_VN(sc);
13717         igu_sb_cnt = sc->igu_sb_cnt;
13718         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13719                            FP_SB_MAX_E1x);
13720         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13721                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13722         return (0);
13723     }
13724
13725     /* IGU in normal mode - read CAM */
13726     for (igu_sb_id = 0;
13727          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13728          igu_sb_id++) {
13729         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13730         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13731             continue;
13732         }
13733         fid = IGU_FID(val);
13734         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13735             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13736                 continue;
13737             }
13738             if (IGU_VEC(val) == 0) {
13739                 /* default status block */
13740                 sc->igu_dsb_id = igu_sb_id;
13741             } else {
13742                 if (sc->igu_base_sb == 0xff) {
13743                     sc->igu_base_sb = igu_sb_id;
13744                 }
13745                 igu_sb_cnt++;
13746             }
13747         }
13748     }
13749
13750     /*
13751      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13752      * that number of CAM entries will not be equal to the value advertised in
13753      * PCI. Driver should use the minimal value of both as the actual status
13754      * block count
13755      */
13756     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13757
13758     if (igu_sb_cnt == 0) {
13759         BLOGE(sc, "CAM configuration error\n");
13760         return (-1);
13761     }
13762
13763     return (0);
13764 }
13765
13766 /*
13767  * Gather various information from the device config space, the device itself,
13768  * shmem, and the user input.
13769  */
13770 static int
13771 bxe_get_device_info(struct bxe_softc *sc)
13772 {
13773     uint32_t val;
13774     int rc;
13775
13776     /* Get the data for the device */
13777     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13778     sc->devinfo.device_id    = pci_get_device(sc->dev);
13779     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13780     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13781
13782     /* get the chip revision (chip metal comes from pci config space) */
13783     sc->devinfo.chip_id     =
13784     sc->link_params.chip_id =
13785         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13786          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13787          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13788          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13789
13790     /* force 57811 according to MISC register */
13791     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13792         if (CHIP_IS_57810(sc)) {
13793             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13794                                    (sc->devinfo.chip_id & 0x0000ffff));
13795         } else if (CHIP_IS_57810_MF(sc)) {
13796             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13797                                    (sc->devinfo.chip_id & 0x0000ffff));
13798         }
13799         sc->devinfo.chip_id |= 0x1;
13800     }
13801
13802     BLOGD(sc, DBG_LOAD,
13803           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13804           sc->devinfo.chip_id,
13805           ((sc->devinfo.chip_id >> 16) & 0xffff),
13806           ((sc->devinfo.chip_id >> 12) & 0xf),
13807           ((sc->devinfo.chip_id >>  4) & 0xff),
13808           ((sc->devinfo.chip_id >>  0) & 0xf));
13809
13810     val = (REG_RD(sc, 0x2874) & 0x55);
13811     if ((sc->devinfo.chip_id & 0x1) ||
13812         (CHIP_IS_E1(sc) && val) ||
13813         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13814         sc->flags |= BXE_ONE_PORT_FLAG;
13815         BLOGD(sc, DBG_LOAD, "single port device\n");
13816     }
13817
13818     /* set the doorbell size */
13819     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13820
13821     /* determine whether the device is in 2 port or 4 port mode */
13822     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13823     if (CHIP_IS_E2E3(sc)) {
13824         /*
13825          * Read port4mode_en_ovwr[0]:
13826          *   If 1, four port mode is in port4mode_en_ovwr[1].
13827          *   If 0, four port mode is in port4mode_en[0].
13828          */
13829         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13830         if (val & 1) {
13831             val = ((val >> 1) & 1);
13832         } else {
13833             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13834         }
13835
13836         sc->devinfo.chip_port_mode =
13837             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13838
13839         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13840     }
13841
13842     /* get the function and path info for the device */
13843     bxe_get_function_num(sc);
13844
13845     /* get the shared memory base address */
13846     sc->devinfo.shmem_base     =
13847     sc->link_params.shmem_base =
13848         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13849     sc->devinfo.shmem2_base =
13850         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13851                                   MISC_REG_GENERIC_CR_0));
13852
13853     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13854           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13855
13856     if (!sc->devinfo.shmem_base) {
13857         /* this should ONLY prevent upcoming shmem reads */
13858         BLOGI(sc, "MCP not active\n");
13859         sc->flags |= BXE_NO_MCP_FLAG;
13860         return (0);
13861     }
13862
13863     /* make sure the shared memory contents are valid */
13864     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13865     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13866         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13867         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13868         return (0);
13869     }
13870     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13871
13872     /* get the bootcode version */
13873     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13874     snprintf(sc->devinfo.bc_ver_str,
13875              sizeof(sc->devinfo.bc_ver_str),
13876              "%d.%d.%d",
13877              ((sc->devinfo.bc_ver >> 24) & 0xff),
13878              ((sc->devinfo.bc_ver >> 16) & 0xff),
13879              ((sc->devinfo.bc_ver >>  8) & 0xff));
13880     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13881
13882     /* get the bootcode shmem address */
13883     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13884     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13885
13886     /* clean indirect addresses as they're not used */
13887     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13888     if (IS_PF(sc)) {
13889         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13890         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13891         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13892         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13893         if (CHIP_IS_E1x(sc)) {
13894             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13895             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13896             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13897             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13898         }
13899
13900         /*
13901          * Enable internal target-read (in case we are probed after PF
13902          * FLR). Must be done prior to any BAR read access. Only for
13903          * 57712 and up
13904          */
13905         if (!CHIP_IS_E1x(sc)) {
13906             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13907         }
13908     }
13909
13910     /* get the nvram size */
13911     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13912     sc->devinfo.flash_size =
13913         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13914     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13915
13916     /* get PCI capabilites */
13917     bxe_probe_pci_caps(sc);
13918
13919     bxe_set_power_state(sc, PCI_PM_D0);
13920
13921     /* get various configuration parameters from shmem */
13922     bxe_get_shmem_info(sc);
13923
13924     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13925         val = pci_read_config(sc->dev,
13926                               (sc->devinfo.pcie_msix_cap_reg +
13927                                PCIR_MSIX_CTRL),
13928                               2);
13929         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13930     } else {
13931         sc->igu_sb_cnt = 1;
13932     }
13933
13934     sc->igu_base_addr = BAR_IGU_INTMEM;
13935
13936     /* initialize IGU parameters */
13937     if (CHIP_IS_E1x(sc)) {
13938         sc->devinfo.int_block = INT_BLOCK_HC;
13939         sc->igu_dsb_id = DEF_SB_IGU_ID;
13940         sc->igu_base_sb = 0;
13941     } else {
13942         sc->devinfo.int_block = INT_BLOCK_IGU;
13943
13944         /* do not allow device reset during IGU info preocessing */
13945         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13946
13947         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13948
13949         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13950             int tout = 5000;
13951
13952             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13953
13954             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13955             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13956             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13957
13958             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13959                 tout--;
13960                 DELAY(1000);
13961             }
13962
13963             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13964                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13965                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13966                 return (-1);
13967             }
13968         }
13969
13970         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13971             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13972             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13973         } else {
13974             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13975         }
13976
13977         rc = bxe_get_igu_cam_info(sc);
13978
13979         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13980
13981         if (rc) {
13982             return (rc);
13983         }
13984     }
13985
13986     /*
13987      * Get base FW non-default (fast path) status block ID. This value is
13988      * used to initialize the fw_sb_id saved on the fp/queue structure to
13989      * determine the id used by the FW.
13990      */
13991     if (CHIP_IS_E1x(sc)) {
13992         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
13993     } else {
13994         /*
13995          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
13996          * the same queue are indicated on the same IGU SB). So we prefer
13997          * FW and IGU SBs to be the same value.
13998          */
13999         sc->base_fw_ndsb = sc->igu_base_sb;
14000     }
14001
14002     BLOGD(sc, DBG_LOAD,
14003           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
14004           sc->igu_dsb_id, sc->igu_base_sb,
14005           sc->igu_sb_cnt, sc->base_fw_ndsb);
14006
14007     elink_phy_probe(&sc->link_params);
14008
14009     return (0);
14010 }
14011
14012 static void
14013 bxe_link_settings_supported(struct bxe_softc *sc,
14014                             uint32_t         switch_cfg)
14015 {
14016     uint32_t cfg_size = 0;
14017     uint32_t idx;
14018     uint8_t port = SC_PORT(sc);
14019
14020     /* aggregation of supported attributes of all external phys */
14021     sc->port.supported[0] = 0;
14022     sc->port.supported[1] = 0;
14023
14024     switch (sc->link_params.num_phys) {
14025     case 1:
14026         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
14027         cfg_size = 1;
14028         break;
14029     case 2:
14030         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
14031         cfg_size = 1;
14032         break;
14033     case 3:
14034         if (sc->link_params.multi_phy_config &
14035             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
14036             sc->port.supported[1] =
14037                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14038             sc->port.supported[0] =
14039                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14040         } else {
14041             sc->port.supported[0] =
14042                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14043             sc->port.supported[1] =
14044                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14045         }
14046         cfg_size = 2;
14047         break;
14048     }
14049
14050     if (!(sc->port.supported[0] || sc->port.supported[1])) {
14051         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14052               SHMEM_RD(sc,
14053                        dev_info.port_hw_config[port].external_phy_config),
14054               SHMEM_RD(sc,
14055                        dev_info.port_hw_config[port].external_phy_config2));
14056         return;
14057     }
14058
14059     if (CHIP_IS_E3(sc))
14060         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14061     else {
14062         switch (switch_cfg) {
14063         case ELINK_SWITCH_CFG_1G:
14064             sc->port.phy_addr =
14065                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14066             break;
14067         case ELINK_SWITCH_CFG_10G:
14068             sc->port.phy_addr =
14069                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14070             break;
14071         default:
14072             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14073                   sc->port.link_config[0]);
14074             return;
14075         }
14076     }
14077
14078     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14079
14080     /* mask what we support according to speed_cap_mask per configuration */
14081     for (idx = 0; idx < cfg_size; idx++) {
14082         if (!(sc->link_params.speed_cap_mask[idx] &
14083               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14084             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14085         }
14086
14087         if (!(sc->link_params.speed_cap_mask[idx] &
14088               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14089             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14090         }
14091
14092         if (!(sc->link_params.speed_cap_mask[idx] &
14093               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14094             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14095         }
14096
14097         if (!(sc->link_params.speed_cap_mask[idx] &
14098               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14099             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14100         }
14101
14102         if (!(sc->link_params.speed_cap_mask[idx] &
14103               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14104             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14105         }
14106
14107         if (!(sc->link_params.speed_cap_mask[idx] &
14108               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14109             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14110         }
14111
14112         if (!(sc->link_params.speed_cap_mask[idx] &
14113               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14114             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14115         }
14116
14117         if (!(sc->link_params.speed_cap_mask[idx] &
14118               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14119             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14120         }
14121     }
14122
14123     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14124           sc->port.supported[0], sc->port.supported[1]);
14125 }
14126
14127 static void
14128 bxe_link_settings_requested(struct bxe_softc *sc)
14129 {
14130     uint32_t link_config;
14131     uint32_t idx;
14132     uint32_t cfg_size = 0;
14133
14134     sc->port.advertising[0] = 0;
14135     sc->port.advertising[1] = 0;
14136
14137     switch (sc->link_params.num_phys) {
14138     case 1:
14139     case 2:
14140         cfg_size = 1;
14141         break;
14142     case 3:
14143         cfg_size = 2;
14144         break;
14145     }
14146
14147     for (idx = 0; idx < cfg_size; idx++) {
14148         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14149         link_config = sc->port.link_config[idx];
14150
14151         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14152         case PORT_FEATURE_LINK_SPEED_AUTO:
14153             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14154                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14155                 sc->port.advertising[idx] |= sc->port.supported[idx];
14156                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14157                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14158                     sc->port.advertising[idx] |=
14159                         (ELINK_SUPPORTED_100baseT_Half |
14160                          ELINK_SUPPORTED_100baseT_Full);
14161             } else {
14162                 /* force 10G, no AN */
14163                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14164                 sc->port.advertising[idx] |=
14165                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14166                 continue;
14167             }
14168             break;
14169
14170         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14171             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14172                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14173                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14174                                               ADVERTISED_TP);
14175             } else {
14176                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14177                           "speed_cap_mask=0x%08x\n",
14178                       link_config, sc->link_params.speed_cap_mask[idx]);
14179                 return;
14180             }
14181             break;
14182
14183         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14184             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14185                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14186                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14187                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14188                                               ADVERTISED_TP);
14189             } else {
14190                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14191                           "speed_cap_mask=0x%08x\n",
14192                       link_config, sc->link_params.speed_cap_mask[idx]);
14193                 return;
14194             }
14195             break;
14196
14197         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14198             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14199                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14200                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14201                                               ADVERTISED_TP);
14202             } else {
14203                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14204                           "speed_cap_mask=0x%08x\n",
14205                       link_config, sc->link_params.speed_cap_mask[idx]);
14206                 return;
14207             }
14208             break;
14209
14210         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14211             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14212                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14213                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14214                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14215                                               ADVERTISED_TP);
14216             } else {
14217                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14218                           "speed_cap_mask=0x%08x\n",
14219                       link_config, sc->link_params.speed_cap_mask[idx]);
14220                 return;
14221             }
14222             break;
14223
14224         case PORT_FEATURE_LINK_SPEED_1G:
14225             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14226                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14227                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14228                                               ADVERTISED_TP);
14229             } else {
14230                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14231                           "speed_cap_mask=0x%08x\n",
14232                       link_config, sc->link_params.speed_cap_mask[idx]);
14233                 return;
14234             }
14235             break;
14236
14237         case PORT_FEATURE_LINK_SPEED_2_5G:
14238             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14239                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14240                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14241                                               ADVERTISED_TP);
14242             } else {
14243                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14244                           "speed_cap_mask=0x%08x\n",
14245                       link_config, sc->link_params.speed_cap_mask[idx]);
14246                 return;
14247             }
14248             break;
14249
14250         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14251             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14252                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14253                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14254                                               ADVERTISED_FIBRE);
14255             } else {
14256                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14257                           "speed_cap_mask=0x%08x\n",
14258                       link_config, sc->link_params.speed_cap_mask[idx]);
14259                 return;
14260             }
14261             break;
14262
14263         case PORT_FEATURE_LINK_SPEED_20G:
14264             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14265             break;
14266
14267         default:
14268             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14269                       "speed_cap_mask=0x%08x\n",
14270                   link_config, sc->link_params.speed_cap_mask[idx]);
14271             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14272             sc->port.advertising[idx] = sc->port.supported[idx];
14273             break;
14274         }
14275
14276         sc->link_params.req_flow_ctrl[idx] =
14277             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14278
14279         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14280             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14281                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14282             } else {
14283                 bxe_set_requested_fc(sc);
14284             }
14285         }
14286
14287         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14288                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14289               sc->link_params.req_line_speed[idx],
14290               sc->link_params.req_duplex[idx],
14291               sc->link_params.req_flow_ctrl[idx],
14292               sc->port.advertising[idx]);
14293     }
14294 }
14295
14296 static void
14297 bxe_get_phy_info(struct bxe_softc *sc)
14298 {
14299     uint8_t port = SC_PORT(sc);
14300     uint32_t config = sc->port.config;
14301     uint32_t eee_mode;
14302
14303     /* shmem data already read in bxe_get_shmem_info() */
14304
14305     BLOGD(sc, DBG_LOAD, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14306                         "link_config0=0x%08x\n",
14307                sc->link_params.lane_config,
14308                sc->link_params.speed_cap_mask[0],
14309                sc->port.link_config[0]);
14310
14311     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14312     bxe_link_settings_requested(sc);
14313
14314     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14315         sc->link_params.feature_config_flags |=
14316             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14317     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14318         sc->link_params.feature_config_flags &=
14319             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14320     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14321         sc->link_params.feature_config_flags |=
14322             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14323     }
14324
14325     /* configure link feature according to nvram value */
14326     eee_mode =
14327         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14328           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14329          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14330     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14331         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14332                                     ELINK_EEE_MODE_ENABLE_LPI |
14333                                     ELINK_EEE_MODE_OUTPUT_TIME);
14334     } else {
14335         sc->link_params.eee_mode = 0;
14336     }
14337
14338     /* get the media type */
14339     bxe_media_detect(sc);
14340 }
14341
14342 static void
14343 bxe_get_params(struct bxe_softc *sc)
14344 {
14345     /* get user tunable params */
14346     bxe_get_tunable_params(sc);
14347
14348     /* select the RX and TX ring sizes */
14349     sc->tx_ring_size = TX_BD_USABLE;
14350     sc->rx_ring_size = RX_BD_USABLE;
14351
14352     /* XXX disable WoL */
14353     sc->wol = 0;
14354 }
14355
14356 static void
14357 bxe_set_modes_bitmap(struct bxe_softc *sc)
14358 {
14359     uint32_t flags = 0;
14360
14361     if (CHIP_REV_IS_FPGA(sc)) {
14362         SET_FLAGS(flags, MODE_FPGA);
14363     } else if (CHIP_REV_IS_EMUL(sc)) {
14364         SET_FLAGS(flags, MODE_EMUL);
14365     } else {
14366         SET_FLAGS(flags, MODE_ASIC);
14367     }
14368
14369     if (CHIP_IS_MODE_4_PORT(sc)) {
14370         SET_FLAGS(flags, MODE_PORT4);
14371     } else {
14372         SET_FLAGS(flags, MODE_PORT2);
14373     }
14374
14375     if (CHIP_IS_E2(sc)) {
14376         SET_FLAGS(flags, MODE_E2);
14377     } else if (CHIP_IS_E3(sc)) {
14378         SET_FLAGS(flags, MODE_E3);
14379         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14380             SET_FLAGS(flags, MODE_E3_A0);
14381         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14382             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14383         }
14384     }
14385
14386     if (IS_MF(sc)) {
14387         SET_FLAGS(flags, MODE_MF);
14388         switch (sc->devinfo.mf_info.mf_mode) {
14389         case MULTI_FUNCTION_SD:
14390             SET_FLAGS(flags, MODE_MF_SD);
14391             break;
14392         case MULTI_FUNCTION_SI:
14393             SET_FLAGS(flags, MODE_MF_SI);
14394             break;
14395         case MULTI_FUNCTION_AFEX:
14396             SET_FLAGS(flags, MODE_MF_AFEX);
14397             break;
14398         }
14399     } else {
14400         SET_FLAGS(flags, MODE_SF);
14401     }
14402
14403 #if defined(__LITTLE_ENDIAN)
14404     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14405 #else /* __BIG_ENDIAN */
14406     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14407 #endif
14408
14409     INIT_MODE_FLAGS(sc) = flags;
14410 }
14411
14412 static int
14413 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14414 {
14415     struct bxe_fastpath *fp;
14416     bus_addr_t busaddr;
14417     int max_agg_queues;
14418     int max_segments;
14419     bus_size_t max_size;
14420     bus_size_t max_seg_size;
14421     char buf[32];
14422     int rc;
14423     int i, j;
14424
14425     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14426
14427     /* allocate the parent bus DMA tag */
14428     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14429                             1,                        /* alignment */
14430                             0,                        /* boundary limit */
14431                             BUS_SPACE_MAXADDR,        /* restricted low */
14432                             BUS_SPACE_MAXADDR,        /* restricted hi */
14433                             NULL,                     /* addr filter() */
14434                             NULL,                     /* addr filter() arg */
14435                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14436                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14437                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14438                             0,                        /* flags */
14439                             NULL,                     /* lock() */
14440                             NULL,                     /* lock() arg */
14441                             &sc->parent_dma_tag);     /* returned dma tag */
14442     if (rc != 0) {
14443         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14444         return (1);
14445     }
14446
14447     /************************/
14448     /* DEFAULT STATUS BLOCK */
14449     /************************/
14450
14451     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14452                       &sc->def_sb_dma, "default status block") != 0) {
14453         /* XXX */
14454         bus_dma_tag_destroy(sc->parent_dma_tag);
14455         return (1);
14456     }
14457
14458     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14459
14460     /***************/
14461     /* EVENT QUEUE */
14462     /***************/
14463
14464     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14465                       &sc->eq_dma, "event queue") != 0) {
14466         /* XXX */
14467         bxe_dma_free(sc, &sc->def_sb_dma);
14468         sc->def_sb = NULL;
14469         bus_dma_tag_destroy(sc->parent_dma_tag);
14470         return (1);
14471     }
14472
14473     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14474
14475     /*************/
14476     /* SLOW PATH */
14477     /*************/
14478
14479     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14480                       &sc->sp_dma, "slow path") != 0) {
14481         /* XXX */
14482         bxe_dma_free(sc, &sc->eq_dma);
14483         sc->eq = NULL;
14484         bxe_dma_free(sc, &sc->def_sb_dma);
14485         sc->def_sb = NULL;
14486         bus_dma_tag_destroy(sc->parent_dma_tag);
14487         return (1);
14488     }
14489
14490     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14491
14492     /*******************/
14493     /* SLOW PATH QUEUE */
14494     /*******************/
14495
14496     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14497                       &sc->spq_dma, "slow path queue") != 0) {
14498         /* XXX */
14499         bxe_dma_free(sc, &sc->sp_dma);
14500         sc->sp = NULL;
14501         bxe_dma_free(sc, &sc->eq_dma);
14502         sc->eq = NULL;
14503         bxe_dma_free(sc, &sc->def_sb_dma);
14504         sc->def_sb = NULL;
14505         bus_dma_tag_destroy(sc->parent_dma_tag);
14506         return (1);
14507     }
14508
14509     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14510
14511     /***************************/
14512     /* FW DECOMPRESSION BUFFER */
14513     /***************************/
14514
14515     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14516                       "fw decompression buffer") != 0) {
14517         /* XXX */
14518         bxe_dma_free(sc, &sc->spq_dma);
14519         sc->spq = NULL;
14520         bxe_dma_free(sc, &sc->sp_dma);
14521         sc->sp = NULL;
14522         bxe_dma_free(sc, &sc->eq_dma);
14523         sc->eq = NULL;
14524         bxe_dma_free(sc, &sc->def_sb_dma);
14525         sc->def_sb = NULL;
14526         bus_dma_tag_destroy(sc->parent_dma_tag);
14527         return (1);
14528     }
14529
14530     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14531
14532     if ((sc->gz_strm =
14533          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14534         /* XXX */
14535         bxe_dma_free(sc, &sc->gz_buf_dma);
14536         sc->gz_buf = NULL;
14537         bxe_dma_free(sc, &sc->spq_dma);
14538         sc->spq = NULL;
14539         bxe_dma_free(sc, &sc->sp_dma);
14540         sc->sp = NULL;
14541         bxe_dma_free(sc, &sc->eq_dma);
14542         sc->eq = NULL;
14543         bxe_dma_free(sc, &sc->def_sb_dma);
14544         sc->def_sb = NULL;
14545         bus_dma_tag_destroy(sc->parent_dma_tag);
14546         return (1);
14547     }
14548
14549     /*************/
14550     /* FASTPATHS */
14551     /*************/
14552
14553     /* allocate DMA memory for each fastpath structure */
14554     for (i = 0; i < sc->num_queues; i++) {
14555         fp = &sc->fp[i];
14556         fp->sc    = sc;
14557         fp->index = i;
14558
14559         /*******************/
14560         /* FP STATUS BLOCK */
14561         /*******************/
14562
14563         snprintf(buf, sizeof(buf), "fp %d status block", i);
14564         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14565                           &fp->sb_dma, buf) != 0) {
14566             /* XXX unwind and free previous fastpath allocations */
14567             BLOGE(sc, "Failed to alloc %s\n", buf);
14568             return (1);
14569         } else {
14570             if (CHIP_IS_E2E3(sc)) {
14571                 fp->status_block.e2_sb =
14572                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14573             } else {
14574                 fp->status_block.e1x_sb =
14575                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14576             }
14577         }
14578
14579         /******************/
14580         /* FP TX BD CHAIN */
14581         /******************/
14582
14583         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14584         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14585                           &fp->tx_dma, buf) != 0) {
14586             /* XXX unwind and free previous fastpath allocations */
14587             BLOGE(sc, "Failed to alloc %s\n", buf);
14588             return (1);
14589         } else {
14590             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14591         }
14592
14593         /* link together the tx bd chain pages */
14594         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14595             /* index into the tx bd chain array to last entry per page */
14596             struct eth_tx_next_bd *tx_next_bd =
14597                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14598             /* point to the next page and wrap from last page */
14599             busaddr = (fp->tx_dma.paddr +
14600                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14601             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14602             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14603         }
14604
14605         /******************/
14606         /* FP RX BD CHAIN */
14607         /******************/
14608
14609         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14610         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14611                           &fp->rx_dma, buf) != 0) {
14612             /* XXX unwind and free previous fastpath allocations */
14613             BLOGE(sc, "Failed to alloc %s\n", buf);
14614             return (1);
14615         } else {
14616             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14617         }
14618
14619         /* link together the rx bd chain pages */
14620         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14621             /* index into the rx bd chain array to last entry per page */
14622             struct eth_rx_bd *rx_bd =
14623                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14624             /* point to the next page and wrap from last page */
14625             busaddr = (fp->rx_dma.paddr +
14626                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14627             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14628             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14629         }
14630
14631         /*******************/
14632         /* FP RX RCQ CHAIN */
14633         /*******************/
14634
14635         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14636         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14637                           &fp->rcq_dma, buf) != 0) {
14638             /* XXX unwind and free previous fastpath allocations */
14639             BLOGE(sc, "Failed to alloc %s\n", buf);
14640             return (1);
14641         } else {
14642             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14643         }
14644
14645         /* link together the rcq chain pages */
14646         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14647             /* index into the rcq chain array to last entry per page */
14648             struct eth_rx_cqe_next_page *rx_cqe_next =
14649                 (struct eth_rx_cqe_next_page *)
14650                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14651             /* point to the next page and wrap from last page */
14652             busaddr = (fp->rcq_dma.paddr +
14653                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14654             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14655             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14656         }
14657
14658         /*******************/
14659         /* FP RX SGE CHAIN */
14660         /*******************/
14661
14662         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14663         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14664                           &fp->rx_sge_dma, buf) != 0) {
14665             /* XXX unwind and free previous fastpath allocations */
14666             BLOGE(sc, "Failed to alloc %s\n", buf);
14667             return (1);
14668         } else {
14669             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14670         }
14671
14672         /* link together the sge chain pages */
14673         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14674             /* index into the rcq chain array to last entry per page */
14675             struct eth_rx_sge *rx_sge =
14676                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14677             /* point to the next page and wrap from last page */
14678             busaddr = (fp->rx_sge_dma.paddr +
14679                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14680             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14681             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14682         }
14683
14684         /***********************/
14685         /* FP TX MBUF DMA MAPS */
14686         /***********************/
14687
14688         /* set required sizes before mapping to conserve resources */
14689         if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
14690             max_size     = BXE_TSO_MAX_SIZE;
14691             max_segments = BXE_TSO_MAX_SEGMENTS;
14692             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14693         } else {
14694             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14695             max_segments = BXE_MAX_SEGMENTS;
14696             max_seg_size = MCLBYTES;
14697         }
14698
14699         /* create a dma tag for the tx mbufs */
14700         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14701                                 1,                  /* alignment */
14702                                 0,                  /* boundary limit */
14703                                 BUS_SPACE_MAXADDR,  /* restricted low */
14704                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14705                                 NULL,               /* addr filter() */
14706                                 NULL,               /* addr filter() arg */
14707                                 max_size,           /* max map size */
14708                                 max_segments,       /* num discontinuous */
14709                                 max_seg_size,       /* max seg size */
14710                                 0,                  /* flags */
14711                                 NULL,               /* lock() */
14712                                 NULL,               /* lock() arg */
14713                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14714         if (rc != 0) {
14715             /* XXX unwind and free previous fastpath allocations */
14716             BLOGE(sc, "Failed to create dma tag for "
14717                       "'fp %d tx mbufs' (%d)\n", i, rc);
14718             return (1);
14719         }
14720
14721         /* create dma maps for each of the tx mbuf clusters */
14722         for (j = 0; j < TX_BD_TOTAL; j++) {
14723             if (bus_dmamap_create(fp->tx_mbuf_tag,
14724                                   BUS_DMA_NOWAIT,
14725                                   &fp->tx_mbuf_chain[j].m_map)) {
14726                 /* XXX unwind and free previous fastpath allocations */
14727                 BLOGE(sc, "Failed to create dma map for "
14728                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14729                 return (1);
14730             }
14731         }
14732
14733         /***********************/
14734         /* FP RX MBUF DMA MAPS */
14735         /***********************/
14736
14737         /* create a dma tag for the rx mbufs */
14738         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14739                                 1,                  /* alignment */
14740                                 0,                  /* boundary limit */
14741                                 BUS_SPACE_MAXADDR,  /* restricted low */
14742                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14743                                 NULL,               /* addr filter() */
14744                                 NULL,               /* addr filter() arg */
14745                                 MJUM9BYTES,         /* max map size */
14746                                 1,                  /* num discontinuous */
14747                                 MJUM9BYTES,         /* max seg size */
14748                                 0,                  /* flags */
14749                                 NULL,               /* lock() */
14750                                 NULL,               /* lock() arg */
14751                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14752         if (rc != 0) {
14753             /* XXX unwind and free previous fastpath allocations */
14754             BLOGE(sc, "Failed to create dma tag for "
14755                       "'fp %d rx mbufs' (%d)\n", i, rc);
14756             return (1);
14757         }
14758
14759         /* create dma maps for each of the rx mbuf clusters */
14760         for (j = 0; j < RX_BD_TOTAL; j++) {
14761             if (bus_dmamap_create(fp->rx_mbuf_tag,
14762                                   BUS_DMA_NOWAIT,
14763                                   &fp->rx_mbuf_chain[j].m_map)) {
14764                 /* XXX unwind and free previous fastpath allocations */
14765                 BLOGE(sc, "Failed to create dma map for "
14766                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14767                 return (1);
14768             }
14769         }
14770
14771         /* create dma map for the spare rx mbuf cluster */
14772         if (bus_dmamap_create(fp->rx_mbuf_tag,
14773                               BUS_DMA_NOWAIT,
14774                               &fp->rx_mbuf_spare_map)) {
14775             /* XXX unwind and free previous fastpath allocations */
14776             BLOGE(sc, "Failed to create dma map for "
14777                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14778             return (1);
14779         }
14780
14781         /***************************/
14782         /* FP RX SGE MBUF DMA MAPS */
14783         /***************************/
14784
14785         /* create a dma tag for the rx sge mbufs */
14786         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14787                                 1,                  /* alignment */
14788                                 0,                  /* boundary limit */
14789                                 BUS_SPACE_MAXADDR,  /* restricted low */
14790                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14791                                 NULL,               /* addr filter() */
14792                                 NULL,               /* addr filter() arg */
14793                                 BCM_PAGE_SIZE,      /* max map size */
14794                                 1,                  /* num discontinuous */
14795                                 BCM_PAGE_SIZE,      /* max seg size */
14796                                 0,                  /* flags */
14797                                 NULL,               /* lock() */
14798                                 NULL,               /* lock() arg */
14799                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14800         if (rc != 0) {
14801             /* XXX unwind and free previous fastpath allocations */
14802             BLOGE(sc, "Failed to create dma tag for "
14803                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14804             return (1);
14805         }
14806
14807         /* create dma maps for the rx sge mbuf clusters */
14808         for (j = 0; j < RX_SGE_TOTAL; j++) {
14809             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14810                                   BUS_DMA_NOWAIT,
14811                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14812                 /* XXX unwind and free previous fastpath allocations */
14813                 BLOGE(sc, "Failed to create dma map for "
14814                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14815                 return (1);
14816             }
14817         }
14818
14819         /* create dma map for the spare rx sge mbuf cluster */
14820         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14821                               BUS_DMA_NOWAIT,
14822                               &fp->rx_sge_mbuf_spare_map)) {
14823             /* XXX unwind and free previous fastpath allocations */
14824             BLOGE(sc, "Failed to create dma map for "
14825                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14826             return (1);
14827         }
14828
14829         /***************************/
14830         /* FP RX TPA MBUF DMA MAPS */
14831         /***************************/
14832
14833         /* create dma maps for the rx tpa mbuf clusters */
14834         max_agg_queues = MAX_AGG_QS(sc);
14835
14836         for (j = 0; j < max_agg_queues; j++) {
14837             if (bus_dmamap_create(fp->rx_mbuf_tag,
14838                                   BUS_DMA_NOWAIT,
14839                                   &fp->rx_tpa_info[j].bd.m_map)) {
14840                 /* XXX unwind and free previous fastpath allocations */
14841                 BLOGE(sc, "Failed to create dma map for "
14842                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14843                 return (1);
14844             }
14845         }
14846
14847         /* create dma map for the spare rx tpa mbuf cluster */
14848         if (bus_dmamap_create(fp->rx_mbuf_tag,
14849                               BUS_DMA_NOWAIT,
14850                               &fp->rx_tpa_info_mbuf_spare_map)) {
14851             /* XXX unwind and free previous fastpath allocations */
14852             BLOGE(sc, "Failed to create dma map for "
14853                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14854             return (1);
14855         }
14856
14857         bxe_init_sge_ring_bit_mask(fp);
14858     }
14859
14860     return (0);
14861 }
14862
14863 static void
14864 bxe_free_hsi_mem(struct bxe_softc *sc)
14865 {
14866     struct bxe_fastpath *fp;
14867     int max_agg_queues;
14868     int i, j;
14869
14870     if (sc->parent_dma_tag == NULL) {
14871         return; /* assume nothing was allocated */
14872     }
14873
14874     for (i = 0; i < sc->num_queues; i++) {
14875         fp = &sc->fp[i];
14876
14877         /*******************/
14878         /* FP STATUS BLOCK */
14879         /*******************/
14880
14881         bxe_dma_free(sc, &fp->sb_dma);
14882         memset(&fp->status_block, 0, sizeof(fp->status_block));
14883
14884         /******************/
14885         /* FP TX BD CHAIN */
14886         /******************/
14887
14888         bxe_dma_free(sc, &fp->tx_dma);
14889         fp->tx_chain = NULL;
14890
14891         /******************/
14892         /* FP RX BD CHAIN */
14893         /******************/
14894
14895         bxe_dma_free(sc, &fp->rx_dma);
14896         fp->rx_chain = NULL;
14897
14898         /*******************/
14899         /* FP RX RCQ CHAIN */
14900         /*******************/
14901
14902         bxe_dma_free(sc, &fp->rcq_dma);
14903         fp->rcq_chain = NULL;
14904
14905         /*******************/
14906         /* FP RX SGE CHAIN */
14907         /*******************/
14908
14909         bxe_dma_free(sc, &fp->rx_sge_dma);
14910         fp->rx_sge_chain = NULL;
14911
14912         /***********************/
14913         /* FP TX MBUF DMA MAPS */
14914         /***********************/
14915
14916         if (fp->tx_mbuf_tag != NULL) {
14917             for (j = 0; j < TX_BD_TOTAL; j++) {
14918                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14919                     bus_dmamap_unload(fp->tx_mbuf_tag,
14920                                       fp->tx_mbuf_chain[j].m_map);
14921                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14922                                        fp->tx_mbuf_chain[j].m_map);
14923                 }
14924             }
14925
14926             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14927             fp->tx_mbuf_tag = NULL;
14928         }
14929
14930         /***********************/
14931         /* FP RX MBUF DMA MAPS */
14932         /***********************/
14933
14934         if (fp->rx_mbuf_tag != NULL) {
14935             for (j = 0; j < RX_BD_TOTAL; j++) {
14936                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14937                     bus_dmamap_unload(fp->rx_mbuf_tag,
14938                                       fp->rx_mbuf_chain[j].m_map);
14939                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14940                                        fp->rx_mbuf_chain[j].m_map);
14941                 }
14942             }
14943
14944             if (fp->rx_mbuf_spare_map != NULL) {
14945                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14946                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14947             }
14948
14949             /***************************/
14950             /* FP RX TPA MBUF DMA MAPS */
14951             /***************************/
14952
14953             max_agg_queues = MAX_AGG_QS(sc);
14954
14955             for (j = 0; j < max_agg_queues; j++) {
14956                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14957                     bus_dmamap_unload(fp->rx_mbuf_tag,
14958                                       fp->rx_tpa_info[j].bd.m_map);
14959                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14960                                        fp->rx_tpa_info[j].bd.m_map);
14961                 }
14962             }
14963
14964             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14965                 bus_dmamap_unload(fp->rx_mbuf_tag,
14966                                   fp->rx_tpa_info_mbuf_spare_map);
14967                 bus_dmamap_destroy(fp->rx_mbuf_tag,
14968                                    fp->rx_tpa_info_mbuf_spare_map);
14969             }
14970
14971             bus_dma_tag_destroy(fp->rx_mbuf_tag);
14972             fp->rx_mbuf_tag = NULL;
14973         }
14974
14975         /***************************/
14976         /* FP RX SGE MBUF DMA MAPS */
14977         /***************************/
14978
14979         if (fp->rx_sge_mbuf_tag != NULL) {
14980             for (j = 0; j < RX_SGE_TOTAL; j++) {
14981                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14982                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14983                                       fp->rx_sge_mbuf_chain[j].m_map);
14984                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14985                                        fp->rx_sge_mbuf_chain[j].m_map);
14986                 }
14987             }
14988
14989             if (fp->rx_sge_mbuf_spare_map != NULL) {
14990                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14991                                   fp->rx_sge_mbuf_spare_map);
14992                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14993                                    fp->rx_sge_mbuf_spare_map);
14994             }
14995
14996             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
14997             fp->rx_sge_mbuf_tag = NULL;
14998         }
14999     }
15000
15001     /***************************/
15002     /* FW DECOMPRESSION BUFFER */
15003     /***************************/
15004
15005     bxe_dma_free(sc, &sc->gz_buf_dma);
15006     sc->gz_buf = NULL;
15007     free(sc->gz_strm, M_DEVBUF);
15008     sc->gz_strm = NULL;
15009
15010     /*******************/
15011     /* SLOW PATH QUEUE */
15012     /*******************/
15013
15014     bxe_dma_free(sc, &sc->spq_dma);
15015     sc->spq = NULL;
15016
15017     /*************/
15018     /* SLOW PATH */
15019     /*************/
15020
15021     bxe_dma_free(sc, &sc->sp_dma);
15022     sc->sp = NULL;
15023
15024     /***************/
15025     /* EVENT QUEUE */
15026     /***************/
15027
15028     bxe_dma_free(sc, &sc->eq_dma);
15029     sc->eq = NULL;
15030
15031     /************************/
15032     /* DEFAULT STATUS BLOCK */
15033     /************************/
15034
15035     bxe_dma_free(sc, &sc->def_sb_dma);
15036     sc->def_sb = NULL;
15037
15038     bus_dma_tag_destroy(sc->parent_dma_tag);
15039     sc->parent_dma_tag = NULL;
15040 }
15041
15042 /*
15043  * Previous driver DMAE transaction may have occurred when pre-boot stage
15044  * ended and boot began. This would invalidate the addresses of the
15045  * transaction, resulting in was-error bit set in the PCI causing all
15046  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15047  * the interrupt which detected this from the pglueb and the was-done bit
15048  */
15049 static void
15050 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15051 {
15052     uint32_t val;
15053
15054     if (!CHIP_IS_E1x(sc)) {
15055         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15056         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15057             BLOGD(sc, DBG_LOAD,
15058                   "Clearing 'was-error' bit that was set in pglueb");
15059             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15060         }
15061     }
15062 }
15063
15064 static int
15065 bxe_prev_mcp_done(struct bxe_softc *sc)
15066 {
15067     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15068                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15069     if (!rc) {
15070         BLOGE(sc, "MCP response failure, aborting\n");
15071         return (-1);
15072     }
15073
15074     return (0);
15075 }
15076
15077 static struct bxe_prev_list_node *
15078 bxe_prev_path_get_entry(struct bxe_softc *sc)
15079 {
15080     struct bxe_prev_list_node *tmp;
15081
15082     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15083         if ((sc->pcie_bus == tmp->bus) &&
15084             (sc->pcie_device == tmp->slot) &&
15085             (SC_PATH(sc) == tmp->path)) {
15086             return (tmp);
15087         }
15088     }
15089
15090     return (NULL);
15091 }
15092
15093 static uint8_t
15094 bxe_prev_is_path_marked(struct bxe_softc *sc)
15095 {
15096     struct bxe_prev_list_node *tmp;
15097     int rc = FALSE;
15098
15099     mtx_lock(&bxe_prev_mtx);
15100
15101     tmp = bxe_prev_path_get_entry(sc);
15102     if (tmp) {
15103         if (tmp->aer) {
15104             BLOGD(sc, DBG_LOAD,
15105                   "Path %d/%d/%d was marked by AER\n",
15106                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15107         } else {
15108             rc = TRUE;
15109             BLOGD(sc, DBG_LOAD,
15110                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15111                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15112         }
15113     }
15114
15115     mtx_unlock(&bxe_prev_mtx);
15116
15117     return (rc);
15118 }
15119
15120 static int
15121 bxe_prev_mark_path(struct bxe_softc *sc,
15122                    uint8_t          after_undi)
15123 {
15124     struct bxe_prev_list_node *tmp;
15125
15126     mtx_lock(&bxe_prev_mtx);
15127
15128     /* Check whether the entry for this path already exists */
15129     tmp = bxe_prev_path_get_entry(sc);
15130     if (tmp) {
15131         if (!tmp->aer) {
15132             BLOGD(sc, DBG_LOAD,
15133                   "Re-marking AER in path %d/%d/%d\n",
15134                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15135         } else {
15136             BLOGD(sc, DBG_LOAD,
15137                   "Removing AER indication from path %d/%d/%d\n",
15138                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15139             tmp->aer = 0;
15140         }
15141
15142         mtx_unlock(&bxe_prev_mtx);
15143         return (0);
15144     }
15145
15146     mtx_unlock(&bxe_prev_mtx);
15147
15148     /* Create an entry for this path and add it */
15149     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15150                  (M_NOWAIT | M_ZERO));
15151     if (!tmp) {
15152         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15153         return (-1);
15154     }
15155
15156     tmp->bus  = sc->pcie_bus;
15157     tmp->slot = sc->pcie_device;
15158     tmp->path = SC_PATH(sc);
15159     tmp->aer  = 0;
15160     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15161
15162     mtx_lock(&bxe_prev_mtx);
15163
15164     BLOGD(sc, DBG_LOAD,
15165           "Marked path %d/%d/%d - finished previous unload\n",
15166           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15167     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15168
15169     mtx_unlock(&bxe_prev_mtx);
15170
15171     return (0);
15172 }
15173
15174 static int
15175 bxe_do_flr(struct bxe_softc *sc)
15176 {
15177     int i;
15178
15179     /* only E2 and onwards support FLR */
15180     if (CHIP_IS_E1x(sc)) {
15181         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15182         return (-1);
15183     }
15184
15185     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15186     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15187         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15188               sc->devinfo.bc_ver);
15189         return (-1);
15190     }
15191
15192     /* Wait for Transaction Pending bit clean */
15193     for (i = 0; i < 4; i++) {
15194         if (i) {
15195             DELAY(((1 << (i - 1)) * 100) * 1000);
15196         }
15197
15198         if (!bxe_is_pcie_pending(sc)) {
15199             goto clear;
15200         }
15201     }
15202
15203     BLOGE(sc, "PCIE transaction is not cleared, "
15204               "proceeding with reset anyway\n");
15205
15206 clear:
15207
15208     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15209     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15210
15211     return (0);
15212 }
15213
15214 struct bxe_mac_vals {
15215     uint32_t xmac_addr;
15216     uint32_t xmac_val;
15217     uint32_t emac_addr;
15218     uint32_t emac_val;
15219     uint32_t umac_addr;
15220     uint32_t umac_val;
15221     uint32_t bmac_addr;
15222     uint32_t bmac_val[2];
15223 };
15224
15225 static void
15226 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15227                           struct bxe_mac_vals *vals)
15228 {
15229     uint32_t val, base_addr, offset, mask, reset_reg;
15230     uint8_t mac_stopped = FALSE;
15231     uint8_t port = SC_PORT(sc);
15232     uint32_t wb_data[2];
15233
15234     /* reset addresses as they also mark which values were changed */
15235     vals->bmac_addr = 0;
15236     vals->umac_addr = 0;
15237     vals->xmac_addr = 0;
15238     vals->emac_addr = 0;
15239
15240     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15241
15242     if (!CHIP_IS_E3(sc)) {
15243         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15244         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15245         if ((mask & reset_reg) && val) {
15246             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15247             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15248                                     : NIG_REG_INGRESS_BMAC0_MEM;
15249             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15250                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15251
15252             /*
15253              * use rd/wr since we cannot use dmae. This is safe
15254              * since MCP won't access the bus due to the request
15255              * to unload, and no function on the path can be
15256              * loaded at this time.
15257              */
15258             wb_data[0] = REG_RD(sc, base_addr + offset);
15259             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15260             vals->bmac_addr = base_addr + offset;
15261             vals->bmac_val[0] = wb_data[0];
15262             vals->bmac_val[1] = wb_data[1];
15263             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15264             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15265             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15266         }
15267
15268         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15269         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15270         vals->emac_val = REG_RD(sc, vals->emac_addr);
15271         REG_WR(sc, vals->emac_addr, 0);
15272         mac_stopped = TRUE;
15273     } else {
15274         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15275             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15276             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15277             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15278             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15279             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15280             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15281             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15282             REG_WR(sc, vals->xmac_addr, 0);
15283             mac_stopped = TRUE;
15284         }
15285
15286         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15287         if (mask & reset_reg) {
15288             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15289             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15290             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15291             vals->umac_val = REG_RD(sc, vals->umac_addr);
15292             REG_WR(sc, vals->umac_addr, 0);
15293             mac_stopped = TRUE;
15294         }
15295     }
15296
15297     if (mac_stopped) {
15298         DELAY(20000);
15299     }
15300 }
15301
15302 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15303 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15304 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15305 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15306
15307 static void
15308 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15309                          uint8_t          port,
15310                          uint8_t          inc)
15311 {
15312     uint16_t rcq, bd;
15313     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15314
15315     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15316     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15317
15318     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15319     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15320
15321     BLOGD(sc, DBG_LOAD,
15322           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15323           port, bd, rcq);
15324 }
15325
15326 static int
15327 bxe_prev_unload_common(struct bxe_softc *sc)
15328 {
15329     uint32_t reset_reg, tmp_reg = 0, rc;
15330     uint8_t prev_undi = FALSE;
15331     struct bxe_mac_vals mac_vals;
15332     uint32_t timer_count = 1000;
15333     uint32_t prev_brb;
15334
15335     /*
15336      * It is possible a previous function received 'common' answer,
15337      * but hasn't loaded yet, therefore creating a scenario of
15338      * multiple functions receiving 'common' on the same path.
15339      */
15340     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15341
15342     memset(&mac_vals, 0, sizeof(mac_vals));
15343
15344     if (bxe_prev_is_path_marked(sc)) {
15345         return (bxe_prev_mcp_done(sc));
15346     }
15347
15348     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15349
15350     /* Reset should be performed after BRB is emptied */
15351     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15352         /* Close the MAC Rx to prevent BRB from filling up */
15353         bxe_prev_unload_close_mac(sc, &mac_vals);
15354
15355         /* close LLH filters towards the BRB */
15356         elink_set_rx_filter(&sc->link_params, 0);
15357
15358         /*
15359          * Check if the UNDI driver was previously loaded.
15360          * UNDI driver initializes CID offset for normal bell to 0x7
15361          */
15362         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15363             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15364             if (tmp_reg == 0x7) {
15365                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15366                 prev_undi = TRUE;
15367                 /* clear the UNDI indication */
15368                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15369                 /* clear possible idle check errors */
15370                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15371             }
15372         }
15373
15374         /* wait until BRB is empty */
15375         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15376         while (timer_count) {
15377             prev_brb = tmp_reg;
15378
15379             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15380             if (!tmp_reg) {
15381                 break;
15382             }
15383
15384             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15385
15386             /* reset timer as long as BRB actually gets emptied */
15387             if (prev_brb > tmp_reg) {
15388                 timer_count = 1000;
15389             } else {
15390                 timer_count--;
15391             }
15392
15393             /* If UNDI resides in memory, manually increment it */
15394             if (prev_undi) {
15395                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15396             }
15397
15398             DELAY(10);
15399         }
15400
15401         if (!timer_count) {
15402             BLOGE(sc, "Failed to empty BRB\n");
15403         }
15404     }
15405
15406     /* No packets are in the pipeline, path is ready for reset */
15407     bxe_reset_common(sc);
15408
15409     if (mac_vals.xmac_addr) {
15410         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15411     }
15412     if (mac_vals.umac_addr) {
15413         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15414     }
15415     if (mac_vals.emac_addr) {
15416         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15417     }
15418     if (mac_vals.bmac_addr) {
15419         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15420         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15421     }
15422
15423     rc = bxe_prev_mark_path(sc, prev_undi);
15424     if (rc) {
15425         bxe_prev_mcp_done(sc);
15426         return (rc);
15427     }
15428
15429     return (bxe_prev_mcp_done(sc));
15430 }
15431
15432 static int
15433 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15434 {
15435     int rc;
15436
15437     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15438
15439     /* Test if previous unload process was already finished for this path */
15440     if (bxe_prev_is_path_marked(sc)) {
15441         return (bxe_prev_mcp_done(sc));
15442     }
15443
15444     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15445
15446     /*
15447      * If function has FLR capabilities, and existing FW version matches
15448      * the one required, then FLR will be sufficient to clean any residue
15449      * left by previous driver
15450      */
15451     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15452     if (!rc) {
15453         /* fw version is good */
15454         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15455         rc = bxe_do_flr(sc);
15456     }
15457
15458     if (!rc) {
15459         /* FLR was performed */
15460         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15461         return (0);
15462     }
15463
15464     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15465
15466     /* Close the MCP request, return failure*/
15467     rc = bxe_prev_mcp_done(sc);
15468     if (!rc) {
15469         rc = BXE_PREV_WAIT_NEEDED;
15470     }
15471
15472     return (rc);
15473 }
15474
15475 static int
15476 bxe_prev_unload(struct bxe_softc *sc)
15477 {
15478     int time_counter = 10;
15479     uint32_t fw, hw_lock_reg, hw_lock_val;
15480     uint32_t rc = 0;
15481
15482     /*
15483      * Clear HW from errors which may have resulted from an interrupted
15484      * DMAE transaction.
15485      */
15486     bxe_prev_interrupted_dmae(sc);
15487
15488     /* Release previously held locks */
15489     hw_lock_reg =
15490         (SC_FUNC(sc) <= 5) ?
15491             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15492             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15493
15494     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15495     if (hw_lock_val) {
15496         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15497             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15498             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15499                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15500         }
15501         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15502         REG_WR(sc, hw_lock_reg, 0xffffffff);
15503     } else {
15504         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15505     }
15506
15507     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15508         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15509         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15510     }
15511
15512     do {
15513         /* Lock MCP using an unload request */
15514         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15515         if (!fw) {
15516             BLOGE(sc, "MCP response failure, aborting\n");
15517             rc = -1;
15518             break;
15519         }
15520
15521         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15522             rc = bxe_prev_unload_common(sc);
15523             break;
15524         }
15525
15526         /* non-common reply from MCP night require looping */
15527         rc = bxe_prev_unload_uncommon(sc);
15528         if (rc != BXE_PREV_WAIT_NEEDED) {
15529             break;
15530         }
15531
15532         DELAY(20000);
15533     } while (--time_counter);
15534
15535     if (!time_counter || rc) {
15536         BLOGE(sc, "Failed to unload previous driver!"
15537             " time_counter %d rc %d\n", time_counter, rc);
15538         rc = -1;
15539     }
15540
15541     return (rc);
15542 }
15543
15544 void
15545 bxe_dcbx_set_state(struct bxe_softc *sc,
15546                    uint8_t          dcb_on,
15547                    uint32_t         dcbx_enabled)
15548 {
15549     if (!CHIP_IS_E1x(sc)) {
15550         sc->dcb_state = dcb_on;
15551         sc->dcbx_enabled = dcbx_enabled;
15552     } else {
15553         sc->dcb_state = FALSE;
15554         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15555     }
15556     BLOGD(sc, DBG_LOAD,
15557           "DCB state [%s:%s]\n",
15558           dcb_on ? "ON" : "OFF",
15559           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15560           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15561           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15562           "on-chip with negotiation" : "invalid");
15563 }
15564
15565 /* must be called after sriov-enable */
15566 static int
15567 bxe_set_qm_cid_count(struct bxe_softc *sc)
15568 {
15569     int cid_count = BXE_L2_MAX_CID(sc);
15570
15571     if (IS_SRIOV(sc)) {
15572         cid_count += BXE_VF_CIDS;
15573     }
15574
15575     if (CNIC_SUPPORT(sc)) {
15576         cid_count += CNIC_CID_MAX;
15577     }
15578
15579     return (roundup(cid_count, QM_CID_ROUND));
15580 }
15581
15582 static void
15583 bxe_init_multi_cos(struct bxe_softc *sc)
15584 {
15585     int pri, cos;
15586
15587     uint32_t pri_map = 0; /* XXX change to user config */
15588
15589     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15590         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15591         if (cos < sc->max_cos) {
15592             sc->prio_to_cos[pri] = cos;
15593         } else {
15594             BLOGW(sc, "Invalid COS %d for priority %d "
15595                       "(max COS is %d), setting to 0\n",
15596                   cos, pri, (sc->max_cos - 1));
15597             sc->prio_to_cos[pri] = 0;
15598         }
15599     }
15600 }
15601
15602 static int
15603 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15604 {
15605     struct bxe_softc *sc;
15606     int error, result;
15607
15608     result = 0;
15609     error = sysctl_handle_int(oidp, &result, 0, req);
15610
15611     if (error || !req->newptr) {
15612         return (error);
15613     }
15614
15615     if (result == 1) {
15616         uint32_t  temp;
15617         sc = (struct bxe_softc *)arg1;
15618
15619         BLOGI(sc, "... dumping driver state ...\n");
15620         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15621         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15622     }
15623
15624     return (error);
15625 }
15626
15627 static int
15628 bxe_sysctl_trigger_grcdump(SYSCTL_HANDLER_ARGS)
15629 {
15630     struct bxe_softc *sc;
15631     int error, result;
15632
15633     result = 0;
15634     error = sysctl_handle_int(oidp, &result, 0, req);
15635
15636     if (error || !req->newptr) {
15637         return (error);
15638     }
15639
15640     if (result == 1) {
15641         sc = (struct bxe_softc *)arg1;
15642
15643         BLOGI(sc, "... grcdump start ...\n");
15644         bxe_grc_dump(sc);
15645         BLOGI(sc, "... grcdump done ...\n");
15646     }
15647
15648     return (error);
15649 }
15650
15651 static int
15652 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15653 {
15654     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15655     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15656     uint32_t *offset;
15657     uint64_t value = 0;
15658     int index = (int)arg2;
15659
15660     if (index >= BXE_NUM_ETH_STATS) {
15661         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15662         return (-1);
15663     }
15664
15665     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15666
15667     switch (bxe_eth_stats_arr[index].size) {
15668     case 4:
15669         value = (uint64_t)*offset;
15670         break;
15671     case 8:
15672         value = HILO_U64(*offset, *(offset + 1));
15673         break;
15674     default:
15675         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15676               index, bxe_eth_stats_arr[index].size);
15677         return (-1);
15678     }
15679
15680     return (sysctl_handle_64(oidp, &value, 0, req));
15681 }
15682
15683 static int
15684 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15685 {
15686     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15687     uint32_t *eth_stats;
15688     uint32_t *offset;
15689     uint64_t value = 0;
15690     uint32_t q_stat = (uint32_t)arg2;
15691     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15692     uint32_t index = (q_stat & 0xffff);
15693
15694     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15695
15696     if (index >= BXE_NUM_ETH_Q_STATS) {
15697         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15698         return (-1);
15699     }
15700
15701     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15702
15703     switch (bxe_eth_q_stats_arr[index].size) {
15704     case 4:
15705         value = (uint64_t)*offset;
15706         break;
15707     case 8:
15708         value = HILO_U64(*offset, *(offset + 1));
15709         break;
15710     default:
15711         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15712               index, bxe_eth_q_stats_arr[index].size);
15713         return (-1);
15714     }
15715
15716     return (sysctl_handle_64(oidp, &value, 0, req));
15717 }
15718
15719 static void
15720 bxe_add_sysctls(struct bxe_softc *sc)
15721 {
15722     struct sysctl_ctx_list *ctx;
15723     struct sysctl_oid_list *children;
15724     struct sysctl_oid *queue_top, *queue;
15725     struct sysctl_oid_list *queue_top_children, *queue_children;
15726     char queue_num_buf[32];
15727     uint32_t q_stat;
15728     int i, j;
15729
15730     ctx = device_get_sysctl_ctx(sc->dev);
15731     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15732
15733     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15734                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15735                       "version");
15736
15737     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15738              BCM_5710_FW_MAJOR_VERSION,
15739              BCM_5710_FW_MINOR_VERSION,
15740              BCM_5710_FW_REVISION_VERSION,
15741              BCM_5710_FW_ENGINEERING_VERSION);
15742
15743     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15744         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15745          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15746          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15747          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15748                                                                 "Unknown"));
15749     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15750                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15751                     "multifunction vnics per port");
15752
15753     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15754         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15755          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15756          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15757                                               "???GT/s"),
15758         sc->devinfo.pcie_link_width);
15759
15760     sc->debug = bxe_debug;
15761
15762 #if __FreeBSD_version >= 900000
15763     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15764                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15765                       "bootcode version");
15766     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15767                       CTLFLAG_RD, sc->fw_ver_str, 0,
15768                       "firmware version");
15769     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15770                       CTLFLAG_RD, sc->mf_mode_str, 0,
15771                       "multifunction mode");
15772     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15773                       CTLFLAG_RD, sc->mac_addr_str, 0,
15774                       "mac address");
15775     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15776                       CTLFLAG_RD, &sc->pci_link_str, 0,
15777                       "pci link status");
15778     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15779                     CTLFLAG_RW, &sc->debug, 0,
15780                     "debug logging mode");
15781 #else
15782     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15783                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15784                       "bootcode version");
15785     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15786                       CTLFLAG_RD, &sc->fw_ver_str, 0,
15787                       "firmware version");
15788     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15789                       CTLFLAG_RD, &sc->mf_mode_str, 0,
15790                       "multifunction mode");
15791     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15792                       CTLFLAG_RD, &sc->mac_addr_str, 0,
15793                       "mac address");
15794     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15795                       CTLFLAG_RD, &sc->pci_link_str, 0,
15796                       "pci link status");
15797     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15798                     CTLFLAG_RW, &sc->debug, 0,
15799                     "debug logging mode");
15800 #endif /* #if __FreeBSD_version >= 900000 */
15801
15802     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "trigger_grcdump",
15803                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15804                     bxe_sysctl_trigger_grcdump, "IU",
15805                     "set by driver when a grcdump is needed");
15806
15807     sc->grcdump_done = 0;
15808     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15809                    CTLFLAG_RW, &sc->grcdump_done, 0,
15810                    "set by driver when grcdump is done");
15811
15812     sc->rx_budget = bxe_rx_budget;
15813     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15814                     CTLFLAG_RW, &sc->rx_budget, 0,
15815                     "rx processing budget");
15816
15817     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15818                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15819                     bxe_sysctl_state, "IU", "dump driver state");
15820
15821     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15822         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15823                         bxe_eth_stats_arr[i].string,
15824                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15825                         bxe_sysctl_eth_stat, "LU",
15826                         bxe_eth_stats_arr[i].string);
15827     }
15828
15829     /* add a new parent node for all queues "dev.bxe.#.queue" */
15830     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15831                                 CTLFLAG_RD, NULL, "queue");
15832     queue_top_children = SYSCTL_CHILDREN(queue_top);
15833
15834     for (i = 0; i < sc->num_queues; i++) {
15835         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15836         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15837         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15838                                 queue_num_buf, CTLFLAG_RD, NULL,
15839                                 "single queue");
15840         queue_children = SYSCTL_CHILDREN(queue);
15841
15842         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15843             q_stat = ((i << 16) | j);
15844             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15845                             bxe_eth_q_stats_arr[j].string,
15846                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15847                             bxe_sysctl_eth_q_stat, "LU",
15848                             bxe_eth_q_stats_arr[j].string);
15849         }
15850     }
15851 }
15852
15853 static int
15854 bxe_alloc_buf_rings(struct bxe_softc *sc)
15855 {
15856 #if __FreeBSD_version >= 800000
15857
15858     int i;
15859     struct bxe_fastpath *fp;
15860
15861     for (i = 0; i < sc->num_queues; i++) {
15862
15863         fp = &sc->fp[i];
15864
15865         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15866                                    M_NOWAIT, &fp->tx_mtx);
15867         if (fp->tx_br == NULL)
15868             return (-1);
15869     }
15870 #endif
15871     return (0);
15872 }
15873
15874 static void
15875 bxe_free_buf_rings(struct bxe_softc *sc)
15876 {
15877 #if __FreeBSD_version >= 800000
15878
15879     int i;
15880     struct bxe_fastpath *fp;
15881
15882     for (i = 0; i < sc->num_queues; i++) {
15883
15884         fp = &sc->fp[i];
15885
15886         if (fp->tx_br) {
15887             buf_ring_free(fp->tx_br, M_DEVBUF);
15888             fp->tx_br = NULL;
15889         }
15890     }
15891
15892 #endif
15893 }
15894
15895 static void
15896 bxe_init_fp_mutexs(struct bxe_softc *sc)
15897 {
15898     int i;
15899     struct bxe_fastpath *fp;
15900
15901     for (i = 0; i < sc->num_queues; i++) {
15902
15903         fp = &sc->fp[i];
15904
15905         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15906             "bxe%d_fp%d_tx_lock", sc->unit, i);
15907         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15908
15909         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15910             "bxe%d_fp%d_rx_lock", sc->unit, i);
15911         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15912     }
15913 }
15914
15915 static void
15916 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15917 {
15918     int i;
15919     struct bxe_fastpath *fp;
15920
15921     for (i = 0; i < sc->num_queues; i++) {
15922
15923         fp = &sc->fp[i];
15924
15925         if (mtx_initialized(&fp->tx_mtx)) {
15926             mtx_destroy(&fp->tx_mtx);
15927         }
15928
15929         if (mtx_initialized(&fp->rx_mtx)) {
15930             mtx_destroy(&fp->rx_mtx);
15931         }
15932     }
15933 }
15934
15935
15936 /*
15937  * Device attach function.
15938  *
15939  * Allocates device resources, performs secondary chip identification, and
15940  * initializes driver instance variables. This function is called from driver
15941  * load after a successful probe.
15942  *
15943  * Returns:
15944  *   0 = Success, >0 = Failure
15945  */
15946 static int
15947 bxe_attach(device_t dev)
15948 {
15949     struct bxe_softc *sc;
15950
15951     sc = device_get_softc(dev);
15952
15953     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15954
15955     sc->state = BXE_STATE_CLOSED;
15956
15957     sc->dev  = dev;
15958     sc->unit = device_get_unit(dev);
15959
15960     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
15961
15962     sc->pcie_bus    = pci_get_bus(dev);
15963     sc->pcie_device = pci_get_slot(dev);
15964     sc->pcie_func   = pci_get_function(dev);
15965
15966     /* enable bus master capability */
15967     pci_enable_busmaster(dev);
15968
15969     /* get the BARs */
15970     if (bxe_allocate_bars(sc) != 0) {
15971         return (ENXIO);
15972     }
15973
15974     /* initialize the mutexes */
15975     bxe_init_mutexes(sc);
15976
15977     /* prepare the periodic callout */
15978     callout_init(&sc->periodic_callout, 0);
15979
15980     /* prepare the chip taskqueue */
15981     sc->chip_tq_flags = CHIP_TQ_NONE;
15982     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
15983              "bxe%d_chip_tq", sc->unit);
15984     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
15985     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
15986                                    taskqueue_thread_enqueue,
15987                                    &sc->chip_tq);
15988     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
15989                             "%s", sc->chip_tq_name);
15990
15991     /* get device info and set params */
15992     if (bxe_get_device_info(sc) != 0) {
15993         BLOGE(sc, "getting device info\n");
15994         bxe_deallocate_bars(sc);
15995         pci_disable_busmaster(dev);
15996         return (ENXIO);
15997     }
15998
15999     /* get final misc params */
16000     bxe_get_params(sc);
16001
16002     /* set the default MTU (changed via ifconfig) */
16003     sc->mtu = ETHERMTU;
16004
16005     bxe_set_modes_bitmap(sc);
16006
16007     /* XXX
16008      * If in AFEX mode and the function is configured for FCoE
16009      * then bail... no L2 allowed.
16010      */
16011
16012     /* get phy settings from shmem and 'and' against admin settings */
16013     bxe_get_phy_info(sc);
16014
16015     /* initialize the FreeBSD ifnet interface */
16016     if (bxe_init_ifnet(sc) != 0) {
16017         bxe_release_mutexes(sc);
16018         bxe_deallocate_bars(sc);
16019         pci_disable_busmaster(dev);
16020         return (ENXIO);
16021     }
16022
16023     if (bxe_add_cdev(sc) != 0) {
16024         if (sc->ifnet != NULL) {
16025             ether_ifdetach(sc->ifnet);
16026         }
16027         ifmedia_removeall(&sc->ifmedia);
16028         bxe_release_mutexes(sc);
16029         bxe_deallocate_bars(sc);
16030         pci_disable_busmaster(dev);
16031         return (ENXIO);
16032     }
16033
16034     /* allocate device interrupts */
16035     if (bxe_interrupt_alloc(sc) != 0) {
16036         bxe_del_cdev(sc);
16037         if (sc->ifnet != NULL) {
16038             ether_ifdetach(sc->ifnet);
16039         }
16040         ifmedia_removeall(&sc->ifmedia);
16041         bxe_release_mutexes(sc);
16042         bxe_deallocate_bars(sc);
16043         pci_disable_busmaster(dev);
16044         return (ENXIO);
16045     }
16046
16047     bxe_init_fp_mutexs(sc);
16048
16049     if (bxe_alloc_buf_rings(sc) != 0) {
16050         bxe_free_buf_rings(sc);
16051         bxe_interrupt_free(sc);
16052         bxe_del_cdev(sc);
16053         if (sc->ifnet != NULL) {
16054             ether_ifdetach(sc->ifnet);
16055         }
16056         ifmedia_removeall(&sc->ifmedia);
16057         bxe_release_mutexes(sc);
16058         bxe_deallocate_bars(sc);
16059         pci_disable_busmaster(dev);
16060         return (ENXIO);
16061     }
16062
16063     /* allocate ilt */
16064     if (bxe_alloc_ilt_mem(sc) != 0) {
16065         bxe_free_buf_rings(sc);
16066         bxe_interrupt_free(sc);
16067         bxe_del_cdev(sc);
16068         if (sc->ifnet != NULL) {
16069             ether_ifdetach(sc->ifnet);
16070         }
16071         ifmedia_removeall(&sc->ifmedia);
16072         bxe_release_mutexes(sc);
16073         bxe_deallocate_bars(sc);
16074         pci_disable_busmaster(dev);
16075         return (ENXIO);
16076     }
16077
16078     /* allocate the host hardware/software hsi structures */
16079     if (bxe_alloc_hsi_mem(sc) != 0) {
16080         bxe_free_ilt_mem(sc);
16081         bxe_free_buf_rings(sc);
16082         bxe_interrupt_free(sc);
16083         bxe_del_cdev(sc);
16084         if (sc->ifnet != NULL) {
16085             ether_ifdetach(sc->ifnet);
16086         }
16087         ifmedia_removeall(&sc->ifmedia);
16088         bxe_release_mutexes(sc);
16089         bxe_deallocate_bars(sc);
16090         pci_disable_busmaster(dev);
16091         return (ENXIO);
16092     }
16093
16094     /* need to reset chip if UNDI was active */
16095     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16096         /* init fw_seq */
16097         sc->fw_seq =
16098             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16099              DRV_MSG_SEQ_NUMBER_MASK);
16100         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16101         bxe_prev_unload(sc);
16102     }
16103
16104 #if 1
16105     /* XXX */
16106     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16107 #else
16108     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16109         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16110         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16111         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16112         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16113         bxe_dcbx_init_params(sc);
16114     } else {
16115         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16116     }
16117 #endif
16118
16119     /* calculate qm_cid_count */
16120     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16121     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16122
16123     sc->max_cos = 1;
16124     bxe_init_multi_cos(sc);
16125
16126     bxe_add_sysctls(sc);
16127
16128     return (0);
16129 }
16130
16131 /*
16132  * Device detach function.
16133  *
16134  * Stops the controller, resets the controller, and releases resources.
16135  *
16136  * Returns:
16137  *   0 = Success, >0 = Failure
16138  */
16139 static int
16140 bxe_detach(device_t dev)
16141 {
16142     struct bxe_softc *sc;
16143     struct ifnet *ifp;
16144
16145     sc = device_get_softc(dev);
16146
16147     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16148
16149     ifp = sc->ifnet;
16150     if (ifp != NULL && ifp->if_vlantrunk != NULL) {
16151         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16152         return(EBUSY);
16153     }
16154
16155     bxe_del_cdev(sc);
16156
16157     /* stop the periodic callout */
16158     bxe_periodic_stop(sc);
16159
16160     /* stop the chip taskqueue */
16161     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16162     if (sc->chip_tq) {
16163         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16164         taskqueue_free(sc->chip_tq);
16165         sc->chip_tq = NULL;
16166     }
16167
16168     /* stop and reset the controller if it was open */
16169     if (sc->state != BXE_STATE_CLOSED) {
16170         BXE_CORE_LOCK(sc);
16171         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16172         BXE_CORE_UNLOCK(sc);
16173     }
16174
16175     /* release the network interface */
16176     if (ifp != NULL) {
16177         ether_ifdetach(ifp);
16178     }
16179     ifmedia_removeall(&sc->ifmedia);
16180
16181     /* XXX do the following based on driver state... */
16182
16183     /* free the host hardware/software hsi structures */
16184     bxe_free_hsi_mem(sc);
16185
16186     /* free ilt */
16187     bxe_free_ilt_mem(sc);
16188
16189     bxe_free_buf_rings(sc);
16190
16191     /* release the interrupts */
16192     bxe_interrupt_free(sc);
16193
16194     /* Release the mutexes*/
16195     bxe_destroy_fp_mutexs(sc);
16196     bxe_release_mutexes(sc);
16197
16198
16199     /* Release the PCIe BAR mapped memory */
16200     bxe_deallocate_bars(sc);
16201
16202     /* Release the FreeBSD interface. */
16203     if (sc->ifnet != NULL) {
16204         if_free(sc->ifnet);
16205     }
16206
16207     pci_disable_busmaster(dev);
16208
16209     return (0);
16210 }
16211
16212 /*
16213  * Device shutdown function.
16214  *
16215  * Stops and resets the controller.
16216  *
16217  * Returns:
16218  *   Nothing
16219  */
16220 static int
16221 bxe_shutdown(device_t dev)
16222 {
16223     struct bxe_softc *sc;
16224
16225     sc = device_get_softc(dev);
16226
16227     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16228
16229     /* stop the periodic callout */
16230     bxe_periodic_stop(sc);
16231
16232     BXE_CORE_LOCK(sc);
16233     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16234     BXE_CORE_UNLOCK(sc);
16235
16236     return (0);
16237 }
16238
16239 void
16240 bxe_igu_ack_sb(struct bxe_softc *sc,
16241                uint8_t          igu_sb_id,
16242                uint8_t          segment,
16243                uint16_t         index,
16244                uint8_t          op,
16245                uint8_t          update)
16246 {
16247     uint32_t igu_addr = sc->igu_base_addr;
16248     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16249     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16250 }
16251
16252 static void
16253 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16254                      uint8_t          func,
16255                      uint8_t          idu_sb_id,
16256                      uint8_t          is_pf)
16257 {
16258     uint32_t data, ctl, cnt = 100;
16259     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16260     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16261     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16262     uint32_t sb_bit =  1 << (idu_sb_id%32);
16263     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16264     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16265
16266     /* Not supported in BC mode */
16267     if (CHIP_INT_MODE_IS_BC(sc)) {
16268         return;
16269     }
16270
16271     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16272              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16273             IGU_REGULAR_CLEANUP_SET |
16274             IGU_REGULAR_BCLEANUP);
16275
16276     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16277            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16278            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16279
16280     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16281             data, igu_addr_data);
16282     REG_WR(sc, igu_addr_data, data);
16283
16284     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16285                       BUS_SPACE_BARRIER_WRITE);
16286     mb();
16287
16288     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16289             ctl, igu_addr_ctl);
16290     REG_WR(sc, igu_addr_ctl, ctl);
16291
16292     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16293                       BUS_SPACE_BARRIER_WRITE);
16294     mb();
16295
16296     /* wait for clean up to finish */
16297     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16298         DELAY(20000);
16299     }
16300
16301     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16302         BLOGD(sc, DBG_LOAD,
16303               "Unable to finish IGU cleanup: "
16304               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16305               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16306     }
16307 }
16308
16309 static void
16310 bxe_igu_clear_sb(struct bxe_softc *sc,
16311                  uint8_t          idu_sb_id)
16312 {
16313     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16314 }
16315
16316
16317
16318
16319
16320
16321
16322 /*******************/
16323 /* ECORE CALLBACKS */
16324 /*******************/
16325
16326 static void
16327 bxe_reset_common(struct bxe_softc *sc)
16328 {
16329     uint32_t val = 0x1400;
16330
16331     /* reset_common */
16332     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16333
16334     if (CHIP_IS_E3(sc)) {
16335         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16336         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16337     }
16338
16339     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16340 }
16341
16342 static void
16343 bxe_common_init_phy(struct bxe_softc *sc)
16344 {
16345     uint32_t shmem_base[2];
16346     uint32_t shmem2_base[2];
16347
16348     /* Avoid common init in case MFW supports LFA */
16349     if (SHMEM2_RD(sc, size) >
16350         (uint32_t)offsetof(struct shmem2_region,
16351                            lfa_host_addr[SC_PORT(sc)])) {
16352         return;
16353     }
16354
16355     shmem_base[0]  = sc->devinfo.shmem_base;
16356     shmem2_base[0] = sc->devinfo.shmem2_base;
16357
16358     if (!CHIP_IS_E1x(sc)) {
16359         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16360         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16361     }
16362
16363     bxe_acquire_phy_lock(sc);
16364     elink_common_init_phy(sc, shmem_base, shmem2_base,
16365                           sc->devinfo.chip_id, 0);
16366     bxe_release_phy_lock(sc);
16367 }
16368
16369 static void
16370 bxe_pf_disable(struct bxe_softc *sc)
16371 {
16372     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16373
16374     val &= ~IGU_PF_CONF_FUNC_EN;
16375
16376     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16377     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16378     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16379 }
16380
16381 static void
16382 bxe_init_pxp(struct bxe_softc *sc)
16383 {
16384     uint16_t devctl;
16385     int r_order, w_order;
16386
16387     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16388
16389     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16390
16391     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16392
16393     if (sc->mrrs == -1) {
16394         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16395     } else {
16396         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16397         r_order = sc->mrrs;
16398     }
16399
16400     ecore_init_pxp_arb(sc, r_order, w_order);
16401 }
16402
16403 static uint32_t
16404 bxe_get_pretend_reg(struct bxe_softc *sc)
16405 {
16406     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16407     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16408     return (base + (SC_ABS_FUNC(sc)) * stride);
16409 }
16410
16411 /*
16412  * Called only on E1H or E2.
16413  * When pretending to be PF, the pretend value is the function number 0..7.
16414  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16415  * combination.
16416  */
16417 static int
16418 bxe_pretend_func(struct bxe_softc *sc,
16419                  uint16_t         pretend_func_val)
16420 {
16421     uint32_t pretend_reg;
16422
16423     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16424         return (-1);
16425     }
16426
16427     /* get my own pretend register */
16428     pretend_reg = bxe_get_pretend_reg(sc);
16429     REG_WR(sc, pretend_reg, pretend_func_val);
16430     REG_RD(sc, pretend_reg);
16431     return (0);
16432 }
16433
16434 static void
16435 bxe_iov_init_dmae(struct bxe_softc *sc)
16436 {
16437     return;
16438 }
16439
16440 static void
16441 bxe_iov_init_dq(struct bxe_softc *sc)
16442 {
16443     return;
16444 }
16445
16446 /* send a NIG loopback debug packet */
16447 static void
16448 bxe_lb_pckt(struct bxe_softc *sc)
16449 {
16450     uint32_t wb_write[3];
16451
16452     /* Ethernet source and destination addresses */
16453     wb_write[0] = 0x55555555;
16454     wb_write[1] = 0x55555555;
16455     wb_write[2] = 0x20;     /* SOP */
16456     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16457
16458     /* NON-IP protocol */
16459     wb_write[0] = 0x09000000;
16460     wb_write[1] = 0x55555555;
16461     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16462     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16463 }
16464
16465 /*
16466  * Some of the internal memories are not directly readable from the driver.
16467  * To test them we send debug packets.
16468  */
16469 static int
16470 bxe_int_mem_test(struct bxe_softc *sc)
16471 {
16472     int factor;
16473     int count, i;
16474     uint32_t val = 0;
16475
16476     if (CHIP_REV_IS_FPGA(sc)) {
16477         factor = 120;
16478     } else if (CHIP_REV_IS_EMUL(sc)) {
16479         factor = 200;
16480     } else {
16481         factor = 1;
16482     }
16483
16484     /* disable inputs of parser neighbor blocks */
16485     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16486     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16487     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16488     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16489
16490     /*  write 0 to parser credits for CFC search request */
16491     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16492
16493     /* send Ethernet packet */
16494     bxe_lb_pckt(sc);
16495
16496     /* TODO do i reset NIG statistic? */
16497     /* Wait until NIG register shows 1 packet of size 0x10 */
16498     count = 1000 * factor;
16499     while (count) {
16500         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16501         val = *BXE_SP(sc, wb_data[0]);
16502         if (val == 0x10) {
16503             break;
16504         }
16505
16506         DELAY(10000);
16507         count--;
16508     }
16509
16510     if (val != 0x10) {
16511         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16512         return (-1);
16513     }
16514
16515     /* wait until PRS register shows 1 packet */
16516     count = (1000 * factor);
16517     while (count) {
16518         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16519         if (val == 1) {
16520             break;
16521         }
16522
16523         DELAY(10000);
16524         count--;
16525     }
16526
16527     if (val != 0x1) {
16528         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16529         return (-2);
16530     }
16531
16532     /* Reset and init BRB, PRS */
16533     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16534     DELAY(50000);
16535     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16536     DELAY(50000);
16537     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16538     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16539
16540     /* Disable inputs of parser neighbor blocks */
16541     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16542     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16543     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16544     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16545
16546     /* Write 0 to parser credits for CFC search request */
16547     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16548
16549     /* send 10 Ethernet packets */
16550     for (i = 0; i < 10; i++) {
16551         bxe_lb_pckt(sc);
16552     }
16553
16554     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16555     count = (1000 * factor);
16556     while (count) {
16557         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16558         val = *BXE_SP(sc, wb_data[0]);
16559         if (val == 0xb0) {
16560             break;
16561         }
16562
16563         DELAY(10000);
16564         count--;
16565     }
16566
16567     if (val != 0xb0) {
16568         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16569         return (-3);
16570     }
16571
16572     /* Wait until PRS register shows 2 packets */
16573     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16574     if (val != 2) {
16575         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16576     }
16577
16578     /* Write 1 to parser credits for CFC search request */
16579     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16580
16581     /* Wait until PRS register shows 3 packets */
16582     DELAY(10000 * factor);
16583
16584     /* Wait until NIG register shows 1 packet of size 0x10 */
16585     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16586     if (val != 3) {
16587         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16588     }
16589
16590     /* clear NIG EOP FIFO */
16591     for (i = 0; i < 11; i++) {
16592         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16593     }
16594
16595     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16596     if (val != 1) {
16597         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16598         return (-4);
16599     }
16600
16601     /* Reset and init BRB, PRS, NIG */
16602     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16603     DELAY(50000);
16604     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16605     DELAY(50000);
16606     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16607     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16608     if (!CNIC_SUPPORT(sc)) {
16609         /* set NIC mode */
16610         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16611     }
16612
16613     /* Enable inputs of parser neighbor blocks */
16614     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16615     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16616     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16617     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16618
16619     return (0);
16620 }
16621
16622 static void
16623 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16624 {
16625     int is_required;
16626     uint32_t val;
16627     int port;
16628
16629     is_required = 0;
16630     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16631            SHARED_HW_CFG_FAN_FAILURE_MASK);
16632
16633     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16634         is_required = 1;
16635     }
16636     /*
16637      * The fan failure mechanism is usually related to the PHY type since
16638      * the power consumption of the board is affected by the PHY. Currently,
16639      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16640      */
16641     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16642         for (port = PORT_0; port < PORT_MAX; port++) {
16643             is_required |= elink_fan_failure_det_req(sc,
16644                                                      sc->devinfo.shmem_base,
16645                                                      sc->devinfo.shmem2_base,
16646                                                      port);
16647         }
16648     }
16649
16650     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16651
16652     if (is_required == 0) {
16653         return;
16654     }
16655
16656     /* Fan failure is indicated by SPIO 5 */
16657     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16658
16659     /* set to active low mode */
16660     val = REG_RD(sc, MISC_REG_SPIO_INT);
16661     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16662     REG_WR(sc, MISC_REG_SPIO_INT, val);
16663
16664     /* enable interrupt to signal the IGU */
16665     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16666     val |= MISC_SPIO_SPIO5;
16667     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16668 }
16669
16670 static void
16671 bxe_enable_blocks_attention(struct bxe_softc *sc)
16672 {
16673     uint32_t val;
16674
16675     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16676     if (!CHIP_IS_E1x(sc)) {
16677         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16678     } else {
16679         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16680     }
16681     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16682     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16683     /*
16684      * mask read length error interrupts in brb for parser
16685      * (parsing unit and 'checksum and crc' unit)
16686      * these errors are legal (PU reads fixed length and CAC can cause
16687      * read length error on truncated packets)
16688      */
16689     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16690     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16691     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16692     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16693     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16694     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16695 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16696 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16697     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16698     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16699     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16700 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16701 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16702     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16703     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16704     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16705     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16706 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16707 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16708
16709     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16710            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16711            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16712     if (!CHIP_IS_E1x(sc)) {
16713         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16714                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16715     }
16716     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16717
16718     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16719     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16720     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16721 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16722
16723     if (!CHIP_IS_E1x(sc)) {
16724         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16725         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16726     }
16727
16728     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16729     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16730 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16731     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16732 }
16733
16734 /**
16735  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16736  *
16737  * @sc:     driver handle
16738  */
16739 static int
16740 bxe_init_hw_common(struct bxe_softc *sc)
16741 {
16742     uint8_t abs_func_id;
16743     uint32_t val;
16744
16745     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16746           SC_ABS_FUNC(sc));
16747
16748     /*
16749      * take the RESET lock to protect undi_unload flow from accessing
16750      * registers while we are resetting the chip
16751      */
16752     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16753
16754     bxe_reset_common(sc);
16755
16756     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16757
16758     val = 0xfffc;
16759     if (CHIP_IS_E3(sc)) {
16760         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16761         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16762     }
16763
16764     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16765
16766     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16767
16768     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16769     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16770
16771     if (!CHIP_IS_E1x(sc)) {
16772         /*
16773          * 4-port mode or 2-port mode we need to turn off master-enable for
16774          * everyone. After that we turn it back on for self. So, we disregard
16775          * multi-function, and always disable all functions on the given path,
16776          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16777          */
16778         for (abs_func_id = SC_PATH(sc);
16779              abs_func_id < (E2_FUNC_MAX * 2);
16780              abs_func_id += 2) {
16781             if (abs_func_id == SC_ABS_FUNC(sc)) {
16782                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16783                 continue;
16784             }
16785
16786             bxe_pretend_func(sc, abs_func_id);
16787
16788             /* clear pf enable */
16789             bxe_pf_disable(sc);
16790
16791             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16792         }
16793     }
16794
16795     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16796
16797     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16798
16799     if (CHIP_IS_E1(sc)) {
16800         /*
16801          * enable HW interrupt from PXP on USDM overflow
16802          * bit 16 on INT_MASK_0
16803          */
16804         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16805     }
16806
16807     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16808     bxe_init_pxp(sc);
16809
16810 #ifdef __BIG_ENDIAN
16811     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16812     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16813     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16814     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16815     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16816     /* make sure this value is 0 */
16817     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16818
16819     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16820     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16821     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16822     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16823     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16824 #endif
16825
16826     ecore_ilt_init_page_size(sc, INITOP_SET);
16827
16828     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16829         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16830     }
16831
16832     /* let the HW do it's magic... */
16833     DELAY(100000);
16834
16835     /* finish PXP init */
16836     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16837     if (val != 1) {
16838         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16839             val);
16840         return (-1);
16841     }
16842     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16843     if (val != 1) {
16844         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16845         return (-1);
16846     }
16847
16848     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16849
16850     /*
16851      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16852      * entries with value "0" and valid bit on. This needs to be done by the
16853      * first PF that is loaded in a path (i.e. common phase)
16854      */
16855     if (!CHIP_IS_E1x(sc)) {
16856 /*
16857  * In E2 there is a bug in the timers block that can cause function 6 / 7
16858  * (i.e. vnic3) to start even if it is marked as "scan-off".
16859  * This occurs when a different function (func2,3) is being marked
16860  * as "scan-off". Real-life scenario for example: if a driver is being
16861  * load-unloaded while func6,7 are down. This will cause the timer to access
16862  * the ilt, translate to a logical address and send a request to read/write.
16863  * Since the ilt for the function that is down is not valid, this will cause
16864  * a translation error which is unrecoverable.
16865  * The Workaround is intended to make sure that when this happens nothing
16866  * fatal will occur. The workaround:
16867  *  1.  First PF driver which loads on a path will:
16868  *      a.  After taking the chip out of reset, by using pretend,
16869  *          it will write "0" to the following registers of
16870  *          the other vnics.
16871  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16872  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16873  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16874  *          And for itself it will write '1' to
16875  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16876  *          dmae-operations (writing to pram for example.)
16877  *          note: can be done for only function 6,7 but cleaner this
16878  *            way.
16879  *      b.  Write zero+valid to the entire ILT.
16880  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16881  *          VNIC3 (of that port). The range allocated will be the
16882  *          entire ILT. This is needed to prevent  ILT range error.
16883  *  2.  Any PF driver load flow:
16884  *      a.  ILT update with the physical addresses of the allocated
16885  *          logical pages.
16886  *      b.  Wait 20msec. - note that this timeout is needed to make
16887  *          sure there are no requests in one of the PXP internal
16888  *          queues with "old" ILT addresses.
16889  *      c.  PF enable in the PGLC.
16890  *      d.  Clear the was_error of the PF in the PGLC. (could have
16891  *          occurred while driver was down)
16892  *      e.  PF enable in the CFC (WEAK + STRONG)
16893  *      f.  Timers scan enable
16894  *  3.  PF driver unload flow:
16895  *      a.  Clear the Timers scan_en.
16896  *      b.  Polling for scan_on=0 for that PF.
16897  *      c.  Clear the PF enable bit in the PXP.
16898  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16899  *      e.  Write zero+valid to all ILT entries (The valid bit must
16900  *          stay set)
16901  *      f.  If this is VNIC 3 of a port then also init
16902  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16903  *          to the last enrty in the ILT.
16904  *
16905  *      Notes:
16906  *      Currently the PF error in the PGLC is non recoverable.
16907  *      In the future the there will be a recovery routine for this error.
16908  *      Currently attention is masked.
16909  *      Having an MCP lock on the load/unload process does not guarantee that
16910  *      there is no Timer disable during Func6/7 enable. This is because the
16911  *      Timers scan is currently being cleared by the MCP on FLR.
16912  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16913  *      there is error before clearing it. But the flow above is simpler and
16914  *      more general.
16915  *      All ILT entries are written by zero+valid and not just PF6/7
16916  *      ILT entries since in the future the ILT entries allocation for
16917  *      PF-s might be dynamic.
16918  */
16919         struct ilt_client_info ilt_cli;
16920         struct ecore_ilt ilt;
16921
16922         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16923         memset(&ilt, 0, sizeof(struct ecore_ilt));
16924
16925         /* initialize dummy TM client */
16926         ilt_cli.start      = 0;
16927         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16928         ilt_cli.client_num = ILT_CLIENT_TM;
16929
16930         /*
16931          * Step 1: set zeroes to all ilt page entries with valid bit on
16932          * Step 2: set the timers first/last ilt entry to point
16933          * to the entire range to prevent ILT range error for 3rd/4th
16934          * vnic (this code assumes existence of the vnic)
16935          *
16936          * both steps performed by call to ecore_ilt_client_init_op()
16937          * with dummy TM client
16938          *
16939          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16940          * and his brother are split registers
16941          */
16942
16943         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16944         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16945         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16946
16947         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16948         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16949         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16950     }
16951
16952     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16953     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16954
16955     if (!CHIP_IS_E1x(sc)) {
16956         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16957                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
16958
16959         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
16960         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
16961
16962         /* let the HW do it's magic... */
16963         do {
16964             DELAY(200000);
16965             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
16966         } while (factor-- && (val != 1));
16967
16968         if (val != 1) {
16969             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
16970             return (-1);
16971         }
16972     }
16973
16974     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
16975
16976     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
16977
16978     bxe_iov_init_dmae(sc);
16979
16980     /* clean the DMAE memory */
16981     sc->dmae_ready = 1;
16982     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
16983
16984     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
16985
16986     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
16987
16988     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
16989
16990     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
16991
16992     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
16993     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
16994     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
16995     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
16996
16997     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
16998
16999     /* QM queues pointers table */
17000     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17001
17002     /* soft reset pulse */
17003     REG_WR(sc, QM_REG_SOFT_RESET, 1);
17004     REG_WR(sc, QM_REG_SOFT_RESET, 0);
17005
17006     if (CNIC_SUPPORT(sc))
17007         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17008
17009     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17010     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17011     if (!CHIP_REV_IS_SLOW(sc)) {
17012         /* enable hw interrupt from doorbell Q */
17013         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17014     }
17015
17016     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17017
17018     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17019     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17020
17021     if (!CHIP_IS_E1(sc)) {
17022         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17023     }
17024
17025     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17026         if (IS_MF_AFEX(sc)) {
17027             /*
17028              * configure that AFEX and VLAN headers must be
17029              * received in AFEX mode
17030              */
17031             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17032             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17033             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17034             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17035             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17036         } else {
17037             /*
17038              * Bit-map indicating which L2 hdrs may appear
17039              * after the basic Ethernet header
17040              */
17041             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17042                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17043         }
17044     }
17045
17046     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17047     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17048     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17049     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17050
17051     if (!CHIP_IS_E1x(sc)) {
17052         /* reset VFC memories */
17053         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17054                VFC_MEMORIES_RST_REG_CAM_RST |
17055                VFC_MEMORIES_RST_REG_RAM_RST);
17056         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17057                VFC_MEMORIES_RST_REG_CAM_RST |
17058                VFC_MEMORIES_RST_REG_RAM_RST);
17059
17060         DELAY(20000);
17061     }
17062
17063     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17064     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17065     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17066     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17067
17068     /* sync semi rtc */
17069     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17070            0x80000000);
17071     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17072            0x80000000);
17073
17074     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17075     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17076     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17077
17078     if (!CHIP_IS_E1x(sc)) {
17079         if (IS_MF_AFEX(sc)) {
17080             /*
17081              * configure that AFEX and VLAN headers must be
17082              * sent in AFEX mode
17083              */
17084             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17085             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17086             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17087             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17088             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17089         } else {
17090             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17091                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17092         }
17093     }
17094
17095     REG_WR(sc, SRC_REG_SOFT_RST, 1);
17096
17097     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17098
17099     if (CNIC_SUPPORT(sc)) {
17100         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17101         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17102         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17103         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17104         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17105         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17106         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17107         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17108         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17109         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17110     }
17111     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17112
17113     if (sizeof(union cdu_context) != 1024) {
17114         /* we currently assume that a context is 1024 bytes */
17115         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17116               (long)sizeof(union cdu_context));
17117     }
17118
17119     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17120     val = (4 << 24) + (0 << 12) + 1024;
17121     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17122
17123     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17124
17125     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17126     /* enable context validation interrupt from CFC */
17127     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17128
17129     /* set the thresholds to prevent CFC/CDU race */
17130     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17131     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17132
17133     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17134         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17135     }
17136
17137     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17138     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17139
17140     /* Reset PCIE errors for debug */
17141     REG_WR(sc, 0x2814, 0xffffffff);
17142     REG_WR(sc, 0x3820, 0xffffffff);
17143
17144     if (!CHIP_IS_E1x(sc)) {
17145         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17146                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17147                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17148         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17149                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17150                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17151                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17152         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17153                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17154                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17155                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17156     }
17157
17158     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17159
17160     if (!CHIP_IS_E1(sc)) {
17161         /* in E3 this done in per-port section */
17162         if (!CHIP_IS_E3(sc))
17163             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17164     }
17165
17166     if (CHIP_IS_E1H(sc)) {
17167         /* not applicable for E2 (and above ...) */
17168         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17169     }
17170
17171     if (CHIP_REV_IS_SLOW(sc)) {
17172         DELAY(200000);
17173     }
17174
17175     /* finish CFC init */
17176     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17177     if (val != 1) {
17178         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17179         return (-1);
17180     }
17181     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17182     if (val != 1) {
17183         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17184         return (-1);
17185     }
17186     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17187     if (val != 1) {
17188         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17189         return (-1);
17190     }
17191     REG_WR(sc, CFC_REG_DEBUG0, 0);
17192
17193     if (CHIP_IS_E1(sc)) {
17194         /* read NIG statistic to see if this is our first up since powerup */
17195         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17196         val = *BXE_SP(sc, wb_data[0]);
17197
17198         /* do internal memory self test */
17199         if ((val == 0) && bxe_int_mem_test(sc)) {
17200             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17201             return (-1);
17202         }
17203     }
17204
17205     bxe_setup_fan_failure_detection(sc);
17206
17207     /* clear PXP2 attentions */
17208     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17209
17210     bxe_enable_blocks_attention(sc);
17211
17212     if (!CHIP_REV_IS_SLOW(sc)) {
17213         ecore_enable_blocks_parity(sc);
17214     }
17215
17216     if (!BXE_NOMCP(sc)) {
17217         if (CHIP_IS_E1x(sc)) {
17218             bxe_common_init_phy(sc);
17219         }
17220     }
17221
17222     return (0);
17223 }
17224
17225 /**
17226  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17227  *
17228  * @sc:     driver handle
17229  */
17230 static int
17231 bxe_init_hw_common_chip(struct bxe_softc *sc)
17232 {
17233     int rc = bxe_init_hw_common(sc);
17234
17235     if (rc) {
17236         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17237         return (rc);
17238     }
17239
17240     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17241     if (!BXE_NOMCP(sc)) {
17242         bxe_common_init_phy(sc);
17243     }
17244
17245     return (0);
17246 }
17247
17248 static int
17249 bxe_init_hw_port(struct bxe_softc *sc)
17250 {
17251     int port = SC_PORT(sc);
17252     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17253     uint32_t low, high;
17254     uint32_t val;
17255
17256     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17257
17258     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17259
17260     ecore_init_block(sc, BLOCK_MISC, init_phase);
17261     ecore_init_block(sc, BLOCK_PXP, init_phase);
17262     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17263
17264     /*
17265      * Timers bug workaround: disables the pf_master bit in pglue at
17266      * common phase, we need to enable it here before any dmae access are
17267      * attempted. Therefore we manually added the enable-master to the
17268      * port phase (it also happens in the function phase)
17269      */
17270     if (!CHIP_IS_E1x(sc)) {
17271         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17272     }
17273
17274     ecore_init_block(sc, BLOCK_ATC, init_phase);
17275     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17276     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17277     ecore_init_block(sc, BLOCK_QM, init_phase);
17278
17279     ecore_init_block(sc, BLOCK_TCM, init_phase);
17280     ecore_init_block(sc, BLOCK_UCM, init_phase);
17281     ecore_init_block(sc, BLOCK_CCM, init_phase);
17282     ecore_init_block(sc, BLOCK_XCM, init_phase);
17283
17284     /* QM cid (connection) count */
17285     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17286
17287     if (CNIC_SUPPORT(sc)) {
17288         ecore_init_block(sc, BLOCK_TM, init_phase);
17289         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17290         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17291     }
17292
17293     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17294
17295     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17296
17297     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17298         if (IS_MF(sc)) {
17299             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17300         } else if (sc->mtu > 4096) {
17301             if (BXE_ONE_PORT(sc)) {
17302                 low = 160;
17303             } else {
17304                 val = sc->mtu;
17305                 /* (24*1024 + val*4)/256 */
17306                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17307             }
17308         } else {
17309             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17310         }
17311         high = (low + 56); /* 14*1024/256 */
17312         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17313         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17314     }
17315
17316     if (CHIP_IS_MODE_4_PORT(sc)) {
17317         REG_WR(sc, SC_PORT(sc) ?
17318                BRB1_REG_MAC_GUARANTIED_1 :
17319                BRB1_REG_MAC_GUARANTIED_0, 40);
17320     }
17321
17322     ecore_init_block(sc, BLOCK_PRS, init_phase);
17323     if (CHIP_IS_E3B0(sc)) {
17324         if (IS_MF_AFEX(sc)) {
17325             /* configure headers for AFEX mode */
17326             REG_WR(sc, SC_PORT(sc) ?
17327                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17328                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17329             REG_WR(sc, SC_PORT(sc) ?
17330                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17331                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17332             REG_WR(sc, SC_PORT(sc) ?
17333                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17334                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17335         } else {
17336             /* Ovlan exists only if we are in multi-function +
17337              * switch-dependent mode, in switch-independent there
17338              * is no ovlan headers
17339              */
17340             REG_WR(sc, SC_PORT(sc) ?
17341                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17342                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17343                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17344         }
17345     }
17346
17347     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17348     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17349     ecore_init_block(sc, BLOCK_USDM, init_phase);
17350     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17351
17352     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17353     ecore_init_block(sc, BLOCK_USEM, init_phase);
17354     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17355     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17356
17357     ecore_init_block(sc, BLOCK_UPB, init_phase);
17358     ecore_init_block(sc, BLOCK_XPB, init_phase);
17359
17360     ecore_init_block(sc, BLOCK_PBF, init_phase);
17361
17362     if (CHIP_IS_E1x(sc)) {
17363         /* configure PBF to work without PAUSE mtu 9000 */
17364         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17365
17366         /* update threshold */
17367         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17368         /* update init credit */
17369         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17370
17371         /* probe changes */
17372         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17373         DELAY(50);
17374         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17375     }
17376
17377     if (CNIC_SUPPORT(sc)) {
17378         ecore_init_block(sc, BLOCK_SRC, init_phase);
17379     }
17380
17381     ecore_init_block(sc, BLOCK_CDU, init_phase);
17382     ecore_init_block(sc, BLOCK_CFC, init_phase);
17383
17384     if (CHIP_IS_E1(sc)) {
17385         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17386         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17387     }
17388     ecore_init_block(sc, BLOCK_HC, init_phase);
17389
17390     ecore_init_block(sc, BLOCK_IGU, init_phase);
17391
17392     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17393     /* init aeu_mask_attn_func_0/1:
17394      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17395      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17396      *             bits 4-7 are used for "per vn group attention" */
17397     val = IS_MF(sc) ? 0xF7 : 0x7;
17398     /* Enable DCBX attention for all but E1 */
17399     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17400     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17401
17402     ecore_init_block(sc, BLOCK_NIG, init_phase);
17403
17404     if (!CHIP_IS_E1x(sc)) {
17405         /* Bit-map indicating which L2 hdrs may appear after the
17406          * basic Ethernet header
17407          */
17408         if (IS_MF_AFEX(sc)) {
17409             REG_WR(sc, SC_PORT(sc) ?
17410                    NIG_REG_P1_HDRS_AFTER_BASIC :
17411                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17412         } else {
17413             REG_WR(sc, SC_PORT(sc) ?
17414                    NIG_REG_P1_HDRS_AFTER_BASIC :
17415                    NIG_REG_P0_HDRS_AFTER_BASIC,
17416                    IS_MF_SD(sc) ? 7 : 6);
17417         }
17418
17419         if (CHIP_IS_E3(sc)) {
17420             REG_WR(sc, SC_PORT(sc) ?
17421                    NIG_REG_LLH1_MF_MODE :
17422                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17423         }
17424     }
17425     if (!CHIP_IS_E3(sc)) {
17426         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17427     }
17428
17429     if (!CHIP_IS_E1(sc)) {
17430         /* 0x2 disable mf_ov, 0x1 enable */
17431         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17432                (IS_MF_SD(sc) ? 0x1 : 0x2));
17433
17434         if (!CHIP_IS_E1x(sc)) {
17435             val = 0;
17436             switch (sc->devinfo.mf_info.mf_mode) {
17437             case MULTI_FUNCTION_SD:
17438                 val = 1;
17439                 break;
17440             case MULTI_FUNCTION_SI:
17441             case MULTI_FUNCTION_AFEX:
17442                 val = 2;
17443                 break;
17444             }
17445
17446             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17447                         NIG_REG_LLH0_CLS_TYPE), val);
17448         }
17449         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17450         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17451         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17452     }
17453
17454     /* If SPIO5 is set to generate interrupts, enable it for this port */
17455     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17456     if (val & MISC_SPIO_SPIO5) {
17457         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17458                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17459         val = REG_RD(sc, reg_addr);
17460         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17461         REG_WR(sc, reg_addr, val);
17462     }
17463
17464     return (0);
17465 }
17466
17467 static uint32_t
17468 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17469                        uint32_t         reg,
17470                        uint32_t         expected,
17471                        uint32_t         poll_count)
17472 {
17473     uint32_t cur_cnt = poll_count;
17474     uint32_t val;
17475
17476     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17477         DELAY(FLR_WAIT_INTERVAL);
17478     }
17479
17480     return (val);
17481 }
17482
17483 static int
17484 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17485                               uint32_t         reg,
17486                               char             *msg,
17487                               uint32_t         poll_cnt)
17488 {
17489     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17490
17491     if (val != 0) {
17492         BLOGE(sc, "%s usage count=%d\n", msg, val);
17493         return (1);
17494     }
17495
17496     return (0);
17497 }
17498
17499 /* Common routines with VF FLR cleanup */
17500 static uint32_t
17501 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17502 {
17503     /* adjust polling timeout */
17504     if (CHIP_REV_IS_EMUL(sc)) {
17505         return (FLR_POLL_CNT * 2000);
17506     }
17507
17508     if (CHIP_REV_IS_FPGA(sc)) {
17509         return (FLR_POLL_CNT * 120);
17510     }
17511
17512     return (FLR_POLL_CNT);
17513 }
17514
17515 static int
17516 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17517                            uint32_t         poll_cnt)
17518 {
17519     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17520     if (bxe_flr_clnup_poll_hw_counter(sc,
17521                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17522                                       "CFC PF usage counter timed out",
17523                                       poll_cnt)) {
17524         return (1);
17525     }
17526
17527     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17528     if (bxe_flr_clnup_poll_hw_counter(sc,
17529                                       DORQ_REG_PF_USAGE_CNT,
17530                                       "DQ PF usage counter timed out",
17531                                       poll_cnt)) {
17532         return (1);
17533     }
17534
17535     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17536     if (bxe_flr_clnup_poll_hw_counter(sc,
17537                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17538                                       "QM PF usage counter timed out",
17539                                       poll_cnt)) {
17540         return (1);
17541     }
17542
17543     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17544     if (bxe_flr_clnup_poll_hw_counter(sc,
17545                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17546                                       "Timers VNIC usage counter timed out",
17547                                       poll_cnt)) {
17548         return (1);
17549     }
17550
17551     if (bxe_flr_clnup_poll_hw_counter(sc,
17552                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17553                                       "Timers NUM_SCANS usage counter timed out",
17554                                       poll_cnt)) {
17555         return (1);
17556     }
17557
17558     /* Wait DMAE PF usage counter to zero */
17559     if (bxe_flr_clnup_poll_hw_counter(sc,
17560                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17561                                       "DMAE dommand register timed out",
17562                                       poll_cnt)) {
17563         return (1);
17564     }
17565
17566     return (0);
17567 }
17568
17569 #define OP_GEN_PARAM(param)                                            \
17570     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17571 #define OP_GEN_TYPE(type)                                           \
17572     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17573 #define OP_GEN_AGG_VECT(index)                                             \
17574     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17575
17576 static int
17577 bxe_send_final_clnup(struct bxe_softc *sc,
17578                      uint8_t          clnup_func,
17579                      uint32_t         poll_cnt)
17580 {
17581     uint32_t op_gen_command = 0;
17582     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17583                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17584     int ret = 0;
17585
17586     if (REG_RD(sc, comp_addr)) {
17587         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17588         return (1);
17589     }
17590
17591     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17592     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17593     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17594     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17595
17596     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17597     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17598
17599     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17600         BLOGE(sc, "FW final cleanup did not succeed\n");
17601         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17602               (REG_RD(sc, comp_addr)));
17603         bxe_panic(sc, ("FLR cleanup failed\n"));
17604         return (1);
17605     }
17606
17607     /* Zero completion for nxt FLR */
17608     REG_WR(sc, comp_addr, 0);
17609
17610     return (ret);
17611 }
17612
17613 static void
17614 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17615                        struct pbf_pN_buf_regs *regs,
17616                        uint32_t               poll_count)
17617 {
17618     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17619     uint32_t cur_cnt = poll_count;
17620
17621     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17622     crd = crd_start = REG_RD(sc, regs->crd);
17623     init_crd = REG_RD(sc, regs->init_crd);
17624
17625     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17626     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17627     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17628
17629     while ((crd != init_crd) &&
17630            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17631             (init_crd - crd_start))) {
17632         if (cur_cnt--) {
17633             DELAY(FLR_WAIT_INTERVAL);
17634             crd = REG_RD(sc, regs->crd);
17635             crd_freed = REG_RD(sc, regs->crd_freed);
17636         } else {
17637             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17638             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17639             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17640             break;
17641         }
17642     }
17643
17644     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17645           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17646 }
17647
17648 static void
17649 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17650                        struct pbf_pN_cmd_regs *regs,
17651                        uint32_t               poll_count)
17652 {
17653     uint32_t occup, to_free, freed, freed_start;
17654     uint32_t cur_cnt = poll_count;
17655
17656     occup = to_free = REG_RD(sc, regs->lines_occup);
17657     freed = freed_start = REG_RD(sc, regs->lines_freed);
17658
17659     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17660     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17661
17662     while (occup &&
17663            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17664         if (cur_cnt--) {
17665             DELAY(FLR_WAIT_INTERVAL);
17666             occup = REG_RD(sc, regs->lines_occup);
17667             freed = REG_RD(sc, regs->lines_freed);
17668         } else {
17669             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17670             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17671             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17672             break;
17673         }
17674     }
17675
17676     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17677           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17678 }
17679
17680 static void
17681 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17682 {
17683     struct pbf_pN_cmd_regs cmd_regs[] = {
17684         {0, (CHIP_IS_E3B0(sc)) ?
17685             PBF_REG_TQ_OCCUPANCY_Q0 :
17686             PBF_REG_P0_TQ_OCCUPANCY,
17687             (CHIP_IS_E3B0(sc)) ?
17688             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17689             PBF_REG_P0_TQ_LINES_FREED_CNT},
17690         {1, (CHIP_IS_E3B0(sc)) ?
17691             PBF_REG_TQ_OCCUPANCY_Q1 :
17692             PBF_REG_P1_TQ_OCCUPANCY,
17693             (CHIP_IS_E3B0(sc)) ?
17694             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17695             PBF_REG_P1_TQ_LINES_FREED_CNT},
17696         {4, (CHIP_IS_E3B0(sc)) ?
17697             PBF_REG_TQ_OCCUPANCY_LB_Q :
17698             PBF_REG_P4_TQ_OCCUPANCY,
17699             (CHIP_IS_E3B0(sc)) ?
17700             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17701             PBF_REG_P4_TQ_LINES_FREED_CNT}
17702     };
17703
17704     struct pbf_pN_buf_regs buf_regs[] = {
17705         {0, (CHIP_IS_E3B0(sc)) ?
17706             PBF_REG_INIT_CRD_Q0 :
17707             PBF_REG_P0_INIT_CRD ,
17708             (CHIP_IS_E3B0(sc)) ?
17709             PBF_REG_CREDIT_Q0 :
17710             PBF_REG_P0_CREDIT,
17711             (CHIP_IS_E3B0(sc)) ?
17712             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17713             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17714         {1, (CHIP_IS_E3B0(sc)) ?
17715             PBF_REG_INIT_CRD_Q1 :
17716             PBF_REG_P1_INIT_CRD,
17717             (CHIP_IS_E3B0(sc)) ?
17718             PBF_REG_CREDIT_Q1 :
17719             PBF_REG_P1_CREDIT,
17720             (CHIP_IS_E3B0(sc)) ?
17721             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17722             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17723         {4, (CHIP_IS_E3B0(sc)) ?
17724             PBF_REG_INIT_CRD_LB_Q :
17725             PBF_REG_P4_INIT_CRD,
17726             (CHIP_IS_E3B0(sc)) ?
17727             PBF_REG_CREDIT_LB_Q :
17728             PBF_REG_P4_CREDIT,
17729             (CHIP_IS_E3B0(sc)) ?
17730             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17731             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17732     };
17733
17734     int i;
17735
17736     /* Verify the command queues are flushed P0, P1, P4 */
17737     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17738         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17739     }
17740
17741     /* Verify the transmission buffers are flushed P0, P1, P4 */
17742     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17743         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17744     }
17745 }
17746
17747 static void
17748 bxe_hw_enable_status(struct bxe_softc *sc)
17749 {
17750     uint32_t val;
17751
17752     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17753     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17754
17755     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17756     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17757
17758     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17759     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17760
17761     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17762     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17763
17764     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17765     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17766
17767     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17768     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17769
17770     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17771     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17772
17773     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17774     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17775 }
17776
17777 static int
17778 bxe_pf_flr_clnup(struct bxe_softc *sc)
17779 {
17780     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17781
17782     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17783
17784     /* Re-enable PF target read access */
17785     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17786
17787     /* Poll HW usage counters */
17788     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17789     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17790         return (-1);
17791     }
17792
17793     /* Zero the igu 'trailing edge' and 'leading edge' */
17794
17795     /* Send the FW cleanup command */
17796     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17797         return (-1);
17798     }
17799
17800     /* ATC cleanup */
17801
17802     /* Verify TX hw is flushed */
17803     bxe_tx_hw_flushed(sc, poll_cnt);
17804
17805     /* Wait 100ms (not adjusted according to platform) */
17806     DELAY(100000);
17807
17808     /* Verify no pending pci transactions */
17809     if (bxe_is_pcie_pending(sc)) {
17810         BLOGE(sc, "PCIE Transactions still pending\n");
17811     }
17812
17813     /* Debug */
17814     bxe_hw_enable_status(sc);
17815
17816     /*
17817      * Master enable - Due to WB DMAE writes performed before this
17818      * register is re-initialized as part of the regular function init
17819      */
17820     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17821
17822     return (0);
17823 }
17824
17825 static int
17826 bxe_init_hw_func(struct bxe_softc *sc)
17827 {
17828     int port = SC_PORT(sc);
17829     int func = SC_FUNC(sc);
17830     int init_phase = PHASE_PF0 + func;
17831     struct ecore_ilt *ilt = sc->ilt;
17832     uint16_t cdu_ilt_start;
17833     uint32_t addr, val;
17834     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17835     int i, main_mem_width, rc;
17836
17837     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17838
17839     /* FLR cleanup */
17840     if (!CHIP_IS_E1x(sc)) {
17841         rc = bxe_pf_flr_clnup(sc);
17842         if (rc) {
17843             BLOGE(sc, "FLR cleanup failed!\n");
17844             // XXX bxe_fw_dump(sc);
17845             // XXX bxe_idle_chk(sc);
17846             return (rc);
17847         }
17848     }
17849
17850     /* set MSI reconfigure capability */
17851     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17852         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17853         val = REG_RD(sc, addr);
17854         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17855         REG_WR(sc, addr, val);
17856     }
17857
17858     ecore_init_block(sc, BLOCK_PXP, init_phase);
17859     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17860
17861     ilt = sc->ilt;
17862     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17863
17864     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17865         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17866         ilt->lines[cdu_ilt_start + i].page_mapping =
17867             sc->context[i].vcxt_dma.paddr;
17868         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17869     }
17870     ecore_ilt_init_op(sc, INITOP_SET);
17871
17872     /* Set NIC mode */
17873     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17874     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17875
17876     if (!CHIP_IS_E1x(sc)) {
17877         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17878
17879         /* Turn on a single ISR mode in IGU if driver is going to use
17880          * INT#x or MSI
17881          */
17882         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17883             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17884         }
17885
17886         /*
17887          * Timers workaround bug: function init part.
17888          * Need to wait 20msec after initializing ILT,
17889          * needed to make sure there are no requests in
17890          * one of the PXP internal queues with "old" ILT addresses
17891          */
17892         DELAY(20000);
17893
17894         /*
17895          * Master enable - Due to WB DMAE writes performed before this
17896          * register is re-initialized as part of the regular function
17897          * init
17898          */
17899         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17900         /* Enable the function in IGU */
17901         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17902     }
17903
17904     sc->dmae_ready = 1;
17905
17906     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17907
17908     if (!CHIP_IS_E1x(sc))
17909         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17910
17911     ecore_init_block(sc, BLOCK_ATC, init_phase);
17912     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17913     ecore_init_block(sc, BLOCK_NIG, init_phase);
17914     ecore_init_block(sc, BLOCK_SRC, init_phase);
17915     ecore_init_block(sc, BLOCK_MISC, init_phase);
17916     ecore_init_block(sc, BLOCK_TCM, init_phase);
17917     ecore_init_block(sc, BLOCK_UCM, init_phase);
17918     ecore_init_block(sc, BLOCK_CCM, init_phase);
17919     ecore_init_block(sc, BLOCK_XCM, init_phase);
17920     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17921     ecore_init_block(sc, BLOCK_USEM, init_phase);
17922     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17923     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17924
17925     if (!CHIP_IS_E1x(sc))
17926         REG_WR(sc, QM_REG_PF_EN, 1);
17927
17928     if (!CHIP_IS_E1x(sc)) {
17929         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17930         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17931         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17932         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17933     }
17934     ecore_init_block(sc, BLOCK_QM, init_phase);
17935
17936     ecore_init_block(sc, BLOCK_TM, init_phase);
17937     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17938
17939     bxe_iov_init_dq(sc);
17940
17941     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17942     ecore_init_block(sc, BLOCK_PRS, init_phase);
17943     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17944     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17945     ecore_init_block(sc, BLOCK_USDM, init_phase);
17946     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17947     ecore_init_block(sc, BLOCK_UPB, init_phase);
17948     ecore_init_block(sc, BLOCK_XPB, init_phase);
17949     ecore_init_block(sc, BLOCK_PBF, init_phase);
17950     if (!CHIP_IS_E1x(sc))
17951         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17952
17953     ecore_init_block(sc, BLOCK_CDU, init_phase);
17954
17955     ecore_init_block(sc, BLOCK_CFC, init_phase);
17956
17957     if (!CHIP_IS_E1x(sc))
17958         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
17959
17960     if (IS_MF(sc)) {
17961         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
17962         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
17963     }
17964
17965     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17966
17967     /* HC init per function */
17968     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17969         if (CHIP_IS_E1H(sc)) {
17970             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17971
17972             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17973             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17974         }
17975         ecore_init_block(sc, BLOCK_HC, init_phase);
17976
17977     } else {
17978         int num_segs, sb_idx, prod_offset;
17979
17980         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17981
17982         if (!CHIP_IS_E1x(sc)) {
17983             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
17984             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
17985         }
17986
17987         ecore_init_block(sc, BLOCK_IGU, init_phase);
17988
17989         if (!CHIP_IS_E1x(sc)) {
17990             int dsb_idx = 0;
17991             /**
17992              * Producer memory:
17993              * E2 mode: address 0-135 match to the mapping memory;
17994              * 136 - PF0 default prod; 137 - PF1 default prod;
17995              * 138 - PF2 default prod; 139 - PF3 default prod;
17996              * 140 - PF0 attn prod;    141 - PF1 attn prod;
17997              * 142 - PF2 attn prod;    143 - PF3 attn prod;
17998              * 144-147 reserved.
17999              *
18000              * E1.5 mode - In backward compatible mode;
18001              * for non default SB; each even line in the memory
18002              * holds the U producer and each odd line hold
18003              * the C producer. The first 128 producers are for
18004              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18005              * producers are for the DSB for each PF.
18006              * Each PF has five segments: (the order inside each
18007              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18008              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18009              * 144-147 attn prods;
18010              */
18011             /* non-default-status-blocks */
18012             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18013                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18014             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18015                 prod_offset = (sc->igu_base_sb + sb_idx) *
18016                     num_segs;
18017
18018                 for (i = 0; i < num_segs; i++) {
18019                     addr = IGU_REG_PROD_CONS_MEMORY +
18020                             (prod_offset + i) * 4;
18021                     REG_WR(sc, addr, 0);
18022                 }
18023                 /* send consumer update with value 0 */
18024                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18025                            USTORM_ID, 0, IGU_INT_NOP, 1);
18026                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18027             }
18028
18029             /* default-status-blocks */
18030             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18031                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18032
18033             if (CHIP_IS_MODE_4_PORT(sc))
18034                 dsb_idx = SC_FUNC(sc);
18035             else
18036                 dsb_idx = SC_VN(sc);
18037
18038             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18039                        IGU_BC_BASE_DSB_PROD + dsb_idx :
18040                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
18041
18042             /*
18043              * igu prods come in chunks of E1HVN_MAX (4) -
18044              * does not matters what is the current chip mode
18045              */
18046             for (i = 0; i < (num_segs * E1HVN_MAX);
18047                  i += E1HVN_MAX) {
18048                 addr = IGU_REG_PROD_CONS_MEMORY +
18049                             (prod_offset + i)*4;
18050                 REG_WR(sc, addr, 0);
18051             }
18052             /* send consumer update with 0 */
18053             if (CHIP_INT_MODE_IS_BC(sc)) {
18054                 bxe_ack_sb(sc, sc->igu_dsb_id,
18055                            USTORM_ID, 0, IGU_INT_NOP, 1);
18056                 bxe_ack_sb(sc, sc->igu_dsb_id,
18057                            CSTORM_ID, 0, IGU_INT_NOP, 1);
18058                 bxe_ack_sb(sc, sc->igu_dsb_id,
18059                            XSTORM_ID, 0, IGU_INT_NOP, 1);
18060                 bxe_ack_sb(sc, sc->igu_dsb_id,
18061                            TSTORM_ID, 0, IGU_INT_NOP, 1);
18062                 bxe_ack_sb(sc, sc->igu_dsb_id,
18063                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18064             } else {
18065                 bxe_ack_sb(sc, sc->igu_dsb_id,
18066                            USTORM_ID, 0, IGU_INT_NOP, 1);
18067                 bxe_ack_sb(sc, sc->igu_dsb_id,
18068                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18069             }
18070             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18071
18072             /* !!! these should become driver const once
18073                rf-tool supports split-68 const */
18074             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18075             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18076             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18077             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18078             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18079             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18080         }
18081     }
18082
18083     /* Reset PCIE errors for debug */
18084     REG_WR(sc, 0x2114, 0xffffffff);
18085     REG_WR(sc, 0x2120, 0xffffffff);
18086
18087     if (CHIP_IS_E1x(sc)) {
18088         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18089         main_mem_base = HC_REG_MAIN_MEMORY +
18090                 SC_PORT(sc) * (main_mem_size * 4);
18091         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18092         main_mem_width = 8;
18093
18094         val = REG_RD(sc, main_mem_prty_clr);
18095         if (val) {
18096             BLOGD(sc, DBG_LOAD,
18097                   "Parity errors in HC block during function init (0x%x)!\n",
18098                   val);
18099         }
18100
18101         /* Clear "false" parity errors in MSI-X table */
18102         for (i = main_mem_base;
18103              i < main_mem_base + main_mem_size * 4;
18104              i += main_mem_width) {
18105             bxe_read_dmae(sc, i, main_mem_width / 4);
18106             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18107                            i, main_mem_width / 4);
18108         }
18109         /* Clear HC parity attention */
18110         REG_RD(sc, main_mem_prty_clr);
18111     }
18112
18113 #if 1
18114     /* Enable STORMs SP logging */
18115     REG_WR8(sc, BAR_USTRORM_INTMEM +
18116            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18117     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18118            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18119     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18120            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18121     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18122            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18123 #endif
18124
18125     elink_phy_probe(&sc->link_params);
18126
18127     return (0);
18128 }
18129
18130 static void
18131 bxe_link_reset(struct bxe_softc *sc)
18132 {
18133     if (!BXE_NOMCP(sc)) {
18134         bxe_acquire_phy_lock(sc);
18135         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18136         bxe_release_phy_lock(sc);
18137     } else {
18138         if (!CHIP_REV_IS_SLOW(sc)) {
18139             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18140         }
18141     }
18142 }
18143
18144 static void
18145 bxe_reset_port(struct bxe_softc *sc)
18146 {
18147     int port = SC_PORT(sc);
18148     uint32_t val;
18149
18150     /* reset physical Link */
18151     bxe_link_reset(sc);
18152
18153     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18154
18155     /* Do not rcv packets to BRB */
18156     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18157     /* Do not direct rcv packets that are not for MCP to the BRB */
18158     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18159                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18160
18161     /* Configure AEU */
18162     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18163
18164     DELAY(100000);
18165
18166     /* Check for BRB port occupancy */
18167     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18168     if (val) {
18169         BLOGD(sc, DBG_LOAD,
18170               "BRB1 is not empty, %d blocks are occupied\n", val);
18171     }
18172
18173     /* TODO: Close Doorbell port? */
18174 }
18175
18176 static void
18177 bxe_ilt_wr(struct bxe_softc *sc,
18178            uint32_t         index,
18179            bus_addr_t       addr)
18180 {
18181     int reg;
18182     uint32_t wb_write[2];
18183
18184     if (CHIP_IS_E1(sc)) {
18185         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18186     } else {
18187         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18188     }
18189
18190     wb_write[0] = ONCHIP_ADDR1(addr);
18191     wb_write[1] = ONCHIP_ADDR2(addr);
18192     REG_WR_DMAE(sc, reg, wb_write, 2);
18193 }
18194
18195 static void
18196 bxe_clear_func_ilt(struct bxe_softc *sc,
18197                    uint32_t         func)
18198 {
18199     uint32_t i, base = FUNC_ILT_BASE(func);
18200     for (i = base; i < base + ILT_PER_FUNC; i++) {
18201         bxe_ilt_wr(sc, i, 0);
18202     }
18203 }
18204
18205 static void
18206 bxe_reset_func(struct bxe_softc *sc)
18207 {
18208     struct bxe_fastpath *fp;
18209     int port = SC_PORT(sc);
18210     int func = SC_FUNC(sc);
18211     int i;
18212
18213     /* Disable the function in the FW */
18214     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18215     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18216     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18217     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18218
18219     /* FP SBs */
18220     FOR_EACH_ETH_QUEUE(sc, i) {
18221         fp = &sc->fp[i];
18222         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18223                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18224                 SB_DISABLED);
18225     }
18226
18227     /* SP SB */
18228     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18229             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18230             SB_DISABLED);
18231
18232     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18233         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18234     }
18235
18236     /* Configure IGU */
18237     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18238         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18239         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18240     } else {
18241         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18242         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18243     }
18244
18245     if (CNIC_LOADED(sc)) {
18246         /* Disable Timer scan */
18247         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18248         /*
18249          * Wait for at least 10ms and up to 2 second for the timers
18250          * scan to complete
18251          */
18252         for (i = 0; i < 200; i++) {
18253             DELAY(10000);
18254             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18255                 break;
18256         }
18257     }
18258
18259     /* Clear ILT */
18260     bxe_clear_func_ilt(sc, func);
18261
18262     /*
18263      * Timers workaround bug for E2: if this is vnic-3,
18264      * we need to set the entire ilt range for this timers.
18265      */
18266     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18267         struct ilt_client_info ilt_cli;
18268         /* use dummy TM client */
18269         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18270         ilt_cli.start = 0;
18271         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18272         ilt_cli.client_num = ILT_CLIENT_TM;
18273
18274         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18275     }
18276
18277     /* this assumes that reset_port() called before reset_func()*/
18278     if (!CHIP_IS_E1x(sc)) {
18279         bxe_pf_disable(sc);
18280     }
18281
18282     sc->dmae_ready = 0;
18283 }
18284
18285 static int
18286 bxe_gunzip_init(struct bxe_softc *sc)
18287 {
18288     return (0);
18289 }
18290
18291 static void
18292 bxe_gunzip_end(struct bxe_softc *sc)
18293 {
18294     return;
18295 }
18296
18297 static int
18298 bxe_init_firmware(struct bxe_softc *sc)
18299 {
18300     if (CHIP_IS_E1(sc)) {
18301         ecore_init_e1_firmware(sc);
18302         sc->iro_array = e1_iro_arr;
18303     } else if (CHIP_IS_E1H(sc)) {
18304         ecore_init_e1h_firmware(sc);
18305         sc->iro_array = e1h_iro_arr;
18306     } else if (!CHIP_IS_E1x(sc)) {
18307         ecore_init_e2_firmware(sc);
18308         sc->iro_array = e2_iro_arr;
18309     } else {
18310         BLOGE(sc, "Unsupported chip revision\n");
18311         return (-1);
18312     }
18313
18314     return (0);
18315 }
18316
18317 static void
18318 bxe_release_firmware(struct bxe_softc *sc)
18319 {
18320     /* Do nothing */
18321     return;
18322 }
18323
18324 static int
18325 ecore_gunzip(struct bxe_softc *sc,
18326              const uint8_t    *zbuf,
18327              int              len)
18328 {
18329     /* XXX : Implement... */
18330     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18331     return (FALSE);
18332 }
18333
18334 static void
18335 ecore_reg_wr_ind(struct bxe_softc *sc,
18336                  uint32_t         addr,
18337                  uint32_t         val)
18338 {
18339     bxe_reg_wr_ind(sc, addr, val);
18340 }
18341
18342 static void
18343 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18344                           bus_addr_t       phys_addr,
18345                           uint32_t         addr,
18346                           uint32_t         len)
18347 {
18348     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18349 }
18350
18351 void
18352 ecore_storm_memset_struct(struct bxe_softc *sc,
18353                           uint32_t         addr,
18354                           size_t           size,
18355                           uint32_t         *data)
18356 {
18357     uint8_t i;
18358     for (i = 0; i < size/4; i++) {
18359         REG_WR(sc, addr + (i * 4), data[i]);
18360     }
18361 }
18362
18363
18364 /*
18365  * character device - ioctl interface definitions
18366  */
18367
18368
18369 #include "bxe_dump.h"
18370 #include "bxe_ioctl.h"
18371 #include <sys/conf.h>
18372
18373 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18374                 struct thread *td);
18375
18376 static struct cdevsw bxe_cdevsw = {
18377     .d_version = D_VERSION,
18378     .d_ioctl = bxe_eioctl,
18379     .d_name = "bxecnic",
18380 };
18381
18382 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18383
18384
18385 #define DUMP_ALL_PRESETS        0x1FFF
18386 #define DUMP_MAX_PRESETS        13
18387 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18388 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18389 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18390 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18391 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18392
18393 #define IS_REG_IN_PRESET(presets, idx)  \
18394                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18395
18396
18397 static int
18398 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18399 {
18400     if (CHIP_IS_E1(sc))
18401         return dump_num_registers[0][preset-1];
18402     else if (CHIP_IS_E1H(sc))
18403         return dump_num_registers[1][preset-1];
18404     else if (CHIP_IS_E2(sc))
18405         return dump_num_registers[2][preset-1];
18406     else if (CHIP_IS_E3A0(sc))
18407         return dump_num_registers[3][preset-1];
18408     else if (CHIP_IS_E3B0(sc))
18409         return dump_num_registers[4][preset-1];
18410     else
18411         return 0;
18412 }
18413
18414 static int
18415 bxe_get_total_regs_len32(struct bxe_softc *sc)
18416 {
18417     uint32_t preset_idx;
18418     int regdump_len32 = 0;
18419
18420
18421     /* Calculate the total preset regs length */
18422     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18423         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18424     }
18425
18426     return regdump_len32;
18427 }
18428
18429 static const uint32_t *
18430 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18431 {
18432     if (CHIP_IS_E2(sc))
18433         return page_vals_e2;
18434     else if (CHIP_IS_E3(sc))
18435         return page_vals_e3;
18436     else
18437         return NULL;
18438 }
18439
18440 static uint32_t
18441 __bxe_get_page_reg_num(struct bxe_softc *sc)
18442 {
18443     if (CHIP_IS_E2(sc))
18444         return PAGE_MODE_VALUES_E2;
18445     else if (CHIP_IS_E3(sc))
18446         return PAGE_MODE_VALUES_E3;
18447     else
18448         return 0;
18449 }
18450
18451 static const uint32_t *
18452 __bxe_get_page_write_ar(struct bxe_softc *sc)
18453 {
18454     if (CHIP_IS_E2(sc))
18455         return page_write_regs_e2;
18456     else if (CHIP_IS_E3(sc))
18457         return page_write_regs_e3;
18458     else
18459         return NULL;
18460 }
18461
18462 static uint32_t
18463 __bxe_get_page_write_num(struct bxe_softc *sc)
18464 {
18465     if (CHIP_IS_E2(sc))
18466         return PAGE_WRITE_REGS_E2;
18467     else if (CHIP_IS_E3(sc))
18468         return PAGE_WRITE_REGS_E3;
18469     else
18470         return 0;
18471 }
18472
18473 static const struct reg_addr *
18474 __bxe_get_page_read_ar(struct bxe_softc *sc)
18475 {
18476     if (CHIP_IS_E2(sc))
18477         return page_read_regs_e2;
18478     else if (CHIP_IS_E3(sc))
18479         return page_read_regs_e3;
18480     else
18481         return NULL;
18482 }
18483
18484 static uint32_t
18485 __bxe_get_page_read_num(struct bxe_softc *sc)
18486 {
18487     if (CHIP_IS_E2(sc))
18488         return PAGE_READ_REGS_E2;
18489     else if (CHIP_IS_E3(sc))
18490         return PAGE_READ_REGS_E3;
18491     else
18492         return 0;
18493 }
18494
18495 static bool
18496 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18497 {
18498     if (CHIP_IS_E1(sc))
18499         return IS_E1_REG(reg_info->chips);
18500     else if (CHIP_IS_E1H(sc))
18501         return IS_E1H_REG(reg_info->chips);
18502     else if (CHIP_IS_E2(sc))
18503         return IS_E2_REG(reg_info->chips);
18504     else if (CHIP_IS_E3A0(sc))
18505         return IS_E3A0_REG(reg_info->chips);
18506     else if (CHIP_IS_E3B0(sc))
18507         return IS_E3B0_REG(reg_info->chips);
18508     else
18509         return 0;
18510 }
18511
18512 static bool
18513 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18514 {
18515     if (CHIP_IS_E1(sc))
18516         return IS_E1_REG(wreg_info->chips);
18517     else if (CHIP_IS_E1H(sc))
18518         return IS_E1H_REG(wreg_info->chips);
18519     else if (CHIP_IS_E2(sc))
18520         return IS_E2_REG(wreg_info->chips);
18521     else if (CHIP_IS_E3A0(sc))
18522         return IS_E3A0_REG(wreg_info->chips);
18523     else if (CHIP_IS_E3B0(sc))
18524         return IS_E3B0_REG(wreg_info->chips);
18525     else
18526         return 0;
18527 }
18528
18529 /**
18530  * bxe_read_pages_regs - read "paged" registers
18531  *
18532  * @bp          device handle
18533  * @p           output buffer
18534  *
18535  * Reads "paged" memories: memories that may only be read by first writing to a
18536  * specific address ("write address") and then reading from a specific address
18537  * ("read address"). There may be more than one write address per "page" and
18538  * more than one read address per write address.
18539  */
18540 static void
18541 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18542 {
18543     uint32_t i, j, k, n;
18544
18545     /* addresses of the paged registers */
18546     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18547     /* number of paged registers */
18548     int num_pages = __bxe_get_page_reg_num(sc);
18549     /* write addresses */
18550     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18551     /* number of write addresses */
18552     int write_num = __bxe_get_page_write_num(sc);
18553     /* read addresses info */
18554     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18555     /* number of read addresses */
18556     int read_num = __bxe_get_page_read_num(sc);
18557     uint32_t addr, size;
18558
18559     for (i = 0; i < num_pages; i++) {
18560         for (j = 0; j < write_num; j++) {
18561             REG_WR(sc, write_addr[j], page_addr[i]);
18562
18563             for (k = 0; k < read_num; k++) {
18564                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18565                     size = read_addr[k].size;
18566                     for (n = 0; n < size; n++) {
18567                         addr = read_addr[k].addr + n*4;
18568                         *p++ = REG_RD(sc, addr);
18569                     }
18570                 }
18571             }
18572         }
18573     }
18574     return;
18575 }
18576
18577
18578 static int
18579 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18580 {
18581     uint32_t i, j, addr;
18582     const struct wreg_addr *wreg_addr_p = NULL;
18583
18584     if (CHIP_IS_E1(sc))
18585         wreg_addr_p = &wreg_addr_e1;
18586     else if (CHIP_IS_E1H(sc))
18587         wreg_addr_p = &wreg_addr_e1h;
18588     else if (CHIP_IS_E2(sc))
18589         wreg_addr_p = &wreg_addr_e2;
18590     else if (CHIP_IS_E3A0(sc))
18591         wreg_addr_p = &wreg_addr_e3;
18592     else if (CHIP_IS_E3B0(sc))
18593         wreg_addr_p = &wreg_addr_e3b0;
18594     else
18595         return (-1);
18596
18597     /* Read the idle_chk registers */
18598     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18599         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18600             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18601             for (j = 0; j < idle_reg_addrs[i].size; j++)
18602                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18603         }
18604     }
18605
18606     /* Read the regular registers */
18607     for (i = 0; i < REGS_COUNT; i++) {
18608         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18609             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18610             for (j = 0; j < reg_addrs[i].size; j++)
18611                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18612         }
18613     }
18614
18615     /* Read the CAM registers */
18616     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18617         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18618         for (i = 0; i < wreg_addr_p->size; i++) {
18619             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18620
18621             /* In case of wreg_addr register, read additional
18622                registers from read_regs array
18623              */
18624             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18625                 addr = *(wreg_addr_p->read_regs);
18626                 *p++ = REG_RD(sc, addr + j*4);
18627             }
18628         }
18629     }
18630
18631     /* Paged registers are supported in E2 & E3 only */
18632     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18633         /* Read "paged" registers */
18634         bxe_read_pages_regs(sc, p, preset);
18635     }
18636
18637     return 0;
18638 }
18639
18640 static int
18641 bxe_grc_dump(struct bxe_softc *sc)
18642 {
18643     int rval = 0;
18644     uint32_t preset_idx;
18645     uint8_t *buf;
18646     uint32_t size;
18647     struct  dump_header *d_hdr;
18648
18649     if (sc->grcdump_done)
18650         return (rval);
18651     
18652     ecore_disable_blocks_parity(sc);
18653
18654     buf = sc->grc_dump;
18655     d_hdr = sc->grc_dump;
18656
18657     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18658     d_hdr->version = BNX2X_DUMP_VERSION;
18659     d_hdr->preset = DUMP_ALL_PRESETS;
18660
18661     if (CHIP_IS_E1(sc)) {
18662         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18663     } else if (CHIP_IS_E1H(sc)) {
18664         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18665     } else if (CHIP_IS_E2(sc)) {
18666         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18667                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18668     } else if (CHIP_IS_E3A0(sc)) {
18669         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18670                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18671     } else if (CHIP_IS_E3B0(sc)) {
18672         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18673                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18674     }
18675
18676     buf += sizeof(struct  dump_header);
18677
18678     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18679
18680         /* Skip presets with IOR */
18681         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18682             (preset_idx == 11))
18683             continue;
18684
18685         rval = bxe_get_preset_regs(sc, sc->grc_dump, preset_idx);
18686
18687         if (rval)
18688             break;
18689
18690         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18691
18692         buf += size;
18693     }
18694
18695     ecore_clear_blocks_parity(sc);
18696     ecore_enable_blocks_parity(sc);
18697
18698     sc->grcdump_done = 1;
18699     return(rval);
18700 }
18701
18702 static int
18703 bxe_add_cdev(struct bxe_softc *sc)
18704 {
18705     int grc_dump_size;
18706
18707     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18708                                 sizeof(struct  dump_header);
18709
18710     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18711
18712     if (sc->grc_dump == NULL)
18713         return (-1);
18714
18715     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18716                             sc->ifnet->if_dunit,
18717                             UID_ROOT,
18718                             GID_WHEEL,
18719                             0600,
18720                             "%s",
18721                             if_name(sc->ifnet));
18722
18723     if (sc->ioctl_dev == NULL) {
18724
18725         free(sc->grc_dump, M_DEVBUF);
18726
18727         return (-1);
18728     }
18729
18730     sc->ioctl_dev->si_drv1 = sc;
18731
18732     return (0);
18733 }
18734
18735 static void
18736 bxe_del_cdev(struct bxe_softc *sc)
18737 {
18738     if (sc->ioctl_dev != NULL)
18739         destroy_dev(sc->ioctl_dev);
18740
18741     if (sc->grc_dump == NULL)
18742         free(sc->grc_dump, M_DEVBUF);
18743
18744     return;
18745 }
18746
18747 static int
18748 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18749         struct thread *td)
18750 {
18751     struct bxe_softc    *sc;
18752     int                 rval = 0;
18753     device_t            pci_dev;
18754     bxe_grcdump_t       *dump = NULL;
18755     int grc_dump_size;
18756
18757     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
18758         return ENXIO;
18759
18760     pci_dev= sc->dev;
18761
18762     dump = (bxe_grcdump_t *)data;
18763
18764     switch(cmd) {
18765
18766         case BXE_GRC_DUMP_SIZE:
18767             dump->pci_func = sc->pcie_func;
18768             dump->grcdump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18769                                         sizeof(struct  dump_header);
18770             break;
18771
18772         case BXE_GRC_DUMP:
18773             
18774             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18775                                 sizeof(struct  dump_header);
18776
18777             if ((sc->grc_dump == NULL) || (dump->grcdump == NULL) ||
18778                 (dump->grcdump_size < grc_dump_size) || (!sc->grcdump_done)) {
18779                 rval = EINVAL;
18780                 break;
18781             }
18782             dump->grcdump_dwords = grc_dump_size >> 2;
18783             rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
18784             sc->grcdump_done = 0;
18785
18786             break;
18787
18788         default:
18789             break;
18790     }
18791
18792     return (rval);
18793 }