]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/dev/bxe/bxe.c
MFC r336438
[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.91"
31
32 #include "bxe.h"
33 #include "ecore_sp.h"
34 #include "ecore_init.h"
35 #include "ecore_init_ops.h"
36
37 #include "57710_int_offsets.h"
38 #include "57711_int_offsets.h"
39 #include "57712_int_offsets.h"
40
41 /*
42  * CTLTYPE_U64 and sysctl_handle_64 were added in r217616. Define these
43  * explicitly here for older kernels that don't include this changeset.
44  */
45 #ifndef CTLTYPE_U64
46 #define CTLTYPE_U64      CTLTYPE_QUAD
47 #define sysctl_handle_64 sysctl_handle_quad
48 #endif
49
50 /*
51  * CSUM_TCP_IPV6 and CSUM_UDP_IPV6 were added in r236170. Define these
52  * here as zero(0) for older kernels that don't include this changeset
53  * thereby masking the functionality.
54  */
55 #ifndef CSUM_TCP_IPV6
56 #define CSUM_TCP_IPV6 0
57 #define CSUM_UDP_IPV6 0
58 #endif
59
60 /*
61  * pci_find_cap was added in r219865. Re-define this at pci_find_extcap
62  * for older kernels that don't include this changeset.
63  */
64 #if __FreeBSD_version < 900035
65 #define pci_find_cap pci_find_extcap
66 #endif
67
68 #define BXE_DEF_SB_ATT_IDX 0x0001
69 #define BXE_DEF_SB_IDX     0x0002
70
71 /*
72  * FLR Support - bxe_pf_flr_clnup() is called during nic_load in the per
73  * function HW initialization.
74  */
75 #define FLR_WAIT_USEC     10000 /* 10 msecs */
76 #define FLR_WAIT_INTERVAL 50    /* usecs */
77 #define FLR_POLL_CNT      (FLR_WAIT_USEC / FLR_WAIT_INTERVAL) /* 200 */
78
79 struct pbf_pN_buf_regs {
80     int pN;
81     uint32_t init_crd;
82     uint32_t crd;
83     uint32_t crd_freed;
84 };
85
86 struct pbf_pN_cmd_regs {
87     int pN;
88     uint32_t lines_occup;
89     uint32_t lines_freed;
90 };
91
92 /*
93  * PCI Device ID Table used by bxe_probe().
94  */
95 #define BXE_DEVDESC_MAX 64
96 static struct bxe_device_type bxe_devs[] = {
97     {
98         BRCM_VENDORID,
99         CHIP_NUM_57710,
100         PCI_ANY_ID, PCI_ANY_ID,
101         "QLogic NetXtreme II BCM57710 10GbE"
102     },
103     {
104         BRCM_VENDORID,
105         CHIP_NUM_57711,
106         PCI_ANY_ID, PCI_ANY_ID,
107         "QLogic NetXtreme II BCM57711 10GbE"
108     },
109     {
110         BRCM_VENDORID,
111         CHIP_NUM_57711E,
112         PCI_ANY_ID, PCI_ANY_ID,
113         "QLogic NetXtreme II BCM57711E 10GbE"
114     },
115     {
116         BRCM_VENDORID,
117         CHIP_NUM_57712,
118         PCI_ANY_ID, PCI_ANY_ID,
119         "QLogic NetXtreme II BCM57712 10GbE"
120     },
121     {
122         BRCM_VENDORID,
123         CHIP_NUM_57712_MF,
124         PCI_ANY_ID, PCI_ANY_ID,
125         "QLogic NetXtreme II BCM57712 MF 10GbE"
126     },
127     {
128         BRCM_VENDORID,
129         CHIP_NUM_57800,
130         PCI_ANY_ID, PCI_ANY_ID,
131         "QLogic NetXtreme II BCM57800 10GbE"
132     },
133     {
134         BRCM_VENDORID,
135         CHIP_NUM_57800_MF,
136         PCI_ANY_ID, PCI_ANY_ID,
137         "QLogic NetXtreme II BCM57800 MF 10GbE"
138     },
139     {
140         BRCM_VENDORID,
141         CHIP_NUM_57810,
142         PCI_ANY_ID, PCI_ANY_ID,
143         "QLogic NetXtreme II BCM57810 10GbE"
144     },
145     {
146         BRCM_VENDORID,
147         CHIP_NUM_57810_MF,
148         PCI_ANY_ID, PCI_ANY_ID,
149         "QLogic NetXtreme II BCM57810 MF 10GbE"
150     },
151     {
152         BRCM_VENDORID,
153         CHIP_NUM_57811,
154         PCI_ANY_ID, PCI_ANY_ID,
155         "QLogic NetXtreme II BCM57811 10GbE"
156     },
157     {
158         BRCM_VENDORID,
159         CHIP_NUM_57811_MF,
160         PCI_ANY_ID, PCI_ANY_ID,
161         "QLogic NetXtreme II BCM57811 MF 10GbE"
162     },
163     {
164         BRCM_VENDORID,
165         CHIP_NUM_57840_4_10,
166         PCI_ANY_ID, PCI_ANY_ID,
167         "QLogic NetXtreme II BCM57840 4x10GbE"
168     },
169     {
170         BRCM_VENDORID,
171         CHIP_NUM_57840_MF,
172         PCI_ANY_ID, PCI_ANY_ID,
173         "QLogic NetXtreme II BCM57840 MF 10GbE"
174     },
175     {
176         0, 0, 0, 0, NULL
177     }
178 };
179
180 MALLOC_DECLARE(M_BXE_ILT);
181 MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
182
183 /*
184  * FreeBSD device entry points.
185  */
186 static int bxe_probe(device_t);
187 static int bxe_attach(device_t);
188 static int bxe_detach(device_t);
189 static int bxe_shutdown(device_t);
190
191 /*
192  * FreeBSD KLD module/device interface event handler method.
193  */
194 static device_method_t bxe_methods[] = {
195     /* Device interface (device_if.h) */
196     DEVMETHOD(device_probe,     bxe_probe),
197     DEVMETHOD(device_attach,    bxe_attach),
198     DEVMETHOD(device_detach,    bxe_detach),
199     DEVMETHOD(device_shutdown,  bxe_shutdown),
200     /* Bus interface (bus_if.h) */
201     DEVMETHOD(bus_print_child,  bus_generic_print_child),
202     DEVMETHOD(bus_driver_added, bus_generic_driver_added),
203     KOBJMETHOD_END
204 };
205
206 /*
207  * FreeBSD KLD Module data declaration
208  */
209 static driver_t bxe_driver = {
210     "bxe",                   /* module name */
211     bxe_methods,             /* event handler */
212     sizeof(struct bxe_softc) /* extra data */
213 };
214
215 /*
216  * FreeBSD dev class is needed to manage dev instances and
217  * to associate with a bus type
218  */
219 static devclass_t bxe_devclass;
220
221 MODULE_DEPEND(bxe, pci, 1, 1, 1);
222 MODULE_DEPEND(bxe, ether, 1, 1, 1);
223 DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
224
225 /* resources needed for unloading a previously loaded device */
226
227 #define BXE_PREV_WAIT_NEEDED 1
228 struct mtx bxe_prev_mtx;
229 MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
230 struct bxe_prev_list_node {
231     LIST_ENTRY(bxe_prev_list_node) node;
232     uint8_t bus;
233     uint8_t slot;
234     uint8_t path;
235     uint8_t aer; /* XXX automatic error recovery */
236     uint8_t undi;
237 };
238 static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
239
240 static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
241
242 /* Tunable device values... */
243
244 SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
245
246 /* Debug */
247 unsigned long bxe_debug = 0;
248 TUNABLE_ULONG("hw.bxe.debug", &bxe_debug);
249 SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, (CTLFLAG_RDTUN),
250              &bxe_debug, 0, "Debug logging mode");
251
252 /* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
253 static int bxe_interrupt_mode = INTR_MODE_MSIX;
254 TUNABLE_INT("hw.bxe.interrupt_mode", &bxe_interrupt_mode);
255 SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
256            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
257
258 /* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
259 static int bxe_queue_count = 4;
260 TUNABLE_INT("hw.bxe.queue_count", &bxe_queue_count);
261 SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
262            &bxe_queue_count, 0, "Multi-Queue queue count");
263
264 /* max number of buffers per queue (default RX_BD_USABLE) */
265 static int bxe_max_rx_bufs = 0;
266 TUNABLE_INT("hw.bxe.max_rx_bufs", &bxe_max_rx_bufs);
267 SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
268            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
269
270 /* Host interrupt coalescing RX tick timer (usecs) */
271 static int bxe_hc_rx_ticks = 25;
272 TUNABLE_INT("hw.bxe.hc_rx_ticks", &bxe_hc_rx_ticks);
273 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
274            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
275
276 /* Host interrupt coalescing TX tick timer (usecs) */
277 static int bxe_hc_tx_ticks = 50;
278 TUNABLE_INT("hw.bxe.hc_tx_ticks", &bxe_hc_tx_ticks);
279 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
280            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
281
282 /* Maximum number of Rx packets to process at a time */
283 static int bxe_rx_budget = 0xffffffff;
284 TUNABLE_INT("hw.bxe.rx_budget", &bxe_rx_budget);
285 SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
286            &bxe_rx_budget, 0, "Rx processing budget");
287
288 /* Maximum LRO aggregation size */
289 static int bxe_max_aggregation_size = 0;
290 TUNABLE_INT("hw.bxe.max_aggregation_size", &bxe_max_aggregation_size);
291 SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
292            &bxe_max_aggregation_size, 0, "max aggregation size");
293
294 /* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
295 static int bxe_mrrs = -1;
296 TUNABLE_INT("hw.bxe.mrrs", &bxe_mrrs);
297 SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
298            &bxe_mrrs, 0, "PCIe maximum read request size");
299
300 /* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
301 static int bxe_autogreeen = 0;
302 TUNABLE_INT("hw.bxe.autogreeen", &bxe_autogreeen);
303 SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
304            &bxe_autogreeen, 0, "AutoGrEEEn support");
305
306 /* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
307 static int bxe_udp_rss = 0;
308 TUNABLE_INT("hw.bxe.udp_rss", &bxe_udp_rss);
309 SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
310            &bxe_udp_rss, 0, "UDP RSS support");
311
312
313 #define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
314
315 #define STATS_OFFSET32(stat_name)                   \
316     (offsetof(struct bxe_eth_stats, stat_name) / 4)
317
318 #define Q_STATS_OFFSET32(stat_name)                   \
319     (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
320
321 static const struct {
322     uint32_t offset;
323     uint32_t size;
324     uint32_t flags;
325 #define STATS_FLAGS_PORT  1
326 #define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
327 #define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
328     char string[STAT_NAME_LEN];
329 } bxe_eth_stats_arr[] = {
330     { STATS_OFFSET32(total_bytes_received_hi),
331                 8, STATS_FLAGS_BOTH, "rx_bytes" },
332     { STATS_OFFSET32(error_bytes_received_hi),
333                 8, STATS_FLAGS_BOTH, "rx_error_bytes" },
334     { STATS_OFFSET32(total_unicast_packets_received_hi),
335                 8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
336     { STATS_OFFSET32(total_multicast_packets_received_hi),
337                 8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
338     { STATS_OFFSET32(total_broadcast_packets_received_hi),
339                 8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
340     { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
341                 8, STATS_FLAGS_PORT, "rx_crc_errors" },
342     { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
343                 8, STATS_FLAGS_PORT, "rx_align_errors" },
344     { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
345                 8, STATS_FLAGS_PORT, "rx_undersize_packets" },
346     { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
347                 8, STATS_FLAGS_PORT, "rx_oversize_packets" },
348     { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
349                 8, STATS_FLAGS_PORT, "rx_fragments" },
350     { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
351                 8, STATS_FLAGS_PORT, "rx_jabbers" },
352     { STATS_OFFSET32(no_buff_discard_hi),
353                 8, STATS_FLAGS_BOTH, "rx_discards" },
354     { STATS_OFFSET32(mac_filter_discard),
355                 4, STATS_FLAGS_PORT, "rx_filtered_packets" },
356     { STATS_OFFSET32(mf_tag_discard),
357                 4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
358     { STATS_OFFSET32(pfc_frames_received_hi),
359                 8, STATS_FLAGS_PORT, "pfc_frames_received" },
360     { STATS_OFFSET32(pfc_frames_sent_hi),
361                 8, STATS_FLAGS_PORT, "pfc_frames_sent" },
362     { STATS_OFFSET32(brb_drop_hi),
363                 8, STATS_FLAGS_PORT, "rx_brb_discard" },
364     { STATS_OFFSET32(brb_truncate_hi),
365                 8, STATS_FLAGS_PORT, "rx_brb_truncate" },
366     { STATS_OFFSET32(pause_frames_received_hi),
367                 8, STATS_FLAGS_PORT, "rx_pause_frames" },
368     { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
369                 8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
370     { STATS_OFFSET32(nig_timer_max),
371                 4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
372     { STATS_OFFSET32(total_bytes_transmitted_hi),
373                 8, STATS_FLAGS_BOTH, "tx_bytes" },
374     { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
375                 8, STATS_FLAGS_PORT, "tx_error_bytes" },
376     { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
377                 8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
378     { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
379                 8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
380     { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
381                 8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
382     { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
383                 8, STATS_FLAGS_PORT, "tx_mac_errors" },
384     { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
385                 8, STATS_FLAGS_PORT, "tx_carrier_errors" },
386     { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
387                 8, STATS_FLAGS_PORT, "tx_single_collisions" },
388     { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
389                 8, STATS_FLAGS_PORT, "tx_multi_collisions" },
390     { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
391                 8, STATS_FLAGS_PORT, "tx_deferred" },
392     { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
393                 8, STATS_FLAGS_PORT, "tx_excess_collisions" },
394     { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
395                 8, STATS_FLAGS_PORT, "tx_late_collisions" },
396     { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
397                 8, STATS_FLAGS_PORT, "tx_total_collisions" },
398     { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
399                 8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
400     { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
401                 8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
402     { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
403                 8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
404     { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
405                 8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
406     { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
407                 8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
408     { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
409                 8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
410     { STATS_OFFSET32(etherstatspktsover1522octets_hi),
411                 8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
412     { STATS_OFFSET32(pause_frames_sent_hi),
413                 8, STATS_FLAGS_PORT, "tx_pause_frames" },
414     { STATS_OFFSET32(total_tpa_aggregations_hi),
415                 8, STATS_FLAGS_FUNC, "tpa_aggregations" },
416     { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
417                 8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
418     { STATS_OFFSET32(total_tpa_bytes_hi),
419                 8, STATS_FLAGS_FUNC, "tpa_bytes"},
420     { STATS_OFFSET32(eee_tx_lpi),
421                 4, STATS_FLAGS_PORT, "eee_tx_lpi"},
422     { STATS_OFFSET32(rx_calls),
423                 4, STATS_FLAGS_FUNC, "rx_calls"},
424     { STATS_OFFSET32(rx_pkts),
425                 4, STATS_FLAGS_FUNC, "rx_pkts"},
426     { STATS_OFFSET32(rx_tpa_pkts),
427                 4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
428     { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
429                 4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
430     { STATS_OFFSET32(rx_bxe_service_rxsgl),
431                 4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
432     { STATS_OFFSET32(rx_jumbo_sge_pkts),
433                 4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
434     { STATS_OFFSET32(rx_soft_errors),
435                 4, STATS_FLAGS_FUNC, "rx_soft_errors"},
436     { STATS_OFFSET32(rx_hw_csum_errors),
437                 4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
438     { STATS_OFFSET32(rx_ofld_frames_csum_ip),
439                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
440     { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
441                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
442     { STATS_OFFSET32(rx_budget_reached),
443                 4, STATS_FLAGS_FUNC, "rx_budget_reached"},
444     { STATS_OFFSET32(tx_pkts),
445                 4, STATS_FLAGS_FUNC, "tx_pkts"},
446     { STATS_OFFSET32(tx_soft_errors),
447                 4, STATS_FLAGS_FUNC, "tx_soft_errors"},
448     { STATS_OFFSET32(tx_ofld_frames_csum_ip),
449                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
450     { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
451                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
452     { STATS_OFFSET32(tx_ofld_frames_csum_udp),
453                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
454     { STATS_OFFSET32(tx_ofld_frames_lso),
455                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
456     { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
457                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
458     { STATS_OFFSET32(tx_encap_failures),
459                 4, STATS_FLAGS_FUNC, "tx_encap_failures"},
460     { STATS_OFFSET32(tx_hw_queue_full),
461                 4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
462     { STATS_OFFSET32(tx_hw_max_queue_depth),
463                 4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
464     { STATS_OFFSET32(tx_dma_mapping_failure),
465                 4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
466     { STATS_OFFSET32(tx_max_drbr_queue_depth),
467                 4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
468     { STATS_OFFSET32(tx_window_violation_std),
469                 4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
470     { STATS_OFFSET32(tx_window_violation_tso),
471                 4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
472     { STATS_OFFSET32(tx_chain_lost_mbuf),
473                 4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
474     { STATS_OFFSET32(tx_frames_deferred),
475                 4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
476     { STATS_OFFSET32(tx_queue_xoff),
477                 4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
478     { STATS_OFFSET32(mbuf_defrag_attempts),
479                 4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
480     { STATS_OFFSET32(mbuf_defrag_failures),
481                 4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
482     { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
483                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
484     { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
485                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
486     { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
487                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
488     { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
489                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
490     { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
491                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
492     { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
493                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
494     { STATS_OFFSET32(mbuf_alloc_tx),
495                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
496     { STATS_OFFSET32(mbuf_alloc_rx),
497                 4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
498     { STATS_OFFSET32(mbuf_alloc_sge),
499                 4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
500     { STATS_OFFSET32(mbuf_alloc_tpa),
501                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"},
502     { STATS_OFFSET32(tx_queue_full_return),
503                 4, STATS_FLAGS_FUNC, "tx_queue_full_return"},
504     { STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
505                 4, STATS_FLAGS_FUNC, "bxe_tx_mq_sc_state_failures"},
506     { STATS_OFFSET32(tx_request_link_down_failures),
507                 4, STATS_FLAGS_FUNC, "tx_request_link_down_failures"},
508     { STATS_OFFSET32(bd_avail_too_less_failures),
509                 4, STATS_FLAGS_FUNC, "bd_avail_too_less_failures"},
510     { STATS_OFFSET32(tx_mq_not_empty),
511                 4, STATS_FLAGS_FUNC, "tx_mq_not_empty"},
512     { STATS_OFFSET32(nsegs_path1_errors),
513                 4, STATS_FLAGS_FUNC, "nsegs_path1_errors"},
514     { STATS_OFFSET32(nsegs_path2_errors),
515                 4, STATS_FLAGS_FUNC, "nsegs_path2_errors"}
516
517
518 };
519
520 static const struct {
521     uint32_t offset;
522     uint32_t size;
523     char string[STAT_NAME_LEN];
524 } bxe_eth_q_stats_arr[] = {
525     { Q_STATS_OFFSET32(total_bytes_received_hi),
526                 8, "rx_bytes" },
527     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
528                 8, "rx_ucast_packets" },
529     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
530                 8, "rx_mcast_packets" },
531     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
532                 8, "rx_bcast_packets" },
533     { Q_STATS_OFFSET32(no_buff_discard_hi),
534                 8, "rx_discards" },
535     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
536                 8, "tx_bytes" },
537     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
538                 8, "tx_ucast_packets" },
539     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
540                 8, "tx_mcast_packets" },
541     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
542                 8, "tx_bcast_packets" },
543     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
544                 8, "tpa_aggregations" },
545     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
546                 8, "tpa_aggregated_frames"},
547     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
548                 8, "tpa_bytes"},
549     { Q_STATS_OFFSET32(rx_calls),
550                 4, "rx_calls"},
551     { Q_STATS_OFFSET32(rx_pkts),
552                 4, "rx_pkts"},
553     { Q_STATS_OFFSET32(rx_tpa_pkts),
554                 4, "rx_tpa_pkts"},
555     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
556                 4, "rx_erroneous_jumbo_sge_pkts"},
557     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
558                 4, "rx_bxe_service_rxsgl"},
559     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
560                 4, "rx_jumbo_sge_pkts"},
561     { Q_STATS_OFFSET32(rx_soft_errors),
562                 4, "rx_soft_errors"},
563     { Q_STATS_OFFSET32(rx_hw_csum_errors),
564                 4, "rx_hw_csum_errors"},
565     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
566                 4, "rx_ofld_frames_csum_ip"},
567     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
568                 4, "rx_ofld_frames_csum_tcp_udp"},
569     { Q_STATS_OFFSET32(rx_budget_reached),
570                 4, "rx_budget_reached"},
571     { Q_STATS_OFFSET32(tx_pkts),
572                 4, "tx_pkts"},
573     { Q_STATS_OFFSET32(tx_soft_errors),
574                 4, "tx_soft_errors"},
575     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
576                 4, "tx_ofld_frames_csum_ip"},
577     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
578                 4, "tx_ofld_frames_csum_tcp"},
579     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
580                 4, "tx_ofld_frames_csum_udp"},
581     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
582                 4, "tx_ofld_frames_lso"},
583     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
584                 4, "tx_ofld_frames_lso_hdr_splits"},
585     { Q_STATS_OFFSET32(tx_encap_failures),
586                 4, "tx_encap_failures"},
587     { Q_STATS_OFFSET32(tx_hw_queue_full),
588                 4, "tx_hw_queue_full"},
589     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
590                 4, "tx_hw_max_queue_depth"},
591     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
592                 4, "tx_dma_mapping_failure"},
593     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
594                 4, "tx_max_drbr_queue_depth"},
595     { Q_STATS_OFFSET32(tx_window_violation_std),
596                 4, "tx_window_violation_std"},
597     { Q_STATS_OFFSET32(tx_window_violation_tso),
598                 4, "tx_window_violation_tso"},
599     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
600                 4, "tx_chain_lost_mbuf"},
601     { Q_STATS_OFFSET32(tx_frames_deferred),
602                 4, "tx_frames_deferred"},
603     { Q_STATS_OFFSET32(tx_queue_xoff),
604                 4, "tx_queue_xoff"},
605     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
606                 4, "mbuf_defrag_attempts"},
607     { Q_STATS_OFFSET32(mbuf_defrag_failures),
608                 4, "mbuf_defrag_failures"},
609     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
610                 4, "mbuf_rx_bd_alloc_failed"},
611     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
612                 4, "mbuf_rx_bd_mapping_failed"},
613     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
614                 4, "mbuf_rx_tpa_alloc_failed"},
615     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
616                 4, "mbuf_rx_tpa_mapping_failed"},
617     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
618                 4, "mbuf_rx_sge_alloc_failed"},
619     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
620                 4, "mbuf_rx_sge_mapping_failed"},
621     { Q_STATS_OFFSET32(mbuf_alloc_tx),
622                 4, "mbuf_alloc_tx"},
623     { Q_STATS_OFFSET32(mbuf_alloc_rx),
624                 4, "mbuf_alloc_rx"},
625     { Q_STATS_OFFSET32(mbuf_alloc_sge),
626                 4, "mbuf_alloc_sge"},
627     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
628                 4, "mbuf_alloc_tpa"},
629     { Q_STATS_OFFSET32(tx_queue_full_return),
630                 4, "tx_queue_full_return"},
631     { Q_STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
632                 4, "bxe_tx_mq_sc_state_failures"},
633     { Q_STATS_OFFSET32(tx_request_link_down_failures),
634                 4, "tx_request_link_down_failures"},
635     { Q_STATS_OFFSET32(bd_avail_too_less_failures),
636                 4, "bd_avail_too_less_failures"},
637     { Q_STATS_OFFSET32(tx_mq_not_empty),
638                 4, "tx_mq_not_empty"},
639     { Q_STATS_OFFSET32(nsegs_path1_errors),
640                 4, "nsegs_path1_errors"},
641     { Q_STATS_OFFSET32(nsegs_path2_errors),
642                 4, "nsegs_path2_errors"}
643 };
644
645 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
646 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
647
648
649 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
650                                  uint8_t          read_cfg,
651                                  uint8_t          cmng_type);
652 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
653 static void    storm_memset_cmng(struct bxe_softc *sc,
654                                  struct cmng_init *cmng,
655                                  uint8_t          port);
656 static void    bxe_set_reset_global(struct bxe_softc *sc);
657 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
658 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
659                                  int              engine);
660 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
661 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
662                                    uint8_t          *global,
663                                    uint8_t          print);
664 static void    bxe_int_disable(struct bxe_softc *sc);
665 static int     bxe_release_leader_lock(struct bxe_softc *sc);
666 static void    bxe_pf_disable(struct bxe_softc *sc);
667 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
668 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
669                                       struct bxe_fastpath *fp,
670                                       uint16_t            rx_bd_prod,
671                                       uint16_t            rx_cq_prod,
672                                       uint16_t            rx_sge_prod);
673 static void    bxe_link_report_locked(struct bxe_softc *sc);
674 static void    bxe_link_report(struct bxe_softc *sc);
675 static void    bxe_link_status_update(struct bxe_softc *sc);
676 static void    bxe_periodic_callout_func(void *xsc);
677 static void    bxe_periodic_start(struct bxe_softc *sc);
678 static void    bxe_periodic_stop(struct bxe_softc *sc);
679 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
680                                     uint16_t prev_index,
681                                     uint16_t index);
682 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
683                                      int                 queue);
684 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
685                                      uint16_t            index);
686 static uint8_t bxe_txeof(struct bxe_softc *sc,
687                          struct bxe_fastpath *fp);
688 static void    bxe_task_fp(struct bxe_fastpath *fp);
689 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
690                                      struct mbuf      *m,
691                                      uint8_t          contents);
692 static int     bxe_alloc_mem(struct bxe_softc *sc);
693 static void    bxe_free_mem(struct bxe_softc *sc);
694 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
695 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
696 static int     bxe_interrupt_attach(struct bxe_softc *sc);
697 static void    bxe_interrupt_detach(struct bxe_softc *sc);
698 static void    bxe_set_rx_mode(struct bxe_softc *sc);
699 static int     bxe_init_locked(struct bxe_softc *sc);
700 static int     bxe_stop_locked(struct bxe_softc *sc);
701 static __noinline int bxe_nic_load(struct bxe_softc *sc,
702                                    int              load_mode);
703 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
704                                      uint32_t         unload_mode,
705                                      uint8_t          keep_link);
706
707 static void bxe_handle_sp_tq(void *context, int pending);
708 static void bxe_handle_fp_tq(void *context, int pending);
709
710 static int bxe_add_cdev(struct bxe_softc *sc);
711 static void bxe_del_cdev(struct bxe_softc *sc);
712 int bxe_grc_dump(struct bxe_softc *sc);
713 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
714 static void bxe_free_buf_rings(struct bxe_softc *sc);
715
716 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
717 uint32_t
718 calc_crc32(uint8_t  *crc32_packet,
719            uint32_t crc32_length,
720            uint32_t crc32_seed,
721            uint8_t  complement)
722 {
723    uint32_t byte         = 0;
724    uint32_t bit          = 0;
725    uint8_t  msb          = 0;
726    uint32_t temp         = 0;
727    uint32_t shft         = 0;
728    uint8_t  current_byte = 0;
729    uint32_t crc32_result = crc32_seed;
730    const uint32_t CRC32_POLY = 0x1edc6f41;
731
732    if ((crc32_packet == NULL) ||
733        (crc32_length == 0) ||
734        ((crc32_length % 8) != 0))
735     {
736         return (crc32_result);
737     }
738
739     for (byte = 0; byte < crc32_length; byte = byte + 1)
740     {
741         current_byte = crc32_packet[byte];
742         for (bit = 0; bit < 8; bit = bit + 1)
743         {
744             /* msb = crc32_result[31]; */
745             msb = (uint8_t)(crc32_result >> 31);
746
747             crc32_result = crc32_result << 1;
748
749             /* it (msb != current_byte[bit]) */
750             if (msb != (0x1 & (current_byte >> bit)))
751             {
752                 crc32_result = crc32_result ^ CRC32_POLY;
753                 /* crc32_result[0] = 1 */
754                 crc32_result |= 1;
755             }
756         }
757     }
758
759     /* Last step is to:
760      * 1. "mirror" every bit
761      * 2. swap the 4 bytes
762      * 3. complement each bit
763      */
764
765     /* Mirror */
766     temp = crc32_result;
767     shft = sizeof(crc32_result) * 8 - 1;
768
769     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
770     {
771         temp <<= 1;
772         temp |= crc32_result & 1;
773         shft-- ;
774     }
775
776     /* temp[31-bit] = crc32_result[bit] */
777     temp <<= shft;
778
779     /* Swap */
780     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
781     {
782         uint32_t t0, t1, t2, t3;
783         t0 = (0x000000ff & (temp >> 24));
784         t1 = (0x0000ff00 & (temp >> 8));
785         t2 = (0x00ff0000 & (temp << 8));
786         t3 = (0xff000000 & (temp << 24));
787         crc32_result = t0 | t1 | t2 | t3;
788     }
789
790     /* Complement */
791     if (complement)
792     {
793         crc32_result = ~crc32_result;
794     }
795
796     return (crc32_result);
797 }
798
799 int
800 bxe_test_bit(int                    nr,
801              volatile unsigned long *addr)
802 {
803     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
804 }
805
806 void
807 bxe_set_bit(unsigned int           nr,
808             volatile unsigned long *addr)
809 {
810     atomic_set_acq_long(addr, (1 << nr));
811 }
812
813 void
814 bxe_clear_bit(int                    nr,
815               volatile unsigned long *addr)
816 {
817     atomic_clear_acq_long(addr, (1 << nr));
818 }
819
820 int
821 bxe_test_and_set_bit(int                    nr,
822                        volatile unsigned long *addr)
823 {
824     unsigned long x;
825     nr = (1 << nr);
826     do {
827         x = *addr;
828     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
829     // if (x & nr) bit_was_set; else bit_was_not_set;
830     return (x & nr);
831 }
832
833 int
834 bxe_test_and_clear_bit(int                    nr,
835                        volatile unsigned long *addr)
836 {
837     unsigned long x;
838     nr = (1 << nr);
839     do {
840         x = *addr;
841     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
842     // if (x & nr) bit_was_set; else bit_was_not_set;
843     return (x & nr);
844 }
845
846 int
847 bxe_cmpxchg(volatile int *addr,
848             int          old,
849             int          new)
850 {
851     int x;
852     do {
853         x = *addr;
854     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
855     return (x);
856 }
857
858 /*
859  * Get DMA memory from the OS.
860  *
861  * Validates that the OS has provided DMA buffers in response to a
862  * bus_dmamap_load call and saves the physical address of those buffers.
863  * When the callback is used the OS will return 0 for the mapping function
864  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
865  * failures back to the caller.
866  *
867  * Returns:
868  *   Nothing.
869  */
870 static void
871 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
872 {
873     struct bxe_dma *dma = arg;
874
875     if (error) {
876         dma->paddr = 0;
877         dma->nseg  = 0;
878         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
879     } else {
880         dma->paddr = segs->ds_addr;
881         dma->nseg  = nseg;
882     }
883 }
884
885 /*
886  * Allocate a block of memory and map it for DMA. No partial completions
887  * allowed and release any resources acquired if we can't acquire all
888  * resources.
889  *
890  * Returns:
891  *   0 = Success, !0 = Failure
892  */
893 int
894 bxe_dma_alloc(struct bxe_softc *sc,
895               bus_size_t       size,
896               struct bxe_dma   *dma,
897               const char       *msg)
898 {
899     int rc;
900
901     if (dma->size > 0) {
902         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
903               (unsigned long)dma->size);
904         return (1);
905     }
906
907     memset(dma, 0, sizeof(*dma)); /* sanity */
908     dma->sc   = sc;
909     dma->size = size;
910     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
911
912     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
913                             BCM_PAGE_SIZE,      /* alignment */
914                             0,                  /* boundary limit */
915                             BUS_SPACE_MAXADDR,  /* restricted low */
916                             BUS_SPACE_MAXADDR,  /* restricted hi */
917                             NULL,               /* addr filter() */
918                             NULL,               /* addr filter() arg */
919                             size,               /* max map size */
920                             1,                  /* num discontinuous */
921                             size,               /* max seg size */
922                             BUS_DMA_ALLOCNOW,   /* flags */
923                             NULL,               /* lock() */
924                             NULL,               /* lock() arg */
925                             &dma->tag);         /* returned dma tag */
926     if (rc != 0) {
927         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
928         memset(dma, 0, sizeof(*dma));
929         return (1);
930     }
931
932     rc = bus_dmamem_alloc(dma->tag,
933                           (void **)&dma->vaddr,
934                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
935                           &dma->map);
936     if (rc != 0) {
937         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
938         bus_dma_tag_destroy(dma->tag);
939         memset(dma, 0, sizeof(*dma));
940         return (1);
941     }
942
943     rc = bus_dmamap_load(dma->tag,
944                          dma->map,
945                          dma->vaddr,
946                          size,
947                          bxe_dma_map_addr, /* BLOGD in here */
948                          dma,
949                          BUS_DMA_NOWAIT);
950     if (rc != 0) {
951         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
952         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
953         bus_dma_tag_destroy(dma->tag);
954         memset(dma, 0, sizeof(*dma));
955         return (1);
956     }
957
958     return (0);
959 }
960
961 void
962 bxe_dma_free(struct bxe_softc *sc,
963              struct bxe_dma   *dma)
964 {
965     if (dma->size > 0) {
966         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
967
968         bus_dmamap_sync(dma->tag, dma->map,
969                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
970         bus_dmamap_unload(dma->tag, dma->map);
971         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
972         bus_dma_tag_destroy(dma->tag);
973     }
974
975     memset(dma, 0, sizeof(*dma));
976 }
977
978 /*
979  * These indirect read and write routines are only during init.
980  * The locking is handled by the MCP.
981  */
982
983 void
984 bxe_reg_wr_ind(struct bxe_softc *sc,
985                uint32_t         addr,
986                uint32_t         val)
987 {
988     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
989     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
990     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
991 }
992
993 uint32_t
994 bxe_reg_rd_ind(struct bxe_softc *sc,
995                uint32_t         addr)
996 {
997     uint32_t val;
998
999     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1000     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
1001     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1002
1003     return (val);
1004 }
1005
1006 static int
1007 bxe_acquire_hw_lock(struct bxe_softc *sc,
1008                     uint32_t         resource)
1009 {
1010     uint32_t lock_status;
1011     uint32_t resource_bit = (1 << resource);
1012     int func = SC_FUNC(sc);
1013     uint32_t hw_lock_control_reg;
1014     int cnt;
1015
1016     /* validate the resource is within range */
1017     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1018         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1019             " resource_bit 0x%x\n", resource, resource_bit);
1020         return (-1);
1021     }
1022
1023     if (func <= 5) {
1024         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1025     } else {
1026         hw_lock_control_reg =
1027                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1028     }
1029
1030     /* validate the resource is not already taken */
1031     lock_status = REG_RD(sc, hw_lock_control_reg);
1032     if (lock_status & resource_bit) {
1033         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1034               resource, lock_status, resource_bit);
1035         return (-1);
1036     }
1037
1038     /* try every 5ms for 5 seconds */
1039     for (cnt = 0; cnt < 1000; cnt++) {
1040         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1041         lock_status = REG_RD(sc, hw_lock_control_reg);
1042         if (lock_status & resource_bit) {
1043             return (0);
1044         }
1045         DELAY(5000);
1046     }
1047
1048     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1049         resource, resource_bit);
1050     return (-1);
1051 }
1052
1053 static int
1054 bxe_release_hw_lock(struct bxe_softc *sc,
1055                     uint32_t         resource)
1056 {
1057     uint32_t lock_status;
1058     uint32_t resource_bit = (1 << resource);
1059     int func = SC_FUNC(sc);
1060     uint32_t hw_lock_control_reg;
1061
1062     /* validate the resource is within range */
1063     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1064         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1065             " resource_bit 0x%x\n", resource, resource_bit);
1066         return (-1);
1067     }
1068
1069     if (func <= 5) {
1070         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1071     } else {
1072         hw_lock_control_reg =
1073                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1074     }
1075
1076     /* validate the resource is currently taken */
1077     lock_status = REG_RD(sc, hw_lock_control_reg);
1078     if (!(lock_status & resource_bit)) {
1079         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1080               resource, lock_status, resource_bit);
1081         return (-1);
1082     }
1083
1084     REG_WR(sc, hw_lock_control_reg, resource_bit);
1085     return (0);
1086 }
1087 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1088 {
1089         BXE_PHY_LOCK(sc);
1090         bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1091 }
1092
1093 static void bxe_release_phy_lock(struct bxe_softc *sc)
1094 {
1095         bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1096         BXE_PHY_UNLOCK(sc);
1097 }
1098 /*
1099  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1100  * had we done things the other way around, if two pfs from the same port
1101  * would attempt to access nvram at the same time, we could run into a
1102  * scenario such as:
1103  * pf A takes the port lock.
1104  * pf B succeeds in taking the same lock since they are from the same port.
1105  * pf A takes the per pf misc lock. Performs eeprom access.
1106  * pf A finishes. Unlocks the per pf misc lock.
1107  * Pf B takes the lock and proceeds to perform it's own access.
1108  * pf A unlocks the per port lock, while pf B is still working (!).
1109  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1110  * access corrupted by pf B).*
1111  */
1112 static int
1113 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1114 {
1115     int port = SC_PORT(sc);
1116     int count, i;
1117     uint32_t val = 0;
1118
1119     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1120     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1121
1122     /* adjust timeout for emulation/FPGA */
1123     count = NVRAM_TIMEOUT_COUNT;
1124     if (CHIP_REV_IS_SLOW(sc)) {
1125         count *= 100;
1126     }
1127
1128     /* request access to nvram interface */
1129     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1130            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1131
1132     for (i = 0; i < count*10; i++) {
1133         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1134         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1135             break;
1136         }
1137
1138         DELAY(5);
1139     }
1140
1141     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1142         BLOGE(sc, "Cannot get access to nvram interface "
1143             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1144             port, val);
1145         return (-1);
1146     }
1147
1148     return (0);
1149 }
1150
1151 static int
1152 bxe_release_nvram_lock(struct bxe_softc *sc)
1153 {
1154     int port = SC_PORT(sc);
1155     int count, i;
1156     uint32_t val = 0;
1157
1158     /* adjust timeout for emulation/FPGA */
1159     count = NVRAM_TIMEOUT_COUNT;
1160     if (CHIP_REV_IS_SLOW(sc)) {
1161         count *= 100;
1162     }
1163
1164     /* relinquish nvram interface */
1165     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1166            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1167
1168     for (i = 0; i < count*10; i++) {
1169         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1170         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1171             break;
1172         }
1173
1174         DELAY(5);
1175     }
1176
1177     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1178         BLOGE(sc, "Cannot free access to nvram interface "
1179             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1180             port, val);
1181         return (-1);
1182     }
1183
1184     /* release HW lock: protect against other PFs in PF Direct Assignment */
1185     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1186
1187     return (0);
1188 }
1189
1190 static void
1191 bxe_enable_nvram_access(struct bxe_softc *sc)
1192 {
1193     uint32_t val;
1194
1195     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1196
1197     /* enable both bits, even on read */
1198     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1199            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1200 }
1201
1202 static void
1203 bxe_disable_nvram_access(struct bxe_softc *sc)
1204 {
1205     uint32_t val;
1206
1207     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1208
1209     /* disable both bits, even after read */
1210     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1211            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1212                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1213 }
1214
1215 static int
1216 bxe_nvram_read_dword(struct bxe_softc *sc,
1217                      uint32_t         offset,
1218                      uint32_t         *ret_val,
1219                      uint32_t         cmd_flags)
1220 {
1221     int count, i, rc;
1222     uint32_t val;
1223
1224     /* build the command word */
1225     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1226
1227     /* need to clear DONE bit separately */
1228     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1229
1230     /* address of the NVRAM to read from */
1231     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1232            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1233
1234     /* issue a read command */
1235     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1236
1237     /* adjust timeout for emulation/FPGA */
1238     count = NVRAM_TIMEOUT_COUNT;
1239     if (CHIP_REV_IS_SLOW(sc)) {
1240         count *= 100;
1241     }
1242
1243     /* wait for completion */
1244     *ret_val = 0;
1245     rc = -1;
1246     for (i = 0; i < count; i++) {
1247         DELAY(5);
1248         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1249
1250         if (val & MCPR_NVM_COMMAND_DONE) {
1251             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1252             /* we read nvram data in cpu order
1253              * but ethtool sees it as an array of bytes
1254              * converting to big-endian will do the work
1255              */
1256             *ret_val = htobe32(val);
1257             rc = 0;
1258             break;
1259         }
1260     }
1261
1262     if (rc == -1) {
1263         BLOGE(sc, "nvram read timeout expired "
1264             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1265             offset, cmd_flags, val);
1266     }
1267
1268     return (rc);
1269 }
1270
1271 static int
1272 bxe_nvram_read(struct bxe_softc *sc,
1273                uint32_t         offset,
1274                uint8_t          *ret_buf,
1275                int              buf_size)
1276 {
1277     uint32_t cmd_flags;
1278     uint32_t val;
1279     int rc;
1280
1281     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1282         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1283               offset, buf_size);
1284         return (-1);
1285     }
1286
1287     if ((offset + buf_size) > sc->devinfo.flash_size) {
1288         BLOGE(sc, "Invalid parameter, "
1289                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1290               offset, buf_size, sc->devinfo.flash_size);
1291         return (-1);
1292     }
1293
1294     /* request access to nvram interface */
1295     rc = bxe_acquire_nvram_lock(sc);
1296     if (rc) {
1297         return (rc);
1298     }
1299
1300     /* enable access to nvram interface */
1301     bxe_enable_nvram_access(sc);
1302
1303     /* read the first word(s) */
1304     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1305     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1306         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1307         memcpy(ret_buf, &val, 4);
1308
1309         /* advance to the next dword */
1310         offset += sizeof(uint32_t);
1311         ret_buf += sizeof(uint32_t);
1312         buf_size -= sizeof(uint32_t);
1313         cmd_flags = 0;
1314     }
1315
1316     if (rc == 0) {
1317         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1318         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1319         memcpy(ret_buf, &val, 4);
1320     }
1321
1322     /* disable access to nvram interface */
1323     bxe_disable_nvram_access(sc);
1324     bxe_release_nvram_lock(sc);
1325
1326     return (rc);
1327 }
1328
1329 static int
1330 bxe_nvram_write_dword(struct bxe_softc *sc,
1331                       uint32_t         offset,
1332                       uint32_t         val,
1333                       uint32_t         cmd_flags)
1334 {
1335     int count, i, rc;
1336
1337     /* build the command word */
1338     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1339
1340     /* need to clear DONE bit separately */
1341     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1342
1343     /* write the data */
1344     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1345
1346     /* address of the NVRAM to write to */
1347     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1348            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1349
1350     /* issue the write command */
1351     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1352
1353     /* adjust timeout for emulation/FPGA */
1354     count = NVRAM_TIMEOUT_COUNT;
1355     if (CHIP_REV_IS_SLOW(sc)) {
1356         count *= 100;
1357     }
1358
1359     /* wait for completion */
1360     rc = -1;
1361     for (i = 0; i < count; i++) {
1362         DELAY(5);
1363         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1364         if (val & MCPR_NVM_COMMAND_DONE) {
1365             rc = 0;
1366             break;
1367         }
1368     }
1369
1370     if (rc == -1) {
1371         BLOGE(sc, "nvram write timeout expired "
1372             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1373             offset, cmd_flags, val);
1374     }
1375
1376     return (rc);
1377 }
1378
1379 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1380
1381 static int
1382 bxe_nvram_write1(struct bxe_softc *sc,
1383                  uint32_t         offset,
1384                  uint8_t          *data_buf,
1385                  int              buf_size)
1386 {
1387     uint32_t cmd_flags;
1388     uint32_t align_offset;
1389     uint32_t val;
1390     int rc;
1391
1392     if ((offset + buf_size) > sc->devinfo.flash_size) {
1393         BLOGE(sc, "Invalid parameter, "
1394                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1395               offset, buf_size, sc->devinfo.flash_size);
1396         return (-1);
1397     }
1398
1399     /* request access to nvram interface */
1400     rc = bxe_acquire_nvram_lock(sc);
1401     if (rc) {
1402         return (rc);
1403     }
1404
1405     /* enable access to nvram interface */
1406     bxe_enable_nvram_access(sc);
1407
1408     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1409     align_offset = (offset & ~0x03);
1410     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1411
1412     if (rc == 0) {
1413         val &= ~(0xff << BYTE_OFFSET(offset));
1414         val |= (*data_buf << BYTE_OFFSET(offset));
1415
1416         /* nvram data is returned as an array of bytes
1417          * convert it back to cpu order
1418          */
1419         val = be32toh(val);
1420
1421         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1422     }
1423
1424     /* disable access to nvram interface */
1425     bxe_disable_nvram_access(sc);
1426     bxe_release_nvram_lock(sc);
1427
1428     return (rc);
1429 }
1430
1431 static int
1432 bxe_nvram_write(struct bxe_softc *sc,
1433                 uint32_t         offset,
1434                 uint8_t          *data_buf,
1435                 int              buf_size)
1436 {
1437     uint32_t cmd_flags;
1438     uint32_t val;
1439     uint32_t written_so_far;
1440     int rc;
1441
1442     if (buf_size == 1) {
1443         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1444     }
1445
1446     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1447         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1448               offset, buf_size);
1449         return (-1);
1450     }
1451
1452     if (buf_size == 0) {
1453         return (0); /* nothing to do */
1454     }
1455
1456     if ((offset + buf_size) > sc->devinfo.flash_size) {
1457         BLOGE(sc, "Invalid parameter, "
1458                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1459               offset, buf_size, sc->devinfo.flash_size);
1460         return (-1);
1461     }
1462
1463     /* request access to nvram interface */
1464     rc = bxe_acquire_nvram_lock(sc);
1465     if (rc) {
1466         return (rc);
1467     }
1468
1469     /* enable access to nvram interface */
1470     bxe_enable_nvram_access(sc);
1471
1472     written_so_far = 0;
1473     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1474     while ((written_so_far < buf_size) && (rc == 0)) {
1475         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1476             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1477         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1478             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1479         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1480             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1481         }
1482
1483         memcpy(&val, data_buf, 4);
1484
1485         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1486
1487         /* advance to the next dword */
1488         offset += sizeof(uint32_t);
1489         data_buf += sizeof(uint32_t);
1490         written_so_far += sizeof(uint32_t);
1491         cmd_flags = 0;
1492     }
1493
1494     /* disable access to nvram interface */
1495     bxe_disable_nvram_access(sc);
1496     bxe_release_nvram_lock(sc);
1497
1498     return (rc);
1499 }
1500
1501 /* copy command into DMAE command memory and set DMAE command Go */
1502 void
1503 bxe_post_dmae(struct bxe_softc    *sc,
1504               struct dmae_cmd *dmae,
1505               int                 idx)
1506 {
1507     uint32_t cmd_offset;
1508     int i;
1509
1510     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1511     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1512         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1513     }
1514
1515     REG_WR(sc, dmae_reg_go_c[idx], 1);
1516 }
1517
1518 uint32_t
1519 bxe_dmae_opcode_add_comp(uint32_t opcode,
1520                          uint8_t  comp_type)
1521 {
1522     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1523                       DMAE_CMD_C_TYPE_ENABLE));
1524 }
1525
1526 uint32_t
1527 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1528 {
1529     return (opcode & ~DMAE_CMD_SRC_RESET);
1530 }
1531
1532 uint32_t
1533 bxe_dmae_opcode(struct bxe_softc *sc,
1534                 uint8_t          src_type,
1535                 uint8_t          dst_type,
1536                 uint8_t          with_comp,
1537                 uint8_t          comp_type)
1538 {
1539     uint32_t opcode = 0;
1540
1541     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1542                (dst_type << DMAE_CMD_DST_SHIFT));
1543
1544     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1545
1546     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1547
1548     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1549                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1550
1551     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1552
1553 #ifdef __BIG_ENDIAN
1554     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1555 #else
1556     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1557 #endif
1558
1559     if (with_comp) {
1560         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1561     }
1562
1563     return (opcode);
1564 }
1565
1566 static void
1567 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1568                         struct dmae_cmd *dmae,
1569                         uint8_t             src_type,
1570                         uint8_t             dst_type)
1571 {
1572     memset(dmae, 0, sizeof(struct dmae_cmd));
1573
1574     /* set the opcode */
1575     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1576                                    TRUE, DMAE_COMP_PCI);
1577
1578     /* fill in the completion parameters */
1579     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1580     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1581     dmae->comp_val     = DMAE_COMP_VAL;
1582 }
1583
1584 /* issue a DMAE command over the init channel and wait for completion */
1585 static int
1586 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1587                          struct dmae_cmd *dmae)
1588 {
1589     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1590     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1591
1592     BXE_DMAE_LOCK(sc);
1593
1594     /* reset completion */
1595     *wb_comp = 0;
1596
1597     /* post the command on the channel used for initializations */
1598     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1599
1600     /* wait for completion */
1601     DELAY(5);
1602
1603     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1604         if (!timeout ||
1605             (sc->recovery_state != BXE_RECOVERY_DONE &&
1606              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1607             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1608                 *wb_comp, sc->recovery_state);
1609             BXE_DMAE_UNLOCK(sc);
1610             return (DMAE_TIMEOUT);
1611         }
1612
1613         timeout--;
1614         DELAY(50);
1615     }
1616
1617     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1618         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1619                 *wb_comp, sc->recovery_state);
1620         BXE_DMAE_UNLOCK(sc);
1621         return (DMAE_PCI_ERROR);
1622     }
1623
1624     BXE_DMAE_UNLOCK(sc);
1625     return (0);
1626 }
1627
1628 void
1629 bxe_read_dmae(struct bxe_softc *sc,
1630               uint32_t         src_addr,
1631               uint32_t         len32)
1632 {
1633     struct dmae_cmd dmae;
1634     uint32_t *data;
1635     int i, rc;
1636
1637     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1638
1639     if (!sc->dmae_ready) {
1640         data = BXE_SP(sc, wb_data[0]);
1641
1642         for (i = 0; i < len32; i++) {
1643             data[i] = (CHIP_IS_E1(sc)) ?
1644                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1645                           REG_RD(sc, (src_addr + (i * 4)));
1646         }
1647
1648         return;
1649     }
1650
1651     /* set opcode and fixed command fields */
1652     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1653
1654     /* fill in addresses and len */
1655     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1656     dmae.src_addr_hi = 0;
1657     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1658     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1659     dmae.len         = len32;
1660
1661     /* issue the command and wait for completion */
1662     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1663         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1664     };
1665 }
1666
1667 void
1668 bxe_write_dmae(struct bxe_softc *sc,
1669                bus_addr_t       dma_addr,
1670                uint32_t         dst_addr,
1671                uint32_t         len32)
1672 {
1673     struct dmae_cmd dmae;
1674     int rc;
1675
1676     if (!sc->dmae_ready) {
1677         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1678
1679         if (CHIP_IS_E1(sc)) {
1680             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1681         } else {
1682             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1683         }
1684
1685         return;
1686     }
1687
1688     /* set opcode and fixed command fields */
1689     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1690
1691     /* fill in addresses and len */
1692     dmae.src_addr_lo = U64_LO(dma_addr);
1693     dmae.src_addr_hi = U64_HI(dma_addr);
1694     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1695     dmae.dst_addr_hi = 0;
1696     dmae.len         = len32;
1697
1698     /* issue the command and wait for completion */
1699     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1700         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1701     }
1702 }
1703
1704 void
1705 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1706                         bus_addr_t       phys_addr,
1707                         uint32_t         addr,
1708                         uint32_t         len)
1709 {
1710     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1711     int offset = 0;
1712
1713     while (len > dmae_wr_max) {
1714         bxe_write_dmae(sc,
1715                        (phys_addr + offset), /* src DMA address */
1716                        (addr + offset),      /* dst GRC address */
1717                        dmae_wr_max);
1718         offset += (dmae_wr_max * 4);
1719         len -= dmae_wr_max;
1720     }
1721
1722     bxe_write_dmae(sc,
1723                    (phys_addr + offset), /* src DMA address */
1724                    (addr + offset),      /* dst GRC address */
1725                    len);
1726 }
1727
1728 void
1729 bxe_set_ctx_validation(struct bxe_softc   *sc,
1730                        struct eth_context *cxt,
1731                        uint32_t           cid)
1732 {
1733     /* ustorm cxt validation */
1734     cxt->ustorm_ag_context.cdu_usage =
1735         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1736             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1737     /* xcontext validation */
1738     cxt->xstorm_ag_context.cdu_reserved =
1739         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1740             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1741 }
1742
1743 static void
1744 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1745                             uint8_t          port,
1746                             uint8_t          fw_sb_id,
1747                             uint8_t          sb_index,
1748                             uint8_t          ticks)
1749 {
1750     uint32_t addr =
1751         (BAR_CSTRORM_INTMEM +
1752          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1753
1754     REG_WR8(sc, addr, ticks);
1755
1756     BLOGD(sc, DBG_LOAD,
1757           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1758           port, fw_sb_id, sb_index, ticks);
1759 }
1760
1761 static void
1762 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1763                             uint8_t          port,
1764                             uint16_t         fw_sb_id,
1765                             uint8_t          sb_index,
1766                             uint8_t          disable)
1767 {
1768     uint32_t enable_flag =
1769         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1770     uint32_t addr =
1771         (BAR_CSTRORM_INTMEM +
1772          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1773     uint8_t flags;
1774
1775     /* clear and set */
1776     flags = REG_RD8(sc, addr);
1777     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1778     flags |= enable_flag;
1779     REG_WR8(sc, addr, flags);
1780
1781     BLOGD(sc, DBG_LOAD,
1782           "port %d fw_sb_id %d sb_index %d disable %d\n",
1783           port, fw_sb_id, sb_index, disable);
1784 }
1785
1786 void
1787 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1788                              uint8_t          fw_sb_id,
1789                              uint8_t          sb_index,
1790                              uint8_t          disable,
1791                              uint16_t         usec)
1792 {
1793     int port = SC_PORT(sc);
1794     uint8_t ticks = (usec / 4); /* XXX ??? */
1795
1796     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1797
1798     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1799     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1800 }
1801
1802 void
1803 elink_cb_udelay(struct bxe_softc *sc,
1804                 uint32_t         usecs)
1805 {
1806     DELAY(usecs);
1807 }
1808
1809 uint32_t
1810 elink_cb_reg_read(struct bxe_softc *sc,
1811                   uint32_t         reg_addr)
1812 {
1813     return (REG_RD(sc, reg_addr));
1814 }
1815
1816 void
1817 elink_cb_reg_write(struct bxe_softc *sc,
1818                    uint32_t         reg_addr,
1819                    uint32_t         val)
1820 {
1821     REG_WR(sc, reg_addr, val);
1822 }
1823
1824 void
1825 elink_cb_reg_wb_write(struct bxe_softc *sc,
1826                       uint32_t         offset,
1827                       uint32_t         *wb_write,
1828                       uint16_t         len)
1829 {
1830     REG_WR_DMAE(sc, offset, wb_write, len);
1831 }
1832
1833 void
1834 elink_cb_reg_wb_read(struct bxe_softc *sc,
1835                      uint32_t         offset,
1836                      uint32_t         *wb_write,
1837                      uint16_t         len)
1838 {
1839     REG_RD_DMAE(sc, offset, wb_write, len);
1840 }
1841
1842 uint8_t
1843 elink_cb_path_id(struct bxe_softc *sc)
1844 {
1845     return (SC_PATH(sc));
1846 }
1847
1848 void
1849 elink_cb_event_log(struct bxe_softc     *sc,
1850                    const elink_log_id_t elink_log_id,
1851                    ...)
1852 {
1853     /* XXX */
1854     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1855 }
1856
1857 static int
1858 bxe_set_spio(struct bxe_softc *sc,
1859              int              spio,
1860              uint32_t         mode)
1861 {
1862     uint32_t spio_reg;
1863
1864     /* Only 2 SPIOs are configurable */
1865     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1866         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1867         return (-1);
1868     }
1869
1870     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1871
1872     /* read SPIO and mask except the float bits */
1873     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1874
1875     switch (mode) {
1876     case MISC_SPIO_OUTPUT_LOW:
1877         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1878         /* clear FLOAT and set CLR */
1879         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1880         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1881         break;
1882
1883     case MISC_SPIO_OUTPUT_HIGH:
1884         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1885         /* clear FLOAT and set SET */
1886         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1887         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1888         break;
1889
1890     case MISC_SPIO_INPUT_HI_Z:
1891         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1892         /* set FLOAT */
1893         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1894         break;
1895
1896     default:
1897         break;
1898     }
1899
1900     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1901     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1902
1903     return (0);
1904 }
1905
1906 static int
1907 bxe_gpio_read(struct bxe_softc *sc,
1908               int              gpio_num,
1909               uint8_t          port)
1910 {
1911     /* The GPIO should be swapped if swap register is set and active */
1912     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1913                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1914     int gpio_shift = (gpio_num +
1915                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1916     uint32_t gpio_mask = (1 << gpio_shift);
1917     uint32_t gpio_reg;
1918
1919     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1920         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1921             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1922             gpio_mask);
1923         return (-1);
1924     }
1925
1926     /* read GPIO value */
1927     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1928
1929     /* get the requested pin value */
1930     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1931 }
1932
1933 static int
1934 bxe_gpio_write(struct bxe_softc *sc,
1935                int              gpio_num,
1936                uint32_t         mode,
1937                uint8_t          port)
1938 {
1939     /* The GPIO should be swapped if swap register is set and active */
1940     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1941                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1942     int gpio_shift = (gpio_num +
1943                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1944     uint32_t gpio_mask = (1 << gpio_shift);
1945     uint32_t gpio_reg;
1946
1947     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1948         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1949             " gpio_shift %d gpio_mask 0x%x\n",
1950             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1951         return (-1);
1952     }
1953
1954     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1955
1956     /* read GPIO and mask except the float bits */
1957     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1958
1959     switch (mode) {
1960     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1961         BLOGD(sc, DBG_PHY,
1962               "Set GPIO %d (shift %d) -> output low\n",
1963               gpio_num, gpio_shift);
1964         /* clear FLOAT and set CLR */
1965         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1966         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1967         break;
1968
1969     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1970         BLOGD(sc, DBG_PHY,
1971               "Set GPIO %d (shift %d) -> output high\n",
1972               gpio_num, gpio_shift);
1973         /* clear FLOAT and set SET */
1974         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1975         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1976         break;
1977
1978     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1979         BLOGD(sc, DBG_PHY,
1980               "Set GPIO %d (shift %d) -> input\n",
1981               gpio_num, gpio_shift);
1982         /* set FLOAT */
1983         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1984         break;
1985
1986     default:
1987         break;
1988     }
1989
1990     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1991     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1992
1993     return (0);
1994 }
1995
1996 static int
1997 bxe_gpio_mult_write(struct bxe_softc *sc,
1998                     uint8_t          pins,
1999                     uint32_t         mode)
2000 {
2001     uint32_t gpio_reg;
2002
2003     /* any port swapping should be handled by caller */
2004
2005     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2006
2007     /* read GPIO and mask except the float bits */
2008     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
2009     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2010     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
2011     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
2012
2013     switch (mode) {
2014     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2015         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
2016         /* set CLR */
2017         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
2018         break;
2019
2020     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2021         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
2022         /* set SET */
2023         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2024         break;
2025
2026     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2027         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2028         /* set FLOAT */
2029         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2030         break;
2031
2032     default:
2033         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2034             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2035         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2036         return (-1);
2037     }
2038
2039     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2040     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2041
2042     return (0);
2043 }
2044
2045 static int
2046 bxe_gpio_int_write(struct bxe_softc *sc,
2047                    int              gpio_num,
2048                    uint32_t         mode,
2049                    uint8_t          port)
2050 {
2051     /* The GPIO should be swapped if swap register is set and active */
2052     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2053                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2054     int gpio_shift = (gpio_num +
2055                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2056     uint32_t gpio_mask = (1 << gpio_shift);
2057     uint32_t gpio_reg;
2058
2059     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2060         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2061             " gpio_shift %d gpio_mask 0x%x\n",
2062             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2063         return (-1);
2064     }
2065
2066     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2067
2068     /* read GPIO int */
2069     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2070
2071     switch (mode) {
2072     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2073         BLOGD(sc, DBG_PHY,
2074               "Clear GPIO INT %d (shift %d) -> output low\n",
2075               gpio_num, gpio_shift);
2076         /* clear SET and set CLR */
2077         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2078         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2079         break;
2080
2081     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2082         BLOGD(sc, DBG_PHY,
2083               "Set GPIO INT %d (shift %d) -> output high\n",
2084               gpio_num, gpio_shift);
2085         /* clear CLR and set SET */
2086         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2087         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2088         break;
2089
2090     default:
2091         break;
2092     }
2093
2094     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2095     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2096
2097     return (0);
2098 }
2099
2100 uint32_t
2101 elink_cb_gpio_read(struct bxe_softc *sc,
2102                    uint16_t         gpio_num,
2103                    uint8_t          port)
2104 {
2105     return (bxe_gpio_read(sc, gpio_num, port));
2106 }
2107
2108 uint8_t
2109 elink_cb_gpio_write(struct bxe_softc *sc,
2110                     uint16_t         gpio_num,
2111                     uint8_t          mode, /* 0=low 1=high */
2112                     uint8_t          port)
2113 {
2114     return (bxe_gpio_write(sc, gpio_num, mode, port));
2115 }
2116
2117 uint8_t
2118 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2119                          uint8_t          pins,
2120                          uint8_t          mode) /* 0=low 1=high */
2121 {
2122     return (bxe_gpio_mult_write(sc, pins, mode));
2123 }
2124
2125 uint8_t
2126 elink_cb_gpio_int_write(struct bxe_softc *sc,
2127                         uint16_t         gpio_num,
2128                         uint8_t          mode, /* 0=low 1=high */
2129                         uint8_t          port)
2130 {
2131     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2132 }
2133
2134 void
2135 elink_cb_notify_link_changed(struct bxe_softc *sc)
2136 {
2137     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2138                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2139 }
2140
2141 /* send the MCP a request, block until there is a reply */
2142 uint32_t
2143 elink_cb_fw_command(struct bxe_softc *sc,
2144                     uint32_t         command,
2145                     uint32_t         param)
2146 {
2147     int mb_idx = SC_FW_MB_IDX(sc);
2148     uint32_t seq;
2149     uint32_t rc = 0;
2150     uint32_t cnt = 1;
2151     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2152
2153     BXE_FWMB_LOCK(sc);
2154
2155     seq = ++sc->fw_seq;
2156     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2157     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2158
2159     BLOGD(sc, DBG_PHY,
2160           "wrote command 0x%08x to FW MB param 0x%08x\n",
2161           (command | seq), param);
2162
2163     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2164     do {
2165         DELAY(delay * 1000);
2166         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2167     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2168
2169     BLOGD(sc, DBG_PHY,
2170           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2171           cnt*delay, rc, seq);
2172
2173     /* is this a reply to our command? */
2174     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2175         rc &= FW_MSG_CODE_MASK;
2176     } else {
2177         /* Ruh-roh! */
2178         BLOGE(sc, "FW failed to respond!\n");
2179         // XXX bxe_fw_dump(sc);
2180         rc = 0;
2181     }
2182
2183     BXE_FWMB_UNLOCK(sc);
2184     return (rc);
2185 }
2186
2187 static uint32_t
2188 bxe_fw_command(struct bxe_softc *sc,
2189                uint32_t         command,
2190                uint32_t         param)
2191 {
2192     return (elink_cb_fw_command(sc, command, param));
2193 }
2194
2195 static void
2196 __storm_memset_dma_mapping(struct bxe_softc *sc,
2197                            uint32_t         addr,
2198                            bus_addr_t       mapping)
2199 {
2200     REG_WR(sc, addr, U64_LO(mapping));
2201     REG_WR(sc, (addr + 4), U64_HI(mapping));
2202 }
2203
2204 static void
2205 storm_memset_spq_addr(struct bxe_softc *sc,
2206                       bus_addr_t       mapping,
2207                       uint16_t         abs_fid)
2208 {
2209     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2210                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2211     __storm_memset_dma_mapping(sc, addr, mapping);
2212 }
2213
2214 static void
2215 storm_memset_vf_to_pf(struct bxe_softc *sc,
2216                       uint16_t         abs_fid,
2217                       uint16_t         pf_id)
2218 {
2219     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2220     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2221     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2222     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2223 }
2224
2225 static void
2226 storm_memset_func_en(struct bxe_softc *sc,
2227                      uint16_t         abs_fid,
2228                      uint8_t          enable)
2229 {
2230     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2231     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2232     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2233     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2234 }
2235
2236 static void
2237 storm_memset_eq_data(struct bxe_softc       *sc,
2238                      struct event_ring_data *eq_data,
2239                      uint16_t               pfid)
2240 {
2241     uint32_t addr;
2242     size_t size;
2243
2244     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2245     size = sizeof(struct event_ring_data);
2246     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2247 }
2248
2249 static void
2250 storm_memset_eq_prod(struct bxe_softc *sc,
2251                      uint16_t         eq_prod,
2252                      uint16_t         pfid)
2253 {
2254     uint32_t addr = (BAR_CSTRORM_INTMEM +
2255                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2256     REG_WR16(sc, addr, eq_prod);
2257 }
2258
2259 /*
2260  * Post a slowpath command.
2261  *
2262  * A slowpath command is used to propogate a configuration change through
2263  * the controller in a controlled manner, allowing each STORM processor and
2264  * other H/W blocks to phase in the change.  The commands sent on the
2265  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2266  * completion of the ramrod will occur in different ways.  Here's a
2267  * breakdown of ramrods and how they complete:
2268  *
2269  * RAMROD_CMD_ID_ETH_PORT_SETUP
2270  *   Used to setup the leading connection on a port.  Completes on the
2271  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2272  *
2273  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2274  *   Used to setup an additional connection on a port.  Completes on the
2275  *   RCQ of the multi-queue/RSS connection being initialized.
2276  *
2277  * RAMROD_CMD_ID_ETH_STAT_QUERY
2278  *   Used to force the storm processors to update the statistics database
2279  *   in host memory.  This ramrod is send on the leading connection CID and
2280  *   completes as an index increment of the CSTORM on the default status
2281  *   block.
2282  *
2283  * RAMROD_CMD_ID_ETH_UPDATE
2284  *   Used to update the state of the leading connection, usually to udpate
2285  *   the RSS indirection table.  Completes on the RCQ of the leading
2286  *   connection. (Not currently used under FreeBSD until OS support becomes
2287  *   available.)
2288  *
2289  * RAMROD_CMD_ID_ETH_HALT
2290  *   Used when tearing down a connection prior to driver unload.  Completes
2291  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2292  *   use this on the leading connection.
2293  *
2294  * RAMROD_CMD_ID_ETH_SET_MAC
2295  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2296  *   the RCQ of the leading connection.
2297  *
2298  * RAMROD_CMD_ID_ETH_CFC_DEL
2299  *   Used when tearing down a conneciton prior to driver unload.  Completes
2300  *   on the RCQ of the leading connection (since the current connection
2301  *   has been completely removed from controller memory).
2302  *
2303  * RAMROD_CMD_ID_ETH_PORT_DEL
2304  *   Used to tear down the leading connection prior to driver unload,
2305  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2306  *   default status block.
2307  *
2308  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2309  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2310  *   RSS connection that is being offloaded.  (Not currently used under
2311  *   FreeBSD.)
2312  *
2313  * There can only be one command pending per function.
2314  *
2315  * Returns:
2316  *   0 = Success, !0 = Failure.
2317  */
2318
2319 /* must be called under the spq lock */
2320 static inline
2321 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2322 {
2323     struct eth_spe *next_spe = sc->spq_prod_bd;
2324
2325     if (sc->spq_prod_bd == sc->spq_last_bd) {
2326         /* wrap back to the first eth_spq */
2327         sc->spq_prod_bd = sc->spq;
2328         sc->spq_prod_idx = 0;
2329     } else {
2330         sc->spq_prod_bd++;
2331         sc->spq_prod_idx++;
2332     }
2333
2334     return (next_spe);
2335 }
2336
2337 /* must be called under the spq lock */
2338 static inline
2339 void bxe_sp_prod_update(struct bxe_softc *sc)
2340 {
2341     int func = SC_FUNC(sc);
2342
2343     /*
2344      * Make sure that BD data is updated before writing the producer.
2345      * BD data is written to the memory, the producer is read from the
2346      * memory, thus we need a full memory barrier to ensure the ordering.
2347      */
2348     mb();
2349
2350     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2351              sc->spq_prod_idx);
2352
2353     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2354                       BUS_SPACE_BARRIER_WRITE);
2355 }
2356
2357 /**
2358  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2359  *
2360  * @cmd:      command to check
2361  * @cmd_type: command type
2362  */
2363 static inline
2364 int bxe_is_contextless_ramrod(int cmd,
2365                               int cmd_type)
2366 {
2367     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2368         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2369         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2370         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2371         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2372         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2373         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2374         return (TRUE);
2375     } else {
2376         return (FALSE);
2377     }
2378 }
2379
2380 /**
2381  * bxe_sp_post - place a single command on an SP ring
2382  *
2383  * @sc:         driver handle
2384  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2385  * @cid:        SW CID the command is related to
2386  * @data_hi:    command private data address (high 32 bits)
2387  * @data_lo:    command private data address (low 32 bits)
2388  * @cmd_type:   command type (e.g. NONE, ETH)
2389  *
2390  * SP data is handled as if it's always an address pair, thus data fields are
2391  * not swapped to little endian in upper functions. Instead this function swaps
2392  * data as if it's two uint32 fields.
2393  */
2394 int
2395 bxe_sp_post(struct bxe_softc *sc,
2396             int              command,
2397             int              cid,
2398             uint32_t         data_hi,
2399             uint32_t         data_lo,
2400             int              cmd_type)
2401 {
2402     struct eth_spe *spe;
2403     uint16_t type;
2404     int common;
2405
2406     common = bxe_is_contextless_ramrod(command, cmd_type);
2407
2408     BXE_SP_LOCK(sc);
2409
2410     if (common) {
2411         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2412             BLOGE(sc, "EQ ring is full!\n");
2413             BXE_SP_UNLOCK(sc);
2414             return (-1);
2415         }
2416     } else {
2417         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2418             BLOGE(sc, "SPQ ring is full!\n");
2419             BXE_SP_UNLOCK(sc);
2420             return (-1);
2421         }
2422     }
2423
2424     spe = bxe_sp_get_next(sc);
2425
2426     /* CID needs port number to be encoded int it */
2427     spe->hdr.conn_and_cmd_data =
2428         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2429
2430     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2431
2432     /* TBD: Check if it works for VFs */
2433     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2434              SPE_HDR_T_FUNCTION_ID);
2435
2436     spe->hdr.type = htole16(type);
2437
2438     spe->data.update_data_addr.hi = htole32(data_hi);
2439     spe->data.update_data_addr.lo = htole32(data_lo);
2440
2441     /*
2442      * It's ok if the actual decrement is issued towards the memory
2443      * somewhere between the lock and unlock. Thus no more explict
2444      * memory barrier is needed.
2445      */
2446     if (common) {
2447         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2448     } else {
2449         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2450     }
2451
2452     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2453     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2454           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2455     BLOGD(sc, DBG_SP,
2456           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2457           sc->spq_prod_idx,
2458           (uint32_t)U64_HI(sc->spq_dma.paddr),
2459           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2460           command,
2461           common,
2462           HW_CID(sc, cid),
2463           data_hi,
2464           data_lo,
2465           type,
2466           atomic_load_acq_long(&sc->cq_spq_left),
2467           atomic_load_acq_long(&sc->eq_spq_left));
2468
2469     bxe_sp_prod_update(sc);
2470
2471     BXE_SP_UNLOCK(sc);
2472     return (0);
2473 }
2474
2475 /**
2476  * bxe_debug_print_ind_table - prints the indirection table configuration.
2477  *
2478  * @sc: driver hanlde
2479  * @p:  pointer to rss configuration
2480  */
2481
2482 /*
2483  * FreeBSD Device probe function.
2484  *
2485  * Compares the device found to the driver's list of supported devices and
2486  * reports back to the bsd loader whether this is the right driver for the device.
2487  * This is the driver entry function called from the "kldload" command.
2488  *
2489  * Returns:
2490  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2491  */
2492 static int
2493 bxe_probe(device_t dev)
2494 {
2495     struct bxe_softc *sc;
2496     struct bxe_device_type *t;
2497     char *descbuf;
2498     uint16_t did, sdid, svid, vid;
2499
2500     /* Find our device structure */
2501     sc = device_get_softc(dev);
2502     sc->dev = dev;
2503     t = bxe_devs;
2504
2505     /* Get the data for the device to be probed. */
2506     vid  = pci_get_vendor(dev);
2507     did  = pci_get_device(dev);
2508     svid = pci_get_subvendor(dev);
2509     sdid = pci_get_subdevice(dev);
2510
2511     BLOGD(sc, DBG_LOAD,
2512           "%s(); VID = 0x%04X, DID = 0x%04X, SVID = 0x%04X, "
2513           "SDID = 0x%04X\n", __FUNCTION__, vid, did, svid, sdid);
2514
2515     /* Look through the list of known devices for a match. */
2516     while (t->bxe_name != NULL) {
2517         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2518             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2519             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2520             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2521             if (descbuf == NULL)
2522                 return (ENOMEM);
2523
2524             /* Print out the device identity. */
2525             snprintf(descbuf, BXE_DEVDESC_MAX,
2526                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2527                      (((pci_read_config(dev, PCIR_REVID, 4) &
2528                         0xf0) >> 4) + 'A'),
2529                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2530                      BXE_DRIVER_VERSION);
2531
2532             device_set_desc_copy(dev, descbuf);
2533             free(descbuf, M_TEMP);
2534             return (BUS_PROBE_DEFAULT);
2535         }
2536         t++;
2537     }
2538
2539     return (ENXIO);
2540 }
2541
2542 static void
2543 bxe_init_mutexes(struct bxe_softc *sc)
2544 {
2545 #ifdef BXE_CORE_LOCK_SX
2546     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2547              "bxe%d_core_lock", sc->unit);
2548     sx_init(&sc->core_sx, sc->core_sx_name);
2549 #else
2550     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2551              "bxe%d_core_lock", sc->unit);
2552     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2553 #endif
2554
2555     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2556              "bxe%d_sp_lock", sc->unit);
2557     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2558
2559     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2560              "bxe%d_dmae_lock", sc->unit);
2561     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2562
2563     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2564              "bxe%d_phy_lock", sc->unit);
2565     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2566
2567     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2568              "bxe%d_fwmb_lock", sc->unit);
2569     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2570
2571     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2572              "bxe%d_print_lock", sc->unit);
2573     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2574
2575     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2576              "bxe%d_stats_lock", sc->unit);
2577     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2578
2579     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2580              "bxe%d_mcast_lock", sc->unit);
2581     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2582 }
2583
2584 static void
2585 bxe_release_mutexes(struct bxe_softc *sc)
2586 {
2587 #ifdef BXE_CORE_LOCK_SX
2588     sx_destroy(&sc->core_sx);
2589 #else
2590     if (mtx_initialized(&sc->core_mtx)) {
2591         mtx_destroy(&sc->core_mtx);
2592     }
2593 #endif
2594
2595     if (mtx_initialized(&sc->sp_mtx)) {
2596         mtx_destroy(&sc->sp_mtx);
2597     }
2598
2599     if (mtx_initialized(&sc->dmae_mtx)) {
2600         mtx_destroy(&sc->dmae_mtx);
2601     }
2602
2603     if (mtx_initialized(&sc->port.phy_mtx)) {
2604         mtx_destroy(&sc->port.phy_mtx);
2605     }
2606
2607     if (mtx_initialized(&sc->fwmb_mtx)) {
2608         mtx_destroy(&sc->fwmb_mtx);
2609     }
2610
2611     if (mtx_initialized(&sc->print_mtx)) {
2612         mtx_destroy(&sc->print_mtx);
2613     }
2614
2615     if (mtx_initialized(&sc->stats_mtx)) {
2616         mtx_destroy(&sc->stats_mtx);
2617     }
2618
2619     if (mtx_initialized(&sc->mcast_mtx)) {
2620         mtx_destroy(&sc->mcast_mtx);
2621     }
2622 }
2623
2624 static void
2625 bxe_tx_disable(struct bxe_softc* sc)
2626 {
2627     struct ifnet *ifp = sc->ifnet;
2628
2629     /* tell the stack the driver is stopped and TX queue is full */
2630     if (ifp != NULL) {
2631         ifp->if_drv_flags = 0;
2632     }
2633 }
2634
2635 static void
2636 bxe_drv_pulse(struct bxe_softc *sc)
2637 {
2638     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2639              sc->fw_drv_pulse_wr_seq);
2640 }
2641
2642 static inline uint16_t
2643 bxe_tx_avail(struct bxe_softc *sc,
2644              struct bxe_fastpath *fp)
2645 {
2646     int16_t  used;
2647     uint16_t prod;
2648     uint16_t cons;
2649
2650     prod = fp->tx_bd_prod;
2651     cons = fp->tx_bd_cons;
2652
2653     used = SUB_S16(prod, cons);
2654
2655     return (int16_t)(sc->tx_ring_size) - used;
2656 }
2657
2658 static inline int
2659 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2660 {
2661     uint16_t hw_cons;
2662
2663     mb(); /* status block fields can change */
2664     hw_cons = le16toh(*fp->tx_cons_sb);
2665     return (hw_cons != fp->tx_pkt_cons);
2666 }
2667
2668 static inline uint8_t
2669 bxe_has_tx_work(struct bxe_fastpath *fp)
2670 {
2671     /* expand this for multi-cos if ever supported */
2672     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2673 }
2674
2675 static inline int
2676 bxe_has_rx_work(struct bxe_fastpath *fp)
2677 {
2678     uint16_t rx_cq_cons_sb;
2679
2680     mb(); /* status block fields can change */
2681     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2682     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2683         rx_cq_cons_sb++;
2684     return (fp->rx_cq_cons != rx_cq_cons_sb);
2685 }
2686
2687 static void
2688 bxe_sp_event(struct bxe_softc    *sc,
2689              struct bxe_fastpath *fp,
2690              union eth_rx_cqe    *rr_cqe)
2691 {
2692     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2693     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2694     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2695     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2696
2697     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2698           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2699
2700     switch (command) {
2701     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2702         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2703         drv_cmd = ECORE_Q_CMD_UPDATE;
2704         break;
2705
2706     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2707         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2708         drv_cmd = ECORE_Q_CMD_SETUP;
2709         break;
2710
2711     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2712         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2713         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2714         break;
2715
2716     case (RAMROD_CMD_ID_ETH_HALT):
2717         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2718         drv_cmd = ECORE_Q_CMD_HALT;
2719         break;
2720
2721     case (RAMROD_CMD_ID_ETH_TERMINATE):
2722         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2723         drv_cmd = ECORE_Q_CMD_TERMINATE;
2724         break;
2725
2726     case (RAMROD_CMD_ID_ETH_EMPTY):
2727         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2728         drv_cmd = ECORE_Q_CMD_EMPTY;
2729         break;
2730
2731     default:
2732         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2733               command, fp->index);
2734         return;
2735     }
2736
2737     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2738         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2739         /*
2740          * q_obj->complete_cmd() failure means that this was
2741          * an unexpected completion.
2742          *
2743          * In this case we don't want to increase the sc->spq_left
2744          * because apparently we haven't sent this command the first
2745          * place.
2746          */
2747         // bxe_panic(sc, ("Unexpected SP completion\n"));
2748         return;
2749     }
2750
2751     atomic_add_acq_long(&sc->cq_spq_left, 1);
2752
2753     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2754           atomic_load_acq_long(&sc->cq_spq_left));
2755 }
2756
2757 /*
2758  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2759  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2760  * the current aggregation queue as in-progress.
2761  */
2762 static void
2763 bxe_tpa_start(struct bxe_softc            *sc,
2764               struct bxe_fastpath         *fp,
2765               uint16_t                    queue,
2766               uint16_t                    cons,
2767               uint16_t                    prod,
2768               struct eth_fast_path_rx_cqe *cqe)
2769 {
2770     struct bxe_sw_rx_bd tmp_bd;
2771     struct bxe_sw_rx_bd *rx_buf;
2772     struct eth_rx_bd *rx_bd;
2773     int max_agg_queues;
2774     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2775     uint16_t index;
2776
2777     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2778                        "cons=%d prod=%d\n",
2779           fp->index, queue, cons, prod);
2780
2781     max_agg_queues = MAX_AGG_QS(sc);
2782
2783     KASSERT((queue < max_agg_queues),
2784             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2785              fp->index, queue, max_agg_queues));
2786
2787     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2788             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2789              fp->index, queue));
2790
2791     /* copy the existing mbuf and mapping from the TPA pool */
2792     tmp_bd = tpa_info->bd;
2793
2794     if (tmp_bd.m == NULL) {
2795         uint32_t *tmp;
2796
2797         tmp = (uint32_t *)cqe;
2798
2799         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2800               fp->index, queue, cons, prod);
2801         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2802             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2803             
2804         /* XXX Error handling? */
2805         return;
2806     }
2807
2808     /* change the TPA queue to the start state */
2809     tpa_info->state            = BXE_TPA_STATE_START;
2810     tpa_info->placement_offset = cqe->placement_offset;
2811     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2812     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2813     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2814
2815     fp->rx_tpa_queue_used |= (1 << queue);
2816
2817     /*
2818      * If all the buffer descriptors are filled with mbufs then fill in
2819      * the current consumer index with a new BD. Else if a maximum Rx
2820      * buffer limit is imposed then fill in the next producer index.
2821      */
2822     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2823                 prod : cons;
2824
2825     /* move the received mbuf and mapping to TPA pool */
2826     tpa_info->bd = fp->rx_mbuf_chain[cons];
2827
2828     /* release any existing RX BD mbuf mappings */
2829     if (cons != index) {
2830         rx_buf = &fp->rx_mbuf_chain[cons];
2831
2832         if (rx_buf->m_map != NULL) {
2833             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2834                             BUS_DMASYNC_POSTREAD);
2835             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2836         }
2837
2838         /*
2839          * We get here when the maximum number of rx buffers is less than
2840          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2841          * it out here without concern of a memory leak.
2842          */
2843         fp->rx_mbuf_chain[cons].m = NULL;
2844     }
2845
2846     /* update the Rx SW BD with the mbuf info from the TPA pool */
2847     fp->rx_mbuf_chain[index] = tmp_bd;
2848
2849     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2850     rx_bd = &fp->rx_chain[index];
2851     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2852     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2853 }
2854
2855 /*
2856  * When a TPA aggregation is completed, loop through the individual mbufs
2857  * of the aggregation, combining them into a single mbuf which will be sent
2858  * up the stack. Refill all freed SGEs with mbufs as we go along.
2859  */
2860 static int
2861 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2862                    struct bxe_fastpath       *fp,
2863                    struct bxe_sw_tpa_info    *tpa_info,
2864                    uint16_t                  queue,
2865                    uint16_t                  pages,
2866                    struct mbuf               *m,
2867                                struct eth_end_agg_rx_cqe *cqe,
2868                    uint16_t                  cqe_idx)
2869 {
2870     struct mbuf *m_frag;
2871     uint32_t frag_len, frag_size, i;
2872     uint16_t sge_idx;
2873     int rc = 0;
2874     int j;
2875
2876     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2877
2878     BLOGD(sc, DBG_LRO,
2879           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2880           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2881
2882     /* make sure the aggregated frame is not too big to handle */
2883     if (pages > 8 * PAGES_PER_SGE) {
2884
2885         uint32_t *tmp = (uint32_t *)cqe;
2886
2887         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2888                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2889               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2890               tpa_info->len_on_bd, frag_size);
2891
2892         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2893             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2894
2895         bxe_panic(sc, ("sge page count error\n"));
2896         return (EINVAL);
2897     }
2898
2899     /*
2900      * Scan through the scatter gather list pulling individual mbufs into a
2901      * single mbuf for the host stack.
2902      */
2903     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2904         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2905
2906         /*
2907          * Firmware gives the indices of the SGE as if the ring is an array
2908          * (meaning that the "next" element will consume 2 indices).
2909          */
2910         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2911
2912         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2913                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2914               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2915
2916         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2917
2918         /* allocate a new mbuf for the SGE */
2919         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2920         if (rc) {
2921             /* Leave all remaining SGEs in the ring! */
2922             return (rc);
2923         }
2924
2925         /* update the fragment length */
2926         m_frag->m_len = frag_len;
2927
2928         /* concatenate the fragment to the head mbuf */
2929         m_cat(m, m_frag);
2930         fp->eth_q_stats.mbuf_alloc_sge--;
2931
2932         /* update the TPA mbuf size and remaining fragment size */
2933         m->m_pkthdr.len += frag_len;
2934         frag_size -= frag_len;
2935     }
2936
2937     BLOGD(sc, DBG_LRO,
2938           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2939           fp->index, queue, frag_size);
2940
2941     return (rc);
2942 }
2943
2944 static inline void
2945 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2946 {
2947     int i, j;
2948
2949     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2950         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2951
2952         for (j = 0; j < 2; j++) {
2953             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2954             idx--;
2955         }
2956     }
2957 }
2958
2959 static inline void
2960 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2961 {
2962     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2963     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2964
2965     /*
2966      * Clear the two last indices in the page to 1. These are the indices that
2967      * correspond to the "next" element, hence will never be indicated and
2968      * should be removed from the calculations.
2969      */
2970     bxe_clear_sge_mask_next_elems(fp);
2971 }
2972
2973 static inline void
2974 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2975                         uint16_t            idx)
2976 {
2977     uint16_t last_max = fp->last_max_sge;
2978
2979     if (SUB_S16(idx, last_max) > 0) {
2980         fp->last_max_sge = idx;
2981     }
2982 }
2983
2984 static inline void
2985 bxe_update_sge_prod(struct bxe_softc          *sc,
2986                     struct bxe_fastpath       *fp,
2987                     uint16_t                  sge_len,
2988                     union eth_sgl_or_raw_data *cqe)
2989 {
2990     uint16_t last_max, last_elem, first_elem;
2991     uint16_t delta = 0;
2992     uint16_t i;
2993
2994     if (!sge_len) {
2995         return;
2996     }
2997
2998     /* first mark all used pages */
2999     for (i = 0; i < sge_len; i++) {
3000         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
3001                             RX_SGE(le16toh(cqe->sgl[i])));
3002     }
3003
3004     BLOGD(sc, DBG_LRO,
3005           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
3006           fp->index, sge_len - 1,
3007           le16toh(cqe->sgl[sge_len - 1]));
3008
3009     /* assume that the last SGE index is the biggest */
3010     bxe_update_last_max_sge(fp,
3011                             le16toh(cqe->sgl[sge_len - 1]));
3012
3013     last_max = RX_SGE(fp->last_max_sge);
3014     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
3015     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
3016
3017     /* if ring is not full */
3018     if (last_elem + 1 != first_elem) {
3019         last_elem++;
3020     }
3021
3022     /* now update the prod */
3023     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
3024         if (__predict_true(fp->sge_mask[i])) {
3025             break;
3026         }
3027
3028         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3029         delta += BIT_VEC64_ELEM_SZ;
3030     }
3031
3032     if (delta > 0) {
3033         fp->rx_sge_prod += delta;
3034         /* clear page-end entries */
3035         bxe_clear_sge_mask_next_elems(fp);
3036     }
3037
3038     BLOGD(sc, DBG_LRO,
3039           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3040           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3041 }
3042
3043 /*
3044  * The aggregation on the current TPA queue has completed. Pull the individual
3045  * mbuf fragments together into a single mbuf, perform all necessary checksum
3046  * calculations, and send the resuting mbuf to the stack.
3047  */
3048 static void
3049 bxe_tpa_stop(struct bxe_softc          *sc,
3050              struct bxe_fastpath       *fp,
3051              struct bxe_sw_tpa_info    *tpa_info,
3052              uint16_t                  queue,
3053              uint16_t                  pages,
3054                          struct eth_end_agg_rx_cqe *cqe,
3055              uint16_t                  cqe_idx)
3056 {
3057     struct ifnet *ifp = sc->ifnet;
3058     struct mbuf *m;
3059     int rc = 0;
3060
3061     BLOGD(sc, DBG_LRO,
3062           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3063           fp->index, queue, tpa_info->placement_offset,
3064           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3065
3066     m = tpa_info->bd.m;
3067
3068     /* allocate a replacement before modifying existing mbuf */
3069     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3070     if (rc) {
3071         /* drop the frame and log an error */
3072         fp->eth_q_stats.rx_soft_errors++;
3073         goto bxe_tpa_stop_exit;
3074     }
3075
3076     /* we have a replacement, fixup the current mbuf */
3077     m_adj(m, tpa_info->placement_offset);
3078     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3079
3080     /* mark the checksums valid (taken care of by the firmware) */
3081     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3082     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3083     m->m_pkthdr.csum_data = 0xffff;
3084     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3085                                CSUM_IP_VALID   |
3086                                CSUM_DATA_VALID |
3087                                CSUM_PSEUDO_HDR);
3088
3089     /* aggregate all of the SGEs into a single mbuf */
3090     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3091     if (rc) {
3092         /* drop the packet and log an error */
3093         fp->eth_q_stats.rx_soft_errors++;
3094         m_freem(m);
3095     } else {
3096         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3097             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3098             m->m_flags |= M_VLANTAG;
3099         }
3100
3101         /* assign packet to this interface interface */
3102         m->m_pkthdr.rcvif = ifp;
3103
3104 #if __FreeBSD_version >= 800000
3105         /* specify what RSS queue was used for this flow */
3106         m->m_pkthdr.flowid = fp->index;
3107         BXE_SET_FLOWID(m);
3108 #endif
3109
3110         ifp->if_ipackets++;
3111         fp->eth_q_stats.rx_tpa_pkts++;
3112
3113         /* pass the frame to the stack */
3114         (*ifp->if_input)(ifp, m);
3115     }
3116
3117     /* we passed an mbuf up the stack or dropped the frame */
3118     fp->eth_q_stats.mbuf_alloc_tpa--;
3119
3120 bxe_tpa_stop_exit:
3121
3122     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3123     fp->rx_tpa_queue_used &= ~(1 << queue);
3124 }
3125
3126 static uint8_t
3127 bxe_service_rxsgl(
3128                  struct bxe_fastpath *fp,
3129                  uint16_t len,
3130                  uint16_t lenonbd,
3131                  struct mbuf *m,
3132                  struct eth_fast_path_rx_cqe *cqe_fp)
3133 {
3134     struct mbuf *m_frag;
3135     uint16_t frags, frag_len;
3136     uint16_t sge_idx = 0;
3137     uint16_t j;
3138     uint8_t i, rc = 0;
3139     uint32_t frag_size;
3140
3141     /* adjust the mbuf */
3142     m->m_len = lenonbd;
3143
3144     frag_size =  len - lenonbd;
3145     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3146
3147     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3148         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3149
3150         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3151         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3152         m_frag->m_len = frag_len;
3153
3154        /* allocate a new mbuf for the SGE */
3155         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3156         if (rc) {
3157             /* Leave all remaining SGEs in the ring! */
3158             return (rc);
3159         }
3160         fp->eth_q_stats.mbuf_alloc_sge--;
3161
3162         /* concatenate the fragment to the head mbuf */
3163         m_cat(m, m_frag);
3164
3165         frag_size -= frag_len;
3166     }
3167
3168     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3169
3170     return rc;
3171 }
3172
3173 static uint8_t
3174 bxe_rxeof(struct bxe_softc    *sc,
3175           struct bxe_fastpath *fp)
3176 {
3177     struct ifnet *ifp = sc->ifnet;
3178     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3179     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3180     int rx_pkts = 0;
3181     int rc = 0;
3182
3183     BXE_FP_RX_LOCK(fp);
3184
3185     /* CQ "next element" is of the size of the regular element */
3186     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3187     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3188         hw_cq_cons++;
3189     }
3190
3191     bd_cons = fp->rx_bd_cons;
3192     bd_prod = fp->rx_bd_prod;
3193     bd_prod_fw = bd_prod;
3194     sw_cq_cons = fp->rx_cq_cons;
3195     sw_cq_prod = fp->rx_cq_prod;
3196
3197     /*
3198      * Memory barrier necessary as speculative reads of the rx
3199      * buffer can be ahead of the index in the status block
3200      */
3201     rmb();
3202
3203     BLOGD(sc, DBG_RX,
3204           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3205           fp->index, hw_cq_cons, sw_cq_cons);
3206
3207     while (sw_cq_cons != hw_cq_cons) {
3208         struct bxe_sw_rx_bd *rx_buf = NULL;
3209         union eth_rx_cqe *cqe;
3210         struct eth_fast_path_rx_cqe *cqe_fp;
3211         uint8_t cqe_fp_flags;
3212         enum eth_rx_cqe_type cqe_fp_type;
3213         uint16_t len, lenonbd,  pad;
3214         struct mbuf *m = NULL;
3215
3216         comp_ring_cons = RCQ(sw_cq_cons);
3217         bd_prod = RX_BD(bd_prod);
3218         bd_cons = RX_BD(bd_cons);
3219
3220         cqe          = &fp->rcq_chain[comp_ring_cons];
3221         cqe_fp       = &cqe->fast_path_cqe;
3222         cqe_fp_flags = cqe_fp->type_error_flags;
3223         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3224
3225         BLOGD(sc, DBG_RX,
3226               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3227               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3228               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3229               fp->index,
3230               hw_cq_cons,
3231               sw_cq_cons,
3232               bd_prod,
3233               bd_cons,
3234               CQE_TYPE(cqe_fp_flags),
3235               cqe_fp_flags,
3236               cqe_fp->status_flags,
3237               le32toh(cqe_fp->rss_hash_result),
3238               le16toh(cqe_fp->vlan_tag),
3239               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3240               le16toh(cqe_fp->len_on_bd));
3241
3242         /* is this a slowpath msg? */
3243         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3244             bxe_sp_event(sc, fp, cqe);
3245             goto next_cqe;
3246         }
3247
3248         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3249
3250         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3251             struct bxe_sw_tpa_info *tpa_info;
3252             uint16_t frag_size, pages;
3253             uint8_t queue;
3254
3255             if (CQE_TYPE_START(cqe_fp_type)) {
3256                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3257                               bd_cons, bd_prod, cqe_fp);
3258                 m = NULL; /* packet not ready yet */
3259                 goto next_rx;
3260             }
3261
3262             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3263                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3264
3265             queue = cqe->end_agg_cqe.queue_index;
3266             tpa_info = &fp->rx_tpa_info[queue];
3267
3268             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3269                   fp->index, queue);
3270
3271             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3272                          tpa_info->len_on_bd);
3273             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3274
3275             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3276                          &cqe->end_agg_cqe, comp_ring_cons);
3277
3278             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3279
3280             goto next_cqe;
3281         }
3282
3283         /* non TPA */
3284
3285         /* is this an error packet? */
3286         if (__predict_false(cqe_fp_flags &
3287                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3288             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3289             fp->eth_q_stats.rx_soft_errors++;
3290             goto next_rx;
3291         }
3292
3293         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3294         lenonbd = le16toh(cqe_fp->len_on_bd);
3295         pad = cqe_fp->placement_offset;
3296
3297         m = rx_buf->m;
3298
3299         if (__predict_false(m == NULL)) {
3300             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3301                   bd_cons, fp->index);
3302             goto next_rx;
3303         }
3304
3305         /* XXX double copy if packet length under a threshold */
3306
3307         /*
3308          * If all the buffer descriptors are filled with mbufs then fill in
3309          * the current consumer index with a new BD. Else if a maximum Rx
3310          * buffer limit is imposed then fill in the next producer index.
3311          */
3312         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3313                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3314                                       bd_prod : bd_cons);
3315         if (rc != 0) {
3316
3317             /* we simply reuse the received mbuf and don't post it to the stack */
3318             m = NULL;
3319
3320             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3321                   fp->index, rc);
3322             fp->eth_q_stats.rx_soft_errors++;
3323
3324             if (sc->max_rx_bufs != RX_BD_USABLE) {
3325                 /* copy this consumer index to the producer index */
3326                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3327                        sizeof(struct bxe_sw_rx_bd));
3328                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3329             }
3330
3331             goto next_rx;
3332         }
3333
3334         /* current mbuf was detached from the bd */
3335         fp->eth_q_stats.mbuf_alloc_rx--;
3336
3337         /* we allocated a replacement mbuf, fixup the current one */
3338         m_adj(m, pad);
3339         m->m_pkthdr.len = m->m_len = len;
3340
3341         if ((len > 60) && (len > lenonbd)) {
3342             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3343             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3344             if (rc)
3345                 break;
3346             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3347         } else if (lenonbd < len) {
3348             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3349         }
3350
3351         /* assign packet to this interface interface */
3352         m->m_pkthdr.rcvif = ifp;
3353
3354         /* assume no hardware checksum has complated */
3355         m->m_pkthdr.csum_flags = 0;
3356
3357         /* validate checksum if offload enabled */
3358         if (ifp->if_capenable & IFCAP_RXCSUM) {
3359             /* check for a valid IP frame */
3360             if (!(cqe->fast_path_cqe.status_flags &
3361                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3362                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3363                 if (__predict_false(cqe_fp_flags &
3364                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3365                     fp->eth_q_stats.rx_hw_csum_errors++;
3366                 } else {
3367                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3368                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3369                 }
3370             }
3371
3372             /* check for a valid TCP/UDP frame */
3373             if (!(cqe->fast_path_cqe.status_flags &
3374                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3375                 if (__predict_false(cqe_fp_flags &
3376                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3377                     fp->eth_q_stats.rx_hw_csum_errors++;
3378                 } else {
3379                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3380                     m->m_pkthdr.csum_data = 0xFFFF;
3381                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3382                                                CSUM_PSEUDO_HDR);
3383                 }
3384             }
3385         }
3386
3387         /* if there is a VLAN tag then flag that info */
3388         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3389             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3390             m->m_flags |= M_VLANTAG;
3391         }
3392
3393 #if __FreeBSD_version >= 800000
3394         /* specify what RSS queue was used for this flow */
3395         m->m_pkthdr.flowid = fp->index;
3396         BXE_SET_FLOWID(m);
3397 #endif
3398
3399 next_rx:
3400
3401         bd_cons    = RX_BD_NEXT(bd_cons);
3402         bd_prod    = RX_BD_NEXT(bd_prod);
3403         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3404
3405         /* pass the frame to the stack */
3406         if (__predict_true(m != NULL)) {
3407             ifp->if_ipackets++;
3408             rx_pkts++;
3409             (*ifp->if_input)(ifp, m);
3410         }
3411
3412 next_cqe:
3413
3414         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3415         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3416
3417         /* limit spinning on the queue */
3418         if (rc != 0)
3419             break;
3420
3421         if (rx_pkts == sc->rx_budget) {
3422             fp->eth_q_stats.rx_budget_reached++;
3423             break;
3424         }
3425     } /* while work to do */
3426
3427     fp->rx_bd_cons = bd_cons;
3428     fp->rx_bd_prod = bd_prod_fw;
3429     fp->rx_cq_cons = sw_cq_cons;
3430     fp->rx_cq_prod = sw_cq_prod;
3431
3432     /* Update producers */
3433     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3434
3435     fp->eth_q_stats.rx_pkts += rx_pkts;
3436     fp->eth_q_stats.rx_calls++;
3437
3438     BXE_FP_RX_UNLOCK(fp);
3439
3440     return (sw_cq_cons != hw_cq_cons);
3441 }
3442
3443 static uint16_t
3444 bxe_free_tx_pkt(struct bxe_softc    *sc,
3445                 struct bxe_fastpath *fp,
3446                 uint16_t            idx)
3447 {
3448     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3449     struct eth_tx_start_bd *tx_start_bd;
3450     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3451     uint16_t new_cons;
3452     int nbd;
3453
3454     /* unmap the mbuf from non-paged memory */
3455     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3456
3457     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3458     nbd = le16toh(tx_start_bd->nbd) - 1;
3459
3460     new_cons = (tx_buf->first_bd + nbd);
3461
3462     /* free the mbuf */
3463     if (__predict_true(tx_buf->m != NULL)) {
3464         m_freem(tx_buf->m);
3465         fp->eth_q_stats.mbuf_alloc_tx--;
3466     } else {
3467         fp->eth_q_stats.tx_chain_lost_mbuf++;
3468     }
3469
3470     tx_buf->m = NULL;
3471     tx_buf->first_bd = 0;
3472
3473     return (new_cons);
3474 }
3475
3476 /* transmit timeout watchdog */
3477 static int
3478 bxe_watchdog(struct bxe_softc    *sc,
3479              struct bxe_fastpath *fp)
3480 {
3481     BXE_FP_TX_LOCK(fp);
3482
3483     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3484         BXE_FP_TX_UNLOCK(fp);
3485         return (0);
3486     }
3487
3488     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3489     if(sc->trigger_grcdump) {
3490          /* taking grcdump */
3491          bxe_grc_dump(sc);
3492     }
3493
3494     BXE_FP_TX_UNLOCK(fp);
3495
3496     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3497     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3498
3499     return (-1);
3500 }
3501
3502 /* processes transmit completions */
3503 static uint8_t
3504 bxe_txeof(struct bxe_softc    *sc,
3505           struct bxe_fastpath *fp)
3506 {
3507     struct ifnet *ifp = sc->ifnet;
3508     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3509     uint16_t tx_bd_avail;
3510
3511     BXE_FP_TX_LOCK_ASSERT(fp);
3512
3513     bd_cons = fp->tx_bd_cons;
3514     hw_cons = le16toh(*fp->tx_cons_sb);
3515     sw_cons = fp->tx_pkt_cons;
3516
3517     while (sw_cons != hw_cons) {
3518         pkt_cons = TX_BD(sw_cons);
3519
3520         BLOGD(sc, DBG_TX,
3521               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3522               fp->index, hw_cons, sw_cons, pkt_cons);
3523
3524         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3525
3526         sw_cons++;
3527     }
3528
3529     fp->tx_pkt_cons = sw_cons;
3530     fp->tx_bd_cons  = bd_cons;
3531
3532     BLOGD(sc, DBG_TX,
3533           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3534           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3535
3536     mb();
3537
3538     tx_bd_avail = bxe_tx_avail(sc, fp);
3539
3540     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3541         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3542     } else {
3543         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3544     }
3545
3546     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3547         /* reset the watchdog timer if there are pending transmits */
3548         fp->watchdog_timer = BXE_TX_TIMEOUT;
3549         return (TRUE);
3550     } else {
3551         /* clear watchdog when there are no pending transmits */
3552         fp->watchdog_timer = 0;
3553         return (FALSE);
3554     }
3555 }
3556
3557 static void
3558 bxe_drain_tx_queues(struct bxe_softc *sc)
3559 {
3560     struct bxe_fastpath *fp;
3561     int i, count;
3562
3563     /* wait until all TX fastpath tasks have completed */
3564     for (i = 0; i < sc->num_queues; i++) {
3565         fp = &sc->fp[i];
3566
3567         count = 1000;
3568
3569         while (bxe_has_tx_work(fp)) {
3570
3571             BXE_FP_TX_LOCK(fp);
3572             bxe_txeof(sc, fp);
3573             BXE_FP_TX_UNLOCK(fp);
3574
3575             if (count == 0) {
3576                 BLOGE(sc, "Timeout waiting for fp[%d] "
3577                           "transmits to complete!\n", i);
3578                 bxe_panic(sc, ("tx drain failure\n"));
3579                 return;
3580             }
3581
3582             count--;
3583             DELAY(1000);
3584             rmb();
3585         }
3586     }
3587
3588     return;
3589 }
3590
3591 static int
3592 bxe_del_all_macs(struct bxe_softc          *sc,
3593                  struct ecore_vlan_mac_obj *mac_obj,
3594                  int                       mac_type,
3595                  uint8_t                   wait_for_comp)
3596 {
3597     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3598     int rc;
3599
3600     /* wait for completion of requested */
3601     if (wait_for_comp) {
3602         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3603     }
3604
3605     /* Set the mac type of addresses we want to clear */
3606     bxe_set_bit(mac_type, &vlan_mac_flags);
3607
3608     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3609     if (rc < 0) {
3610         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3611             rc, mac_type, wait_for_comp);
3612     }
3613
3614     return (rc);
3615 }
3616
3617 static int
3618 bxe_fill_accept_flags(struct bxe_softc *sc,
3619                       uint32_t         rx_mode,
3620                       unsigned long    *rx_accept_flags,
3621                       unsigned long    *tx_accept_flags)
3622 {
3623     /* Clear the flags first */
3624     *rx_accept_flags = 0;
3625     *tx_accept_flags = 0;
3626
3627     switch (rx_mode) {
3628     case BXE_RX_MODE_NONE:
3629         /*
3630          * 'drop all' supersedes any accept flags that may have been
3631          * passed to the function.
3632          */
3633         break;
3634
3635     case BXE_RX_MODE_NORMAL:
3636         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3637         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3638         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3639
3640         /* internal switching mode */
3641         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3642         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3643         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3644
3645         break;
3646
3647     case BXE_RX_MODE_ALLMULTI:
3648         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3649         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3650         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3651
3652         /* internal switching mode */
3653         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3654         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3655         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3656
3657         break;
3658
3659     case BXE_RX_MODE_PROMISC:
3660         /*
3661          * According to deffinition of SI mode, iface in promisc mode
3662          * should receive matched and unmatched (in resolution of port)
3663          * unicast packets.
3664          */
3665         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3666         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3667         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3668         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3669
3670         /* internal switching mode */
3671         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3672         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3673
3674         if (IS_MF_SI(sc)) {
3675             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3676         } else {
3677             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3678         }
3679
3680         break;
3681
3682     default:
3683         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3684         return (-1);
3685     }
3686
3687     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3688     if (rx_mode != BXE_RX_MODE_NONE) {
3689         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3690         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3691     }
3692
3693     return (0);
3694 }
3695
3696 static int
3697 bxe_set_q_rx_mode(struct bxe_softc *sc,
3698                   uint8_t          cl_id,
3699                   unsigned long    rx_mode_flags,
3700                   unsigned long    rx_accept_flags,
3701                   unsigned long    tx_accept_flags,
3702                   unsigned long    ramrod_flags)
3703 {
3704     struct ecore_rx_mode_ramrod_params ramrod_param;
3705     int rc;
3706
3707     memset(&ramrod_param, 0, sizeof(ramrod_param));
3708
3709     /* Prepare ramrod parameters */
3710     ramrod_param.cid = 0;
3711     ramrod_param.cl_id = cl_id;
3712     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3713     ramrod_param.func_id = SC_FUNC(sc);
3714
3715     ramrod_param.pstate = &sc->sp_state;
3716     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3717
3718     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3719     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3720
3721     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3722
3723     ramrod_param.ramrod_flags = ramrod_flags;
3724     ramrod_param.rx_mode_flags = rx_mode_flags;
3725
3726     ramrod_param.rx_accept_flags = rx_accept_flags;
3727     ramrod_param.tx_accept_flags = tx_accept_flags;
3728
3729     rc = ecore_config_rx_mode(sc, &ramrod_param);
3730     if (rc < 0) {
3731         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3732             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3733             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3734             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3735             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3736         return (rc);
3737     }
3738
3739     return (0);
3740 }
3741
3742 static int
3743 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3744 {
3745     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3746     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3747     int rc;
3748
3749     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3750                                &tx_accept_flags);
3751     if (rc) {
3752         return (rc);
3753     }
3754
3755     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3756     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3757
3758     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3759     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3760                               rx_accept_flags, tx_accept_flags,
3761                               ramrod_flags));
3762 }
3763
3764 /* returns the "mcp load_code" according to global load_count array */
3765 static int
3766 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3767 {
3768     int path = SC_PATH(sc);
3769     int port = SC_PORT(sc);
3770
3771     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3772           path, load_count[path][0], load_count[path][1],
3773           load_count[path][2]);
3774     load_count[path][0]++;
3775     load_count[path][1 + port]++;
3776     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3777           path, load_count[path][0], load_count[path][1],
3778           load_count[path][2]);
3779     if (load_count[path][0] == 1) {
3780         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3781     } else if (load_count[path][1 + port] == 1) {
3782         return (FW_MSG_CODE_DRV_LOAD_PORT);
3783     } else {
3784         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3785     }
3786 }
3787
3788 /* returns the "mcp load_code" according to global load_count array */
3789 static int
3790 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3791 {
3792     int port = SC_PORT(sc);
3793     int path = SC_PATH(sc);
3794
3795     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3796           path, load_count[path][0], load_count[path][1],
3797           load_count[path][2]);
3798     load_count[path][0]--;
3799     load_count[path][1 + port]--;
3800     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3801           path, load_count[path][0], load_count[path][1],
3802           load_count[path][2]);
3803     if (load_count[path][0] == 0) {
3804         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3805     } else if (load_count[path][1 + port] == 0) {
3806         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3807     } else {
3808         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3809     }
3810 }
3811
3812 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3813 static uint32_t
3814 bxe_send_unload_req(struct bxe_softc *sc,
3815                     int              unload_mode)
3816 {
3817     uint32_t reset_code = 0;
3818
3819     /* Select the UNLOAD request mode */
3820     if (unload_mode == UNLOAD_NORMAL) {
3821         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3822     } else {
3823         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3824     }
3825
3826     /* Send the request to the MCP */
3827     if (!BXE_NOMCP(sc)) {
3828         reset_code = bxe_fw_command(sc, reset_code, 0);
3829     } else {
3830         reset_code = bxe_nic_unload_no_mcp(sc);
3831     }
3832
3833     return (reset_code);
3834 }
3835
3836 /* send UNLOAD_DONE command to the MCP */
3837 static void
3838 bxe_send_unload_done(struct bxe_softc *sc,
3839                      uint8_t          keep_link)
3840 {
3841     uint32_t reset_param =
3842         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3843
3844     /* Report UNLOAD_DONE to MCP */
3845     if (!BXE_NOMCP(sc)) {
3846         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3847     }
3848 }
3849
3850 static int
3851 bxe_func_wait_started(struct bxe_softc *sc)
3852 {
3853     int tout = 50;
3854
3855     if (!sc->port.pmf) {
3856         return (0);
3857     }
3858
3859     /*
3860      * (assumption: No Attention from MCP at this stage)
3861      * PMF probably in the middle of TX disable/enable transaction
3862      * 1. Sync IRS for default SB
3863      * 2. Sync SP queue - this guarantees us that attention handling started
3864      * 3. Wait, that TX disable/enable transaction completes
3865      *
3866      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3867      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3868      * received completion for the transaction the state is TX_STOPPED.
3869      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3870      * transaction.
3871      */
3872
3873     /* XXX make sure default SB ISR is done */
3874     /* need a way to synchronize an irq (intr_mtx?) */
3875
3876     /* XXX flush any work queues */
3877
3878     while (ecore_func_get_state(sc, &sc->func_obj) !=
3879            ECORE_F_STATE_STARTED && tout--) {
3880         DELAY(20000);
3881     }
3882
3883     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3884         /*
3885          * Failed to complete the transaction in a "good way"
3886          * Force both transactions with CLR bit.
3887          */
3888         struct ecore_func_state_params func_params = { NULL };
3889
3890         BLOGE(sc, "Unexpected function state! "
3891                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3892
3893         func_params.f_obj = &sc->func_obj;
3894         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3895
3896         /* STARTED-->TX_STOPPED */
3897         func_params.cmd = ECORE_F_CMD_TX_STOP;
3898         ecore_func_state_change(sc, &func_params);
3899
3900         /* TX_STOPPED-->STARTED */
3901         func_params.cmd = ECORE_F_CMD_TX_START;
3902         return (ecore_func_state_change(sc, &func_params));
3903     }
3904
3905     return (0);
3906 }
3907
3908 static int
3909 bxe_stop_queue(struct bxe_softc *sc,
3910                int              index)
3911 {
3912     struct bxe_fastpath *fp = &sc->fp[index];
3913     struct ecore_queue_state_params q_params = { NULL };
3914     int rc;
3915
3916     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3917
3918     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3919     /* We want to wait for completion in this context */
3920     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3921
3922     /* Stop the primary connection: */
3923
3924     /* ...halt the connection */
3925     q_params.cmd = ECORE_Q_CMD_HALT;
3926     rc = ecore_queue_state_change(sc, &q_params);
3927     if (rc) {
3928         return (rc);
3929     }
3930
3931     /* ...terminate the connection */
3932     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3933     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3934     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3935     rc = ecore_queue_state_change(sc, &q_params);
3936     if (rc) {
3937         return (rc);
3938     }
3939
3940     /* ...delete cfc entry */
3941     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3942     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3943     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3944     return (ecore_queue_state_change(sc, &q_params));
3945 }
3946
3947 /* wait for the outstanding SP commands */
3948 static inline uint8_t
3949 bxe_wait_sp_comp(struct bxe_softc *sc,
3950                  unsigned long    mask)
3951 {
3952     unsigned long tmp;
3953     int tout = 5000; /* wait for 5 secs tops */
3954
3955     while (tout--) {
3956         mb();
3957         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3958             return (TRUE);
3959         }
3960
3961         DELAY(1000);
3962     }
3963
3964     mb();
3965
3966     tmp = atomic_load_acq_long(&sc->sp_state);
3967     if (tmp & mask) {
3968         BLOGE(sc, "Filtering completion timed out: "
3969                   "sp_state 0x%lx, mask 0x%lx\n",
3970               tmp, mask);
3971         return (FALSE);
3972     }
3973
3974     return (FALSE);
3975 }
3976
3977 static int
3978 bxe_func_stop(struct bxe_softc *sc)
3979 {
3980     struct ecore_func_state_params func_params = { NULL };
3981     int rc;
3982
3983     /* prepare parameters for function state transitions */
3984     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3985     func_params.f_obj = &sc->func_obj;
3986     func_params.cmd = ECORE_F_CMD_STOP;
3987
3988     /*
3989      * Try to stop the function the 'good way'. If it fails (in case
3990      * of a parity error during bxe_chip_cleanup()) and we are
3991      * not in a debug mode, perform a state transaction in order to
3992      * enable further HW_RESET transaction.
3993      */
3994     rc = ecore_func_state_change(sc, &func_params);
3995     if (rc) {
3996         BLOGE(sc, "FUNC_STOP ramrod failed. "
3997                   "Running a dry transaction (%d)\n", rc);
3998         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3999         return (ecore_func_state_change(sc, &func_params));
4000     }
4001
4002     return (0);
4003 }
4004
4005 static int
4006 bxe_reset_hw(struct bxe_softc *sc,
4007              uint32_t         load_code)
4008 {
4009     struct ecore_func_state_params func_params = { NULL };
4010
4011     /* Prepare parameters for function state transitions */
4012     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4013
4014     func_params.f_obj = &sc->func_obj;
4015     func_params.cmd = ECORE_F_CMD_HW_RESET;
4016
4017     func_params.params.hw_init.load_phase = load_code;
4018
4019     return (ecore_func_state_change(sc, &func_params));
4020 }
4021
4022 static void
4023 bxe_int_disable_sync(struct bxe_softc *sc,
4024                      int              disable_hw)
4025 {
4026     if (disable_hw) {
4027         /* prevent the HW from sending interrupts */
4028         bxe_int_disable(sc);
4029     }
4030
4031     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4032     /* make sure all ISRs are done */
4033
4034     /* XXX make sure sp_task is not running */
4035     /* cancel and flush work queues */
4036 }
4037
4038 static void
4039 bxe_chip_cleanup(struct bxe_softc *sc,
4040                  uint32_t         unload_mode,
4041                  uint8_t          keep_link)
4042 {
4043     int port = SC_PORT(sc);
4044     struct ecore_mcast_ramrod_params rparam = { NULL };
4045     uint32_t reset_code;
4046     int i, rc = 0;
4047
4048     bxe_drain_tx_queues(sc);
4049
4050     /* give HW time to discard old tx messages */
4051     DELAY(1000);
4052
4053     /* Clean all ETH MACs */
4054     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4055     if (rc < 0) {
4056         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4057     }
4058
4059     /* Clean up UC list  */
4060     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4061     if (rc < 0) {
4062         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4063     }
4064
4065     /* Disable LLH */
4066     if (!CHIP_IS_E1(sc)) {
4067         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4068     }
4069
4070     /* Set "drop all" to stop Rx */
4071
4072     /*
4073      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4074      * a race between the completion code and this code.
4075      */
4076     BXE_MCAST_LOCK(sc);
4077
4078     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4079         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4080     } else {
4081         bxe_set_storm_rx_mode(sc);
4082     }
4083
4084     /* Clean up multicast configuration */
4085     rparam.mcast_obj = &sc->mcast_obj;
4086     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4087     if (rc < 0) {
4088         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4089     }
4090
4091     BXE_MCAST_UNLOCK(sc);
4092
4093     // XXX bxe_iov_chip_cleanup(sc);
4094
4095     /*
4096      * Send the UNLOAD_REQUEST to the MCP. This will return if
4097      * this function should perform FUNCTION, PORT, or COMMON HW
4098      * reset.
4099      */
4100     reset_code = bxe_send_unload_req(sc, unload_mode);
4101
4102     /*
4103      * (assumption: No Attention from MCP at this stage)
4104      * PMF probably in the middle of TX disable/enable transaction
4105      */
4106     rc = bxe_func_wait_started(sc);
4107     if (rc) {
4108         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4109     }
4110
4111     /*
4112      * Close multi and leading connections
4113      * Completions for ramrods are collected in a synchronous way
4114      */
4115     for (i = 0; i < sc->num_queues; i++) {
4116         if (bxe_stop_queue(sc, i)) {
4117             goto unload_error;
4118         }
4119     }
4120
4121     /*
4122      * If SP settings didn't get completed so far - something
4123      * very wrong has happen.
4124      */
4125     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4126         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4127     }
4128
4129 unload_error:
4130
4131     rc = bxe_func_stop(sc);
4132     if (rc) {
4133         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4134     }
4135
4136     /* disable HW interrupts */
4137     bxe_int_disable_sync(sc, TRUE);
4138
4139     /* detach interrupts */
4140     bxe_interrupt_detach(sc);
4141
4142     /* Reset the chip */
4143     rc = bxe_reset_hw(sc, reset_code);
4144     if (rc) {
4145         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4146     }
4147
4148     /* Report UNLOAD_DONE to MCP */
4149     bxe_send_unload_done(sc, keep_link);
4150 }
4151
4152 static void
4153 bxe_disable_close_the_gate(struct bxe_softc *sc)
4154 {
4155     uint32_t val;
4156     int port = SC_PORT(sc);
4157
4158     BLOGD(sc, DBG_LOAD,
4159           "Disabling 'close the gates'\n");
4160
4161     if (CHIP_IS_E1(sc)) {
4162         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4163                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4164         val = REG_RD(sc, addr);
4165         val &= ~(0x300);
4166         REG_WR(sc, addr, val);
4167     } else {
4168         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4169         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4170                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4171         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4172     }
4173 }
4174
4175 /*
4176  * Cleans the object that have internal lists without sending
4177  * ramrods. Should be run when interrutps are disabled.
4178  */
4179 static void
4180 bxe_squeeze_objects(struct bxe_softc *sc)
4181 {
4182     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4183     struct ecore_mcast_ramrod_params rparam = { NULL };
4184     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4185     int rc;
4186
4187     /* Cleanup MACs' object first... */
4188
4189     /* Wait for completion of requested */
4190     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4191     /* Perform a dry cleanup */
4192     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4193
4194     /* Clean ETH primary MAC */
4195     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4196     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4197                              &ramrod_flags);
4198     if (rc != 0) {
4199         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4200     }
4201
4202     /* Cleanup UC list */
4203     vlan_mac_flags = 0;
4204     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4205     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4206                              &ramrod_flags);
4207     if (rc != 0) {
4208         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4209     }
4210
4211     /* Now clean mcast object... */
4212
4213     rparam.mcast_obj = &sc->mcast_obj;
4214     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4215
4216     /* Add a DEL command... */
4217     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4218     if (rc < 0) {
4219         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4220     }
4221
4222     /* now wait until all pending commands are cleared */
4223
4224     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4225     while (rc != 0) {
4226         if (rc < 0) {
4227             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4228             return;
4229         }
4230
4231         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4232     }
4233 }
4234
4235 /* stop the controller */
4236 static __noinline int
4237 bxe_nic_unload(struct bxe_softc *sc,
4238                uint32_t         unload_mode,
4239                uint8_t          keep_link)
4240 {
4241     uint8_t global = FALSE;
4242     uint32_t val;
4243     int i;
4244
4245     BXE_CORE_LOCK_ASSERT(sc);
4246
4247     sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
4248
4249     for (i = 0; i < sc->num_queues; i++) {
4250         struct bxe_fastpath *fp;
4251
4252         fp = &sc->fp[i];
4253         BXE_FP_TX_LOCK(fp);
4254         BXE_FP_TX_UNLOCK(fp);
4255     }
4256
4257     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4258
4259     /* mark driver as unloaded in shmem2 */
4260     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4261         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4262         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4263                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4264     }
4265
4266     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4267         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4268         /*
4269          * We can get here if the driver has been unloaded
4270          * during parity error recovery and is either waiting for a
4271          * leader to complete or for other functions to unload and
4272          * then ifconfig down has been issued. In this case we want to
4273          * unload and let other functions to complete a recovery
4274          * process.
4275          */
4276         sc->recovery_state = BXE_RECOVERY_DONE;
4277         sc->is_leader = 0;
4278         bxe_release_leader_lock(sc);
4279         mb();
4280
4281         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4282         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4283             " state = 0x%x\n", sc->recovery_state, sc->state);
4284         return (-1);
4285     }
4286
4287     /*
4288      * Nothing to do during unload if previous bxe_nic_load()
4289      * did not completed succesfully - all resourses are released.
4290      */
4291     if ((sc->state == BXE_STATE_CLOSED) ||
4292         (sc->state == BXE_STATE_ERROR)) {
4293         return (0);
4294     }
4295
4296     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4297     mb();
4298
4299     /* stop tx */
4300     bxe_tx_disable(sc);
4301
4302     sc->rx_mode = BXE_RX_MODE_NONE;
4303     /* XXX set rx mode ??? */
4304
4305     if (IS_PF(sc) && !sc->grcdump_done) {
4306         /* set ALWAYS_ALIVE bit in shmem */
4307         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4308
4309         bxe_drv_pulse(sc);
4310
4311         bxe_stats_handle(sc, STATS_EVENT_STOP);
4312         bxe_save_statistics(sc);
4313     }
4314
4315     /* wait till consumers catch up with producers in all queues */
4316     bxe_drain_tx_queues(sc);
4317
4318     /* if VF indicate to PF this function is going down (PF will delete sp
4319      * elements and clear initializations
4320      */
4321     if (IS_VF(sc)) {
4322         ; /* bxe_vfpf_close_vf(sc); */
4323     } else if (unload_mode != UNLOAD_RECOVERY) {
4324         /* if this is a normal/close unload need to clean up chip */
4325         if (!sc->grcdump_done)
4326             bxe_chip_cleanup(sc, unload_mode, keep_link);
4327     } else {
4328         /* Send the UNLOAD_REQUEST to the MCP */
4329         bxe_send_unload_req(sc, unload_mode);
4330
4331         /*
4332          * Prevent transactions to host from the functions on the
4333          * engine that doesn't reset global blocks in case of global
4334          * attention once gloabl blocks are reset and gates are opened
4335          * (the engine which leader will perform the recovery
4336          * last).
4337          */
4338         if (!CHIP_IS_E1x(sc)) {
4339             bxe_pf_disable(sc);
4340         }
4341
4342         /* disable HW interrupts */
4343         bxe_int_disable_sync(sc, TRUE);
4344
4345         /* detach interrupts */
4346         bxe_interrupt_detach(sc);
4347
4348         /* Report UNLOAD_DONE to MCP */
4349         bxe_send_unload_done(sc, FALSE);
4350     }
4351
4352     /*
4353      * At this stage no more interrupts will arrive so we may safely clean
4354      * the queue'able objects here in case they failed to get cleaned so far.
4355      */
4356     if (IS_PF(sc)) {
4357         bxe_squeeze_objects(sc);
4358     }
4359
4360     /* There should be no more pending SP commands at this stage */
4361     sc->sp_state = 0;
4362
4363     sc->port.pmf = 0;
4364
4365     bxe_free_fp_buffers(sc);
4366
4367     if (IS_PF(sc)) {
4368         bxe_free_mem(sc);
4369     }
4370
4371     bxe_free_fw_stats_mem(sc);
4372
4373     sc->state = BXE_STATE_CLOSED;
4374
4375     /*
4376      * Check if there are pending parity attentions. If there are - set
4377      * RECOVERY_IN_PROGRESS.
4378      */
4379     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4380         bxe_set_reset_in_progress(sc);
4381
4382         /* Set RESET_IS_GLOBAL if needed */
4383         if (global) {
4384             bxe_set_reset_global(sc);
4385         }
4386     }
4387
4388     /*
4389      * The last driver must disable a "close the gate" if there is no
4390      * parity attention or "process kill" pending.
4391      */
4392     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4393         bxe_reset_is_done(sc, SC_PATH(sc))) {
4394         bxe_disable_close_the_gate(sc);
4395     }
4396
4397     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4398
4399     bxe_link_report(sc);
4400
4401     return (0);
4402 }
4403
4404 /*
4405  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4406  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4407  */
4408 static int
4409 bxe_ifmedia_update(struct ifnet *ifp)
4410 {
4411     struct bxe_softc *sc = (struct bxe_softc *)ifp->if_softc;
4412     struct ifmedia *ifm;
4413
4414     ifm = &sc->ifmedia;
4415
4416     /* We only support Ethernet media type. */
4417     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4418         return (EINVAL);
4419     }
4420
4421     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4422     case IFM_AUTO:
4423          break;
4424     case IFM_10G_CX4:
4425     case IFM_10G_SR:
4426     case IFM_10G_T:
4427     case IFM_10G_TWINAX:
4428     default:
4429         /* We don't support changing the media type. */
4430         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4431               IFM_SUBTYPE(ifm->ifm_media));
4432         return (EINVAL);
4433     }
4434
4435     return (0);
4436 }
4437
4438 /*
4439  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4440  */
4441 static void
4442 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4443 {
4444     struct bxe_softc *sc = ifp->if_softc;
4445
4446     /* Bug 165447: the 'ifconfig' tool skips printing of the "status: ..."
4447        line if the IFM_AVALID flag is *NOT* set. So we need to set this
4448        flag unconditionally (irrespective of the admininistrative
4449        'up/down' state of the interface) to ensure that that line is always
4450        displayed.
4451     */
4452     ifmr->ifm_status = IFM_AVALID;
4453
4454     /* Setup the default interface info. */
4455     ifmr->ifm_active = IFM_ETHER;
4456
4457     /* Report link down if the driver isn't running. */
4458     if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4459         ifmr->ifm_active |= IFM_NONE;
4460         BLOGD(sc, DBG_PHY, "in %s : nic still not loaded fully\n", __func__);
4461         BLOGD(sc, DBG_PHY, "in %s : link_up (1) : %d\n",
4462                 __func__, sc->link_vars.link_up);
4463         return;
4464     }
4465
4466
4467     if (sc->link_vars.link_up) {
4468         ifmr->ifm_status |= IFM_ACTIVE;
4469         ifmr->ifm_active |= IFM_FDX;
4470     } else {
4471         ifmr->ifm_active |= IFM_NONE;
4472         BLOGD(sc, DBG_PHY, "in %s : setting IFM_NONE\n",
4473                 __func__);
4474         return;
4475     }
4476
4477     ifmr->ifm_active |= sc->media;
4478     return;
4479 }
4480
4481 static void
4482 bxe_handle_chip_tq(void *context,
4483                    int  pending)
4484 {
4485     struct bxe_softc *sc = (struct bxe_softc *)context;
4486     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4487
4488     switch (work)
4489     {
4490     case CHIP_TQ_REINIT:
4491         if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
4492             /* restart the interface */
4493             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4494             bxe_periodic_stop(sc);
4495             BXE_CORE_LOCK(sc);
4496             bxe_stop_locked(sc);
4497             bxe_init_locked(sc);
4498             BXE_CORE_UNLOCK(sc);
4499         }
4500         break;
4501
4502     default:
4503         break;
4504     }
4505 }
4506
4507 /*
4508  * Handles any IOCTL calls from the operating system.
4509  *
4510  * Returns:
4511  *   0 = Success, >0 Failure
4512  */
4513 static int
4514 bxe_ioctl(struct ifnet *ifp,
4515           u_long       command,
4516           caddr_t      data)
4517 {
4518     struct bxe_softc *sc = ifp->if_softc;
4519     struct ifreq *ifr = (struct ifreq *)data;
4520     int mask = 0;
4521     int reinit = 0;
4522     int error = 0;
4523
4524     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4525     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4526
4527     switch (command)
4528     {
4529     case SIOCSIFMTU:
4530         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4531               ifr->ifr_mtu);
4532
4533         if (sc->mtu == ifr->ifr_mtu) {
4534             /* nothing to change */
4535             break;
4536         }
4537
4538         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4539             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4540                   ifr->ifr_mtu, mtu_min, mtu_max);
4541             error = EINVAL;
4542             break;
4543         }
4544
4545         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4546                              (unsigned long)ifr->ifr_mtu);
4547         atomic_store_rel_long((volatile unsigned long *)&ifp->if_mtu,
4548                               (unsigned long)ifr->ifr_mtu);
4549
4550         reinit = 1;
4551         break;
4552
4553     case SIOCSIFFLAGS:
4554         /* toggle the interface state up or down */
4555         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4556
4557         BXE_CORE_LOCK(sc);
4558         /* check if the interface is up */
4559         if (ifp->if_flags & IFF_UP) {
4560             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4561                 /* set the receive mode flags */
4562                 bxe_set_rx_mode(sc);
4563             } else if(sc->state != BXE_STATE_DISABLED) {
4564                 bxe_init_locked(sc);
4565             }
4566         } else {
4567             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4568                 bxe_periodic_stop(sc);
4569                 bxe_stop_locked(sc);
4570             }
4571         }
4572         BXE_CORE_UNLOCK(sc);
4573
4574         break;
4575
4576     case SIOCADDMULTI:
4577     case SIOCDELMULTI:
4578         /* add/delete multicast addresses */
4579         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4580
4581         /* check if the interface is up */
4582         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4583             /* set the receive mode flags */
4584             BXE_CORE_LOCK(sc);
4585             bxe_set_rx_mode(sc);
4586             BXE_CORE_UNLOCK(sc); 
4587         }
4588
4589         break;
4590
4591     case SIOCSIFCAP:
4592         /* find out which capabilities have changed */
4593         mask = (ifr->ifr_reqcap ^ ifp->if_capenable);
4594
4595         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4596               mask);
4597
4598         /* toggle the LRO capabilites enable flag */
4599         if (mask & IFCAP_LRO) {
4600             ifp->if_capenable ^= IFCAP_LRO;
4601             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4602                   (ifp->if_capenable & IFCAP_LRO) ? "ON" : "OFF");
4603             reinit = 1;
4604         }
4605
4606         /* toggle the TXCSUM checksum capabilites enable flag */
4607         if (mask & IFCAP_TXCSUM) {
4608             ifp->if_capenable ^= IFCAP_TXCSUM;
4609             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4610                   (ifp->if_capenable & IFCAP_TXCSUM) ? "ON" : "OFF");
4611             if (ifp->if_capenable & IFCAP_TXCSUM) {
4612                 ifp->if_hwassist = (CSUM_IP       |
4613                                     CSUM_TCP      |
4614                                     CSUM_UDP      |
4615                                     CSUM_TSO      |
4616                                     CSUM_TCP_IPV6 |
4617                                     CSUM_UDP_IPV6);
4618             } else {
4619                 ifp->if_hwassist = 0;
4620             }
4621         }
4622
4623         /* toggle the RXCSUM checksum capabilities enable flag */
4624         if (mask & IFCAP_RXCSUM) {
4625             ifp->if_capenable ^= IFCAP_RXCSUM;
4626             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4627                   (ifp->if_capenable & IFCAP_RXCSUM) ? "ON" : "OFF");
4628             if (ifp->if_capenable & IFCAP_RXCSUM) {
4629                 ifp->if_hwassist = (CSUM_IP       |
4630                                     CSUM_TCP      |
4631                                     CSUM_UDP      |
4632                                     CSUM_TSO      |
4633                                     CSUM_TCP_IPV6 |
4634                                     CSUM_UDP_IPV6);
4635             } else {
4636                 ifp->if_hwassist = 0;
4637             }
4638         }
4639
4640         /* toggle TSO4 capabilities enabled flag */
4641         if (mask & IFCAP_TSO4) {
4642             ifp->if_capenable ^= IFCAP_TSO4;
4643             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4644                   (ifp->if_capenable & IFCAP_TSO4) ? "ON" : "OFF");
4645         }
4646
4647         /* toggle TSO6 capabilities enabled flag */
4648         if (mask & IFCAP_TSO6) {
4649             ifp->if_capenable ^= IFCAP_TSO6;
4650             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4651                   (ifp->if_capenable & IFCAP_TSO6) ? "ON" : "OFF");
4652         }
4653
4654         /* toggle VLAN_HWTSO capabilities enabled flag */
4655         if (mask & IFCAP_VLAN_HWTSO) {
4656             ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
4657             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4658                   (ifp->if_capenable & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4659         }
4660
4661         /* toggle VLAN_HWCSUM capabilities enabled flag */
4662         if (mask & IFCAP_VLAN_HWCSUM) {
4663             /* XXX investigate this... */
4664             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4665             error = EINVAL;
4666         }
4667
4668         /* toggle VLAN_MTU capabilities enable flag */
4669         if (mask & IFCAP_VLAN_MTU) {
4670             /* XXX investigate this... */
4671             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4672             error = EINVAL;
4673         }
4674
4675         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4676         if (mask & IFCAP_VLAN_HWTAGGING) {
4677             /* XXX investigate this... */
4678             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4679             error = EINVAL;
4680         }
4681
4682         /* toggle VLAN_HWFILTER capabilities enabled flag */
4683         if (mask & IFCAP_VLAN_HWFILTER) {
4684             /* XXX investigate this... */
4685             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4686             error = EINVAL;
4687         }
4688
4689         /* XXX not yet...
4690          * IFCAP_WOL_MAGIC
4691          */
4692
4693         break;
4694
4695     case SIOCSIFMEDIA:
4696     case SIOCGIFMEDIA:
4697         /* set/get interface media */
4698         BLOGD(sc, DBG_IOCTL,
4699               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4700               (command & 0xff));
4701         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4702         break;
4703
4704     default:
4705         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4706               (command & 0xff));
4707         error = ether_ioctl(ifp, command, data);
4708         break;
4709     }
4710
4711     if (reinit && (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
4712         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4713               "Re-initializing hardware from IOCTL change\n");
4714         bxe_periodic_stop(sc);
4715         BXE_CORE_LOCK(sc);
4716         bxe_stop_locked(sc);
4717         bxe_init_locked(sc);
4718         BXE_CORE_UNLOCK(sc);
4719     }
4720
4721     return (error);
4722 }
4723
4724 static __noinline void
4725 bxe_dump_mbuf(struct bxe_softc *sc,
4726               struct mbuf      *m,
4727               uint8_t          contents)
4728 {
4729     char * type;
4730     int i = 0;
4731
4732     if (!(sc->debug & DBG_MBUF)) {
4733         return;
4734     }
4735
4736     if (m == NULL) {
4737         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4738         return;
4739     }
4740
4741     while (m) {
4742
4743 #if __FreeBSD_version >= 1000000
4744         BLOGD(sc, DBG_MBUF,
4745               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4746               i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4747
4748         if (m->m_flags & M_PKTHDR) {
4749              BLOGD(sc, DBG_MBUF,
4750                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4751                    i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4752                    (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4753         }
4754 #else
4755         BLOGD(sc, DBG_MBUF,
4756               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4757               i, m, m->m_len, m->m_flags,
4758               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4759
4760         if (m->m_flags & M_PKTHDR) {
4761              BLOGD(sc, DBG_MBUF,
4762                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4763                    i, m->m_pkthdr.len, m->m_flags,
4764                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4765                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4766                    "\22M_PROMISC\23M_NOFREE",
4767                    (int)m->m_pkthdr.csum_flags,
4768                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4769                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4770                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4771                    "\14CSUM_PSEUDO_HDR");
4772         }
4773 #endif /* #if __FreeBSD_version >= 1000000 */
4774
4775         if (m->m_flags & M_EXT) {
4776             switch (m->m_ext.ext_type) {
4777             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4778             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4779             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4780             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4781             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4782             case EXT_PACKET:     type = "EXT_PACKET";     break;
4783             case EXT_MBUF:       type = "EXT_MBUF";       break;
4784             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4785             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4786             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4787             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4788             default:             type = "UNKNOWN";        break;
4789             }
4790
4791             BLOGD(sc, DBG_MBUF,
4792                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4793                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4794         }
4795
4796         if (contents) {
4797             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4798         }
4799
4800         m = m->m_next;
4801         i++;
4802     }
4803 }
4804
4805 /*
4806  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4807  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4808  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4809  * The headers comes in a seperate bd in FreeBSD so 13-3=10.
4810  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4811  */
4812 static int
4813 bxe_chktso_window(struct bxe_softc  *sc,
4814                   int               nsegs,
4815                   bus_dma_segment_t *segs,
4816                   struct mbuf       *m)
4817 {
4818     uint32_t num_wnds, wnd_size, wnd_sum;
4819     int32_t frag_idx, wnd_idx;
4820     unsigned short lso_mss;
4821     int defrag;
4822
4823     defrag = 0;
4824     wnd_sum = 0;
4825     wnd_size = 10;
4826     num_wnds = nsegs - wnd_size;
4827     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4828
4829     /*
4830      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4831      * first window sum of data while skipping the first assuming it is the
4832      * header in FreeBSD.
4833      */
4834     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4835         wnd_sum += htole16(segs[frag_idx].ds_len);
4836     }
4837
4838     /* check the first 10 bd window size */
4839     if (wnd_sum < lso_mss) {
4840         return (1);
4841     }
4842
4843     /* run through the windows */
4844     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4845         /* subtract the first mbuf->m_len of the last wndw(-header) */
4846         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4847         /* add the next mbuf len to the len of our new window */
4848         wnd_sum += htole16(segs[frag_idx].ds_len);
4849         if (wnd_sum < lso_mss) {
4850             return (1);
4851         }
4852     }
4853
4854     return (0);
4855 }
4856
4857 static uint8_t
4858 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4859                     struct mbuf         *m,
4860                     uint32_t            *parsing_data)
4861 {
4862     struct ether_vlan_header *eh = NULL;
4863     struct ip *ip4 = NULL;
4864     struct ip6_hdr *ip6 = NULL;
4865     caddr_t ip = NULL;
4866     struct tcphdr *th = NULL;
4867     int e_hlen, ip_hlen, l4_off;
4868     uint16_t proto;
4869
4870     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4871         /* no L4 checksum offload needed */
4872         return (0);
4873     }
4874
4875     /* get the Ethernet header */
4876     eh = mtod(m, struct ether_vlan_header *);
4877
4878     /* handle VLAN encapsulation if present */
4879     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4880         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4881         proto  = ntohs(eh->evl_proto);
4882     } else {
4883         e_hlen = ETHER_HDR_LEN;
4884         proto  = ntohs(eh->evl_encap_proto);
4885     }
4886
4887     switch (proto) {
4888     case ETHERTYPE_IP:
4889         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4890         ip4 = (m->m_len < sizeof(struct ip)) ?
4891                   (struct ip *)m->m_next->m_data :
4892                   (struct ip *)(m->m_data + e_hlen);
4893         /* ip_hl is number of 32-bit words */
4894         ip_hlen = (ip4->ip_hl << 2);
4895         ip = (caddr_t)ip4;
4896         break;
4897     case ETHERTYPE_IPV6:
4898         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4899         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4900                   (struct ip6_hdr *)m->m_next->m_data :
4901                   (struct ip6_hdr *)(m->m_data + e_hlen);
4902         /* XXX cannot support offload with IPv6 extensions */
4903         ip_hlen = sizeof(struct ip6_hdr);
4904         ip = (caddr_t)ip6;
4905         break;
4906     default:
4907         /* We can't offload in this case... */
4908         /* XXX error stat ??? */
4909         return (0);
4910     }
4911
4912     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4913     l4_off = (e_hlen + ip_hlen);
4914
4915     *parsing_data |=
4916         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4917          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4918
4919     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4920                                   CSUM_TSO |
4921                                   CSUM_TCP_IPV6)) {
4922         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4923         th = (struct tcphdr *)(ip + ip_hlen);
4924         /* th_off is number of 32-bit words */
4925         *parsing_data |= ((th->th_off <<
4926                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4927                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4928         return (l4_off + (th->th_off << 2)); /* entire header length */
4929     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4930                                          CSUM_UDP_IPV6)) {
4931         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4932         return (l4_off + sizeof(struct udphdr)); /* entire header length */
4933     } else {
4934         /* XXX error stat ??? */
4935         return (0);
4936     }
4937 }
4938
4939 static uint8_t
4940 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4941                  struct mbuf                *m,
4942                  struct eth_tx_parse_bd_e1x *pbd)
4943 {
4944     struct ether_vlan_header *eh = NULL;
4945     struct ip *ip4 = NULL;
4946     struct ip6_hdr *ip6 = NULL;
4947     caddr_t ip = NULL;
4948     struct tcphdr *th = NULL;
4949     struct udphdr *uh = NULL;
4950     int e_hlen, ip_hlen;
4951     uint16_t proto;
4952     uint8_t hlen;
4953     uint16_t tmp_csum;
4954     uint32_t *tmp_uh;
4955
4956     /* get the Ethernet header */
4957     eh = mtod(m, struct ether_vlan_header *);
4958
4959     /* handle VLAN encapsulation if present */
4960     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4961         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4962         proto  = ntohs(eh->evl_proto);
4963     } else {
4964         e_hlen = ETHER_HDR_LEN;
4965         proto  = ntohs(eh->evl_encap_proto);
4966     }
4967
4968     switch (proto) {
4969     case ETHERTYPE_IP:
4970         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4971         ip4 = (m->m_len < sizeof(struct ip)) ?
4972                   (struct ip *)m->m_next->m_data :
4973                   (struct ip *)(m->m_data + e_hlen);
4974         /* ip_hl is number of 32-bit words */
4975         ip_hlen = (ip4->ip_hl << 1);
4976         ip = (caddr_t)ip4;
4977         break;
4978     case ETHERTYPE_IPV6:
4979         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4980         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4981                   (struct ip6_hdr *)m->m_next->m_data :
4982                   (struct ip6_hdr *)(m->m_data + e_hlen);
4983         /* XXX cannot support offload with IPv6 extensions */
4984         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4985         ip = (caddr_t)ip6;
4986         break;
4987     default:
4988         /* We can't offload in this case... */
4989         /* XXX error stat ??? */
4990         return (0);
4991     }
4992
4993     hlen = (e_hlen >> 1);
4994
4995     /* note that rest of global_data is indirectly zeroed here */
4996     if (m->m_flags & M_VLANTAG) {
4997         pbd->global_data =
4998             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
4999     } else {
5000         pbd->global_data = htole16(hlen);
5001     }
5002
5003     pbd->ip_hlen_w = ip_hlen;
5004
5005     hlen += pbd->ip_hlen_w;
5006
5007     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5008
5009     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5010                                   CSUM_TSO |
5011                                   CSUM_TCP_IPV6)) {
5012         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5013         /* th_off is number of 32-bit words */
5014         hlen += (uint16_t)(th->th_off << 1);
5015     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5016                                          CSUM_UDP_IPV6)) {
5017         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5018         hlen += (sizeof(struct udphdr) / 2);
5019     } else {
5020         /* valid case as only CSUM_IP was set */
5021         return (0);
5022     }
5023
5024     pbd->total_hlen_w = htole16(hlen);
5025
5026     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5027                                   CSUM_TSO |
5028                                   CSUM_TCP_IPV6)) {
5029         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5030         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5031     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5032                                          CSUM_UDP_IPV6)) {
5033         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5034
5035         /*
5036          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5037          * checksums and does not know anything about the UDP header and where
5038          * the checksum field is located. It only knows about TCP. Therefore
5039          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5040          * offload. Since the checksum field offset for TCP is 16 bytes and
5041          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5042          * bytes less than the start of the UDP header. This allows the
5043          * hardware to write the checksum in the correct spot. But the
5044          * hardware will compute a checksum which includes the last 10 bytes
5045          * of the IP header. To correct this we tweak the stack computed
5046          * pseudo checksum by folding in the calculation of the inverse
5047          * checksum for those final 10 bytes of the IP header. This allows
5048          * the correct checksum to be computed by the hardware.
5049          */
5050
5051         /* set pointer 10 bytes before UDP header */
5052         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5053
5054         /* calculate a pseudo header checksum over the first 10 bytes */
5055         tmp_csum = in_pseudo(*tmp_uh,
5056                              *(tmp_uh + 1),
5057                              *(uint16_t *)(tmp_uh + 2));
5058
5059         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5060     }
5061
5062     return (hlen * 2); /* entire header length, number of bytes */
5063 }
5064
5065 static void
5066 bxe_set_pbd_lso_e2(struct mbuf *m,
5067                    uint32_t    *parsing_data)
5068 {
5069     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5070                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5071                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5072
5073     /* XXX test for IPv6 with extension header... */
5074 }
5075
5076 static void
5077 bxe_set_pbd_lso(struct mbuf                *m,
5078                 struct eth_tx_parse_bd_e1x *pbd)
5079 {
5080     struct ether_vlan_header *eh = NULL;
5081     struct ip *ip = NULL;
5082     struct tcphdr *th = NULL;
5083     int e_hlen;
5084
5085     /* get the Ethernet header */
5086     eh = mtod(m, struct ether_vlan_header *);
5087
5088     /* handle VLAN encapsulation if present */
5089     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5090                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5091
5092     /* get the IP and TCP header, with LSO entire header in first mbuf */
5093     /* XXX assuming IPv4 */
5094     ip = (struct ip *)(m->m_data + e_hlen);
5095     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5096
5097     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5098     pbd->tcp_send_seq = ntohl(th->th_seq);
5099     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5100
5101 #if 1
5102         /* XXX IPv4 */
5103         pbd->ip_id = ntohs(ip->ip_id);
5104         pbd->tcp_pseudo_csum =
5105             ntohs(in_pseudo(ip->ip_src.s_addr,
5106                             ip->ip_dst.s_addr,
5107                             htons(IPPROTO_TCP)));
5108 #else
5109         /* XXX IPv6 */
5110         pbd->tcp_pseudo_csum =
5111             ntohs(in_pseudo(&ip6->ip6_src,
5112                             &ip6->ip6_dst,
5113                             htons(IPPROTO_TCP)));
5114 #endif
5115
5116     pbd->global_data |=
5117         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5118 }
5119
5120 /*
5121  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5122  * visible to the controller.
5123  *
5124  * If an mbuf is submitted to this routine and cannot be given to the
5125  * controller (e.g. it has too many fragments) then the function may free
5126  * the mbuf and return to the caller.
5127  *
5128  * Returns:
5129  *   0 = Success, !0 = Failure
5130  *   Note the side effect that an mbuf may be freed if it causes a problem.
5131  */
5132 static int
5133 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5134 {
5135     bus_dma_segment_t segs[32];
5136     struct mbuf *m0;
5137     struct bxe_sw_tx_bd *tx_buf;
5138     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5139     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5140     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5141     struct eth_tx_bd *tx_data_bd;
5142     struct eth_tx_bd *tx_total_pkt_size_bd;
5143     struct eth_tx_start_bd *tx_start_bd;
5144     uint16_t bd_prod, pkt_prod, total_pkt_size;
5145     uint8_t mac_type;
5146     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5147     struct bxe_softc *sc;
5148     uint16_t tx_bd_avail;
5149     struct ether_vlan_header *eh;
5150     uint32_t pbd_e2_parsing_data = 0;
5151     uint8_t hlen = 0;
5152     int tmp_bd;
5153     int i;
5154
5155     sc = fp->sc;
5156
5157 #if __FreeBSD_version >= 800000
5158     M_ASSERTPKTHDR(*m_head);
5159 #endif /* #if __FreeBSD_version >= 800000 */
5160
5161     m0 = *m_head;
5162     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5163     tx_start_bd = NULL;
5164     tx_data_bd = NULL;
5165     tx_total_pkt_size_bd = NULL;
5166
5167     /* get the H/W pointer for packets and BDs */
5168     pkt_prod = fp->tx_pkt_prod;
5169     bd_prod = fp->tx_bd_prod;
5170
5171     mac_type = UNICAST_ADDRESS;
5172
5173     /* map the mbuf into the next open DMAable memory */
5174     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5175     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5176                                     tx_buf->m_map, m0,
5177                                     segs, &nsegs, BUS_DMA_NOWAIT);
5178
5179     /* mapping errors */
5180     if(__predict_false(error != 0)) {
5181         fp->eth_q_stats.tx_dma_mapping_failure++;
5182         if (error == ENOMEM) {
5183             /* resource issue, try again later */
5184             rc = ENOMEM;
5185         } else if (error == EFBIG) {
5186             /* possibly recoverable with defragmentation */
5187             fp->eth_q_stats.mbuf_defrag_attempts++;
5188             m0 = m_defrag(*m_head, M_DONTWAIT);
5189             if (m0 == NULL) {
5190                 fp->eth_q_stats.mbuf_defrag_failures++;
5191                 rc = ENOBUFS;
5192             } else {
5193                 /* defrag successful, try mapping again */
5194                 *m_head = m0;
5195                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5196                                                 tx_buf->m_map, m0,
5197                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5198                 if (error) {
5199                     fp->eth_q_stats.tx_dma_mapping_failure++;
5200                     rc = error;
5201                 }
5202             }
5203         } else {
5204             /* unknown, unrecoverable mapping error */
5205             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5206             bxe_dump_mbuf(sc, m0, FALSE);
5207             rc = error;
5208         }
5209
5210         goto bxe_tx_encap_continue;
5211     }
5212
5213     tx_bd_avail = bxe_tx_avail(sc, fp);
5214
5215     /* make sure there is enough room in the send queue */
5216     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5217         /* Recoverable, try again later. */
5218         fp->eth_q_stats.tx_hw_queue_full++;
5219         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5220         rc = ENOMEM;
5221         goto bxe_tx_encap_continue;
5222     }
5223
5224     /* capture the current H/W TX chain high watermark */
5225     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5226                         (TX_BD_USABLE - tx_bd_avail))) {
5227         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5228     }
5229
5230     /* make sure it fits in the packet window */
5231     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5232         /*
5233          * The mbuf may be to big for the controller to handle. If the frame
5234          * is a TSO frame we'll need to do an additional check.
5235          */
5236         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5237             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5238                 goto bxe_tx_encap_continue; /* OK to send */
5239             } else {
5240                 fp->eth_q_stats.tx_window_violation_tso++;
5241             }
5242         } else {
5243             fp->eth_q_stats.tx_window_violation_std++;
5244         }
5245
5246         /* lets try to defragment this mbuf and remap it */
5247         fp->eth_q_stats.mbuf_defrag_attempts++;
5248         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5249
5250         m0 = m_defrag(*m_head, M_DONTWAIT);
5251         if (m0 == NULL) {
5252             fp->eth_q_stats.mbuf_defrag_failures++;
5253             /* Ugh, just drop the frame... :( */
5254             rc = ENOBUFS;
5255         } else {
5256             /* defrag successful, try mapping again */
5257             *m_head = m0;
5258             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5259                                             tx_buf->m_map, m0,
5260                                             segs, &nsegs, BUS_DMA_NOWAIT);
5261             if (error) {
5262                 fp->eth_q_stats.tx_dma_mapping_failure++;
5263                 /* No sense in trying to defrag/copy chain, drop it. :( */
5264                 rc = error;
5265             } else {
5266                /* if the chain is still too long then drop it */
5267                 if(m0->m_pkthdr.csum_flags & CSUM_TSO) {
5268                     /*
5269                      * in case TSO is enabled nsegs should be checked against
5270                      * BXE_TSO_MAX_SEGMENTS
5271                      */
5272                     if (__predict_false(nsegs > BXE_TSO_MAX_SEGMENTS)) {
5273                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5274                         fp->eth_q_stats.nsegs_path1_errors++;
5275                         rc = ENODEV;
5276                     }
5277                 } else {
5278                     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5279                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5280                         fp->eth_q_stats.nsegs_path2_errors++;
5281                         rc = ENODEV;
5282                     }
5283                 }
5284             }
5285         }
5286     }
5287
5288 bxe_tx_encap_continue:
5289
5290     /* Check for errors */
5291     if (rc) {
5292         if (rc == ENOMEM) {
5293             /* recoverable try again later  */
5294         } else {
5295             fp->eth_q_stats.tx_soft_errors++;
5296             fp->eth_q_stats.mbuf_alloc_tx--;
5297             m_freem(*m_head);
5298             *m_head = NULL;
5299         }
5300
5301         return (rc);
5302     }
5303
5304     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5305     if (m0->m_flags & M_BCAST) {
5306         mac_type = BROADCAST_ADDRESS;
5307     } else if (m0->m_flags & M_MCAST) {
5308         mac_type = MULTICAST_ADDRESS;
5309     }
5310
5311     /* store the mbuf into the mbuf ring */
5312     tx_buf->m        = m0;
5313     tx_buf->first_bd = fp->tx_bd_prod;
5314     tx_buf->flags    = 0;
5315
5316     /* prepare the first transmit (start) BD for the mbuf */
5317     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5318
5319     BLOGD(sc, DBG_TX,
5320           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5321           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5322
5323     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5324     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5325     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5326     total_pkt_size += tx_start_bd->nbytes;
5327     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5328
5329     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5330
5331     /* all frames have at least Start BD + Parsing BD */
5332     nbds = nsegs + 1;
5333     tx_start_bd->nbd = htole16(nbds);
5334
5335     if (m0->m_flags & M_VLANTAG) {
5336         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5337         tx_start_bd->bd_flags.as_bitfield |=
5338             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5339     } else {
5340         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5341         if (IS_VF(sc)) {
5342             /* map ethernet header to find type and header length */
5343             eh = mtod(m0, struct ether_vlan_header *);
5344             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5345         } else {
5346             /* used by FW for packet accounting */
5347             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5348         }
5349     }
5350
5351     /*
5352      * add a parsing BD from the chain. The parsing BD is always added
5353      * though it is only used for TSO and chksum
5354      */
5355     bd_prod = TX_BD_NEXT(bd_prod);
5356
5357     if (m0->m_pkthdr.csum_flags) {
5358         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5359             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5360             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5361         }
5362
5363         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5364             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5365                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5366         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5367             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5368                                                   ETH_TX_BD_FLAGS_IS_UDP |
5369                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5370         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5371                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5372             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5373         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5374             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5375                                                   ETH_TX_BD_FLAGS_IS_UDP);
5376         }
5377     }
5378
5379     if (!CHIP_IS_E1x(sc)) {
5380         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5381         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5382
5383         if (m0->m_pkthdr.csum_flags) {
5384             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5385         }
5386
5387         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5388                  mac_type);
5389     } else {
5390         uint16_t global_data = 0;
5391
5392         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5393         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5394
5395         if (m0->m_pkthdr.csum_flags) {
5396             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5397         }
5398
5399         SET_FLAG(global_data,
5400                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5401         pbd_e1x->global_data |= htole16(global_data);
5402     }
5403
5404     /* setup the parsing BD with TSO specific info */
5405     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5406         fp->eth_q_stats.tx_ofld_frames_lso++;
5407         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5408
5409         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5410             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5411
5412             /* split the first BD into header/data making the fw job easy */
5413             nbds++;
5414             tx_start_bd->nbd = htole16(nbds);
5415             tx_start_bd->nbytes = htole16(hlen);
5416
5417             bd_prod = TX_BD_NEXT(bd_prod);
5418
5419             /* new transmit BD after the tx_parse_bd */
5420             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5421             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5422             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5423             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5424             if (tx_total_pkt_size_bd == NULL) {
5425                 tx_total_pkt_size_bd = tx_data_bd;
5426             }
5427
5428             BLOGD(sc, DBG_TX,
5429                   "TSO split header size is %d (%x:%x) nbds %d\n",
5430                   le16toh(tx_start_bd->nbytes),
5431                   le32toh(tx_start_bd->addr_hi),
5432                   le32toh(tx_start_bd->addr_lo),
5433                   nbds);
5434         }
5435
5436         if (!CHIP_IS_E1x(sc)) {
5437             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5438         } else {
5439             bxe_set_pbd_lso(m0, pbd_e1x);
5440         }
5441     }
5442
5443     if (pbd_e2_parsing_data) {
5444         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5445     }
5446
5447     /* prepare remaining BDs, start tx bd contains first seg/frag */
5448     for (i = 1; i < nsegs ; i++) {
5449         bd_prod = TX_BD_NEXT(bd_prod);
5450         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5451         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5452         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5453         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5454         if (tx_total_pkt_size_bd == NULL) {
5455             tx_total_pkt_size_bd = tx_data_bd;
5456         }
5457         total_pkt_size += tx_data_bd->nbytes;
5458     }
5459
5460     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5461
5462     if (tx_total_pkt_size_bd != NULL) {
5463         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5464     }
5465
5466     if (__predict_false(sc->debug & DBG_TX)) {
5467         tmp_bd = tx_buf->first_bd;
5468         for (i = 0; i < nbds; i++)
5469         {
5470             if (i == 0) {
5471                 BLOGD(sc, DBG_TX,
5472                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5473                       "bd_flags=0x%x hdr_nbds=%d\n",
5474                       tx_start_bd,
5475                       tmp_bd,
5476                       le16toh(tx_start_bd->nbd),
5477                       le16toh(tx_start_bd->vlan_or_ethertype),
5478                       tx_start_bd->bd_flags.as_bitfield,
5479                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5480             } else if (i == 1) {
5481                 if (pbd_e1x) {
5482                     BLOGD(sc, DBG_TX,
5483                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5484                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5485                           "tcp_seq=%u total_hlen_w=%u\n",
5486                           pbd_e1x,
5487                           tmp_bd,
5488                           pbd_e1x->global_data,
5489                           pbd_e1x->ip_hlen_w,
5490                           pbd_e1x->ip_id,
5491                           pbd_e1x->lso_mss,
5492                           pbd_e1x->tcp_flags,
5493                           pbd_e1x->tcp_pseudo_csum,
5494                           pbd_e1x->tcp_send_seq,
5495                           le16toh(pbd_e1x->total_hlen_w));
5496                 } else { /* if (pbd_e2) */
5497                     BLOGD(sc, DBG_TX,
5498                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5499                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5500                           pbd_e2,
5501                           tmp_bd,
5502                           pbd_e2->data.mac_addr.dst_hi,
5503                           pbd_e2->data.mac_addr.dst_mid,
5504                           pbd_e2->data.mac_addr.dst_lo,
5505                           pbd_e2->data.mac_addr.src_hi,
5506                           pbd_e2->data.mac_addr.src_mid,
5507                           pbd_e2->data.mac_addr.src_lo,
5508                           pbd_e2->parsing_data);
5509                 }
5510             }
5511
5512             if (i != 1) { /* skip parse db as it doesn't hold data */
5513                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5514                 BLOGD(sc, DBG_TX,
5515                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5516                       tx_data_bd,
5517                       tmp_bd,
5518                       le16toh(tx_data_bd->nbytes),
5519                       le32toh(tx_data_bd->addr_hi),
5520                       le32toh(tx_data_bd->addr_lo));
5521             }
5522
5523             tmp_bd = TX_BD_NEXT(tmp_bd);
5524         }
5525     }
5526
5527     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5528
5529     /* update TX BD producer index value for next TX */
5530     bd_prod = TX_BD_NEXT(bd_prod);
5531
5532     /*
5533      * If the chain of tx_bd's describing this frame is adjacent to or spans
5534      * an eth_tx_next_bd element then we need to increment the nbds value.
5535      */
5536     if (TX_BD_IDX(bd_prod) < nbds) {
5537         nbds++;
5538     }
5539
5540     /* don't allow reordering of writes for nbd and packets */
5541     mb();
5542
5543     fp->tx_db.data.prod += nbds;
5544
5545     /* producer points to the next free tx_bd at this point */
5546     fp->tx_pkt_prod++;
5547     fp->tx_bd_prod = bd_prod;
5548
5549     DOORBELL(sc, fp->index, fp->tx_db.raw);
5550
5551     fp->eth_q_stats.tx_pkts++;
5552
5553     /* Prevent speculative reads from getting ahead of the status block. */
5554     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5555                       0, 0, BUS_SPACE_BARRIER_READ);
5556
5557     /* Prevent speculative reads from getting ahead of the doorbell. */
5558     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5559                       0, 0, BUS_SPACE_BARRIER_READ);
5560
5561     return (0);
5562 }
5563
5564 static void
5565 bxe_tx_start_locked(struct bxe_softc    *sc,
5566                     struct ifnet        *ifp,
5567                     struct bxe_fastpath *fp)
5568 {
5569     struct mbuf *m = NULL;
5570     int tx_count = 0;
5571     uint16_t tx_bd_avail;
5572
5573     BXE_FP_TX_LOCK_ASSERT(fp);
5574
5575     /* keep adding entries while there are frames to send */
5576     while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
5577
5578         /*
5579          * check for any frames to send
5580          * dequeue can still be NULL even if queue is not empty
5581          */
5582         IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
5583         if (__predict_false(m == NULL)) {
5584             break;
5585         }
5586
5587         /* the mbuf now belongs to us */
5588         fp->eth_q_stats.mbuf_alloc_tx++;
5589
5590         /*
5591          * Put the frame into the transmit ring. If we don't have room,
5592          * place the mbuf back at the head of the TX queue, set the
5593          * OACTIVE flag, and wait for the NIC to drain the chain.
5594          */
5595         if (__predict_false(bxe_tx_encap(fp, &m))) {
5596             fp->eth_q_stats.tx_encap_failures++;
5597             if (m != NULL) {
5598                 /* mark the TX queue as full and return the frame */
5599                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5600                 IFQ_DRV_PREPEND(&ifp->if_snd, m);
5601                 fp->eth_q_stats.mbuf_alloc_tx--;
5602                 fp->eth_q_stats.tx_queue_xoff++;
5603             }
5604
5605             /* stop looking for more work */
5606             break;
5607         }
5608
5609         /* the frame was enqueued successfully */
5610         tx_count++;
5611
5612         /* send a copy of the frame to any BPF listeners. */
5613         BPF_MTAP(ifp, m);
5614
5615         tx_bd_avail = bxe_tx_avail(sc, fp);
5616
5617         /* handle any completions if we're running low */
5618         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5619             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5620             bxe_txeof(sc, fp);
5621             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5622                 break;
5623             }
5624         }
5625     }
5626
5627     /* all TX packets were dequeued and/or the tx ring is full */
5628     if (tx_count > 0) {
5629         /* reset the TX watchdog timeout timer */
5630         fp->watchdog_timer = BXE_TX_TIMEOUT;
5631     }
5632 }
5633
5634 /* Legacy (non-RSS) dispatch routine */
5635 static void
5636 bxe_tx_start(struct ifnet *ifp)
5637 {
5638     struct bxe_softc *sc;
5639     struct bxe_fastpath *fp;
5640
5641     sc = ifp->if_softc;
5642
5643     if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5644         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5645         return;
5646     }
5647
5648     if (!sc->link_vars.link_up) {
5649         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5650         return;
5651     }
5652
5653     fp = &sc->fp[0];
5654
5655     if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5656         fp->eth_q_stats.tx_queue_full_return++;
5657         return;
5658     }
5659
5660     BXE_FP_TX_LOCK(fp);
5661     bxe_tx_start_locked(sc, ifp, fp);
5662     BXE_FP_TX_UNLOCK(fp);
5663 }
5664
5665 #if __FreeBSD_version >= 800000
5666
5667 static int
5668 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5669                        struct ifnet        *ifp,
5670                        struct bxe_fastpath *fp,
5671                        struct mbuf         *m)
5672 {
5673     struct buf_ring *tx_br = fp->tx_br;
5674     struct mbuf *next;
5675     int depth, rc, tx_count;
5676     uint16_t tx_bd_avail;
5677
5678     rc = tx_count = 0;
5679
5680     BXE_FP_TX_LOCK_ASSERT(fp);
5681
5682     if (sc->state != BXE_STATE_OPEN)  {
5683         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5684         return ENETDOWN;
5685     }
5686
5687     if (!tx_br) {
5688         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5689         return (EINVAL);
5690     }
5691
5692     if (!sc->link_vars.link_up ||
5693         (ifp->if_drv_flags &
5694         (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) != IFF_DRV_RUNNING) {
5695         rc = drbr_enqueue(ifp, tx_br, m);
5696         goto bxe_tx_mq_start_locked_exit;
5697     }
5698
5699     /* fetch the depth of the driver queue */
5700     depth = drbr_inuse(ifp, tx_br);
5701     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5702         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5703     }
5704
5705     if (m == NULL) {
5706         /* no new work, check for pending frames */
5707         next = drbr_dequeue(ifp, tx_br);
5708     } else if (drbr_needs_enqueue(ifp, tx_br)) {
5709         /* have both new and pending work, maintain packet order */
5710         rc = drbr_enqueue(ifp, tx_br, m);
5711         if (rc != 0) {
5712             fp->eth_q_stats.tx_soft_errors++;
5713             goto bxe_tx_mq_start_locked_exit;
5714         }
5715         next = drbr_dequeue(ifp, tx_br);
5716     } else {
5717         /* new work only and nothing pending */
5718         next = m;
5719     }
5720
5721     /* keep adding entries while there are frames to send */
5722     while (next != NULL) {
5723
5724         /* the mbuf now belongs to us */
5725         fp->eth_q_stats.mbuf_alloc_tx++;
5726
5727         /*
5728          * Put the frame into the transmit ring. If we don't have room,
5729          * place the mbuf back at the head of the TX queue, set the
5730          * OACTIVE flag, and wait for the NIC to drain the chain.
5731          */
5732         rc = bxe_tx_encap(fp, &next);
5733         if (__predict_false(rc != 0)) {
5734             fp->eth_q_stats.tx_encap_failures++;
5735             if (next != NULL) {
5736                 /* mark the TX queue as full and save the frame */
5737                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5738                 /* XXX this may reorder the frame */
5739                 rc = drbr_enqueue(ifp, tx_br, next);
5740                 fp->eth_q_stats.mbuf_alloc_tx--;
5741                 fp->eth_q_stats.tx_frames_deferred++;
5742             }
5743
5744             /* stop looking for more work */
5745             break;
5746         }
5747
5748         /* the transmit frame was enqueued successfully */
5749         tx_count++;
5750
5751         /* send a copy of the frame to any BPF listeners */
5752         BPF_MTAP(ifp, next);
5753
5754         tx_bd_avail = bxe_tx_avail(sc, fp);
5755
5756         /* handle any completions if we're running low */
5757         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5758             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5759             bxe_txeof(sc, fp);
5760             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5761                 break;
5762             }
5763         }
5764
5765         next = drbr_dequeue(ifp, tx_br);
5766     }
5767
5768     /* all TX packets were dequeued and/or the tx ring is full */
5769     if (tx_count > 0) {
5770         /* reset the TX watchdog timeout timer */
5771         fp->watchdog_timer = BXE_TX_TIMEOUT;
5772     }
5773
5774 bxe_tx_mq_start_locked_exit:
5775
5776     return (rc);
5777 }
5778
5779 /* Multiqueue (TSS) dispatch routine. */
5780 static int
5781 bxe_tx_mq_start(struct ifnet *ifp,
5782                 struct mbuf  *m)
5783 {
5784     struct bxe_softc *sc = ifp->if_softc;
5785     struct bxe_fastpath *fp;
5786     int fp_index, rc;
5787
5788     fp_index = 0; /* default is the first queue */
5789
5790     /* check if flowid is set */
5791
5792     if (BXE_VALID_FLOWID(m))
5793         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5794
5795     fp = &sc->fp[fp_index];
5796
5797     if (sc->state != BXE_STATE_OPEN)  {
5798         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5799         return ENETDOWN;
5800     }
5801
5802     if (BXE_FP_TX_TRYLOCK(fp)) {
5803         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5804         BXE_FP_TX_UNLOCK(fp);
5805     } else
5806         rc = drbr_enqueue(ifp, fp->tx_br, m);
5807
5808     return (rc);
5809 }
5810
5811 static void
5812 bxe_mq_flush(struct ifnet *ifp)
5813 {
5814     struct bxe_softc *sc = ifp->if_softc;
5815     struct bxe_fastpath *fp;
5816     struct mbuf *m;
5817     int i;
5818
5819     for (i = 0; i < sc->num_queues; i++) {
5820         fp = &sc->fp[i];
5821
5822         if (fp->state != BXE_FP_STATE_IRQ) {
5823             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5824                   fp->index, fp->state);
5825             continue;
5826         }
5827
5828         if (fp->tx_br != NULL) {
5829             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5830             BXE_FP_TX_LOCK(fp);
5831             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5832                 m_freem(m);
5833             }
5834             BXE_FP_TX_UNLOCK(fp);
5835         }
5836     }
5837
5838     if_qflush(ifp);
5839 }
5840
5841 #endif /* FreeBSD_version >= 800000 */
5842
5843 static uint16_t
5844 bxe_cid_ilt_lines(struct bxe_softc *sc)
5845 {
5846     if (IS_SRIOV(sc)) {
5847         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5848     }
5849     return (L2_ILT_LINES(sc));
5850 }
5851
5852 static void
5853 bxe_ilt_set_info(struct bxe_softc *sc)
5854 {
5855     struct ilt_client_info *ilt_client;
5856     struct ecore_ilt *ilt = sc->ilt;
5857     uint16_t line = 0;
5858
5859     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5860     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5861
5862     /* CDU */
5863     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5864     ilt_client->client_num = ILT_CLIENT_CDU;
5865     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5866     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5867     ilt_client->start = line;
5868     line += bxe_cid_ilt_lines(sc);
5869
5870     if (CNIC_SUPPORT(sc)) {
5871         line += CNIC_ILT_LINES;
5872     }
5873
5874     ilt_client->end = (line - 1);
5875
5876     BLOGD(sc, DBG_LOAD,
5877           "ilt client[CDU]: start %d, end %d, "
5878           "psz 0x%x, flags 0x%x, hw psz %d\n",
5879           ilt_client->start, ilt_client->end,
5880           ilt_client->page_size,
5881           ilt_client->flags,
5882           ilog2(ilt_client->page_size >> 12));
5883
5884     /* QM */
5885     if (QM_INIT(sc->qm_cid_count)) {
5886         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5887         ilt_client->client_num = ILT_CLIENT_QM;
5888         ilt_client->page_size = QM_ILT_PAGE_SZ;
5889         ilt_client->flags = 0;
5890         ilt_client->start = line;
5891
5892         /* 4 bytes for each cid */
5893         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5894                              QM_ILT_PAGE_SZ);
5895
5896         ilt_client->end = (line - 1);
5897
5898         BLOGD(sc, DBG_LOAD,
5899               "ilt client[QM]: start %d, end %d, "
5900               "psz 0x%x, flags 0x%x, hw psz %d\n",
5901               ilt_client->start, ilt_client->end,
5902               ilt_client->page_size, ilt_client->flags,
5903               ilog2(ilt_client->page_size >> 12));
5904     }
5905
5906     if (CNIC_SUPPORT(sc)) {
5907         /* SRC */
5908         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5909         ilt_client->client_num = ILT_CLIENT_SRC;
5910         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5911         ilt_client->flags = 0;
5912         ilt_client->start = line;
5913         line += SRC_ILT_LINES;
5914         ilt_client->end = (line - 1);
5915
5916         BLOGD(sc, DBG_LOAD,
5917               "ilt client[SRC]: start %d, end %d, "
5918               "psz 0x%x, flags 0x%x, hw psz %d\n",
5919               ilt_client->start, ilt_client->end,
5920               ilt_client->page_size, ilt_client->flags,
5921               ilog2(ilt_client->page_size >> 12));
5922
5923         /* TM */
5924         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5925         ilt_client->client_num = ILT_CLIENT_TM;
5926         ilt_client->page_size = TM_ILT_PAGE_SZ;
5927         ilt_client->flags = 0;
5928         ilt_client->start = line;
5929         line += TM_ILT_LINES;
5930         ilt_client->end = (line - 1);
5931
5932         BLOGD(sc, DBG_LOAD,
5933               "ilt client[TM]: start %d, end %d, "
5934               "psz 0x%x, flags 0x%x, hw psz %d\n",
5935               ilt_client->start, ilt_client->end,
5936               ilt_client->page_size, ilt_client->flags,
5937               ilog2(ilt_client->page_size >> 12));
5938     }
5939
5940     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5941 }
5942
5943 static void
5944 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5945 {
5946     int i;
5947     uint32_t rx_buf_size;
5948
5949     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5950
5951     for (i = 0; i < sc->num_queues; i++) {
5952         if(rx_buf_size <= MCLBYTES){
5953             sc->fp[i].rx_buf_size = rx_buf_size;
5954             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5955         }else if (rx_buf_size <= MJUMPAGESIZE){
5956             sc->fp[i].rx_buf_size = rx_buf_size;
5957             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5958         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5959             sc->fp[i].rx_buf_size = MCLBYTES;
5960             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5961         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5962             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5963             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5964         }else {
5965             sc->fp[i].rx_buf_size = MCLBYTES;
5966             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5967         }
5968     }
5969 }
5970
5971 static int
5972 bxe_alloc_ilt_mem(struct bxe_softc *sc)
5973 {
5974     int rc = 0;
5975
5976     if ((sc->ilt =
5977          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
5978                                     M_BXE_ILT,
5979                                     (M_NOWAIT | M_ZERO))) == NULL) {
5980         rc = 1;
5981     }
5982
5983     return (rc);
5984 }
5985
5986 static int
5987 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
5988 {
5989     int rc = 0;
5990
5991     if ((sc->ilt->lines =
5992          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
5993                                     M_BXE_ILT,
5994                                     (M_NOWAIT | M_ZERO))) == NULL) {
5995         rc = 1;
5996     }
5997
5998     return (rc);
5999 }
6000
6001 static void
6002 bxe_free_ilt_mem(struct bxe_softc *sc)
6003 {
6004     if (sc->ilt != NULL) {
6005         free(sc->ilt, M_BXE_ILT);
6006         sc->ilt = NULL;
6007     }
6008 }
6009
6010 static void
6011 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6012 {
6013     if (sc->ilt->lines != NULL) {
6014         free(sc->ilt->lines, M_BXE_ILT);
6015         sc->ilt->lines = NULL;
6016     }
6017 }
6018
6019 static void
6020 bxe_free_mem(struct bxe_softc *sc)
6021 {
6022     int i;
6023
6024     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6025         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6026         sc->context[i].vcxt = NULL;
6027         sc->context[i].size = 0;
6028     }
6029
6030     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6031
6032     bxe_free_ilt_lines_mem(sc);
6033
6034 }
6035
6036 static int
6037 bxe_alloc_mem(struct bxe_softc *sc)
6038 {
6039
6040     int context_size;
6041     int allocated;
6042     int i;
6043
6044     /*
6045      * Allocate memory for CDU context:
6046      * This memory is allocated separately and not in the generic ILT
6047      * functions because CDU differs in few aspects:
6048      * 1. There can be multiple entities allocating memory for context -
6049      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6050      * its own ILT lines.
6051      * 2. Since CDU page-size is not a single 4KB page (which is the case
6052      * for the other ILT clients), to be efficient we want to support
6053      * allocation of sub-page-size in the last entry.
6054      * 3. Context pointers are used by the driver to pass to FW / update
6055      * the context (for the other ILT clients the pointers are used just to
6056      * free the memory during unload).
6057      */
6058     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6059     for (i = 0, allocated = 0; allocated < context_size; i++) {
6060         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6061                                   (context_size - allocated));
6062
6063         if (bxe_dma_alloc(sc, sc->context[i].size,
6064                           &sc->context[i].vcxt_dma,
6065                           "cdu context") != 0) {
6066             bxe_free_mem(sc);
6067             return (-1);
6068         }
6069
6070         sc->context[i].vcxt =
6071             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6072
6073         allocated += sc->context[i].size;
6074     }
6075
6076     bxe_alloc_ilt_lines_mem(sc);
6077
6078     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6079           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6080     {
6081         for (i = 0; i < 4; i++) {
6082             BLOGD(sc, DBG_LOAD,
6083                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6084                   i,
6085                   sc->ilt->clients[i].page_size,
6086                   sc->ilt->clients[i].start,
6087                   sc->ilt->clients[i].end,
6088                   sc->ilt->clients[i].client_num,
6089                   sc->ilt->clients[i].flags);
6090         }
6091     }
6092     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6093         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6094         bxe_free_mem(sc);
6095         return (-1);
6096     }
6097
6098     return (0);
6099 }
6100
6101 static void
6102 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6103 {
6104     struct bxe_softc *sc;
6105     int i;
6106
6107     sc = fp->sc;
6108
6109     if (fp->rx_mbuf_tag == NULL) {
6110         return;
6111     }
6112
6113     /* free all mbufs and unload all maps */
6114     for (i = 0; i < RX_BD_TOTAL; i++) {
6115         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6116             bus_dmamap_sync(fp->rx_mbuf_tag,
6117                             fp->rx_mbuf_chain[i].m_map,
6118                             BUS_DMASYNC_POSTREAD);
6119             bus_dmamap_unload(fp->rx_mbuf_tag,
6120                               fp->rx_mbuf_chain[i].m_map);
6121         }
6122
6123         if (fp->rx_mbuf_chain[i].m != NULL) {
6124             m_freem(fp->rx_mbuf_chain[i].m);
6125             fp->rx_mbuf_chain[i].m = NULL;
6126             fp->eth_q_stats.mbuf_alloc_rx--;
6127         }
6128     }
6129 }
6130
6131 static void
6132 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6133 {
6134     struct bxe_softc *sc;
6135     int i, max_agg_queues;
6136
6137     sc = fp->sc;
6138
6139     if (fp->rx_mbuf_tag == NULL) {
6140         return;
6141     }
6142
6143     max_agg_queues = MAX_AGG_QS(sc);
6144
6145     /* release all mbufs and unload all DMA maps in the TPA pool */
6146     for (i = 0; i < max_agg_queues; i++) {
6147         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6148             bus_dmamap_sync(fp->rx_mbuf_tag,
6149                             fp->rx_tpa_info[i].bd.m_map,
6150                             BUS_DMASYNC_POSTREAD);
6151             bus_dmamap_unload(fp->rx_mbuf_tag,
6152                               fp->rx_tpa_info[i].bd.m_map);
6153         }
6154
6155         if (fp->rx_tpa_info[i].bd.m != NULL) {
6156             m_freem(fp->rx_tpa_info[i].bd.m);
6157             fp->rx_tpa_info[i].bd.m = NULL;
6158             fp->eth_q_stats.mbuf_alloc_tpa--;
6159         }
6160     }
6161 }
6162
6163 static void
6164 bxe_free_sge_chain(struct bxe_fastpath *fp)
6165 {
6166     struct bxe_softc *sc;
6167     int i;
6168
6169     sc = fp->sc;
6170
6171     if (fp->rx_sge_mbuf_tag == NULL) {
6172         return;
6173     }
6174
6175     /* rree all mbufs and unload all maps */
6176     for (i = 0; i < RX_SGE_TOTAL; i++) {
6177         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6178             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6179                             fp->rx_sge_mbuf_chain[i].m_map,
6180                             BUS_DMASYNC_POSTREAD);
6181             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6182                               fp->rx_sge_mbuf_chain[i].m_map);
6183         }
6184
6185         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6186             m_freem(fp->rx_sge_mbuf_chain[i].m);
6187             fp->rx_sge_mbuf_chain[i].m = NULL;
6188             fp->eth_q_stats.mbuf_alloc_sge--;
6189         }
6190     }
6191 }
6192
6193 static void
6194 bxe_free_fp_buffers(struct bxe_softc *sc)
6195 {
6196     struct bxe_fastpath *fp;
6197     int i;
6198
6199     for (i = 0; i < sc->num_queues; i++) {
6200         fp = &sc->fp[i];
6201
6202 #if __FreeBSD_version >= 800000
6203         if (fp->tx_br != NULL) {
6204             /* just in case bxe_mq_flush() wasn't called */
6205             if (mtx_initialized(&fp->tx_mtx)) {
6206                 struct mbuf *m;
6207
6208                 BXE_FP_TX_LOCK(fp);
6209                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6210                     m_freem(m);
6211                 BXE_FP_TX_UNLOCK(fp);
6212             }
6213         }
6214 #endif
6215
6216         /* free all RX buffers */
6217         bxe_free_rx_bd_chain(fp);
6218         bxe_free_tpa_pool(fp);
6219         bxe_free_sge_chain(fp);
6220
6221         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6222             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6223                   fp->eth_q_stats.mbuf_alloc_rx);
6224         }
6225
6226         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6227             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6228                   fp->eth_q_stats.mbuf_alloc_sge);
6229         }
6230
6231         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6232             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6233                   fp->eth_q_stats.mbuf_alloc_tpa);
6234         }
6235
6236         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6237             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6238                   fp->eth_q_stats.mbuf_alloc_tx);
6239         }
6240
6241         /* XXX verify all mbufs were reclaimed */
6242     }
6243 }
6244
6245 static int
6246 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6247                      uint16_t            prev_index,
6248                      uint16_t            index)
6249 {
6250     struct bxe_sw_rx_bd *rx_buf;
6251     struct eth_rx_bd *rx_bd;
6252     bus_dma_segment_t segs[1];
6253     bus_dmamap_t map;
6254     struct mbuf *m;
6255     int nsegs, rc;
6256
6257     rc = 0;
6258
6259     /* allocate the new RX BD mbuf */
6260     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6261     if (__predict_false(m == NULL)) {
6262         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6263         return (ENOBUFS);
6264     }
6265
6266     fp->eth_q_stats.mbuf_alloc_rx++;
6267
6268     /* initialize the mbuf buffer length */
6269     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6270
6271     /* map the mbuf into non-paged pool */
6272     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6273                                  fp->rx_mbuf_spare_map,
6274                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6275     if (__predict_false(rc != 0)) {
6276         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6277         m_freem(m);
6278         fp->eth_q_stats.mbuf_alloc_rx--;
6279         return (rc);
6280     }
6281
6282     /* all mbufs must map to a single segment */
6283     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6284
6285     /* release any existing RX BD mbuf mappings */
6286
6287     if (prev_index != index) {
6288         rx_buf = &fp->rx_mbuf_chain[prev_index];
6289
6290         if (rx_buf->m_map != NULL) {
6291             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6292                             BUS_DMASYNC_POSTREAD);
6293             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6294         }
6295
6296         /*
6297          * We only get here from bxe_rxeof() when the maximum number
6298          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6299          * holds the mbuf in the prev_index so it's OK to NULL it out
6300          * here without concern of a memory leak.
6301          */
6302         fp->rx_mbuf_chain[prev_index].m = NULL;
6303     }
6304
6305     rx_buf = &fp->rx_mbuf_chain[index];
6306
6307     if (rx_buf->m_map != NULL) {
6308         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6309                         BUS_DMASYNC_POSTREAD);
6310         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6311     }
6312
6313     /* save the mbuf and mapping info for a future packet */
6314     map = (prev_index != index) ?
6315               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6316     rx_buf->m_map = fp->rx_mbuf_spare_map;
6317     fp->rx_mbuf_spare_map = map;
6318     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6319                     BUS_DMASYNC_PREREAD);
6320     rx_buf->m = m;
6321
6322     rx_bd = &fp->rx_chain[index];
6323     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6324     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6325
6326     return (rc);
6327 }
6328
6329 static int
6330 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6331                       int                 queue)
6332 {
6333     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6334     bus_dma_segment_t segs[1];
6335     bus_dmamap_t map;
6336     struct mbuf *m;
6337     int nsegs;
6338     int rc = 0;
6339
6340     /* allocate the new TPA mbuf */
6341     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6342     if (__predict_false(m == NULL)) {
6343         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6344         return (ENOBUFS);
6345     }
6346
6347     fp->eth_q_stats.mbuf_alloc_tpa++;
6348
6349     /* initialize the mbuf buffer length */
6350     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6351
6352     /* map the mbuf into non-paged pool */
6353     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6354                                  fp->rx_tpa_info_mbuf_spare_map,
6355                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6356     if (__predict_false(rc != 0)) {
6357         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6358         m_free(m);
6359         fp->eth_q_stats.mbuf_alloc_tpa--;
6360         return (rc);
6361     }
6362
6363     /* all mbufs must map to a single segment */
6364     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6365
6366     /* release any existing TPA mbuf mapping */
6367     if (tpa_info->bd.m_map != NULL) {
6368         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6369                         BUS_DMASYNC_POSTREAD);
6370         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6371     }
6372
6373     /* save the mbuf and mapping info for the TPA mbuf */
6374     map = tpa_info->bd.m_map;
6375     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6376     fp->rx_tpa_info_mbuf_spare_map = map;
6377     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6378                     BUS_DMASYNC_PREREAD);
6379     tpa_info->bd.m = m;
6380     tpa_info->seg = segs[0];
6381
6382     return (rc);
6383 }
6384
6385 /*
6386  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6387  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6388  * chain.
6389  */
6390 static int
6391 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6392                       uint16_t            index)
6393 {
6394     struct bxe_sw_rx_bd *sge_buf;
6395     struct eth_rx_sge *sge;
6396     bus_dma_segment_t segs[1];
6397     bus_dmamap_t map;
6398     struct mbuf *m;
6399     int nsegs;
6400     int rc = 0;
6401
6402     /* allocate a new SGE mbuf */
6403     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6404     if (__predict_false(m == NULL)) {
6405         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6406         return (ENOMEM);
6407     }
6408
6409     fp->eth_q_stats.mbuf_alloc_sge++;
6410
6411     /* initialize the mbuf buffer length */
6412     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6413
6414     /* map the SGE mbuf into non-paged pool */
6415     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6416                                  fp->rx_sge_mbuf_spare_map,
6417                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6418     if (__predict_false(rc != 0)) {
6419         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6420         m_freem(m);
6421         fp->eth_q_stats.mbuf_alloc_sge--;
6422         return (rc);
6423     }
6424
6425     /* all mbufs must map to a single segment */
6426     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6427
6428     sge_buf = &fp->rx_sge_mbuf_chain[index];
6429
6430     /* release any existing SGE mbuf mapping */
6431     if (sge_buf->m_map != NULL) {
6432         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6433                         BUS_DMASYNC_POSTREAD);
6434         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6435     }
6436
6437     /* save the mbuf and mapping info for a future packet */
6438     map = sge_buf->m_map;
6439     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6440     fp->rx_sge_mbuf_spare_map = map;
6441     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6442                     BUS_DMASYNC_PREREAD);
6443     sge_buf->m = m;
6444
6445     sge = &fp->rx_sge_chain[index];
6446     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6447     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6448
6449     return (rc);
6450 }
6451
6452 static __noinline int
6453 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6454 {
6455     struct bxe_fastpath *fp;
6456     int i, j, rc = 0;
6457     int ring_prod, cqe_ring_prod;
6458     int max_agg_queues;
6459
6460     for (i = 0; i < sc->num_queues; i++) {
6461         fp = &sc->fp[i];
6462
6463         ring_prod = cqe_ring_prod = 0;
6464         fp->rx_bd_cons = 0;
6465         fp->rx_cq_cons = 0;
6466
6467         /* allocate buffers for the RX BDs in RX BD chain */
6468         for (j = 0; j < sc->max_rx_bufs; j++) {
6469             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6470             if (rc != 0) {
6471                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6472                       i, rc);
6473                 goto bxe_alloc_fp_buffers_error;
6474             }
6475
6476             ring_prod     = RX_BD_NEXT(ring_prod);
6477             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6478         }
6479
6480         fp->rx_bd_prod = ring_prod;
6481         fp->rx_cq_prod = cqe_ring_prod;
6482         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6483
6484         max_agg_queues = MAX_AGG_QS(sc);
6485
6486         fp->tpa_enable = TRUE;
6487
6488         /* fill the TPA pool */
6489         for (j = 0; j < max_agg_queues; j++) {
6490             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6491             if (rc != 0) {
6492                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6493                           i, j);
6494                 fp->tpa_enable = FALSE;
6495                 goto bxe_alloc_fp_buffers_error;
6496             }
6497
6498             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6499         }
6500
6501         if (fp->tpa_enable) {
6502             /* fill the RX SGE chain */
6503             ring_prod = 0;
6504             for (j = 0; j < RX_SGE_USABLE; j++) {
6505                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6506                 if (rc != 0) {
6507                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6508                               i, ring_prod);
6509                     fp->tpa_enable = FALSE;
6510                     ring_prod = 0;
6511                     goto bxe_alloc_fp_buffers_error;
6512                 }
6513
6514                 ring_prod = RX_SGE_NEXT(ring_prod);
6515             }
6516
6517             fp->rx_sge_prod = ring_prod;
6518         }
6519     }
6520
6521     return (0);
6522
6523 bxe_alloc_fp_buffers_error:
6524
6525     /* unwind what was already allocated */
6526     bxe_free_rx_bd_chain(fp);
6527     bxe_free_tpa_pool(fp);
6528     bxe_free_sge_chain(fp);
6529
6530     return (ENOBUFS);
6531 }
6532
6533 static void
6534 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6535 {
6536     bxe_dma_free(sc, &sc->fw_stats_dma);
6537
6538     sc->fw_stats_num = 0;
6539
6540     sc->fw_stats_req_size = 0;
6541     sc->fw_stats_req = NULL;
6542     sc->fw_stats_req_mapping = 0;
6543
6544     sc->fw_stats_data_size = 0;
6545     sc->fw_stats_data = NULL;
6546     sc->fw_stats_data_mapping = 0;
6547 }
6548
6549 static int
6550 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6551 {
6552     uint8_t num_queue_stats;
6553     int num_groups;
6554
6555     /* number of queues for statistics is number of eth queues */
6556     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6557
6558     /*
6559      * Total number of FW statistics requests =
6560      *   1 for port stats + 1 for PF stats + num of queues
6561      */
6562     sc->fw_stats_num = (2 + num_queue_stats);
6563
6564     /*
6565      * Request is built from stats_query_header and an array of
6566      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6567      * rules. The real number or requests is configured in the
6568      * stats_query_header.
6569      */
6570     num_groups =
6571         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6572          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6573
6574     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6575           sc->fw_stats_num, num_groups);
6576
6577     sc->fw_stats_req_size =
6578         (sizeof(struct stats_query_header) +
6579          (num_groups * sizeof(struct stats_query_cmd_group)));
6580
6581     /*
6582      * Data for statistics requests + stats_counter.
6583      * stats_counter holds per-STORM counters that are incremented when
6584      * STORM has finished with the current request. Memory for FCoE
6585      * offloaded statistics are counted anyway, even if they will not be sent.
6586      * VF stats are not accounted for here as the data of VF stats is stored
6587      * in memory allocated by the VF, not here.
6588      */
6589     sc->fw_stats_data_size =
6590         (sizeof(struct stats_counter) +
6591          sizeof(struct per_port_stats) +
6592          sizeof(struct per_pf_stats) +
6593          /* sizeof(struct fcoe_statistics_params) + */
6594          (sizeof(struct per_queue_stats) * num_queue_stats));
6595
6596     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6597                       &sc->fw_stats_dma, "fw stats") != 0) {
6598         bxe_free_fw_stats_mem(sc);
6599         return (-1);
6600     }
6601
6602     /* set up the shortcuts */
6603
6604     sc->fw_stats_req =
6605         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6606     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6607
6608     sc->fw_stats_data =
6609         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6610                                      sc->fw_stats_req_size);
6611     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6612                                  sc->fw_stats_req_size);
6613
6614     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6615           (uintmax_t)sc->fw_stats_req_mapping);
6616
6617     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6618           (uintmax_t)sc->fw_stats_data_mapping);
6619
6620     return (0);
6621 }
6622
6623 /*
6624  * Bits map:
6625  * 0-7  - Engine0 load counter.
6626  * 8-15 - Engine1 load counter.
6627  * 16   - Engine0 RESET_IN_PROGRESS bit.
6628  * 17   - Engine1 RESET_IN_PROGRESS bit.
6629  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6630  *        function on the engine
6631  * 19   - Engine1 ONE_IS_LOADED.
6632  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6633  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6634  *        for just the one belonging to its engine).
6635  */
6636 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6637 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6638 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6639 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6640 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6641 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6642 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6643 #define BXE_GLOBAL_RESET_BIT      0x00040000
6644
6645 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6646 static void
6647 bxe_set_reset_global(struct bxe_softc *sc)
6648 {
6649     uint32_t val;
6650     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6651     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6652     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6653     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6654 }
6655
6656 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6657 static void
6658 bxe_clear_reset_global(struct bxe_softc *sc)
6659 {
6660     uint32_t val;
6661     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6662     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6663     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6664     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6665 }
6666
6667 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6668 static uint8_t
6669 bxe_reset_is_global(struct bxe_softc *sc)
6670 {
6671     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6672     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6673     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6674 }
6675
6676 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6677 static void
6678 bxe_set_reset_done(struct bxe_softc *sc)
6679 {
6680     uint32_t val;
6681     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6682                                  BXE_PATH0_RST_IN_PROG_BIT;
6683
6684     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6685
6686     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6687     /* Clear the bit */
6688     val &= ~bit;
6689     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6690
6691     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6692 }
6693
6694 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6695 static void
6696 bxe_set_reset_in_progress(struct bxe_softc *sc)
6697 {
6698     uint32_t val;
6699     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6700                                  BXE_PATH0_RST_IN_PROG_BIT;
6701
6702     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6703
6704     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6705     /* Set the bit */
6706     val |= bit;
6707     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6708
6709     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6710 }
6711
6712 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6713 static uint8_t
6714 bxe_reset_is_done(struct bxe_softc *sc,
6715                   int              engine)
6716 {
6717     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6718     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6719                             BXE_PATH0_RST_IN_PROG_BIT;
6720
6721     /* return false if bit is set */
6722     return (val & bit) ? FALSE : TRUE;
6723 }
6724
6725 /* get the load status for an engine, should be run under rtnl lock */
6726 static uint8_t
6727 bxe_get_load_status(struct bxe_softc *sc,
6728                     int              engine)
6729 {
6730     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6731                              BXE_PATH0_LOAD_CNT_MASK;
6732     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6733                               BXE_PATH0_LOAD_CNT_SHIFT;
6734     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6735
6736     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6737
6738     val = ((val & mask) >> shift);
6739
6740     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6741
6742     return (val != 0);
6743 }
6744
6745 /* set pf load mark */
6746 /* XXX needs to be under rtnl lock */
6747 static void
6748 bxe_set_pf_load(struct bxe_softc *sc)
6749 {
6750     uint32_t val;
6751     uint32_t val1;
6752     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6753                                   BXE_PATH0_LOAD_CNT_MASK;
6754     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6755                                    BXE_PATH0_LOAD_CNT_SHIFT;
6756
6757     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6758
6759     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6760     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6761
6762     /* get the current counter value */
6763     val1 = ((val & mask) >> shift);
6764
6765     /* set bit of this PF */
6766     val1 |= (1 << SC_ABS_FUNC(sc));
6767
6768     /* clear the old value */
6769     val &= ~mask;
6770
6771     /* set the new one */
6772     val |= ((val1 << shift) & mask);
6773
6774     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6775
6776     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6777 }
6778
6779 /* clear pf load mark */
6780 /* XXX needs to be under rtnl lock */
6781 static uint8_t
6782 bxe_clear_pf_load(struct bxe_softc *sc)
6783 {
6784     uint32_t val1, val;
6785     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6786                                   BXE_PATH0_LOAD_CNT_MASK;
6787     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6788                                    BXE_PATH0_LOAD_CNT_SHIFT;
6789
6790     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6791     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6792     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6793
6794     /* get the current counter value */
6795     val1 = (val & mask) >> shift;
6796
6797     /* clear bit of that PF */
6798     val1 &= ~(1 << SC_ABS_FUNC(sc));
6799
6800     /* clear the old value */
6801     val &= ~mask;
6802
6803     /* set the new one */
6804     val |= ((val1 << shift) & mask);
6805
6806     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6807     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6808     return (val1 != 0);
6809 }
6810
6811 /* send load requrest to mcp and analyze response */
6812 static int
6813 bxe_nic_load_request(struct bxe_softc *sc,
6814                      uint32_t         *load_code)
6815 {
6816     /* init fw_seq */
6817     sc->fw_seq =
6818         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6819          DRV_MSG_SEQ_NUMBER_MASK);
6820
6821     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6822
6823     /* get the current FW pulse sequence */
6824     sc->fw_drv_pulse_wr_seq =
6825         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6826          DRV_PULSE_SEQ_MASK);
6827
6828     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6829           sc->fw_drv_pulse_wr_seq);
6830
6831     /* load request */
6832     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6833                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6834
6835     /* if the MCP fails to respond we must abort */
6836     if (!(*load_code)) {
6837         BLOGE(sc, "MCP response failure!\n");
6838         return (-1);
6839     }
6840
6841     /* if MCP refused then must abort */
6842     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6843         BLOGE(sc, "MCP refused load request\n");
6844         return (-1);
6845     }
6846
6847     return (0);
6848 }
6849
6850 /*
6851  * Check whether another PF has already loaded FW to chip. In virtualized
6852  * environments a pf from anoth VM may have already initialized the device
6853  * including loading FW.
6854  */
6855 static int
6856 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6857                          uint32_t         load_code)
6858 {
6859     uint32_t my_fw, loaded_fw;
6860
6861     /* is another pf loaded on this engine? */
6862     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6863         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6864         /* build my FW version dword */
6865         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6866                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6867                  (BCM_5710_FW_REVISION_VERSION << 16) +
6868                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6869
6870         /* read loaded FW from chip */
6871         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6872         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6873               loaded_fw, my_fw);
6874
6875         /* abort nic load if version mismatch */
6876         if (my_fw != loaded_fw) {
6877             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6878                   loaded_fw, my_fw);
6879             return (-1);
6880         }
6881     }
6882
6883     return (0);
6884 }
6885
6886 /* mark PMF if applicable */
6887 static void
6888 bxe_nic_load_pmf(struct bxe_softc *sc,
6889                  uint32_t         load_code)
6890 {
6891     uint32_t ncsi_oem_data_addr;
6892
6893     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6894         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6895         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6896         /*
6897          * Barrier here for ordering between the writing to sc->port.pmf here
6898          * and reading it from the periodic task.
6899          */
6900         sc->port.pmf = 1;
6901         mb();
6902     } else {
6903         sc->port.pmf = 0;
6904     }
6905
6906     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6907
6908     /* XXX needed? */
6909     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6910         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6911             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6912             if (ncsi_oem_data_addr) {
6913                 REG_WR(sc,
6914                        (ncsi_oem_data_addr +
6915                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6916                        0);
6917             }
6918         }
6919     }
6920 }
6921
6922 static void
6923 bxe_read_mf_cfg(struct bxe_softc *sc)
6924 {
6925     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6926     int abs_func;
6927     int vn;
6928
6929     if (BXE_NOMCP(sc)) {
6930         return; /* what should be the default bvalue in this case */
6931     }
6932
6933     /*
6934      * The formula for computing the absolute function number is...
6935      * For 2 port configuration (4 functions per port):
6936      *   abs_func = 2 * vn + SC_PORT + SC_PATH
6937      * For 4 port configuration (2 functions per port):
6938      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6939      */
6940     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6941         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6942         if (abs_func >= E1H_FUNC_MAX) {
6943             break;
6944         }
6945         sc->devinfo.mf_info.mf_config[vn] =
6946             MFCFG_RD(sc, func_mf_config[abs_func].config);
6947     }
6948
6949     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6950         FUNC_MF_CFG_FUNC_DISABLED) {
6951         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6952         sc->flags |= BXE_MF_FUNC_DIS;
6953     } else {
6954         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6955         sc->flags &= ~BXE_MF_FUNC_DIS;
6956     }
6957 }
6958
6959 /* acquire split MCP access lock register */
6960 static int bxe_acquire_alr(struct bxe_softc *sc)
6961 {
6962     uint32_t j, val;
6963
6964     for (j = 0; j < 1000; j++) {
6965         val = (1UL << 31);
6966         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6967         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6968         if (val & (1L << 31))
6969             break;
6970
6971         DELAY(5000);
6972     }
6973
6974     if (!(val & (1L << 31))) {
6975         BLOGE(sc, "Cannot acquire MCP access lock register\n");
6976         return (-1);
6977     }
6978
6979     return (0);
6980 }
6981
6982 /* release split MCP access lock register */
6983 static void bxe_release_alr(struct bxe_softc *sc)
6984 {
6985     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
6986 }
6987
6988 static void
6989 bxe_fan_failure(struct bxe_softc *sc)
6990 {
6991     int port = SC_PORT(sc);
6992     uint32_t ext_phy_config;
6993
6994     /* mark the failure */
6995     ext_phy_config =
6996         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
6997
6998     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
6999     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7000     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7001              ext_phy_config);
7002
7003     /* log the failure */
7004     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7005               "the card to prevent permanent damage. "
7006               "Please contact OEM Support for assistance\n");
7007
7008     /* XXX */
7009 #if 1
7010     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7011 #else
7012     /*
7013      * Schedule device reset (unload)
7014      * This is due to some boards consuming sufficient power when driver is
7015      * up to overheat if fan fails.
7016      */
7017     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7018     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7019 #endif
7020 }
7021
7022 /* this function is called upon a link interrupt */
7023 static void
7024 bxe_link_attn(struct bxe_softc *sc)
7025 {
7026     uint32_t pause_enabled = 0;
7027     struct host_port_stats *pstats;
7028     int cmng_fns;
7029
7030     /* Make sure that we are synced with the current statistics */
7031     bxe_stats_handle(sc, STATS_EVENT_STOP);
7032     BLOGD(sc, DBG_LOAD, "link_vars phy_flags : %x\n", sc->link_vars.phy_flags);
7033     elink_link_update(&sc->link_params, &sc->link_vars);
7034
7035     if (sc->link_vars.link_up) {
7036
7037         /* dropless flow control */
7038         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7039             pause_enabled = 0;
7040
7041             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7042                 pause_enabled = 1;
7043             }
7044
7045             REG_WR(sc,
7046                    (BAR_USTRORM_INTMEM +
7047                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7048                    pause_enabled);
7049         }
7050
7051         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7052             pstats = BXE_SP(sc, port_stats);
7053             /* reset old mac stats */
7054             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7055         }
7056
7057         if (sc->state == BXE_STATE_OPEN) {
7058             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7059         }
7060     }
7061
7062     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7063         cmng_fns = bxe_get_cmng_fns_mode(sc);
7064
7065         if (cmng_fns != CMNG_FNS_NONE) {
7066             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7067             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7068         } else {
7069             /* rate shaping and fairness are disabled */
7070             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7071         }
7072     }
7073
7074     bxe_link_report_locked(sc);
7075
7076     if (IS_MF(sc)) {
7077         ; // XXX bxe_link_sync_notify(sc);
7078     }
7079 }
7080
7081 static void
7082 bxe_attn_int_asserted(struct bxe_softc *sc,
7083                       uint32_t         asserted)
7084 {
7085     int port = SC_PORT(sc);
7086     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7087                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7088     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7089                                         NIG_REG_MASK_INTERRUPT_PORT0;
7090     uint32_t aeu_mask;
7091     uint32_t nig_mask = 0;
7092     uint32_t reg_addr;
7093     uint32_t igu_acked;
7094     uint32_t cnt;
7095
7096     if (sc->attn_state & asserted) {
7097         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7098     }
7099
7100     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7101
7102     aeu_mask = REG_RD(sc, aeu_addr);
7103
7104     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7105           aeu_mask, asserted);
7106
7107     aeu_mask &= ~(asserted & 0x3ff);
7108
7109     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7110
7111     REG_WR(sc, aeu_addr, aeu_mask);
7112
7113     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7114
7115     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7116     sc->attn_state |= asserted;
7117     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7118
7119     if (asserted & ATTN_HARD_WIRED_MASK) {
7120         if (asserted & ATTN_NIG_FOR_FUNC) {
7121
7122             bxe_acquire_phy_lock(sc);
7123             /* save nig interrupt mask */
7124             nig_mask = REG_RD(sc, nig_int_mask_addr);
7125
7126             /* If nig_mask is not set, no need to call the update function */
7127             if (nig_mask) {
7128                 REG_WR(sc, nig_int_mask_addr, 0);
7129
7130                 bxe_link_attn(sc);
7131             }
7132
7133             /* handle unicore attn? */
7134         }
7135
7136         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7137             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7138         }
7139
7140         if (asserted & GPIO_2_FUNC) {
7141             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7142         }
7143
7144         if (asserted & GPIO_3_FUNC) {
7145             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7146         }
7147
7148         if (asserted & GPIO_4_FUNC) {
7149             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7150         }
7151
7152         if (port == 0) {
7153             if (asserted & ATTN_GENERAL_ATTN_1) {
7154                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7155                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7156             }
7157             if (asserted & ATTN_GENERAL_ATTN_2) {
7158                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7159                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7160             }
7161             if (asserted & ATTN_GENERAL_ATTN_3) {
7162                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7163                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7164             }
7165         } else {
7166             if (asserted & ATTN_GENERAL_ATTN_4) {
7167                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7168                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7169             }
7170             if (asserted & ATTN_GENERAL_ATTN_5) {
7171                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7172                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7173             }
7174             if (asserted & ATTN_GENERAL_ATTN_6) {
7175                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7176                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7177             }
7178         }
7179     } /* hardwired */
7180
7181     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7182         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7183     } else {
7184         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7185     }
7186
7187     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7188           asserted,
7189           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7190     REG_WR(sc, reg_addr, asserted);
7191
7192     /* now set back the mask */
7193     if (asserted & ATTN_NIG_FOR_FUNC) {
7194         /*
7195          * Verify that IGU ack through BAR was written before restoring
7196          * NIG mask. This loop should exit after 2-3 iterations max.
7197          */
7198         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7199             cnt = 0;
7200
7201             do {
7202                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7203             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7204                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7205
7206             if (!igu_acked) {
7207                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7208             }
7209
7210             mb();
7211         }
7212
7213         REG_WR(sc, nig_int_mask_addr, nig_mask);
7214
7215         bxe_release_phy_lock(sc);
7216     }
7217 }
7218
7219 static void
7220 bxe_print_next_block(struct bxe_softc *sc,
7221                      int              idx,
7222                      const char       *blk)
7223 {
7224     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7225 }
7226
7227 static int
7228 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7229                               uint32_t         sig,
7230                               int              par_num,
7231                               uint8_t          print)
7232 {
7233     uint32_t cur_bit = 0;
7234     int i = 0;
7235
7236     for (i = 0; sig; i++) {
7237         cur_bit = ((uint32_t)0x1 << i);
7238         if (sig & cur_bit) {
7239             switch (cur_bit) {
7240             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7241                 if (print)
7242                     bxe_print_next_block(sc, par_num++, "BRB");
7243                 break;
7244             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7245                 if (print)
7246                     bxe_print_next_block(sc, par_num++, "PARSER");
7247                 break;
7248             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7249                 if (print)
7250                     bxe_print_next_block(sc, par_num++, "TSDM");
7251                 break;
7252             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7253                 if (print)
7254                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7255                 break;
7256             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7257                 if (print)
7258                     bxe_print_next_block(sc, par_num++, "TCM");
7259                 break;
7260             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7261                 if (print)
7262                     bxe_print_next_block(sc, par_num++, "TSEMI");
7263                 break;
7264             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7265                 if (print)
7266                     bxe_print_next_block(sc, par_num++, "XPB");
7267                 break;
7268             }
7269
7270             /* Clear the bit */
7271             sig &= ~cur_bit;
7272         }
7273     }
7274
7275     return (par_num);
7276 }
7277
7278 static int
7279 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7280                               uint32_t         sig,
7281                               int              par_num,
7282                               uint8_t          *global,
7283                               uint8_t          print)
7284 {
7285     int i = 0;
7286     uint32_t cur_bit = 0;
7287     for (i = 0; sig; i++) {
7288         cur_bit = ((uint32_t)0x1 << i);
7289         if (sig & cur_bit) {
7290             switch (cur_bit) {
7291             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7292                 if (print)
7293                     bxe_print_next_block(sc, par_num++, "PBF");
7294                 break;
7295             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7296                 if (print)
7297                     bxe_print_next_block(sc, par_num++, "QM");
7298                 break;
7299             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7300                 if (print)
7301                     bxe_print_next_block(sc, par_num++, "TM");
7302                 break;
7303             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7304                 if (print)
7305                     bxe_print_next_block(sc, par_num++, "XSDM");
7306                 break;
7307             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7308                 if (print)
7309                     bxe_print_next_block(sc, par_num++, "XCM");
7310                 break;
7311             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7312                 if (print)
7313                     bxe_print_next_block(sc, par_num++, "XSEMI");
7314                 break;
7315             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7316                 if (print)
7317                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7318                 break;
7319             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7320                 if (print)
7321                     bxe_print_next_block(sc, par_num++, "NIG");
7322                 break;
7323             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7324                 if (print)
7325                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7326                 *global = TRUE;
7327                 break;
7328             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7329                 if (print)
7330                     bxe_print_next_block(sc, par_num++, "DEBUG");
7331                 break;
7332             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7333                 if (print)
7334                     bxe_print_next_block(sc, par_num++, "USDM");
7335                 break;
7336             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7337                 if (print)
7338                     bxe_print_next_block(sc, par_num++, "UCM");
7339                 break;
7340             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7341                 if (print)
7342                     bxe_print_next_block(sc, par_num++, "USEMI");
7343                 break;
7344             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7345                 if (print)
7346                     bxe_print_next_block(sc, par_num++, "UPB");
7347                 break;
7348             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7349                 if (print)
7350                     bxe_print_next_block(sc, par_num++, "CSDM");
7351                 break;
7352             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7353                 if (print)
7354                     bxe_print_next_block(sc, par_num++, "CCM");
7355                 break;
7356             }
7357
7358             /* Clear the bit */
7359             sig &= ~cur_bit;
7360         }
7361     }
7362
7363     return (par_num);
7364 }
7365
7366 static int
7367 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7368                               uint32_t         sig,
7369                               int              par_num,
7370                               uint8_t          print)
7371 {
7372     uint32_t cur_bit = 0;
7373     int i = 0;
7374
7375     for (i = 0; sig; i++) {
7376         cur_bit = ((uint32_t)0x1 << i);
7377         if (sig & cur_bit) {
7378             switch (cur_bit) {
7379             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7380                 if (print)
7381                     bxe_print_next_block(sc, par_num++, "CSEMI");
7382                 break;
7383             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7384                 if (print)
7385                     bxe_print_next_block(sc, par_num++, "PXP");
7386                 break;
7387             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7388                 if (print)
7389                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7390                 break;
7391             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7392                 if (print)
7393                     bxe_print_next_block(sc, par_num++, "CFC");
7394                 break;
7395             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7396                 if (print)
7397                     bxe_print_next_block(sc, par_num++, "CDU");
7398                 break;
7399             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7400                 if (print)
7401                     bxe_print_next_block(sc, par_num++, "DMAE");
7402                 break;
7403             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7404                 if (print)
7405                     bxe_print_next_block(sc, par_num++, "IGU");
7406                 break;
7407             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7408                 if (print)
7409                     bxe_print_next_block(sc, par_num++, "MISC");
7410                 break;
7411             }
7412
7413             /* Clear the bit */
7414             sig &= ~cur_bit;
7415         }
7416     }
7417
7418     return (par_num);
7419 }
7420
7421 static int
7422 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7423                               uint32_t         sig,
7424                               int              par_num,
7425                               uint8_t          *global,
7426                               uint8_t          print)
7427 {
7428     uint32_t cur_bit = 0;
7429     int i = 0;
7430
7431     for (i = 0; sig; i++) {
7432         cur_bit = ((uint32_t)0x1 << i);
7433         if (sig & cur_bit) {
7434             switch (cur_bit) {
7435             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7436                 if (print)
7437                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7438                 *global = TRUE;
7439                 break;
7440             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7441                 if (print)
7442                     bxe_print_next_block(sc, par_num++,
7443                               "MCP UMP RX");
7444                 *global = TRUE;
7445                 break;
7446             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7447                 if (print)
7448                     bxe_print_next_block(sc, par_num++,
7449                               "MCP UMP TX");
7450                 *global = TRUE;
7451                 break;
7452             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7453                 if (print)
7454                     bxe_print_next_block(sc, par_num++,
7455                               "MCP SCPAD");
7456                 *global = TRUE;
7457                 break;
7458             }
7459
7460             /* Clear the bit */
7461             sig &= ~cur_bit;
7462         }
7463     }
7464
7465     return (par_num);
7466 }
7467
7468 static int
7469 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7470                               uint32_t         sig,
7471                               int              par_num,
7472                               uint8_t          print)
7473 {
7474     uint32_t cur_bit = 0;
7475     int i = 0;
7476
7477     for (i = 0; sig; i++) {
7478         cur_bit = ((uint32_t)0x1 << i);
7479         if (sig & cur_bit) {
7480             switch (cur_bit) {
7481             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7482                 if (print)
7483                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7484                 break;
7485             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7486                 if (print)
7487                     bxe_print_next_block(sc, par_num++, "ATC");
7488                 break;
7489             }
7490
7491             /* Clear the bit */
7492             sig &= ~cur_bit;
7493         }
7494     }
7495
7496     return (par_num);
7497 }
7498
7499 static uint8_t
7500 bxe_parity_attn(struct bxe_softc *sc,
7501                 uint8_t          *global,
7502                 uint8_t          print,
7503                 uint32_t         *sig)
7504 {
7505     int par_num = 0;
7506
7507     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7508         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7509         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7510         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7511         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7512         BLOGE(sc, "Parity error: HW block parity attention:\n"
7513                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7514               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7515               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7516               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7517               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7518               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7519
7520         if (print)
7521             BLOGI(sc, "Parity errors detected in blocks: ");
7522
7523         par_num =
7524             bxe_check_blocks_with_parity0(sc, sig[0] &
7525                                           HW_PRTY_ASSERT_SET_0,
7526                                           par_num, print);
7527         par_num =
7528             bxe_check_blocks_with_parity1(sc, sig[1] &
7529                                           HW_PRTY_ASSERT_SET_1,
7530                                           par_num, global, print);
7531         par_num =
7532             bxe_check_blocks_with_parity2(sc, sig[2] &
7533                                           HW_PRTY_ASSERT_SET_2,
7534                                           par_num, print);
7535         par_num =
7536             bxe_check_blocks_with_parity3(sc, sig[3] &
7537                                           HW_PRTY_ASSERT_SET_3,
7538                                           par_num, global, print);
7539         par_num =
7540             bxe_check_blocks_with_parity4(sc, sig[4] &
7541                                           HW_PRTY_ASSERT_SET_4,
7542                                           par_num, print);
7543
7544         if (print)
7545             BLOGI(sc, "\n");
7546
7547         return (TRUE);
7548     }
7549
7550     return (FALSE);
7551 }
7552
7553 static uint8_t
7554 bxe_chk_parity_attn(struct bxe_softc *sc,
7555                     uint8_t          *global,
7556                     uint8_t          print)
7557 {
7558     struct attn_route attn = { {0} };
7559     int port = SC_PORT(sc);
7560
7561     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7562     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7563     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7564     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7565
7566     /*
7567      * Since MCP attentions can't be disabled inside the block, we need to
7568      * read AEU registers to see whether they're currently disabled
7569      */
7570     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7571                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7572                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7573                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7574
7575
7576     if (!CHIP_IS_E1x(sc))
7577         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7578
7579     return (bxe_parity_attn(sc, global, print, attn.sig));
7580 }
7581
7582 static void
7583 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7584                          uint32_t         attn)
7585 {
7586     uint32_t val;
7587
7588     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7589         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7590         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7591         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7592             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7593         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7594             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7595         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7596             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7597         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7598             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7599         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7600             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7601         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7602             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7603         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7604             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7605         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7606             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7607         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7608             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7609     }
7610
7611     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7612         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7613         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7614         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7615             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7616         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7617             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7618         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7619             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7620         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7621             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7622         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7623             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7624         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7625             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7626     }
7627
7628     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7629                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7630         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7631               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7632                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7633     }
7634 }
7635
7636 static void
7637 bxe_e1h_disable(struct bxe_softc *sc)
7638 {
7639     int port = SC_PORT(sc);
7640
7641     bxe_tx_disable(sc);
7642
7643     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7644 }
7645
7646 static void
7647 bxe_e1h_enable(struct bxe_softc *sc)
7648 {
7649     int port = SC_PORT(sc);
7650
7651     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7652
7653     // XXX bxe_tx_enable(sc);
7654 }
7655
7656 /*
7657  * called due to MCP event (on pmf):
7658  *   reread new bandwidth configuration
7659  *   configure FW
7660  *   notify others function about the change
7661  */
7662 static void
7663 bxe_config_mf_bw(struct bxe_softc *sc)
7664 {
7665     if (sc->link_vars.link_up) {
7666         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7667         // XXX bxe_link_sync_notify(sc);
7668     }
7669
7670     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7671 }
7672
7673 static void
7674 bxe_set_mf_bw(struct bxe_softc *sc)
7675 {
7676     bxe_config_mf_bw(sc);
7677     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7678 }
7679
7680 static void
7681 bxe_handle_eee_event(struct bxe_softc *sc)
7682 {
7683     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7684     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7685 }
7686
7687 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7688
7689 static void
7690 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7691 {
7692     struct eth_stats_info *ether_stat =
7693         &sc->sp->drv_info_to_mcp.ether_stat;
7694
7695     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7696             ETH_STAT_INFO_VERSION_LEN);
7697
7698     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7699     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7700                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7701                                           ether_stat->mac_local + MAC_PAD,
7702                                           MAC_PAD, ETH_ALEN);
7703
7704     ether_stat->mtu_size = sc->mtu;
7705
7706     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7707     if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
7708         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7709     }
7710
7711     // XXX ether_stat->feature_flags |= ???;
7712
7713     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7714
7715     ether_stat->txq_size = sc->tx_ring_size;
7716     ether_stat->rxq_size = sc->rx_ring_size;
7717 }
7718
7719 static void
7720 bxe_handle_drv_info_req(struct bxe_softc *sc)
7721 {
7722     enum drv_info_opcode op_code;
7723     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7724
7725     /* if drv_info version supported by MFW doesn't match - send NACK */
7726     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7727         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7728         return;
7729     }
7730
7731     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7732                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7733
7734     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7735
7736     switch (op_code) {
7737     case ETH_STATS_OPCODE:
7738         bxe_drv_info_ether_stat(sc);
7739         break;
7740     case FCOE_STATS_OPCODE:
7741     case ISCSI_STATS_OPCODE:
7742     default:
7743         /* if op code isn't supported - send NACK */
7744         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7745         return;
7746     }
7747
7748     /*
7749      * If we got drv_info attn from MFW then these fields are defined in
7750      * shmem2 for sure
7751      */
7752     SHMEM2_WR(sc, drv_info_host_addr_lo,
7753               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7754     SHMEM2_WR(sc, drv_info_host_addr_hi,
7755               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7756
7757     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7758 }
7759
7760 static void
7761 bxe_dcc_event(struct bxe_softc *sc,
7762               uint32_t         dcc_event)
7763 {
7764     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7765
7766     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7767         /*
7768          * This is the only place besides the function initialization
7769          * where the sc->flags can change so it is done without any
7770          * locks
7771          */
7772         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7773             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7774             sc->flags |= BXE_MF_FUNC_DIS;
7775             bxe_e1h_disable(sc);
7776         } else {
7777             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7778             sc->flags &= ~BXE_MF_FUNC_DIS;
7779             bxe_e1h_enable(sc);
7780         }
7781         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7782     }
7783
7784     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7785         bxe_config_mf_bw(sc);
7786         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7787     }
7788
7789     /* Report results to MCP */
7790     if (dcc_event)
7791         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7792     else
7793         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7794 }
7795
7796 static void
7797 bxe_pmf_update(struct bxe_softc *sc)
7798 {
7799     int port = SC_PORT(sc);
7800     uint32_t val;
7801
7802     sc->port.pmf = 1;
7803     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7804
7805     /*
7806      * We need the mb() to ensure the ordering between the writing to
7807      * sc->port.pmf here and reading it from the bxe_periodic_task().
7808      */
7809     mb();
7810
7811     /* queue a periodic task */
7812     // XXX schedule task...
7813
7814     // XXX bxe_dcbx_pmf_update(sc);
7815
7816     /* enable nig attention */
7817     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7818     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7819         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7820         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7821     } else if (!CHIP_IS_E1x(sc)) {
7822         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7823         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7824     }
7825
7826     bxe_stats_handle(sc, STATS_EVENT_PMF);
7827 }
7828
7829 static int
7830 bxe_mc_assert(struct bxe_softc *sc)
7831 {
7832     char last_idx;
7833     int i, rc = 0;
7834     uint32_t row0, row1, row2, row3;
7835
7836     /* XSTORM */
7837     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7838     if (last_idx)
7839         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7840
7841     /* print the asserts */
7842     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7843
7844         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7845         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7846         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7847         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7848
7849         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7850             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7851                   i, row3, row2, row1, row0);
7852             rc++;
7853         } else {
7854             break;
7855         }
7856     }
7857
7858     /* TSTORM */
7859     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7860     if (last_idx) {
7861         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7862     }
7863
7864     /* print the asserts */
7865     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7866
7867         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7868         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7869         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7870         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7871
7872         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7873             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7874                   i, row3, row2, row1, row0);
7875             rc++;
7876         } else {
7877             break;
7878         }
7879     }
7880
7881     /* CSTORM */
7882     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7883     if (last_idx) {
7884         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7885     }
7886
7887     /* print the asserts */
7888     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7889
7890         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7891         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7892         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7893         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7894
7895         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7896             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7897                   i, row3, row2, row1, row0);
7898             rc++;
7899         } else {
7900             break;
7901         }
7902     }
7903
7904     /* USTORM */
7905     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7906     if (last_idx) {
7907         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7908     }
7909
7910     /* print the asserts */
7911     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7912
7913         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7914         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7915         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7916         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7917
7918         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7919             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7920                   i, row3, row2, row1, row0);
7921             rc++;
7922         } else {
7923             break;
7924         }
7925     }
7926
7927     return (rc);
7928 }
7929
7930 static void
7931 bxe_attn_int_deasserted3(struct bxe_softc *sc,
7932                          uint32_t         attn)
7933 {
7934     int func = SC_FUNC(sc);
7935     uint32_t val;
7936
7937     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7938
7939         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7940
7941             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7942             bxe_read_mf_cfg(sc);
7943             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7944                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7945             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7946
7947             if (val & DRV_STATUS_DCC_EVENT_MASK)
7948                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7949
7950             if (val & DRV_STATUS_SET_MF_BW)
7951                 bxe_set_mf_bw(sc);
7952
7953             if (val & DRV_STATUS_DRV_INFO_REQ)
7954                 bxe_handle_drv_info_req(sc);
7955
7956             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
7957                 bxe_pmf_update(sc);
7958
7959             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
7960                 bxe_handle_eee_event(sc);
7961
7962             if (sc->link_vars.periodic_flags &
7963                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
7964                 /* sync with link */
7965                 bxe_acquire_phy_lock(sc);
7966                 sc->link_vars.periodic_flags &=
7967                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
7968                 bxe_release_phy_lock(sc);
7969                 if (IS_MF(sc))
7970                     ; // XXX bxe_link_sync_notify(sc);
7971                 bxe_link_report(sc);
7972             }
7973
7974             /*
7975              * Always call it here: bxe_link_report() will
7976              * prevent the link indication duplication.
7977              */
7978             bxe_link_status_update(sc);
7979
7980         } else if (attn & BXE_MC_ASSERT_BITS) {
7981
7982             BLOGE(sc, "MC assert!\n");
7983             bxe_mc_assert(sc);
7984             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
7985             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
7986             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
7987             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
7988             bxe_panic(sc, ("MC assert!\n"));
7989
7990         } else if (attn & BXE_MCP_ASSERT) {
7991
7992             BLOGE(sc, "MCP assert!\n");
7993             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
7994             // XXX bxe_fw_dump(sc);
7995
7996         } else {
7997             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
7998         }
7999     }
8000
8001     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8002         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8003         if (attn & BXE_GRC_TIMEOUT) {
8004             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8005             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8006         }
8007         if (attn & BXE_GRC_RSV) {
8008             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8009             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8010         }
8011         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8012     }
8013 }
8014
8015 static void
8016 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8017                          uint32_t         attn)
8018 {
8019     int port = SC_PORT(sc);
8020     int reg_offset;
8021     uint32_t val0, mask0, val1, mask1;
8022     uint32_t val;
8023
8024     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8025         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8026         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8027         /* CFC error attention */
8028         if (val & 0x2) {
8029             BLOGE(sc, "FATAL error from CFC\n");
8030         }
8031     }
8032
8033     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8034         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8035         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8036         /* RQ_USDMDP_FIFO_OVERFLOW */
8037         if (val & 0x18000) {
8038             BLOGE(sc, "FATAL error from PXP\n");
8039         }
8040
8041         if (!CHIP_IS_E1x(sc)) {
8042             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8043             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8044         }
8045     }
8046
8047 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8048 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8049
8050     if (attn & AEU_PXP2_HW_INT_BIT) {
8051         /*  CQ47854 workaround do not panic on
8052          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8053          */
8054         if (!CHIP_IS_E1x(sc)) {
8055             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8056             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8057             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8058             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8059             /*
8060              * If the olny PXP2_EOP_ERROR_BIT is set in
8061              * STS0 and STS1 - clear it
8062              *
8063              * probably we lose additional attentions between
8064              * STS0 and STS_CLR0, in this case user will not
8065              * be notified about them
8066              */
8067             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8068                 !(val1 & mask1))
8069                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8070
8071             /* print the register, since no one can restore it */
8072             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8073
8074             /*
8075              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8076              * then notify
8077              */
8078             if (val0 & PXP2_EOP_ERROR_BIT) {
8079                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8080
8081                 /*
8082                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8083                  * set then clear attention from PXP2 block without panic
8084                  */
8085                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8086                     ((val1 & mask1) == 0))
8087                     attn &= ~AEU_PXP2_HW_INT_BIT;
8088             }
8089         }
8090     }
8091
8092     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8093         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8094                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8095
8096         val = REG_RD(sc, reg_offset);
8097         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8098         REG_WR(sc, reg_offset, val);
8099
8100         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8101               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8102         bxe_panic(sc, ("HW block attention set2\n"));
8103     }
8104 }
8105
8106 static void
8107 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8108                          uint32_t         attn)
8109 {
8110     int port = SC_PORT(sc);
8111     int reg_offset;
8112     uint32_t val;
8113
8114     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8115         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8116         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8117         /* DORQ discard attention */
8118         if (val & 0x2) {
8119             BLOGE(sc, "FATAL error from DORQ\n");
8120         }
8121     }
8122
8123     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8124         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8125                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8126
8127         val = REG_RD(sc, reg_offset);
8128         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8129         REG_WR(sc, reg_offset, val);
8130
8131         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8132               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8133         bxe_panic(sc, ("HW block attention set1\n"));
8134     }
8135 }
8136
8137 static void
8138 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8139                          uint32_t         attn)
8140 {
8141     int port = SC_PORT(sc);
8142     int reg_offset;
8143     uint32_t val;
8144
8145     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8146                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8147
8148     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8149         val = REG_RD(sc, reg_offset);
8150         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8151         REG_WR(sc, reg_offset, val);
8152
8153         BLOGW(sc, "SPIO5 hw attention\n");
8154
8155         /* Fan failure attention */
8156         elink_hw_reset_phy(&sc->link_params);
8157         bxe_fan_failure(sc);
8158     }
8159
8160     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8161         bxe_acquire_phy_lock(sc);
8162         elink_handle_module_detect_int(&sc->link_params);
8163         bxe_release_phy_lock(sc);
8164     }
8165
8166     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8167         val = REG_RD(sc, reg_offset);
8168         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8169         REG_WR(sc, reg_offset, val);
8170
8171         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8172                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8173     }
8174 }
8175
8176 static void
8177 bxe_attn_int_deasserted(struct bxe_softc *sc,
8178                         uint32_t         deasserted)
8179 {
8180     struct attn_route attn;
8181     struct attn_route *group_mask;
8182     int port = SC_PORT(sc);
8183     int index;
8184     uint32_t reg_addr;
8185     uint32_t val;
8186     uint32_t aeu_mask;
8187     uint8_t global = FALSE;
8188
8189     /*
8190      * Need to take HW lock because MCP or other port might also
8191      * try to handle this event.
8192      */
8193     bxe_acquire_alr(sc);
8194
8195     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8196         /* XXX
8197          * In case of parity errors don't handle attentions so that
8198          * other function would "see" parity errors.
8199          */
8200         sc->recovery_state = BXE_RECOVERY_INIT;
8201         // XXX schedule a recovery task...
8202         /* disable HW interrupts */
8203         bxe_int_disable(sc);
8204         bxe_release_alr(sc);
8205         return;
8206     }
8207
8208     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8209     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8210     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8211     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8212     if (!CHIP_IS_E1x(sc)) {
8213         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8214     } else {
8215         attn.sig[4] = 0;
8216     }
8217
8218     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8219           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8220
8221     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8222         if (deasserted & (1 << index)) {
8223             group_mask = &sc->attn_group[index];
8224
8225             BLOGD(sc, DBG_INTR,
8226                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8227                   group_mask->sig[0], group_mask->sig[1],
8228                   group_mask->sig[2], group_mask->sig[3],
8229                   group_mask->sig[4]);
8230
8231             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8232             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8233             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8234             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8235             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8236         }
8237     }
8238
8239     bxe_release_alr(sc);
8240
8241     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8242         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8243                     COMMAND_REG_ATTN_BITS_CLR);
8244     } else {
8245         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8246     }
8247
8248     val = ~deasserted;
8249     BLOGD(sc, DBG_INTR,
8250           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8251           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8252     REG_WR(sc, reg_addr, val);
8253
8254     if (~sc->attn_state & deasserted) {
8255         BLOGE(sc, "IGU error\n");
8256     }
8257
8258     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8259                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8260
8261     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8262
8263     aeu_mask = REG_RD(sc, reg_addr);
8264
8265     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8266           aeu_mask, deasserted);
8267     aeu_mask |= (deasserted & 0x3ff);
8268     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8269
8270     REG_WR(sc, reg_addr, aeu_mask);
8271     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8272
8273     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8274     sc->attn_state &= ~deasserted;
8275     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8276 }
8277
8278 static void
8279 bxe_attn_int(struct bxe_softc *sc)
8280 {
8281     /* read local copy of bits */
8282     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8283     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8284     uint32_t attn_state = sc->attn_state;
8285
8286     /* look for changed bits */
8287     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8288     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8289
8290     BLOGD(sc, DBG_INTR,
8291           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8292           attn_bits, attn_ack, asserted, deasserted);
8293
8294     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8295         BLOGE(sc, "BAD attention state\n");
8296     }
8297
8298     /* handle bits that were raised */
8299     if (asserted) {
8300         bxe_attn_int_asserted(sc, asserted);
8301     }
8302
8303     if (deasserted) {
8304         bxe_attn_int_deasserted(sc, deasserted);
8305     }
8306 }
8307
8308 static uint16_t
8309 bxe_update_dsb_idx(struct bxe_softc *sc)
8310 {
8311     struct host_sp_status_block *def_sb = sc->def_sb;
8312     uint16_t rc = 0;
8313
8314     mb(); /* status block is written to by the chip */
8315
8316     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8317         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8318         rc |= BXE_DEF_SB_ATT_IDX;
8319     }
8320
8321     if (sc->def_idx != def_sb->sp_sb.running_index) {
8322         sc->def_idx = def_sb->sp_sb.running_index;
8323         rc |= BXE_DEF_SB_IDX;
8324     }
8325
8326     mb();
8327
8328     return (rc);
8329 }
8330
8331 static inline struct ecore_queue_sp_obj *
8332 bxe_cid_to_q_obj(struct bxe_softc *sc,
8333                  uint32_t         cid)
8334 {
8335     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8336     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8337 }
8338
8339 static void
8340 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8341 {
8342     struct ecore_mcast_ramrod_params rparam;
8343     int rc;
8344
8345     memset(&rparam, 0, sizeof(rparam));
8346
8347     rparam.mcast_obj = &sc->mcast_obj;
8348
8349     BXE_MCAST_LOCK(sc);
8350
8351     /* clear pending state for the last command */
8352     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8353
8354     /* if there are pending mcast commands - send them */
8355     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8356         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8357         if (rc < 0) {
8358             BLOGD(sc, DBG_SP,
8359                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8360         }
8361     }
8362
8363     BXE_MCAST_UNLOCK(sc);
8364 }
8365
8366 static void
8367 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8368                               union event_ring_elem *elem)
8369 {
8370     unsigned long ramrod_flags = 0;
8371     int rc = 0;
8372     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8373     struct ecore_vlan_mac_obj *vlan_mac_obj;
8374
8375     /* always push next commands out, don't wait here */
8376     bit_set(&ramrod_flags, RAMROD_CONT);
8377
8378     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8379     case ECORE_FILTER_MAC_PENDING:
8380         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8381         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8382         break;
8383
8384     case ECORE_FILTER_MCAST_PENDING:
8385         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8386         /*
8387          * This is only relevant for 57710 where multicast MACs are
8388          * configured as unicast MACs using the same ramrod.
8389          */
8390         bxe_handle_mcast_eqe(sc);
8391         return;
8392
8393     default:
8394         BLOGE(sc, "Unsupported classification command: %d\n",
8395               elem->message.data.eth_event.echo);
8396         return;
8397     }
8398
8399     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8400
8401     if (rc < 0) {
8402         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8403     } else if (rc > 0) {
8404         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8405     }
8406 }
8407
8408 static void
8409 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8410                        union event_ring_elem *elem)
8411 {
8412     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8413
8414     /* send rx_mode command again if was requested */
8415     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8416                                &sc->sp_state)) {
8417         bxe_set_storm_rx_mode(sc);
8418     }
8419 }
8420
8421 static void
8422 bxe_update_eq_prod(struct bxe_softc *sc,
8423                    uint16_t         prod)
8424 {
8425     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8426     wmb(); /* keep prod updates ordered */
8427 }
8428
8429 static void
8430 bxe_eq_int(struct bxe_softc *sc)
8431 {
8432     uint16_t hw_cons, sw_cons, sw_prod;
8433     union event_ring_elem *elem;
8434     uint8_t echo;
8435     uint32_t cid;
8436     uint8_t opcode;
8437     int spqe_cnt = 0;
8438     struct ecore_queue_sp_obj *q_obj;
8439     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8440     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8441
8442     hw_cons = le16toh(*sc->eq_cons_sb);
8443
8444     /*
8445      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8446      * when we get to the next-page we need to adjust so the loop
8447      * condition below will be met. The next element is the size of a
8448      * regular element and hence incrementing by 1
8449      */
8450     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8451         hw_cons++;
8452     }
8453
8454     /*
8455      * This function may never run in parallel with itself for a
8456      * specific sc and no need for a read memory barrier here.
8457      */
8458     sw_cons = sc->eq_cons;
8459     sw_prod = sc->eq_prod;
8460
8461     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8462           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8463
8464     for (;
8465          sw_cons != hw_cons;
8466          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8467
8468         elem = &sc->eq[EQ_DESC(sw_cons)];
8469
8470         /* elem CID originates from FW, actually LE */
8471         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8472         opcode = elem->message.opcode;
8473
8474         /* handle eq element */
8475         switch (opcode) {
8476
8477         case EVENT_RING_OPCODE_STAT_QUERY:
8478             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8479                   sc->stats_comp++);
8480             /* nothing to do with stats comp */
8481             goto next_spqe;
8482
8483         case EVENT_RING_OPCODE_CFC_DEL:
8484             /* handle according to cid range */
8485             /* we may want to verify here that the sc state is HALTING */
8486             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8487             q_obj = bxe_cid_to_q_obj(sc, cid);
8488             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8489                 break;
8490             }
8491             goto next_spqe;
8492
8493         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8494             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8495             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8496                 break;
8497             }
8498             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8499             goto next_spqe;
8500
8501         case EVENT_RING_OPCODE_START_TRAFFIC:
8502             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8503             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8504                 break;
8505             }
8506             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8507             goto next_spqe;
8508
8509         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8510             echo = elem->message.data.function_update_event.echo;
8511             if (echo == SWITCH_UPDATE) {
8512                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8513                 if (f_obj->complete_cmd(sc, f_obj,
8514                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8515                     break;
8516                 }
8517             }
8518             else {
8519                 BLOGD(sc, DBG_SP,
8520                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8521             }
8522             goto next_spqe;
8523
8524         case EVENT_RING_OPCODE_FORWARD_SETUP:
8525             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8526             if (q_obj->complete_cmd(sc, q_obj,
8527                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8528                 break;
8529             }
8530             goto next_spqe;
8531
8532         case EVENT_RING_OPCODE_FUNCTION_START:
8533             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8534             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8535                 break;
8536             }
8537             goto next_spqe;
8538
8539         case EVENT_RING_OPCODE_FUNCTION_STOP:
8540             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8541             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8542                 break;
8543             }
8544             goto next_spqe;
8545         }
8546
8547         switch (opcode | sc->state) {
8548         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8549         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8550             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8551             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8552             rss_raw->clear_pending(rss_raw);
8553             break;
8554
8555         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8556         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8557         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8558         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8559         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8560         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8561             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8562             bxe_handle_classification_eqe(sc, elem);
8563             break;
8564
8565         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8566         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8567         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8568             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8569             bxe_handle_mcast_eqe(sc);
8570             break;
8571
8572         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8573         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8574         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8575             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8576             bxe_handle_rx_mode_eqe(sc, elem);
8577             break;
8578
8579         default:
8580             /* unknown event log error and continue */
8581             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8582                   elem->message.opcode, sc->state);
8583         }
8584
8585 next_spqe:
8586         spqe_cnt++;
8587     } /* for */
8588
8589     mb();
8590     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8591
8592     sc->eq_cons = sw_cons;
8593     sc->eq_prod = sw_prod;
8594
8595     /* make sure that above mem writes were issued towards the memory */
8596     wmb();
8597
8598     /* update producer */
8599     bxe_update_eq_prod(sc, sc->eq_prod);
8600 }
8601
8602 static void
8603 bxe_handle_sp_tq(void *context,
8604                  int  pending)
8605 {
8606     struct bxe_softc *sc = (struct bxe_softc *)context;
8607     uint16_t status;
8608
8609     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8610
8611     /* what work needs to be performed? */
8612     status = bxe_update_dsb_idx(sc);
8613
8614     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8615
8616     /* HW attentions */
8617     if (status & BXE_DEF_SB_ATT_IDX) {
8618         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8619         bxe_attn_int(sc);
8620         status &= ~BXE_DEF_SB_ATT_IDX;
8621     }
8622
8623     /* SP events: STAT_QUERY and others */
8624     if (status & BXE_DEF_SB_IDX) {
8625         /* handle EQ completions */
8626         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8627         bxe_eq_int(sc);
8628         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8629                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8630         status &= ~BXE_DEF_SB_IDX;
8631     }
8632
8633     /* if status is non zero then something went wrong */
8634     if (__predict_false(status)) {
8635         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8636     }
8637
8638     /* ack status block only if something was actually handled */
8639     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8640                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8641
8642     /*
8643      * Must be called after the EQ processing (since eq leads to sriov
8644      * ramrod completion flows).
8645      * This flow may have been scheduled by the arrival of a ramrod
8646      * completion, or by the sriov code rescheduling itself.
8647      */
8648     // XXX bxe_iov_sp_task(sc);
8649
8650 }
8651
8652 static void
8653 bxe_handle_fp_tq(void *context,
8654                  int  pending)
8655 {
8656     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8657     struct bxe_softc *sc = fp->sc;
8658     uint8_t more_tx = FALSE;
8659     uint8_t more_rx = FALSE;
8660
8661     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8662
8663     /* XXX
8664      * IFF_DRV_RUNNING state can't be checked here since we process
8665      * slowpath events on a client queue during setup. Instead
8666      * we need to add a "process/continue" flag here that the driver
8667      * can use to tell the task here not to do anything.
8668      */
8669 #if 0
8670     if (!(sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
8671         return;
8672     }
8673 #endif
8674
8675     /* update the fastpath index */
8676     bxe_update_fp_sb_idx(fp);
8677
8678     /* XXX add loop here if ever support multiple tx CoS */
8679     /* fp->txdata[cos] */
8680     if (bxe_has_tx_work(fp)) {
8681         BXE_FP_TX_LOCK(fp);
8682         more_tx = bxe_txeof(sc, fp);
8683         BXE_FP_TX_UNLOCK(fp);
8684     }
8685
8686     if (bxe_has_rx_work(fp)) {
8687         more_rx = bxe_rxeof(sc, fp);
8688     }
8689
8690     if (more_rx /*|| more_tx*/) {
8691         /* still more work to do */
8692         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8693         return;
8694     }
8695
8696     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8697                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8698 }
8699
8700 static void
8701 bxe_task_fp(struct bxe_fastpath *fp)
8702 {
8703     struct bxe_softc *sc = fp->sc;
8704     uint8_t more_tx = FALSE;
8705     uint8_t more_rx = FALSE;
8706
8707     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8708
8709     /* update the fastpath index */
8710     bxe_update_fp_sb_idx(fp);
8711
8712     /* XXX add loop here if ever support multiple tx CoS */
8713     /* fp->txdata[cos] */
8714     if (bxe_has_tx_work(fp)) {
8715         BXE_FP_TX_LOCK(fp);
8716         more_tx = bxe_txeof(sc, fp);
8717         BXE_FP_TX_UNLOCK(fp);
8718     }
8719
8720     if (bxe_has_rx_work(fp)) {
8721         more_rx = bxe_rxeof(sc, fp);
8722     }
8723
8724     if (more_rx /*|| more_tx*/) {
8725         /* still more work to do, bail out if this ISR and process later */
8726         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8727         return;
8728     }
8729
8730     /*
8731      * Here we write the fastpath index taken before doing any tx or rx work.
8732      * It is very well possible other hw events occurred up to this point and
8733      * they were actually processed accordingly above. Since we're going to
8734      * write an older fastpath index, an interrupt is coming which we might
8735      * not do any work in.
8736      */
8737     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8738                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8739 }
8740
8741 /*
8742  * Legacy interrupt entry point.
8743  *
8744  * Verifies that the controller generated the interrupt and
8745  * then calls a separate routine to handle the various
8746  * interrupt causes: link, RX, and TX.
8747  */
8748 static void
8749 bxe_intr_legacy(void *xsc)
8750 {
8751     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8752     struct bxe_fastpath *fp;
8753     uint16_t status, mask;
8754     int i;
8755
8756     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8757
8758     /*
8759      * 0 for ustorm, 1 for cstorm
8760      * the bits returned from ack_int() are 0-15
8761      * bit 0 = attention status block
8762      * bit 1 = fast path status block
8763      * a mask of 0x2 or more = tx/rx event
8764      * a mask of 1 = slow path event
8765      */
8766
8767     status = bxe_ack_int(sc);
8768
8769     /* the interrupt is not for us */
8770     if (__predict_false(status == 0)) {
8771         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8772         return;
8773     }
8774
8775     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8776
8777     FOR_EACH_ETH_QUEUE(sc, i) {
8778         fp = &sc->fp[i];
8779         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8780         if (status & mask) {
8781             /* acknowledge and disable further fastpath interrupts */
8782             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8783             bxe_task_fp(fp);
8784             status &= ~mask;
8785         }
8786     }
8787
8788     if (__predict_false(status & 0x1)) {
8789         /* acknowledge and disable further slowpath interrupts */
8790         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8791
8792         /* schedule slowpath handler */
8793         taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8794
8795         status &= ~0x1;
8796     }
8797
8798     if (__predict_false(status)) {
8799         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8800     }
8801 }
8802
8803 /* slowpath interrupt entry point */
8804 static void
8805 bxe_intr_sp(void *xsc)
8806 {
8807     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8808
8809     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8810
8811     /* acknowledge and disable further slowpath interrupts */
8812     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8813
8814     /* schedule slowpath handler */
8815     taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8816 }
8817
8818 /* fastpath interrupt entry point */
8819 static void
8820 bxe_intr_fp(void *xfp)
8821 {
8822     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8823     struct bxe_softc *sc = fp->sc;
8824
8825     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8826
8827     BLOGD(sc, DBG_INTR,
8828           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8829           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8830
8831     /* acknowledge and disable further fastpath interrupts */
8832     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8833
8834     bxe_task_fp(fp);
8835 }
8836
8837 /* Release all interrupts allocated by the driver. */
8838 static void
8839 bxe_interrupt_free(struct bxe_softc *sc)
8840 {
8841     int i;
8842
8843     switch (sc->interrupt_mode) {
8844     case INTR_MODE_INTX:
8845         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8846         if (sc->intr[0].resource != NULL) {
8847             bus_release_resource(sc->dev,
8848                                  SYS_RES_IRQ,
8849                                  sc->intr[0].rid,
8850                                  sc->intr[0].resource);
8851         }
8852         break;
8853     case INTR_MODE_MSI:
8854         for (i = 0; i < sc->intr_count; i++) {
8855             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8856             if (sc->intr[i].resource && sc->intr[i].rid) {
8857                 bus_release_resource(sc->dev,
8858                                      SYS_RES_IRQ,
8859                                      sc->intr[i].rid,
8860                                      sc->intr[i].resource);
8861             }
8862         }
8863         pci_release_msi(sc->dev);
8864         break;
8865     case INTR_MODE_MSIX:
8866         for (i = 0; i < sc->intr_count; i++) {
8867             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8868             if (sc->intr[i].resource && sc->intr[i].rid) {
8869                 bus_release_resource(sc->dev,
8870                                      SYS_RES_IRQ,
8871                                      sc->intr[i].rid,
8872                                      sc->intr[i].resource);
8873             }
8874         }
8875         pci_release_msi(sc->dev);
8876         break;
8877     default:
8878         /* nothing to do as initial allocation failed */
8879         break;
8880     }
8881 }
8882
8883 /*
8884  * This function determines and allocates the appropriate
8885  * interrupt based on system capabilites and user request.
8886  *
8887  * The user may force a particular interrupt mode, specify
8888  * the number of receive queues, specify the method for
8889  * distribuitng received frames to receive queues, or use
8890  * the default settings which will automatically select the
8891  * best supported combination.  In addition, the OS may or
8892  * may not support certain combinations of these settings.
8893  * This routine attempts to reconcile the settings requested
8894  * by the user with the capabilites available from the system
8895  * to select the optimal combination of features.
8896  *
8897  * Returns:
8898  *   0 = Success, !0 = Failure.
8899  */
8900 static int
8901 bxe_interrupt_alloc(struct bxe_softc *sc)
8902 {
8903     int msix_count = 0;
8904     int msi_count = 0;
8905     int num_requested = 0;
8906     int num_allocated = 0;
8907     int rid, i, j;
8908     int rc;
8909
8910     /* get the number of available MSI/MSI-X interrupts from the OS */
8911     if (sc->interrupt_mode > 0) {
8912         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8913             msix_count = pci_msix_count(sc->dev);
8914         }
8915
8916         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8917             msi_count = pci_msi_count(sc->dev);
8918         }
8919
8920         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8921               msi_count, msix_count);
8922     }
8923
8924     do { /* try allocating MSI-X interrupt resources (at least 2) */
8925         if (sc->interrupt_mode != INTR_MODE_MSIX) {
8926             break;
8927         }
8928
8929         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
8930             (msix_count < 2)) {
8931             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8932             break;
8933         }
8934
8935         /* ask for the necessary number of MSI-X vectors */
8936         num_requested = min((sc->num_queues + 1), msix_count);
8937
8938         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
8939
8940         num_allocated = num_requested;
8941         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
8942             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
8943             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8944             break;
8945         }
8946
8947         if (num_allocated < 2) { /* possible? */
8948             BLOGE(sc, "MSI-X allocation less than 2!\n");
8949             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8950             pci_release_msi(sc->dev);
8951             break;
8952         }
8953
8954         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
8955               num_requested, num_allocated);
8956
8957         /* best effort so use the number of vectors allocated to us */
8958         sc->intr_count = num_allocated;
8959         sc->num_queues = num_allocated - 1;
8960
8961         rid = 1; /* initial resource identifier */
8962
8963         /* allocate the MSI-X vectors */
8964         for (i = 0; i < num_allocated; i++) {
8965             sc->intr[i].rid = (rid + i);
8966
8967             if ((sc->intr[i].resource =
8968                  bus_alloc_resource_any(sc->dev,
8969                                         SYS_RES_IRQ,
8970                                         &sc->intr[i].rid,
8971                                         RF_ACTIVE)) == NULL) {
8972                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
8973                       i, (rid + i));
8974
8975                 for (j = (i - 1); j >= 0; j--) {
8976                     bus_release_resource(sc->dev,
8977                                          SYS_RES_IRQ,
8978                                          sc->intr[j].rid,
8979                                          sc->intr[j].resource);
8980                 }
8981
8982                 sc->intr_count = 0;
8983                 sc->num_queues = 0;
8984                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8985                 pci_release_msi(sc->dev);
8986                 break;
8987             }
8988
8989             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
8990         }
8991     } while (0);
8992
8993     do { /* try allocating MSI vector resources (at least 2) */
8994         if (sc->interrupt_mode != INTR_MODE_MSI) {
8995             break;
8996         }
8997
8998         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
8999             (msi_count < 1)) {
9000             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9001             break;
9002         }
9003
9004         /* ask for a single MSI vector */
9005         num_requested = 1;
9006
9007         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9008
9009         num_allocated = num_requested;
9010         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9011             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9012             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9013             break;
9014         }
9015
9016         if (num_allocated != 1) { /* possible? */
9017             BLOGE(sc, "MSI allocation is not 1!\n");
9018             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9019             pci_release_msi(sc->dev);
9020             break;
9021         }
9022
9023         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9024               num_requested, num_allocated);
9025
9026         /* best effort so use the number of vectors allocated to us */
9027         sc->intr_count = num_allocated;
9028         sc->num_queues = num_allocated;
9029
9030         rid = 1; /* initial resource identifier */
9031
9032         sc->intr[0].rid = rid;
9033
9034         if ((sc->intr[0].resource =
9035              bus_alloc_resource_any(sc->dev,
9036                                     SYS_RES_IRQ,
9037                                     &sc->intr[0].rid,
9038                                     RF_ACTIVE)) == NULL) {
9039             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9040             sc->intr_count = 0;
9041             sc->num_queues = 0;
9042             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9043             pci_release_msi(sc->dev);
9044             break;
9045         }
9046
9047         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9048     } while (0);
9049
9050     do { /* try allocating INTx vector resources */
9051         if (sc->interrupt_mode != INTR_MODE_INTX) {
9052             break;
9053         }
9054
9055         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9056
9057         /* only one vector for INTx */
9058         sc->intr_count = 1;
9059         sc->num_queues = 1;
9060
9061         rid = 0; /* initial resource identifier */
9062
9063         sc->intr[0].rid = rid;
9064
9065         if ((sc->intr[0].resource =
9066              bus_alloc_resource_any(sc->dev,
9067                                     SYS_RES_IRQ,
9068                                     &sc->intr[0].rid,
9069                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9070             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9071             sc->intr_count = 0;
9072             sc->num_queues = 0;
9073             sc->interrupt_mode = -1; /* Failed! */
9074             break;
9075         }
9076
9077         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9078     } while (0);
9079
9080     if (sc->interrupt_mode == -1) {
9081         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9082         rc = 1;
9083     } else {
9084         BLOGD(sc, DBG_LOAD,
9085               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9086               sc->interrupt_mode, sc->num_queues);
9087         rc = 0;
9088     }
9089
9090     return (rc);
9091 }
9092
9093 static void
9094 bxe_interrupt_detach(struct bxe_softc *sc)
9095 {
9096     struct bxe_fastpath *fp;
9097     int i;
9098
9099     /* release interrupt resources */
9100     for (i = 0; i < sc->intr_count; i++) {
9101         if (sc->intr[i].resource && sc->intr[i].tag) {
9102             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9103             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9104         }
9105     }
9106
9107     for (i = 0; i < sc->num_queues; i++) {
9108         fp = &sc->fp[i];
9109         if (fp->tq) {
9110             taskqueue_drain(fp->tq, &fp->tq_task);
9111         }
9112
9113         for (i = 0; i < sc->num_queues; i++) {
9114             fp = &sc->fp[i];
9115             if (fp->tq != NULL) {
9116                 taskqueue_free(fp->tq);
9117                 fp->tq = NULL;
9118             }
9119         }
9120     }
9121
9122     if (sc->sp_tq) {
9123         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9124         taskqueue_free(sc->sp_tq);
9125         sc->sp_tq = NULL;
9126     }
9127 }
9128
9129 /*
9130  * Enables interrupts and attach to the ISR.
9131  *
9132  * When using multiple MSI/MSI-X vectors the first vector
9133  * is used for slowpath operations while all remaining
9134  * vectors are used for fastpath operations.  If only a
9135  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9136  * ISR must look for both slowpath and fastpath completions.
9137  */
9138 static int
9139 bxe_interrupt_attach(struct bxe_softc *sc)
9140 {
9141     struct bxe_fastpath *fp;
9142     int rc = 0;
9143     int i;
9144
9145     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9146              "bxe%d_sp_tq", sc->unit);
9147     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9148     sc->sp_tq = taskqueue_create_fast(sc->sp_tq_name, M_NOWAIT,
9149                                       taskqueue_thread_enqueue,
9150                                       &sc->sp_tq);
9151     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9152                             "%s", sc->sp_tq_name);
9153
9154
9155     for (i = 0; i < sc->num_queues; i++) {
9156         fp = &sc->fp[i];
9157         snprintf(fp->tq_name, sizeof(fp->tq_name),
9158                  "bxe%d_fp%d_tq", sc->unit, i);
9159         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9160         fp->tq = taskqueue_create_fast(fp->tq_name, M_NOWAIT,
9161                                        taskqueue_thread_enqueue,
9162                                        &fp->tq);
9163         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9164                                 "%s", fp->tq_name);
9165     }
9166
9167     /* setup interrupt handlers */
9168     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9169         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9170
9171         /*
9172          * Setup the interrupt handler. Note that we pass the driver instance
9173          * to the interrupt handler for the slowpath.
9174          */
9175         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9176                                  (INTR_TYPE_NET | INTR_MPSAFE),
9177                                  NULL, bxe_intr_sp, sc,
9178                                  &sc->intr[0].tag)) != 0) {
9179             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9180             goto bxe_interrupt_attach_exit;
9181         }
9182
9183         bus_describe_intr(sc->dev, sc->intr[0].resource,
9184                           sc->intr[0].tag, "sp");
9185
9186         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9187
9188         /* initialize the fastpath vectors (note the first was used for sp) */
9189         for (i = 0; i < sc->num_queues; i++) {
9190             fp = &sc->fp[i];
9191             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9192
9193             /*
9194              * Setup the interrupt handler. Note that we pass the
9195              * fastpath context to the interrupt handler in this
9196              * case.
9197              */
9198             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9199                                      (INTR_TYPE_NET | INTR_MPSAFE),
9200                                      NULL, bxe_intr_fp, fp,
9201                                      &sc->intr[i + 1].tag)) != 0) {
9202                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9203                       (i + 1), rc);
9204                 goto bxe_interrupt_attach_exit;
9205             }
9206
9207             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9208                               sc->intr[i + 1].tag, "fp%02d", i);
9209
9210             /* bind the fastpath instance to a cpu */
9211             if (sc->num_queues > 1) {
9212                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9213             }
9214
9215             fp->state = BXE_FP_STATE_IRQ;
9216         }
9217     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9218         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9219
9220         /*
9221          * Setup the interrupt handler. Note that we pass the
9222          * driver instance to the interrupt handler which
9223          * will handle both the slowpath and fastpath.
9224          */
9225         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9226                                  (INTR_TYPE_NET | INTR_MPSAFE),
9227                                  NULL, bxe_intr_legacy, sc,
9228                                  &sc->intr[0].tag)) != 0) {
9229             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9230             goto bxe_interrupt_attach_exit;
9231         }
9232
9233     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9234         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9235
9236         /*
9237          * Setup the interrupt handler. Note that we pass the
9238          * driver instance to the interrupt handler which
9239          * will handle both the slowpath and fastpath.
9240          */
9241         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9242                                  (INTR_TYPE_NET | INTR_MPSAFE),
9243                                  NULL, bxe_intr_legacy, sc,
9244                                  &sc->intr[0].tag)) != 0) {
9245             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9246             goto bxe_interrupt_attach_exit;
9247         }
9248     }
9249
9250 bxe_interrupt_attach_exit:
9251
9252     return (rc);
9253 }
9254
9255 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9256 static int  bxe_init_hw_common(struct bxe_softc *sc);
9257 static int  bxe_init_hw_port(struct bxe_softc *sc);
9258 static int  bxe_init_hw_func(struct bxe_softc *sc);
9259 static void bxe_reset_common(struct bxe_softc *sc);
9260 static void bxe_reset_port(struct bxe_softc *sc);
9261 static void bxe_reset_func(struct bxe_softc *sc);
9262 static int  bxe_gunzip_init(struct bxe_softc *sc);
9263 static void bxe_gunzip_end(struct bxe_softc *sc);
9264 static int  bxe_init_firmware(struct bxe_softc *sc);
9265 static void bxe_release_firmware(struct bxe_softc *sc);
9266
9267 static struct
9268 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9269     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9270     .init_hw_cmn      = bxe_init_hw_common,
9271     .init_hw_port     = bxe_init_hw_port,
9272     .init_hw_func     = bxe_init_hw_func,
9273
9274     .reset_hw_cmn     = bxe_reset_common,
9275     .reset_hw_port    = bxe_reset_port,
9276     .reset_hw_func    = bxe_reset_func,
9277
9278     .gunzip_init      = bxe_gunzip_init,
9279     .gunzip_end       = bxe_gunzip_end,
9280
9281     .init_fw          = bxe_init_firmware,
9282     .release_fw       = bxe_release_firmware,
9283 };
9284
9285 static void
9286 bxe_init_func_obj(struct bxe_softc *sc)
9287 {
9288     sc->dmae_ready = 0;
9289
9290     ecore_init_func_obj(sc,
9291                         &sc->func_obj,
9292                         BXE_SP(sc, func_rdata),
9293                         BXE_SP_MAPPING(sc, func_rdata),
9294                         BXE_SP(sc, func_afex_rdata),
9295                         BXE_SP_MAPPING(sc, func_afex_rdata),
9296                         &bxe_func_sp_drv);
9297 }
9298
9299 static int
9300 bxe_init_hw(struct bxe_softc *sc,
9301             uint32_t         load_code)
9302 {
9303     struct ecore_func_state_params func_params = { NULL };
9304     int rc;
9305
9306     /* prepare the parameters for function state transitions */
9307     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9308
9309     func_params.f_obj = &sc->func_obj;
9310     func_params.cmd = ECORE_F_CMD_HW_INIT;
9311
9312     func_params.params.hw_init.load_phase = load_code;
9313
9314     /*
9315      * Via a plethora of function pointers, we will eventually reach
9316      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9317      */
9318     rc = ecore_func_state_change(sc, &func_params);
9319
9320     return (rc);
9321 }
9322
9323 static void
9324 bxe_fill(struct bxe_softc *sc,
9325          uint32_t         addr,
9326          int              fill,
9327          uint32_t         len)
9328 {
9329     uint32_t i;
9330
9331     if (!(len % 4) && !(addr % 4)) {
9332         for (i = 0; i < len; i += 4) {
9333             REG_WR(sc, (addr + i), fill);
9334         }
9335     } else {
9336         for (i = 0; i < len; i++) {
9337             REG_WR8(sc, (addr + i), fill);
9338         }
9339     }
9340 }
9341
9342 /* writes FP SP data to FW - data_size in dwords */
9343 static void
9344 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9345                   int              fw_sb_id,
9346                   uint32_t         *sb_data_p,
9347                   uint32_t         data_size)
9348 {
9349     int index;
9350
9351     for (index = 0; index < data_size; index++) {
9352         REG_WR(sc,
9353                (BAR_CSTRORM_INTMEM +
9354                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9355                 (sizeof(uint32_t) * index)),
9356                *(sb_data_p + index));
9357     }
9358 }
9359
9360 static void
9361 bxe_zero_fp_sb(struct bxe_softc *sc,
9362                int              fw_sb_id)
9363 {
9364     struct hc_status_block_data_e2 sb_data_e2;
9365     struct hc_status_block_data_e1x sb_data_e1x;
9366     uint32_t *sb_data_p;
9367     uint32_t data_size = 0;
9368
9369     if (!CHIP_IS_E1x(sc)) {
9370         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9371         sb_data_e2.common.state = SB_DISABLED;
9372         sb_data_e2.common.p_func.vf_valid = FALSE;
9373         sb_data_p = (uint32_t *)&sb_data_e2;
9374         data_size = (sizeof(struct hc_status_block_data_e2) /
9375                      sizeof(uint32_t));
9376     } else {
9377         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9378         sb_data_e1x.common.state = SB_DISABLED;
9379         sb_data_e1x.common.p_func.vf_valid = FALSE;
9380         sb_data_p = (uint32_t *)&sb_data_e1x;
9381         data_size = (sizeof(struct hc_status_block_data_e1x) /
9382                      sizeof(uint32_t));
9383     }
9384
9385     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9386
9387     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9388              0, CSTORM_STATUS_BLOCK_SIZE);
9389     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9390              0, CSTORM_SYNC_BLOCK_SIZE);
9391 }
9392
9393 static void
9394 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9395                   struct hc_sp_status_block_data *sp_sb_data)
9396 {
9397     int i;
9398
9399     for (i = 0;
9400          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9401          i++) {
9402         REG_WR(sc,
9403                (BAR_CSTRORM_INTMEM +
9404                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9405                 (i * sizeof(uint32_t))),
9406                *((uint32_t *)sp_sb_data + i));
9407     }
9408 }
9409
9410 static void
9411 bxe_zero_sp_sb(struct bxe_softc *sc)
9412 {
9413     struct hc_sp_status_block_data sp_sb_data;
9414
9415     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9416
9417     sp_sb_data.state           = SB_DISABLED;
9418     sp_sb_data.p_func.vf_valid = FALSE;
9419
9420     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9421
9422     bxe_fill(sc,
9423              (BAR_CSTRORM_INTMEM +
9424               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9425               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9426     bxe_fill(sc,
9427              (BAR_CSTRORM_INTMEM +
9428               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9429               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9430 }
9431
9432 static void
9433 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9434                              int                       igu_sb_id,
9435                              int                       igu_seg_id)
9436 {
9437     hc_sm->igu_sb_id      = igu_sb_id;
9438     hc_sm->igu_seg_id     = igu_seg_id;
9439     hc_sm->timer_value    = 0xFF;
9440     hc_sm->time_to_expire = 0xFFFFFFFF;
9441 }
9442
9443 static void
9444 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9445 {
9446     /* zero out state machine indices */
9447
9448     /* rx indices */
9449     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9450
9451     /* tx indices */
9452     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9453     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9454     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9455     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9456
9457     /* map indices */
9458
9459     /* rx indices */
9460     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9461         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9462
9463     /* tx indices */
9464     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9465         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9466     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9467         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9468     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9469         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9470     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9471         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9472 }
9473
9474 static void
9475 bxe_init_sb(struct bxe_softc *sc,
9476             bus_addr_t       busaddr,
9477             int              vfid,
9478             uint8_t          vf_valid,
9479             int              fw_sb_id,
9480             int              igu_sb_id)
9481 {
9482     struct hc_status_block_data_e2  sb_data_e2;
9483     struct hc_status_block_data_e1x sb_data_e1x;
9484     struct hc_status_block_sm       *hc_sm_p;
9485     uint32_t *sb_data_p;
9486     int igu_seg_id;
9487     int data_size;
9488
9489     if (CHIP_INT_MODE_IS_BC(sc)) {
9490         igu_seg_id = HC_SEG_ACCESS_NORM;
9491     } else {
9492         igu_seg_id = IGU_SEG_ACCESS_NORM;
9493     }
9494
9495     bxe_zero_fp_sb(sc, fw_sb_id);
9496
9497     if (!CHIP_IS_E1x(sc)) {
9498         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9499         sb_data_e2.common.state = SB_ENABLED;
9500         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9501         sb_data_e2.common.p_func.vf_id = vfid;
9502         sb_data_e2.common.p_func.vf_valid = vf_valid;
9503         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9504         sb_data_e2.common.same_igu_sb_1b = TRUE;
9505         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9506         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9507         hc_sm_p = sb_data_e2.common.state_machine;
9508         sb_data_p = (uint32_t *)&sb_data_e2;
9509         data_size = (sizeof(struct hc_status_block_data_e2) /
9510                      sizeof(uint32_t));
9511         bxe_map_sb_state_machines(sb_data_e2.index_data);
9512     } else {
9513         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9514         sb_data_e1x.common.state = SB_ENABLED;
9515         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9516         sb_data_e1x.common.p_func.vf_id = 0xff;
9517         sb_data_e1x.common.p_func.vf_valid = FALSE;
9518         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9519         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9520         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9521         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9522         hc_sm_p = sb_data_e1x.common.state_machine;
9523         sb_data_p = (uint32_t *)&sb_data_e1x;
9524         data_size = (sizeof(struct hc_status_block_data_e1x) /
9525                      sizeof(uint32_t));
9526         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9527     }
9528
9529     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9530     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9531
9532     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9533
9534     /* write indices to HW - PCI guarantees endianity of regpairs */
9535     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9536 }
9537
9538 static inline uint8_t
9539 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9540 {
9541     if (CHIP_IS_E1x(fp->sc)) {
9542         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9543     } else {
9544         return (fp->cl_id);
9545     }
9546 }
9547
9548 static inline uint32_t
9549 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9550                            struct bxe_fastpath *fp)
9551 {
9552     uint32_t offset = BAR_USTRORM_INTMEM;
9553
9554     if (!CHIP_IS_E1x(sc)) {
9555         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9556     } else {
9557         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9558     }
9559
9560     return (offset);
9561 }
9562
9563 static void
9564 bxe_init_eth_fp(struct bxe_softc *sc,
9565                 int              idx)
9566 {
9567     struct bxe_fastpath *fp = &sc->fp[idx];
9568     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9569     unsigned long q_type = 0;
9570     int cos;
9571
9572     fp->sc    = sc;
9573     fp->index = idx;
9574
9575     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9576     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9577
9578     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9579                     (SC_L_ID(sc) + idx) :
9580                     /* want client ID same as IGU SB ID for non-E1 */
9581                     fp->igu_sb_id;
9582     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9583
9584     /* setup sb indices */
9585     if (!CHIP_IS_E1x(sc)) {
9586         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9587         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9588     } else {
9589         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9590         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9591     }
9592
9593     /* init shortcut */
9594     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9595
9596     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9597
9598     /*
9599      * XXX If multiple CoS is ever supported then each fastpath structure
9600      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9601      */
9602     for (cos = 0; cos < sc->max_cos; cos++) {
9603         cids[cos] = idx;
9604     }
9605     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9606
9607     /* nothing more for a VF to do */
9608     if (IS_VF(sc)) {
9609         return;
9610     }
9611
9612     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9613                 fp->fw_sb_id, fp->igu_sb_id);
9614
9615     bxe_update_fp_sb_idx(fp);
9616
9617     /* Configure Queue State object */
9618     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9619     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9620
9621     ecore_init_queue_obj(sc,
9622                          &sc->sp_objs[idx].q_obj,
9623                          fp->cl_id,
9624                          cids,
9625                          sc->max_cos,
9626                          SC_FUNC(sc),
9627                          BXE_SP(sc, q_rdata),
9628                          BXE_SP_MAPPING(sc, q_rdata),
9629                          q_type);
9630
9631     /* configure classification DBs */
9632     ecore_init_mac_obj(sc,
9633                        &sc->sp_objs[idx].mac_obj,
9634                        fp->cl_id,
9635                        idx,
9636                        SC_FUNC(sc),
9637                        BXE_SP(sc, mac_rdata),
9638                        BXE_SP_MAPPING(sc, mac_rdata),
9639                        ECORE_FILTER_MAC_PENDING,
9640                        &sc->sp_state,
9641                        ECORE_OBJ_TYPE_RX_TX,
9642                        &sc->macs_pool);
9643
9644     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9645           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9646 }
9647
9648 static inline void
9649 bxe_update_rx_prod(struct bxe_softc    *sc,
9650                    struct bxe_fastpath *fp,
9651                    uint16_t            rx_bd_prod,
9652                    uint16_t            rx_cq_prod,
9653                    uint16_t            rx_sge_prod)
9654 {
9655     struct ustorm_eth_rx_producers rx_prods = { 0 };
9656     uint32_t i;
9657
9658     /* update producers */
9659     rx_prods.bd_prod  = rx_bd_prod;
9660     rx_prods.cqe_prod = rx_cq_prod;
9661     rx_prods.sge_prod = rx_sge_prod;
9662
9663     /*
9664      * Make sure that the BD and SGE data is updated before updating the
9665      * producers since FW might read the BD/SGE right after the producer
9666      * is updated.
9667      * This is only applicable for weak-ordered memory model archs such
9668      * as IA-64. The following barrier is also mandatory since FW will
9669      * assumes BDs must have buffers.
9670      */
9671     wmb();
9672
9673     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9674         REG_WR(sc,
9675                (fp->ustorm_rx_prods_offset + (i * 4)),
9676                ((uint32_t *)&rx_prods)[i]);
9677     }
9678
9679     wmb(); /* keep prod updates ordered */
9680
9681     BLOGD(sc, DBG_RX,
9682           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9683           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9684 }
9685
9686 static void
9687 bxe_init_rx_rings(struct bxe_softc *sc)
9688 {
9689     struct bxe_fastpath *fp;
9690     int i;
9691
9692     for (i = 0; i < sc->num_queues; i++) {
9693         fp = &sc->fp[i];
9694
9695         fp->rx_bd_cons = 0;
9696
9697         /*
9698          * Activate the BD ring...
9699          * Warning, this will generate an interrupt (to the TSTORM)
9700          * so this can only be done after the chip is initialized
9701          */
9702         bxe_update_rx_prod(sc, fp,
9703                            fp->rx_bd_prod,
9704                            fp->rx_cq_prod,
9705                            fp->rx_sge_prod);
9706
9707         if (i != 0) {
9708             continue;
9709         }
9710
9711         if (CHIP_IS_E1(sc)) {
9712             REG_WR(sc,
9713                    (BAR_USTRORM_INTMEM +
9714                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9715                    U64_LO(fp->rcq_dma.paddr));
9716             REG_WR(sc,
9717                    (BAR_USTRORM_INTMEM +
9718                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9719                    U64_HI(fp->rcq_dma.paddr));
9720         }
9721     }
9722 }
9723
9724 static void
9725 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9726 {
9727     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9728     fp->tx_db.data.zero_fill1 = 0;
9729     fp->tx_db.data.prod = 0;
9730
9731     fp->tx_pkt_prod = 0;
9732     fp->tx_pkt_cons = 0;
9733     fp->tx_bd_prod = 0;
9734     fp->tx_bd_cons = 0;
9735     fp->eth_q_stats.tx_pkts = 0;
9736 }
9737
9738 static inline void
9739 bxe_init_tx_rings(struct bxe_softc *sc)
9740 {
9741     int i;
9742
9743     for (i = 0; i < sc->num_queues; i++) {
9744         bxe_init_tx_ring_one(&sc->fp[i]);
9745     }
9746 }
9747
9748 static void
9749 bxe_init_def_sb(struct bxe_softc *sc)
9750 {
9751     struct host_sp_status_block *def_sb = sc->def_sb;
9752     bus_addr_t mapping = sc->def_sb_dma.paddr;
9753     int igu_sp_sb_index;
9754     int igu_seg_id;
9755     int port = SC_PORT(sc);
9756     int func = SC_FUNC(sc);
9757     int reg_offset, reg_offset_en5;
9758     uint64_t section;
9759     int index, sindex;
9760     struct hc_sp_status_block_data sp_sb_data;
9761
9762     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9763
9764     if (CHIP_INT_MODE_IS_BC(sc)) {
9765         igu_sp_sb_index = DEF_SB_IGU_ID;
9766         igu_seg_id = HC_SEG_ACCESS_DEF;
9767     } else {
9768         igu_sp_sb_index = sc->igu_dsb_id;
9769         igu_seg_id = IGU_SEG_ACCESS_DEF;
9770     }
9771
9772     /* attentions */
9773     section = ((uint64_t)mapping +
9774                offsetof(struct host_sp_status_block, atten_status_block));
9775     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9776     sc->attn_state = 0;
9777
9778     reg_offset = (port) ?
9779                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9780                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9781     reg_offset_en5 = (port) ?
9782                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9783                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9784
9785     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9786         /* take care of sig[0]..sig[4] */
9787         for (sindex = 0; sindex < 4; sindex++) {
9788             sc->attn_group[index].sig[sindex] =
9789                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9790         }
9791
9792         if (!CHIP_IS_E1x(sc)) {
9793             /*
9794              * enable5 is separate from the rest of the registers,
9795              * and the address skip is 4 and not 16 between the
9796              * different groups
9797              */
9798             sc->attn_group[index].sig[4] =
9799                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9800         } else {
9801             sc->attn_group[index].sig[4] = 0;
9802         }
9803     }
9804
9805     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9806         reg_offset = (port) ?
9807                          HC_REG_ATTN_MSG1_ADDR_L :
9808                          HC_REG_ATTN_MSG0_ADDR_L;
9809         REG_WR(sc, reg_offset, U64_LO(section));
9810         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9811     } else if (!CHIP_IS_E1x(sc)) {
9812         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9813         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9814     }
9815
9816     section = ((uint64_t)mapping +
9817                offsetof(struct host_sp_status_block, sp_sb));
9818
9819     bxe_zero_sp_sb(sc);
9820
9821     /* PCI guarantees endianity of regpair */
9822     sp_sb_data.state           = SB_ENABLED;
9823     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9824     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9825     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9826     sp_sb_data.igu_seg_id      = igu_seg_id;
9827     sp_sb_data.p_func.pf_id    = func;
9828     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9829     sp_sb_data.p_func.vf_id    = 0xff;
9830
9831     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9832
9833     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9834 }
9835
9836 static void
9837 bxe_init_sp_ring(struct bxe_softc *sc)
9838 {
9839     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9840     sc->spq_prod_idx = 0;
9841     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9842     sc->spq_prod_bd = sc->spq;
9843     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9844 }
9845
9846 static void
9847 bxe_init_eq_ring(struct bxe_softc *sc)
9848 {
9849     union event_ring_elem *elem;
9850     int i;
9851
9852     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9853         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9854
9855         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9856                                                  BCM_PAGE_SIZE *
9857                                                  (i % NUM_EQ_PAGES)));
9858         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9859                                                  BCM_PAGE_SIZE *
9860                                                  (i % NUM_EQ_PAGES)));
9861     }
9862
9863     sc->eq_cons    = 0;
9864     sc->eq_prod    = NUM_EQ_DESC;
9865     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9866
9867     atomic_store_rel_long(&sc->eq_spq_left,
9868                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9869                                NUM_EQ_DESC) - 1));
9870 }
9871
9872 static void
9873 bxe_init_internal_common(struct bxe_softc *sc)
9874 {
9875     int i;
9876
9877     /*
9878      * Zero this manually as its initialization is currently missing
9879      * in the initTool.
9880      */
9881     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9882         REG_WR(sc,
9883                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9884                0);
9885     }
9886
9887     if (!CHIP_IS_E1x(sc)) {
9888         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9889                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9890     }
9891 }
9892
9893 static void
9894 bxe_init_internal(struct bxe_softc *sc,
9895                   uint32_t         load_code)
9896 {
9897     switch (load_code) {
9898     case FW_MSG_CODE_DRV_LOAD_COMMON:
9899     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9900         bxe_init_internal_common(sc);
9901         /* no break */
9902
9903     case FW_MSG_CODE_DRV_LOAD_PORT:
9904         /* nothing to do */
9905         /* no break */
9906
9907     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9908         /* internal memory per function is initialized inside bxe_pf_init */
9909         break;
9910
9911     default:
9912         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9913         break;
9914     }
9915 }
9916
9917 static void
9918 storm_memset_func_cfg(struct bxe_softc                         *sc,
9919                       struct tstorm_eth_function_common_config *tcfg,
9920                       uint16_t                                  abs_fid)
9921 {
9922     uint32_t addr;
9923     size_t size;
9924
9925     addr = (BAR_TSTRORM_INTMEM +
9926             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
9927     size = sizeof(struct tstorm_eth_function_common_config);
9928     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
9929 }
9930
9931 static void
9932 bxe_func_init(struct bxe_softc            *sc,
9933               struct bxe_func_init_params *p)
9934 {
9935     struct tstorm_eth_function_common_config tcfg = { 0 };
9936
9937     if (CHIP_IS_E1x(sc)) {
9938         storm_memset_func_cfg(sc, &tcfg, p->func_id);
9939     }
9940
9941     /* Enable the function in the FW */
9942     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
9943     storm_memset_func_en(sc, p->func_id, 1);
9944
9945     /* spq */
9946     if (p->func_flgs & FUNC_FLG_SPQ) {
9947         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
9948         REG_WR(sc,
9949                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
9950                p->spq_prod);
9951     }
9952 }
9953
9954 /*
9955  * Calculates the sum of vn_min_rates.
9956  * It's needed for further normalizing of the min_rates.
9957  * Returns:
9958  *   sum of vn_min_rates.
9959  *     or
9960  *   0 - if all the min_rates are 0.
9961  * In the later case fainess algorithm should be deactivated.
9962  * If all min rates are not zero then those that are zeroes will be set to 1.
9963  */
9964 static void
9965 bxe_calc_vn_min(struct bxe_softc       *sc,
9966                 struct cmng_init_input *input)
9967 {
9968     uint32_t vn_cfg;
9969     uint32_t vn_min_rate;
9970     int all_zero = 1;
9971     int vn;
9972
9973     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
9974         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9975         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
9976                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
9977
9978         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9979             /* skip hidden VNs */
9980             vn_min_rate = 0;
9981         } else if (!vn_min_rate) {
9982             /* If min rate is zero - set it to 100 */
9983             vn_min_rate = DEF_MIN_RATE;
9984         } else {
9985             all_zero = 0;
9986         }
9987
9988         input->vnic_min_rate[vn] = vn_min_rate;
9989     }
9990
9991     /* if ETS or all min rates are zeros - disable fairness */
9992     if (BXE_IS_ETS_ENABLED(sc)) {
9993         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9994         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
9995     } else if (all_zero) {
9996         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9997         BLOGD(sc, DBG_LOAD,
9998               "Fariness disabled (all MIN values are zeroes)\n");
9999     } else {
10000         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10001     }
10002 }
10003
10004 static inline uint16_t
10005 bxe_extract_max_cfg(struct bxe_softc *sc,
10006                     uint32_t         mf_cfg)
10007 {
10008     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10009                         FUNC_MF_CFG_MAX_BW_SHIFT);
10010
10011     if (!max_cfg) {
10012         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10013         max_cfg = 100;
10014     }
10015
10016     return (max_cfg);
10017 }
10018
10019 static void
10020 bxe_calc_vn_max(struct bxe_softc       *sc,
10021                 int                    vn,
10022                 struct cmng_init_input *input)
10023 {
10024     uint16_t vn_max_rate;
10025     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10026     uint32_t max_cfg;
10027
10028     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10029         vn_max_rate = 0;
10030     } else {
10031         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10032
10033         if (IS_MF_SI(sc)) {
10034             /* max_cfg in percents of linkspeed */
10035             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10036         } else { /* SD modes */
10037             /* max_cfg is absolute in 100Mb units */
10038             vn_max_rate = (max_cfg * 100);
10039         }
10040     }
10041
10042     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10043
10044     input->vnic_max_rate[vn] = vn_max_rate;
10045 }
10046
10047 static void
10048 bxe_cmng_fns_init(struct bxe_softc *sc,
10049                   uint8_t          read_cfg,
10050                   uint8_t          cmng_type)
10051 {
10052     struct cmng_init_input input;
10053     int vn;
10054
10055     memset(&input, 0, sizeof(struct cmng_init_input));
10056
10057     input.port_rate = sc->link_vars.line_speed;
10058
10059     if (cmng_type == CMNG_FNS_MINMAX) {
10060         /* read mf conf from shmem */
10061         if (read_cfg) {
10062             bxe_read_mf_cfg(sc);
10063         }
10064
10065         /* get VN min rate and enable fairness if not 0 */
10066         bxe_calc_vn_min(sc, &input);
10067
10068         /* get VN max rate */
10069         if (sc->port.pmf) {
10070             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10071                 bxe_calc_vn_max(sc, vn, &input);
10072             }
10073         }
10074
10075         /* always enable rate shaping and fairness */
10076         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10077
10078         ecore_init_cmng(&input, &sc->cmng);
10079         return;
10080     }
10081
10082     /* rate shaping and fairness are disabled */
10083     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10084 }
10085
10086 static int
10087 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10088 {
10089     if (CHIP_REV_IS_SLOW(sc)) {
10090         return (CMNG_FNS_NONE);
10091     }
10092
10093     if (IS_MF(sc)) {
10094         return (CMNG_FNS_MINMAX);
10095     }
10096
10097     return (CMNG_FNS_NONE);
10098 }
10099
10100 static void
10101 storm_memset_cmng(struct bxe_softc *sc,
10102                   struct cmng_init *cmng,
10103                   uint8_t          port)
10104 {
10105     int vn;
10106     int func;
10107     uint32_t addr;
10108     size_t size;
10109
10110     addr = (BAR_XSTRORM_INTMEM +
10111             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10112     size = sizeof(struct cmng_struct_per_port);
10113     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10114
10115     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10116         func = func_by_vn(sc, vn);
10117
10118         addr = (BAR_XSTRORM_INTMEM +
10119                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10120         size = sizeof(struct rate_shaping_vars_per_vn);
10121         ecore_storm_memset_struct(sc, addr, size,
10122                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10123
10124         addr = (BAR_XSTRORM_INTMEM +
10125                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10126         size = sizeof(struct fairness_vars_per_vn);
10127         ecore_storm_memset_struct(sc, addr, size,
10128                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10129     }
10130 }
10131
10132 static void
10133 bxe_pf_init(struct bxe_softc *sc)
10134 {
10135     struct bxe_func_init_params func_init = { 0 };
10136     struct event_ring_data eq_data = { { 0 } };
10137     uint16_t flags;
10138
10139     if (!CHIP_IS_E1x(sc)) {
10140         /* reset IGU PF statistics: MSIX + ATTN */
10141         /* PF */
10142         REG_WR(sc,
10143                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10144                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10145                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10146                0);
10147         /* ATTN */
10148         REG_WR(sc,
10149                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10150                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10151                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10152                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10153                0);
10154     }
10155
10156     /* function setup flags */
10157     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10158
10159     /*
10160      * This flag is relevant for E1x only.
10161      * E2 doesn't have a TPA configuration in a function level.
10162      */
10163     flags |= (sc->ifnet->if_capenable & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10164
10165     func_init.func_flgs = flags;
10166     func_init.pf_id     = SC_FUNC(sc);
10167     func_init.func_id   = SC_FUNC(sc);
10168     func_init.spq_map   = sc->spq_dma.paddr;
10169     func_init.spq_prod  = sc->spq_prod_idx;
10170
10171     bxe_func_init(sc, &func_init);
10172
10173     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10174
10175     /*
10176      * Congestion management values depend on the link rate.
10177      * There is no active link so initial link rate is set to 10Gbps.
10178      * When the link comes up the congestion management values are
10179      * re-calculated according to the actual link rate.
10180      */
10181     sc->link_vars.line_speed = SPEED_10000;
10182     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10183
10184     /* Only the PMF sets the HW */
10185     if (sc->port.pmf) {
10186         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10187     }
10188
10189     /* init Event Queue - PCI bus guarantees correct endainity */
10190     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10191     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10192     eq_data.producer     = sc->eq_prod;
10193     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10194     eq_data.sb_id        = DEF_SB_ID;
10195     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10196 }
10197
10198 static void
10199 bxe_hc_int_enable(struct bxe_softc *sc)
10200 {
10201     int port = SC_PORT(sc);
10202     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10203     uint32_t val = REG_RD(sc, addr);
10204     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10205     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10206                            (sc->intr_count == 1)) ? TRUE : FALSE;
10207     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10208
10209     if (msix) {
10210         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10211                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10212         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10213                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10214         if (single_msix) {
10215             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10216         }
10217     } else if (msi) {
10218         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10219         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10220                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10221                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10222     } else {
10223         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10224                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10225                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10226                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10227
10228         if (!CHIP_IS_E1(sc)) {
10229             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10230                   val, port, addr);
10231
10232             REG_WR(sc, addr, val);
10233
10234             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10235         }
10236     }
10237
10238     if (CHIP_IS_E1(sc)) {
10239         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10240     }
10241
10242     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10243           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10244
10245     REG_WR(sc, addr, val);
10246
10247     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10248     mb();
10249
10250     if (!CHIP_IS_E1(sc)) {
10251         /* init leading/trailing edge */
10252         if (IS_MF(sc)) {
10253             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10254             if (sc->port.pmf) {
10255                 /* enable nig and gpio3 attention */
10256                 val |= 0x1100;
10257             }
10258         } else {
10259             val = 0xffff;
10260         }
10261
10262         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10263         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10264     }
10265
10266     /* make sure that interrupts are indeed enabled from here on */
10267     mb();
10268 }
10269
10270 static void
10271 bxe_igu_int_enable(struct bxe_softc *sc)
10272 {
10273     uint32_t val;
10274     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10275     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10276                            (sc->intr_count == 1)) ? TRUE : FALSE;
10277     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10278
10279     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10280
10281     if (msix) {
10282         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10283                  IGU_PF_CONF_SINGLE_ISR_EN);
10284         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10285                 IGU_PF_CONF_ATTN_BIT_EN);
10286         if (single_msix) {
10287             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10288         }
10289     } else if (msi) {
10290         val &= ~IGU_PF_CONF_INT_LINE_EN;
10291         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10292                 IGU_PF_CONF_ATTN_BIT_EN |
10293                 IGU_PF_CONF_SINGLE_ISR_EN);
10294     } else {
10295         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10296         val |= (IGU_PF_CONF_INT_LINE_EN |
10297                 IGU_PF_CONF_ATTN_BIT_EN |
10298                 IGU_PF_CONF_SINGLE_ISR_EN);
10299     }
10300
10301     /* clean previous status - need to configure igu prior to ack*/
10302     if ((!msix) || single_msix) {
10303         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10304         bxe_ack_int(sc);
10305     }
10306
10307     val |= IGU_PF_CONF_FUNC_EN;
10308
10309     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10310           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10311
10312     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10313
10314     mb();
10315
10316     /* init leading/trailing edge */
10317     if (IS_MF(sc)) {
10318         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10319         if (sc->port.pmf) {
10320             /* enable nig and gpio3 attention */
10321             val |= 0x1100;
10322         }
10323     } else {
10324         val = 0xffff;
10325     }
10326
10327     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10328     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10329
10330     /* make sure that interrupts are indeed enabled from here on */
10331     mb();
10332 }
10333
10334 static void
10335 bxe_int_enable(struct bxe_softc *sc)
10336 {
10337     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10338         bxe_hc_int_enable(sc);
10339     } else {
10340         bxe_igu_int_enable(sc);
10341     }
10342 }
10343
10344 static void
10345 bxe_hc_int_disable(struct bxe_softc *sc)
10346 {
10347     int port = SC_PORT(sc);
10348     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10349     uint32_t val = REG_RD(sc, addr);
10350
10351     /*
10352      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10353      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10354      * block
10355      */
10356     if (CHIP_IS_E1(sc)) {
10357         /*
10358          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10359          * to prevent from HC sending interrupts after we exit the function
10360          */
10361         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10362
10363         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10364                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10365                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10366     } else {
10367         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10368                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10369                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10370                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10371     }
10372
10373     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10374
10375     /* flush all outstanding writes */
10376     mb();
10377
10378     REG_WR(sc, addr, val);
10379     if (REG_RD(sc, addr) != val) {
10380         BLOGE(sc, "proper val not read from HC IGU!\n");
10381     }
10382 }
10383
10384 static void
10385 bxe_igu_int_disable(struct bxe_softc *sc)
10386 {
10387     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10388
10389     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10390              IGU_PF_CONF_INT_LINE_EN |
10391              IGU_PF_CONF_ATTN_BIT_EN);
10392
10393     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10394
10395     /* flush all outstanding writes */
10396     mb();
10397
10398     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10399     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10400         BLOGE(sc, "proper val not read from IGU!\n");
10401     }
10402 }
10403
10404 static void
10405 bxe_int_disable(struct bxe_softc *sc)
10406 {
10407     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10408         bxe_hc_int_disable(sc);
10409     } else {
10410         bxe_igu_int_disable(sc);
10411     }
10412 }
10413
10414 static void
10415 bxe_nic_init(struct bxe_softc *sc,
10416              int              load_code)
10417 {
10418     int i;
10419
10420     for (i = 0; i < sc->num_queues; i++) {
10421         bxe_init_eth_fp(sc, i);
10422     }
10423
10424     rmb(); /* ensure status block indices were read */
10425
10426     bxe_init_rx_rings(sc);
10427     bxe_init_tx_rings(sc);
10428
10429     if (IS_VF(sc)) {
10430         return;
10431     }
10432
10433     /* initialize MOD_ABS interrupts */
10434     elink_init_mod_abs_int(sc, &sc->link_vars,
10435                            sc->devinfo.chip_id,
10436                            sc->devinfo.shmem_base,
10437                            sc->devinfo.shmem2_base,
10438                            SC_PORT(sc));
10439
10440     bxe_init_def_sb(sc);
10441     bxe_update_dsb_idx(sc);
10442     bxe_init_sp_ring(sc);
10443     bxe_init_eq_ring(sc);
10444     bxe_init_internal(sc, load_code);
10445     bxe_pf_init(sc);
10446     bxe_stats_init(sc);
10447
10448     /* flush all before enabling interrupts */
10449     mb();
10450
10451     bxe_int_enable(sc);
10452
10453     /* check for SPIO5 */
10454     bxe_attn_int_deasserted0(sc,
10455                              REG_RD(sc,
10456                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10457                                      SC_PORT(sc)*4)) &
10458                              AEU_INPUTS_ATTN_BITS_SPIO5);
10459 }
10460
10461 static inline void
10462 bxe_init_objs(struct bxe_softc *sc)
10463 {
10464     /* mcast rules must be added to tx if tx switching is enabled */
10465     ecore_obj_type o_type =
10466         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10467                                          ECORE_OBJ_TYPE_RX;
10468
10469     /* RX_MODE controlling object */
10470     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10471
10472     /* multicast configuration controlling object */
10473     ecore_init_mcast_obj(sc,
10474                          &sc->mcast_obj,
10475                          sc->fp[0].cl_id,
10476                          sc->fp[0].index,
10477                          SC_FUNC(sc),
10478                          SC_FUNC(sc),
10479                          BXE_SP(sc, mcast_rdata),
10480                          BXE_SP_MAPPING(sc, mcast_rdata),
10481                          ECORE_FILTER_MCAST_PENDING,
10482                          &sc->sp_state,
10483                          o_type);
10484
10485     /* Setup CAM credit pools */
10486     ecore_init_mac_credit_pool(sc,
10487                                &sc->macs_pool,
10488                                SC_FUNC(sc),
10489                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10490                                                  VNICS_PER_PATH(sc));
10491
10492     ecore_init_vlan_credit_pool(sc,
10493                                 &sc->vlans_pool,
10494                                 SC_ABS_FUNC(sc) >> 1,
10495                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10496                                                   VNICS_PER_PATH(sc));
10497
10498     /* RSS configuration object */
10499     ecore_init_rss_config_obj(sc,
10500                               &sc->rss_conf_obj,
10501                               sc->fp[0].cl_id,
10502                               sc->fp[0].index,
10503                               SC_FUNC(sc),
10504                               SC_FUNC(sc),
10505                               BXE_SP(sc, rss_rdata),
10506                               BXE_SP_MAPPING(sc, rss_rdata),
10507                               ECORE_FILTER_RSS_CONF_PENDING,
10508                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10509 }
10510
10511 /*
10512  * Initialize the function. This must be called before sending CLIENT_SETUP
10513  * for the first client.
10514  */
10515 static inline int
10516 bxe_func_start(struct bxe_softc *sc)
10517 {
10518     struct ecore_func_state_params func_params = { NULL };
10519     struct ecore_func_start_params *start_params = &func_params.params.start;
10520
10521     /* Prepare parameters for function state transitions */
10522     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10523
10524     func_params.f_obj = &sc->func_obj;
10525     func_params.cmd = ECORE_F_CMD_START;
10526
10527     /* Function parameters */
10528     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10529     start_params->sd_vlan_tag = OVLAN(sc);
10530
10531     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10532         start_params->network_cos_mode = STATIC_COS;
10533     } else { /* CHIP_IS_E1X */
10534         start_params->network_cos_mode = FW_WRR;
10535     }
10536
10537     //start_params->gre_tunnel_mode = 0;
10538     //start_params->gre_tunnel_rss  = 0;
10539
10540     return (ecore_func_state_change(sc, &func_params));
10541 }
10542
10543 static int
10544 bxe_set_power_state(struct bxe_softc *sc,
10545                     uint8_t          state)
10546 {
10547     uint16_t pmcsr;
10548
10549     /* If there is no power capability, silently succeed */
10550     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10551         BLOGW(sc, "No power capability\n");
10552         return (0);
10553     }
10554
10555     pmcsr = pci_read_config(sc->dev,
10556                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10557                             2);
10558
10559     switch (state) {
10560     case PCI_PM_D0:
10561         pci_write_config(sc->dev,
10562                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10563                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10564
10565         if (pmcsr & PCIM_PSTAT_DMASK) {
10566             /* delay required during transition out of D3hot */
10567             DELAY(20000);
10568         }
10569
10570         break;
10571
10572     case PCI_PM_D3hot:
10573         /* XXX if there are other clients above don't shut down the power */
10574
10575         /* don't shut down the power for emulation and FPGA */
10576         if (CHIP_REV_IS_SLOW(sc)) {
10577             return (0);
10578         }
10579
10580         pmcsr &= ~PCIM_PSTAT_DMASK;
10581         pmcsr |= PCIM_PSTAT_D3;
10582
10583         if (sc->wol) {
10584             pmcsr |= PCIM_PSTAT_PMEENABLE;
10585         }
10586
10587         pci_write_config(sc->dev,
10588                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10589                          pmcsr, 4);
10590
10591         /*
10592          * No more memory access after this point until device is brought back
10593          * to D0 state.
10594          */
10595         break;
10596
10597     default:
10598         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10599             state, pmcsr);
10600         return (-1);
10601     }
10602
10603     return (0);
10604 }
10605
10606
10607 /* return true if succeeded to acquire the lock */
10608 static uint8_t
10609 bxe_trylock_hw_lock(struct bxe_softc *sc,
10610                     uint32_t         resource)
10611 {
10612     uint32_t lock_status;
10613     uint32_t resource_bit = (1 << resource);
10614     int func = SC_FUNC(sc);
10615     uint32_t hw_lock_control_reg;
10616
10617     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10618
10619     /* Validating that the resource is within range */
10620     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10621         BLOGD(sc, DBG_LOAD,
10622               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10623               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10624         return (FALSE);
10625     }
10626
10627     if (func <= 5) {
10628         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10629     } else {
10630         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10631     }
10632
10633     /* try to acquire the lock */
10634     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10635     lock_status = REG_RD(sc, hw_lock_control_reg);
10636     if (lock_status & resource_bit) {
10637         return (TRUE);
10638     }
10639
10640     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10641         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10642         lock_status, resource_bit);
10643
10644     return (FALSE);
10645 }
10646
10647 /*
10648  * Get the recovery leader resource id according to the engine this function
10649  * belongs to. Currently only only 2 engines is supported.
10650  */
10651 static int
10652 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10653 {
10654     if (SC_PATH(sc)) {
10655         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10656     } else {
10657         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10658     }
10659 }
10660
10661 /* try to acquire a leader lock for current engine */
10662 static uint8_t
10663 bxe_trylock_leader_lock(struct bxe_softc *sc)
10664 {
10665     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10666 }
10667
10668 static int
10669 bxe_release_leader_lock(struct bxe_softc *sc)
10670 {
10671     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10672 }
10673
10674 /* close gates #2, #3 and #4 */
10675 static void
10676 bxe_set_234_gates(struct bxe_softc *sc,
10677                   uint8_t          close)
10678 {
10679     uint32_t val;
10680
10681     /* gates #2 and #4a are closed/opened for "not E1" only */
10682     if (!CHIP_IS_E1(sc)) {
10683         /* #4 */
10684         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10685         /* #2 */
10686         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10687     }
10688
10689     /* #3 */
10690     if (CHIP_IS_E1x(sc)) {
10691         /* prevent interrupts from HC on both ports */
10692         val = REG_RD(sc, HC_REG_CONFIG_1);
10693         REG_WR(sc, HC_REG_CONFIG_1,
10694                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10695                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10696
10697         val = REG_RD(sc, HC_REG_CONFIG_0);
10698         REG_WR(sc, HC_REG_CONFIG_0,
10699                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10700                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10701     } else {
10702         /* Prevent incomming interrupts in IGU */
10703         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10704
10705         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10706                (!close) ?
10707                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10708                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10709     }
10710
10711     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10712           close ? "closing" : "opening");
10713
10714     wmb();
10715 }
10716
10717 /* poll for pending writes bit, it should get cleared in no more than 1s */
10718 static int
10719 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10720 {
10721     uint32_t cnt = 1000;
10722     uint32_t pend_bits = 0;
10723
10724     do {
10725         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10726
10727         if (pend_bits == 0) {
10728             break;
10729         }
10730
10731         DELAY(1000);
10732     } while (--cnt > 0);
10733
10734     if (cnt == 0) {
10735         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10736         return (-1);
10737     }
10738
10739     return (0);
10740 }
10741
10742 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10743
10744 static void
10745 bxe_clp_reset_prep(struct bxe_softc *sc,
10746                    uint32_t         *magic_val)
10747 {
10748     /* Do some magic... */
10749     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10750     *magic_val = val & SHARED_MF_CLP_MAGIC;
10751     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10752 }
10753
10754 /* restore the value of the 'magic' bit */
10755 static void
10756 bxe_clp_reset_done(struct bxe_softc *sc,
10757                    uint32_t         magic_val)
10758 {
10759     /* Restore the 'magic' bit value... */
10760     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10761     MFCFG_WR(sc, shared_mf_config.clp_mb,
10762               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10763 }
10764
10765 /* prepare for MCP reset, takes care of CLP configurations */
10766 static void
10767 bxe_reset_mcp_prep(struct bxe_softc *sc,
10768                    uint32_t         *magic_val)
10769 {
10770     uint32_t shmem;
10771     uint32_t validity_offset;
10772
10773     /* set `magic' bit in order to save MF config */
10774     if (!CHIP_IS_E1(sc)) {
10775         bxe_clp_reset_prep(sc, magic_val);
10776     }
10777
10778     /* get shmem offset */
10779     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10780     validity_offset =
10781         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10782
10783     /* Clear validity map flags */
10784     if (shmem > 0) {
10785         REG_WR(sc, shmem + validity_offset, 0);
10786     }
10787 }
10788
10789 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10790 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10791
10792 static void
10793 bxe_mcp_wait_one(struct bxe_softc *sc)
10794 {
10795     /* special handling for emulation and FPGA (10 times longer) */
10796     if (CHIP_REV_IS_SLOW(sc)) {
10797         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10798     } else {
10799         DELAY((MCP_ONE_TIMEOUT) * 1000);
10800     }
10801 }
10802
10803 /* initialize shmem_base and waits for validity signature to appear */
10804 static int
10805 bxe_init_shmem(struct bxe_softc *sc)
10806 {
10807     int cnt = 0;
10808     uint32_t val = 0;
10809
10810     do {
10811         sc->devinfo.shmem_base     =
10812         sc->link_params.shmem_base =
10813             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10814
10815         if (sc->devinfo.shmem_base) {
10816             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10817             if (val & SHR_MEM_VALIDITY_MB)
10818                 return (0);
10819         }
10820
10821         bxe_mcp_wait_one(sc);
10822
10823     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10824
10825     BLOGE(sc, "BAD MCP validity signature\n");
10826
10827     return (-1);
10828 }
10829
10830 static int
10831 bxe_reset_mcp_comp(struct bxe_softc *sc,
10832                    uint32_t         magic_val)
10833 {
10834     int rc = bxe_init_shmem(sc);
10835
10836     /* Restore the `magic' bit value */
10837     if (!CHIP_IS_E1(sc)) {
10838         bxe_clp_reset_done(sc, magic_val);
10839     }
10840
10841     return (rc);
10842 }
10843
10844 static void
10845 bxe_pxp_prep(struct bxe_softc *sc)
10846 {
10847     if (!CHIP_IS_E1(sc)) {
10848         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10849         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10850         wmb();
10851     }
10852 }
10853
10854 /*
10855  * Reset the whole chip except for:
10856  *      - PCIE core
10857  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10858  *      - IGU
10859  *      - MISC (including AEU)
10860  *      - GRC
10861  *      - RBCN, RBCP
10862  */
10863 static void
10864 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10865                             uint8_t          global)
10866 {
10867     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10868     uint32_t global_bits2, stay_reset2;
10869
10870     /*
10871      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10872      * (per chip) blocks.
10873      */
10874     global_bits2 =
10875         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10876         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10877
10878     /*
10879      * Don't reset the following blocks.
10880      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10881      *            reset, as in 4 port device they might still be owned
10882      *            by the MCP (there is only one leader per path).
10883      */
10884     not_reset_mask1 =
10885         MISC_REGISTERS_RESET_REG_1_RST_HC |
10886         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10887         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10888
10889     not_reset_mask2 =
10890         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10891         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10892         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10893         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10894         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10895         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10896         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10897         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10898         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10899         MISC_REGISTERS_RESET_REG_2_PGLC |
10900         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10901         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10902         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10903         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10904         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10905         MISC_REGISTERS_RESET_REG_2_UMAC1;
10906
10907     /*
10908      * Keep the following blocks in reset:
10909      *  - all xxMACs are handled by the elink code.
10910      */
10911     stay_reset2 =
10912         MISC_REGISTERS_RESET_REG_2_XMAC |
10913         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10914
10915     /* Full reset masks according to the chip */
10916     reset_mask1 = 0xffffffff;
10917
10918     if (CHIP_IS_E1(sc))
10919         reset_mask2 = 0xffff;
10920     else if (CHIP_IS_E1H(sc))
10921         reset_mask2 = 0x1ffff;
10922     else if (CHIP_IS_E2(sc))
10923         reset_mask2 = 0xfffff;
10924     else /* CHIP_IS_E3 */
10925         reset_mask2 = 0x3ffffff;
10926
10927     /* Don't reset global blocks unless we need to */
10928     if (!global)
10929         reset_mask2 &= ~global_bits2;
10930
10931     /*
10932      * In case of attention in the QM, we need to reset PXP
10933      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
10934      * because otherwise QM reset would release 'close the gates' shortly
10935      * before resetting the PXP, then the PSWRQ would send a write
10936      * request to PGLUE. Then when PXP is reset, PGLUE would try to
10937      * read the payload data from PSWWR, but PSWWR would not
10938      * respond. The write queue in PGLUE would stuck, dmae commands
10939      * would not return. Therefore it's important to reset the second
10940      * reset register (containing the
10941      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
10942      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
10943      * bit).
10944      */
10945     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
10946            reset_mask2 & (~not_reset_mask2));
10947
10948     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
10949            reset_mask1 & (~not_reset_mask1));
10950
10951     mb();
10952     wmb();
10953
10954     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
10955            reset_mask2 & (~stay_reset2));
10956
10957     mb();
10958     wmb();
10959
10960     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
10961     wmb();
10962 }
10963
10964 static int
10965 bxe_process_kill(struct bxe_softc *sc,
10966                  uint8_t          global)
10967 {
10968     int cnt = 1000;
10969     uint32_t val = 0;
10970     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
10971     uint32_t tags_63_32 = 0;
10972
10973     /* Empty the Tetris buffer, wait for 1s */
10974     do {
10975         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
10976         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
10977         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
10978         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
10979         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
10980         if (CHIP_IS_E3(sc)) {
10981             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
10982         }
10983
10984         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
10985             ((port_is_idle_0 & 0x1) == 0x1) &&
10986             ((port_is_idle_1 & 0x1) == 0x1) &&
10987             (pgl_exp_rom2 == 0xffffffff) &&
10988             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
10989             break;
10990         DELAY(1000);
10991     } while (cnt-- > 0);
10992
10993     if (cnt <= 0) {
10994         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
10995                   "are still outstanding read requests after 1s! "
10996                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
10997                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
10998               sr_cnt, blk_cnt, port_is_idle_0,
10999               port_is_idle_1, pgl_exp_rom2);
11000         return (-1);
11001     }
11002
11003     mb();
11004
11005     /* Close gates #2, #3 and #4 */
11006     bxe_set_234_gates(sc, TRUE);
11007
11008     /* Poll for IGU VQs for 57712 and newer chips */
11009     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11010         return (-1);
11011     }
11012
11013     /* XXX indicate that "process kill" is in progress to MCP */
11014
11015     /* clear "unprepared" bit */
11016     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11017     mb();
11018
11019     /* Make sure all is written to the chip before the reset */
11020     wmb();
11021
11022     /*
11023      * Wait for 1ms to empty GLUE and PCI-E core queues,
11024      * PSWHST, GRC and PSWRD Tetris buffer.
11025      */
11026     DELAY(1000);
11027
11028     /* Prepare to chip reset: */
11029     /* MCP */
11030     if (global) {
11031         bxe_reset_mcp_prep(sc, &val);
11032     }
11033
11034     /* PXP */
11035     bxe_pxp_prep(sc);
11036     mb();
11037
11038     /* reset the chip */
11039     bxe_process_kill_chip_reset(sc, global);
11040     mb();
11041
11042     /* clear errors in PGB */
11043     if (!CHIP_IS_E1(sc))
11044         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11045
11046     /* Recover after reset: */
11047     /* MCP */
11048     if (global && bxe_reset_mcp_comp(sc, val)) {
11049         return (-1);
11050     }
11051
11052     /* XXX add resetting the NO_MCP mode DB here */
11053
11054     /* Open the gates #2, #3 and #4 */
11055     bxe_set_234_gates(sc, FALSE);
11056
11057     /* XXX
11058      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11059      * re-enable attentions
11060      */
11061
11062     return (0);
11063 }
11064
11065 static int
11066 bxe_leader_reset(struct bxe_softc *sc)
11067 {
11068     int rc = 0;
11069     uint8_t global = bxe_reset_is_global(sc);
11070     uint32_t load_code;
11071
11072     /*
11073      * If not going to reset MCP, load "fake" driver to reset HW while
11074      * driver is owner of the HW.
11075      */
11076     if (!global && !BXE_NOMCP(sc)) {
11077         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11078                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11079         if (!load_code) {
11080             BLOGE(sc, "MCP response failure, aborting\n");
11081             rc = -1;
11082             goto exit_leader_reset;
11083         }
11084
11085         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11086             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11087             BLOGE(sc, "MCP unexpected response, aborting\n");
11088             rc = -1;
11089             goto exit_leader_reset2;
11090         }
11091
11092         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11093         if (!load_code) {
11094             BLOGE(sc, "MCP response failure, aborting\n");
11095             rc = -1;
11096             goto exit_leader_reset2;
11097         }
11098     }
11099
11100     /* try to recover after the failure */
11101     if (bxe_process_kill(sc, global)) {
11102         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11103         rc = -1;
11104         goto exit_leader_reset2;
11105     }
11106
11107     /*
11108      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11109      * state.
11110      */
11111     bxe_set_reset_done(sc);
11112     if (global) {
11113         bxe_clear_reset_global(sc);
11114     }
11115
11116 exit_leader_reset2:
11117
11118     /* unload "fake driver" if it was loaded */
11119     if (!global && !BXE_NOMCP(sc)) {
11120         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11121         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11122     }
11123
11124 exit_leader_reset:
11125
11126     sc->is_leader = 0;
11127     bxe_release_leader_lock(sc);
11128
11129     mb();
11130     return (rc);
11131 }
11132
11133 /*
11134  * prepare INIT transition, parameters configured:
11135  *   - HC configuration
11136  *   - Queue's CDU context
11137  */
11138 static void
11139 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11140                    struct bxe_fastpath            *fp,
11141                    struct ecore_queue_init_params *init_params)
11142 {
11143     uint8_t cos;
11144     int cxt_index, cxt_offset;
11145
11146     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11147     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11148
11149     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11150     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11151
11152     /* HC rate */
11153     init_params->rx.hc_rate =
11154         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11155     init_params->tx.hc_rate =
11156         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11157
11158     /* FW SB ID */
11159     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11160
11161     /* CQ index among the SB indices */
11162     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11163     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11164
11165     /* set maximum number of COSs supported by this queue */
11166     init_params->max_cos = sc->max_cos;
11167
11168     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11169           fp->index, init_params->max_cos);
11170
11171     /* set the context pointers queue object */
11172     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11173         /* XXX change index/cid here if ever support multiple tx CoS */
11174         /* fp->txdata[cos]->cid */
11175         cxt_index = fp->index / ILT_PAGE_CIDS;
11176         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11177         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11178     }
11179 }
11180
11181 /* set flags that are common for the Tx-only and not normal connections */
11182 static unsigned long
11183 bxe_get_common_flags(struct bxe_softc    *sc,
11184                      struct bxe_fastpath *fp,
11185                      uint8_t             zero_stats)
11186 {
11187     unsigned long flags = 0;
11188
11189     /* PF driver will always initialize the Queue to an ACTIVE state */
11190     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11191
11192     /*
11193      * tx only connections collect statistics (on the same index as the
11194      * parent connection). The statistics are zeroed when the parent
11195      * connection is initialized.
11196      */
11197
11198     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11199     if (zero_stats) {
11200         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11201     }
11202
11203     /*
11204      * tx only connections can support tx-switching, though their
11205      * CoS-ness doesn't survive the loopback
11206      */
11207     if (sc->flags & BXE_TX_SWITCHING) {
11208         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11209     }
11210
11211     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11212
11213     return (flags);
11214 }
11215
11216 static unsigned long
11217 bxe_get_q_flags(struct bxe_softc    *sc,
11218                 struct bxe_fastpath *fp,
11219                 uint8_t             leading)
11220 {
11221     unsigned long flags = 0;
11222
11223     if (IS_MF_SD(sc)) {
11224         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11225     }
11226
11227     if (sc->ifnet->if_capenable & IFCAP_LRO) {
11228         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11229 #if __FreeBSD_version >= 800000
11230         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11231 #endif
11232     }
11233
11234     if (leading) {
11235         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11236         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11237     }
11238
11239     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11240
11241     /* merge with common flags */
11242     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11243 }
11244
11245 static void
11246 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11247                       struct bxe_fastpath               *fp,
11248                       struct ecore_general_setup_params *gen_init,
11249                       uint8_t                           cos)
11250 {
11251     gen_init->stat_id = bxe_stats_id(fp);
11252     gen_init->spcl_id = fp->cl_id;
11253     gen_init->mtu = sc->mtu;
11254     gen_init->cos = cos;
11255 }
11256
11257 static void
11258 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11259                  struct bxe_fastpath           *fp,
11260                  struct rxq_pause_params       *pause,
11261                  struct ecore_rxq_setup_params *rxq_init)
11262 {
11263     uint8_t max_sge = 0;
11264     uint16_t sge_sz = 0;
11265     uint16_t tpa_agg_size = 0;
11266
11267     pause->sge_th_lo = SGE_TH_LO(sc);
11268     pause->sge_th_hi = SGE_TH_HI(sc);
11269
11270     /* validate SGE ring has enough to cross high threshold */
11271     if (sc->dropless_fc &&
11272             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11273             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11274         BLOGW(sc, "sge ring threshold limit\n");
11275     }
11276
11277     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11278     tpa_agg_size = (2 * sc->mtu);
11279     if (tpa_agg_size < sc->max_aggregation_size) {
11280         tpa_agg_size = sc->max_aggregation_size;
11281     }
11282
11283     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11284     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11285                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11286     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11287
11288     /* pause - not for e1 */
11289     if (!CHIP_IS_E1(sc)) {
11290         pause->bd_th_lo = BD_TH_LO(sc);
11291         pause->bd_th_hi = BD_TH_HI(sc);
11292
11293         pause->rcq_th_lo = RCQ_TH_LO(sc);
11294         pause->rcq_th_hi = RCQ_TH_HI(sc);
11295
11296         /* validate rings have enough entries to cross high thresholds */
11297         if (sc->dropless_fc &&
11298             pause->bd_th_hi + FW_PREFETCH_CNT >
11299             sc->rx_ring_size) {
11300             BLOGW(sc, "rx bd ring threshold limit\n");
11301         }
11302
11303         if (sc->dropless_fc &&
11304             pause->rcq_th_hi + FW_PREFETCH_CNT >
11305             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11306             BLOGW(sc, "rcq ring threshold limit\n");
11307         }
11308
11309         pause->pri_map = 1;
11310     }
11311
11312     /* rxq setup */
11313     rxq_init->dscr_map   = fp->rx_dma.paddr;
11314     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11315     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11316     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11317
11318     /*
11319      * This should be a maximum number of data bytes that may be
11320      * placed on the BD (not including paddings).
11321      */
11322     rxq_init->buf_sz = (fp->rx_buf_size -
11323                         IP_HEADER_ALIGNMENT_PADDING);
11324
11325     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11326     rxq_init->tpa_agg_sz      = tpa_agg_size;
11327     rxq_init->sge_buf_sz      = sge_sz;
11328     rxq_init->max_sges_pkt    = max_sge;
11329     rxq_init->rss_engine_id   = SC_FUNC(sc);
11330     rxq_init->mcast_engine_id = SC_FUNC(sc);
11331
11332     /*
11333      * Maximum number or simultaneous TPA aggregation for this Queue.
11334      * For PF Clients it should be the maximum available number.
11335      * VF driver(s) may want to define it to a smaller value.
11336      */
11337     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11338
11339     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11340     rxq_init->fw_sb_id = fp->fw_sb_id;
11341
11342     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11343
11344     /*
11345      * configure silent vlan removal
11346      * if multi function mode is afex, then mask default vlan
11347      */
11348     if (IS_MF_AFEX(sc)) {
11349         rxq_init->silent_removal_value =
11350             sc->devinfo.mf_info.afex_def_vlan_tag;
11351         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11352     }
11353 }
11354
11355 static void
11356 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11357                  struct bxe_fastpath           *fp,
11358                  struct ecore_txq_setup_params *txq_init,
11359                  uint8_t                       cos)
11360 {
11361     /*
11362      * XXX If multiple CoS is ever supported then each fastpath structure
11363      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11364      * fp->txdata[cos]->tx_dma.paddr;
11365      */
11366     txq_init->dscr_map     = fp->tx_dma.paddr;
11367     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11368     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11369     txq_init->fw_sb_id     = fp->fw_sb_id;
11370
11371     /*
11372      * set the TSS leading client id for TX classfication to the
11373      * leading RSS client id
11374      */
11375     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11376 }
11377
11378 /*
11379  * This function performs 2 steps in a queue state machine:
11380  *   1) RESET->INIT
11381  *   2) INIT->SETUP
11382  */
11383 static int
11384 bxe_setup_queue(struct bxe_softc    *sc,
11385                 struct bxe_fastpath *fp,
11386                 uint8_t             leading)
11387 {
11388     struct ecore_queue_state_params q_params = { NULL };
11389     struct ecore_queue_setup_params *setup_params =
11390                         &q_params.params.setup;
11391     int rc;
11392
11393     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11394
11395     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11396
11397     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11398
11399     /* we want to wait for completion in this context */
11400     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11401
11402     /* prepare the INIT parameters */
11403     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11404
11405     /* Set the command */
11406     q_params.cmd = ECORE_Q_CMD_INIT;
11407
11408     /* Change the state to INIT */
11409     rc = ecore_queue_state_change(sc, &q_params);
11410     if (rc) {
11411         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11412         return (rc);
11413     }
11414
11415     BLOGD(sc, DBG_LOAD, "init complete\n");
11416
11417     /* now move the Queue to the SETUP state */
11418     memset(setup_params, 0, sizeof(*setup_params));
11419
11420     /* set Queue flags */
11421     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11422
11423     /* set general SETUP parameters */
11424     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11425                           FIRST_TX_COS_INDEX);
11426
11427     bxe_pf_rx_q_prep(sc, fp,
11428                      &setup_params->pause_params,
11429                      &setup_params->rxq_params);
11430
11431     bxe_pf_tx_q_prep(sc, fp,
11432                      &setup_params->txq_params,
11433                      FIRST_TX_COS_INDEX);
11434
11435     /* Set the command */
11436     q_params.cmd = ECORE_Q_CMD_SETUP;
11437
11438     /* change the state to SETUP */
11439     rc = ecore_queue_state_change(sc, &q_params);
11440     if (rc) {
11441         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11442         return (rc);
11443     }
11444
11445     return (rc);
11446 }
11447
11448 static int
11449 bxe_setup_leading(struct bxe_softc *sc)
11450 {
11451     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11452 }
11453
11454 static int
11455 bxe_config_rss_pf(struct bxe_softc            *sc,
11456                   struct ecore_rss_config_obj *rss_obj,
11457                   uint8_t                     config_hash)
11458 {
11459     struct ecore_config_rss_params params = { NULL };
11460     int i;
11461
11462     /*
11463      * Although RSS is meaningless when there is a single HW queue we
11464      * still need it enabled in order to have HW Rx hash generated.
11465      */
11466
11467     params.rss_obj = rss_obj;
11468
11469     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11470
11471     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11472
11473     /* RSS configuration */
11474     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11475     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11476     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11477     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11478     if (rss_obj->udp_rss_v4) {
11479         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11480     }
11481     if (rss_obj->udp_rss_v6) {
11482         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11483     }
11484
11485     /* Hash bits */
11486     params.rss_result_mask = MULTI_MASK;
11487
11488     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11489
11490     if (config_hash) {
11491         /* RSS keys */
11492         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11493             params.rss_key[i] = arc4random();
11494         }
11495
11496         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11497     }
11498
11499     return (ecore_config_rss(sc, &params));
11500 }
11501
11502 static int
11503 bxe_config_rss_eth(struct bxe_softc *sc,
11504                    uint8_t          config_hash)
11505 {
11506     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11507 }
11508
11509 static int
11510 bxe_init_rss_pf(struct bxe_softc *sc)
11511 {
11512     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11513     int i;
11514
11515     /*
11516      * Prepare the initial contents of the indirection table if
11517      * RSS is enabled
11518      */
11519     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11520         sc->rss_conf_obj.ind_table[i] =
11521             (sc->fp->cl_id + (i % num_eth_queues));
11522     }
11523
11524     if (sc->udp_rss) {
11525         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11526     }
11527
11528     /*
11529      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11530      * per-port, so if explicit configuration is needed, do it only
11531      * for a PMF.
11532      *
11533      * For 57712 and newer it's a per-function configuration.
11534      */
11535     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11536 }
11537
11538 static int
11539 bxe_set_mac_one(struct bxe_softc          *sc,
11540                 uint8_t                   *mac,
11541                 struct ecore_vlan_mac_obj *obj,
11542                 uint8_t                   set,
11543                 int                       mac_type,
11544                 unsigned long             *ramrod_flags)
11545 {
11546     struct ecore_vlan_mac_ramrod_params ramrod_param;
11547     int rc;
11548
11549     memset(&ramrod_param, 0, sizeof(ramrod_param));
11550
11551     /* fill in general parameters */
11552     ramrod_param.vlan_mac_obj = obj;
11553     ramrod_param.ramrod_flags = *ramrod_flags;
11554
11555     /* fill a user request section if needed */
11556     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11557         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11558
11559         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11560
11561         /* Set the command: ADD or DEL */
11562         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11563                                             ECORE_VLAN_MAC_DEL;
11564     }
11565
11566     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11567
11568     if (rc == ECORE_EXISTS) {
11569         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11570         /* do not treat adding same MAC as error */
11571         rc = 0;
11572     } else if (rc < 0) {
11573         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11574     }
11575
11576     return (rc);
11577 }
11578
11579 static int
11580 bxe_set_eth_mac(struct bxe_softc *sc,
11581                 uint8_t          set)
11582 {
11583     unsigned long ramrod_flags = 0;
11584
11585     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11586
11587     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11588
11589     /* Eth MAC is set on RSS leading client (fp[0]) */
11590     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11591                             &sc->sp_objs->mac_obj,
11592                             set, ECORE_ETH_MAC, &ramrod_flags));
11593 }
11594
11595 static int
11596 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11597 {
11598     uint32_t sel_phy_idx = 0;
11599
11600     if (sc->link_params.num_phys <= 1) {
11601         return (ELINK_INT_PHY);
11602     }
11603
11604     if (sc->link_vars.link_up) {
11605         sel_phy_idx = ELINK_EXT_PHY1;
11606         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11607         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11608             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11609              ELINK_SUPPORTED_FIBRE))
11610             sel_phy_idx = ELINK_EXT_PHY2;
11611     } else {
11612         switch (elink_phy_selection(&sc->link_params)) {
11613         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11614         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11615         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11616                sel_phy_idx = ELINK_EXT_PHY1;
11617                break;
11618         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11619         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11620                sel_phy_idx = ELINK_EXT_PHY2;
11621                break;
11622         }
11623     }
11624
11625     return (sel_phy_idx);
11626 }
11627
11628 static int
11629 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11630 {
11631     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11632
11633     /*
11634      * The selected activated PHY is always after swapping (in case PHY
11635      * swapping is enabled). So when swapping is enabled, we need to reverse
11636      * the configuration
11637      */
11638
11639     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11640         if (sel_phy_idx == ELINK_EXT_PHY1)
11641             sel_phy_idx = ELINK_EXT_PHY2;
11642         else if (sel_phy_idx == ELINK_EXT_PHY2)
11643             sel_phy_idx = ELINK_EXT_PHY1;
11644     }
11645
11646     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11647 }
11648
11649 static void
11650 bxe_set_requested_fc(struct bxe_softc *sc)
11651 {
11652     /*
11653      * Initialize link parameters structure variables
11654      * It is recommended to turn off RX FC for jumbo frames
11655      * for better performance
11656      */
11657     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11658         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11659     } else {
11660         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11661     }
11662 }
11663
11664 static void
11665 bxe_calc_fc_adv(struct bxe_softc *sc)
11666 {
11667     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11668
11669
11670     sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11671                                            ADVERTISED_Pause);
11672
11673     switch (sc->link_vars.ieee_fc &
11674             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11675
11676     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11677         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11678                                           ADVERTISED_Pause);
11679         break;
11680
11681     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11682         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11683         break;
11684
11685     default:
11686         break;
11687
11688     }
11689 }
11690
11691 static uint16_t
11692 bxe_get_mf_speed(struct bxe_softc *sc)
11693 {
11694     uint16_t line_speed = sc->link_vars.line_speed;
11695     if (IS_MF(sc)) {
11696         uint16_t maxCfg =
11697             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11698
11699         /* calculate the current MAX line speed limit for the MF devices */
11700         if (IS_MF_SI(sc)) {
11701             line_speed = (line_speed * maxCfg) / 100;
11702         } else { /* SD mode */
11703             uint16_t vn_max_rate = maxCfg * 100;
11704
11705             if (vn_max_rate < line_speed) {
11706                 line_speed = vn_max_rate;
11707             }
11708         }
11709     }
11710
11711     return (line_speed);
11712 }
11713
11714 static void
11715 bxe_fill_report_data(struct bxe_softc            *sc,
11716                      struct bxe_link_report_data *data)
11717 {
11718     uint16_t line_speed = bxe_get_mf_speed(sc);
11719
11720     memset(data, 0, sizeof(*data));
11721
11722     /* fill the report data with the effective line speed */
11723     data->line_speed = line_speed;
11724
11725     /* Link is down */
11726     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11727         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11728     }
11729
11730     /* Full DUPLEX */
11731     if (sc->link_vars.duplex == DUPLEX_FULL) {
11732         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11733     }
11734
11735     /* Rx Flow Control is ON */
11736     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11737         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11738     }
11739
11740     /* Tx Flow Control is ON */
11741     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11742         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11743     }
11744 }
11745
11746 /* report link status to OS, should be called under phy_lock */
11747 static void
11748 bxe_link_report_locked(struct bxe_softc *sc)
11749 {
11750     struct bxe_link_report_data cur_data;
11751
11752     /* reread mf_cfg */
11753     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11754         bxe_read_mf_cfg(sc);
11755     }
11756
11757     /* Read the current link report info */
11758     bxe_fill_report_data(sc, &cur_data);
11759
11760     /* Don't report link down or exactly the same link status twice */
11761     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11762         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11763                       &sc->last_reported_link.link_report_flags) &&
11764          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11765                       &cur_data.link_report_flags))) {
11766         return;
11767     }
11768
11769         ELINK_DEBUG_P2(sc, "Change in link status : cur_data = %x, last_reported_link = %x\n",
11770                                         cur_data.link_report_flags, sc->last_reported_link.link_report_flags);
11771     sc->link_cnt++;
11772
11773         ELINK_DEBUG_P1(sc, "link status change count = %x\n", sc->link_cnt);
11774     /* report new link params and remember the state for the next time */
11775     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11776
11777     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11778                      &cur_data.link_report_flags)) {
11779         if_link_state_change(sc->ifnet, LINK_STATE_DOWN);
11780     } else {
11781         const char *duplex;
11782         const char *flow;
11783
11784         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11785                                    &cur_data.link_report_flags)) {
11786             duplex = "full";
11787                         ELINK_DEBUG_P0(sc, "link set to full duplex\n");
11788         } else {
11789             duplex = "half";
11790                         ELINK_DEBUG_P0(sc, "link set to half duplex\n");
11791         }
11792
11793         /*
11794          * Handle the FC at the end so that only these flags would be
11795          * possibly set. This way we may easily check if there is no FC
11796          * enabled.
11797          */
11798         if (cur_data.link_report_flags) {
11799             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11800                              &cur_data.link_report_flags) &&
11801                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11802                              &cur_data.link_report_flags)) {
11803                 flow = "ON - receive & transmit";
11804             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11805                                     &cur_data.link_report_flags) &&
11806                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11807                                      &cur_data.link_report_flags)) {
11808                 flow = "ON - receive";
11809             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11810                                      &cur_data.link_report_flags) &&
11811                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11812                                     &cur_data.link_report_flags)) {
11813                 flow = "ON - transmit";
11814             } else {
11815                 flow = "none"; /* possible? */
11816             }
11817         } else {
11818             flow = "none";
11819         }
11820
11821         if_link_state_change(sc->ifnet, LINK_STATE_UP);
11822         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11823               cur_data.line_speed, duplex, flow);
11824     }
11825 }
11826
11827 static void
11828 bxe_link_report(struct bxe_softc *sc)
11829 {
11830     bxe_acquire_phy_lock(sc);
11831     bxe_link_report_locked(sc);
11832     bxe_release_phy_lock(sc);
11833 }
11834
11835 static void
11836 bxe_link_status_update(struct bxe_softc *sc)
11837 {
11838     if (sc->state != BXE_STATE_OPEN) {
11839         return;
11840     }
11841
11842     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11843         elink_link_status_update(&sc->link_params, &sc->link_vars);
11844     } else {
11845         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11846                                   ELINK_SUPPORTED_10baseT_Full |
11847                                   ELINK_SUPPORTED_100baseT_Half |
11848                                   ELINK_SUPPORTED_100baseT_Full |
11849                                   ELINK_SUPPORTED_1000baseT_Full |
11850                                   ELINK_SUPPORTED_2500baseX_Full |
11851                                   ELINK_SUPPORTED_10000baseT_Full |
11852                                   ELINK_SUPPORTED_TP |
11853                                   ELINK_SUPPORTED_FIBRE |
11854                                   ELINK_SUPPORTED_Autoneg |
11855                                   ELINK_SUPPORTED_Pause |
11856                                   ELINK_SUPPORTED_Asym_Pause);
11857         sc->port.advertising[0] = sc->port.supported[0];
11858
11859         sc->link_params.sc                = sc;
11860         sc->link_params.port              = SC_PORT(sc);
11861         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11862         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11863         sc->link_params.req_line_speed[0] = SPEED_10000;
11864         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11865         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11866
11867         if (CHIP_REV_IS_FPGA(sc)) {
11868             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11869             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11870             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11871                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11872         } else {
11873             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11874             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11875             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11876                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11877         }
11878
11879         sc->link_vars.link_up = 1;
11880
11881         sc->link_vars.duplex    = DUPLEX_FULL;
11882         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11883
11884         if (IS_PF(sc)) {
11885             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11886             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11887             bxe_link_report(sc);
11888         }
11889     }
11890
11891     if (IS_PF(sc)) {
11892         if (sc->link_vars.link_up) {
11893             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11894         } else {
11895             bxe_stats_handle(sc, STATS_EVENT_STOP);
11896         }
11897         bxe_link_report(sc);
11898     } else {
11899         bxe_link_report(sc);
11900         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11901     }
11902 }
11903
11904 static int
11905 bxe_initial_phy_init(struct bxe_softc *sc,
11906                      int              load_mode)
11907 {
11908     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11909     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11910     struct elink_params *lp = &sc->link_params;
11911
11912     bxe_set_requested_fc(sc);
11913
11914     if (CHIP_REV_IS_SLOW(sc)) {
11915         uint32_t bond = CHIP_BOND_ID(sc);
11916         uint32_t feat = 0;
11917
11918         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11919             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11920         } else if (bond & 0x4) {
11921             if (CHIP_IS_E3(sc)) {
11922                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11923             } else {
11924                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11925             }
11926         } else if (bond & 0x8) {
11927             if (CHIP_IS_E3(sc)) {
11928                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11929             } else {
11930                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11931             }
11932         }
11933
11934         /* disable EMAC for E3 and above */
11935         if (bond & 0x2) {
11936             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11937         }
11938
11939         sc->link_params.feature_config_flags |= feat;
11940     }
11941
11942     bxe_acquire_phy_lock(sc);
11943
11944     if (load_mode == LOAD_DIAG) {
11945         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
11946         /* Prefer doing PHY loopback at 10G speed, if possible */
11947         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
11948             if (lp->speed_cap_mask[cfg_idx] &
11949                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
11950                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
11951             } else {
11952                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
11953             }
11954         }
11955     }
11956
11957     if (load_mode == LOAD_LOOPBACK_EXT) {
11958         lp->loopback_mode = ELINK_LOOPBACK_EXT;
11959     }
11960
11961     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
11962
11963     bxe_release_phy_lock(sc);
11964
11965     bxe_calc_fc_adv(sc);
11966
11967     if (sc->link_vars.link_up) {
11968         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11969         bxe_link_report(sc);
11970     }
11971
11972     if (!CHIP_REV_IS_SLOW(sc)) {
11973         bxe_periodic_start(sc);
11974     }
11975
11976     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
11977     return (rc);
11978 }
11979
11980 /* must be called under IF_ADDR_LOCK */
11981 static int
11982 bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
11983                          struct ecore_mcast_ramrod_params *p)
11984 {
11985     struct ifnet *ifp = sc->ifnet;
11986     int mc_count = 0;
11987     struct ifmultiaddr *ifma;
11988     struct ecore_mcast_list_elem *mc_mac;
11989
11990     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
11991         if (ifma->ifma_addr->sa_family != AF_LINK) {
11992             continue;
11993         }
11994
11995         mc_count++;
11996     }
11997
11998     ECORE_LIST_INIT(&p->mcast_list);
11999     p->mcast_list_len = 0;
12000
12001     if (!mc_count) {
12002         return (0);
12003     }
12004
12005     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12006                     (M_NOWAIT | M_ZERO));
12007     if (!mc_mac) {
12008         BLOGE(sc, "Failed to allocate temp mcast list\n");
12009         return (-1);
12010     }
12011     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12012
12013     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12014         if (ifma->ifma_addr->sa_family != AF_LINK) {
12015             continue;
12016         }
12017
12018         mc_mac->mac = (uint8_t *)LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
12019         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &p->mcast_list);
12020
12021         BLOGD(sc, DBG_LOAD,
12022               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X and mc_count %d\n",
12023               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12024               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5], mc_count);
12025        mc_mac++;
12026     }
12027
12028     p->mcast_list_len = mc_count;
12029
12030     return (0);
12031 }
12032
12033 static void
12034 bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12035 {
12036     struct ecore_mcast_list_elem *mc_mac =
12037         ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12038                                struct ecore_mcast_list_elem,
12039                                link);
12040
12041     if (mc_mac) {
12042         /* only a single free as all mc_macs are in the same heap array */
12043         free(mc_mac, M_DEVBUF);
12044     }
12045 }
12046
12047 static int
12048 bxe_set_mc_list(struct bxe_softc *sc)
12049 {
12050     struct ecore_mcast_ramrod_params rparam = { NULL };
12051     int rc = 0;
12052
12053     rparam.mcast_obj = &sc->mcast_obj;
12054
12055     BXE_MCAST_LOCK(sc);
12056
12057     /* first, clear all configured multicast MACs */
12058     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12059     if (rc < 0) {
12060         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12061         /* Manual backport parts of FreeBSD upstream r284470. */
12062         BXE_MCAST_UNLOCK(sc);
12063         return (rc);
12064     }
12065
12066     /* configure a new MACs list */
12067     rc = bxe_init_mcast_macs_list(sc, &rparam);
12068     if (rc) {
12069         BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12070         BXE_MCAST_UNLOCK(sc);
12071         return (rc);
12072     }
12073
12074     /* Now add the new MACs */
12075     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12076     if (rc < 0) {
12077         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12078     }
12079
12080     bxe_free_mcast_macs_list(&rparam);
12081
12082     BXE_MCAST_UNLOCK(sc);
12083
12084     return (rc);
12085 }
12086
12087 static int
12088 bxe_set_uc_list(struct bxe_softc *sc)
12089 {
12090     struct ifnet *ifp = sc->ifnet;
12091     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12092     struct ifaddr *ifa;
12093     unsigned long ramrod_flags = 0;
12094     int rc;
12095
12096 #if __FreeBSD_version < 800000
12097     IF_ADDR_LOCK(ifp);
12098 #else
12099     if_addr_rlock(ifp);
12100 #endif
12101
12102     /* first schedule a cleanup up of old configuration */
12103     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12104     if (rc < 0) {
12105         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12106 #if __FreeBSD_version < 800000
12107         IF_ADDR_UNLOCK(ifp);
12108 #else
12109         if_addr_runlock(ifp);
12110 #endif
12111         return (rc);
12112     }
12113
12114     ifa = ifp->if_addr;
12115     while (ifa) {
12116         if (ifa->ifa_addr->sa_family != AF_LINK) {
12117             ifa = TAILQ_NEXT(ifa, ifa_link);
12118             continue;
12119         }
12120
12121         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12122                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12123         if (rc == -EEXIST) {
12124             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12125             /* do not treat adding same MAC as an error */
12126             rc = 0;
12127         } else if (rc < 0) {
12128             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12129 #if __FreeBSD_version < 800000
12130             IF_ADDR_UNLOCK(ifp);
12131 #else
12132             if_addr_runlock(ifp);
12133 #endif
12134             return (rc);
12135         }
12136
12137         ifa = TAILQ_NEXT(ifa, ifa_link);
12138     }
12139
12140 #if __FreeBSD_version < 800000
12141     IF_ADDR_UNLOCK(ifp);
12142 #else
12143     if_addr_runlock(ifp);
12144 #endif
12145
12146     /* Execute the pending commands */
12147     bit_set(&ramrod_flags, RAMROD_CONT);
12148     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12149                             ECORE_UC_LIST_MAC, &ramrod_flags));
12150 }
12151
12152 static void
12153 bxe_set_rx_mode(struct bxe_softc *sc)
12154 {
12155     struct ifnet *ifp = sc->ifnet;
12156     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12157
12158     if (sc->state != BXE_STATE_OPEN) {
12159         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12160         return;
12161     }
12162
12163     BLOGD(sc, DBG_SP, "ifp->if_flags=0x%x\n", ifp->if_flags);
12164
12165     if (ifp->if_flags & IFF_PROMISC) {
12166         rx_mode = BXE_RX_MODE_PROMISC;
12167     } else if ((ifp->if_flags & IFF_ALLMULTI) ||
12168                ((ifp->if_amcount > BXE_MAX_MULTICAST) &&
12169                 CHIP_IS_E1(sc))) {
12170         rx_mode = BXE_RX_MODE_ALLMULTI;
12171     } else {
12172         if (IS_PF(sc)) {
12173             /* some multicasts */
12174             if (bxe_set_mc_list(sc) < 0) {
12175                 rx_mode = BXE_RX_MODE_ALLMULTI;
12176             }
12177             if (bxe_set_uc_list(sc) < 0) {
12178                 rx_mode = BXE_RX_MODE_PROMISC;
12179             }
12180         }
12181     }
12182
12183     sc->rx_mode = rx_mode;
12184
12185     /* schedule the rx_mode command */
12186     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12187         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12188         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12189         return;
12190     }
12191
12192     if (IS_PF(sc)) {
12193         bxe_set_storm_rx_mode(sc);
12194     }
12195 }
12196
12197
12198 /* update flags in shmem */
12199 static void
12200 bxe_update_drv_flags(struct bxe_softc *sc,
12201                      uint32_t         flags,
12202                      uint32_t         set)
12203 {
12204     uint32_t drv_flags;
12205
12206     if (SHMEM2_HAS(sc, drv_flags)) {
12207         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12208         drv_flags = SHMEM2_RD(sc, drv_flags);
12209
12210         if (set) {
12211             SET_FLAGS(drv_flags, flags);
12212         } else {
12213             RESET_FLAGS(drv_flags, flags);
12214         }
12215
12216         SHMEM2_WR(sc, drv_flags, drv_flags);
12217         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12218
12219         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12220     }
12221 }
12222
12223 /* periodic timer callout routine, only runs when the interface is up */
12224
12225 static void
12226 bxe_periodic_callout_func(void *xsc)
12227 {
12228     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12229     struct bxe_fastpath *fp;
12230     uint16_t tx_bd_avail;
12231     int i;
12232
12233     if (!BXE_CORE_TRYLOCK(sc)) {
12234         /* just bail and try again next time */
12235
12236         if ((sc->state == BXE_STATE_OPEN) &&
12237             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12238             /* schedule the next periodic callout */
12239             callout_reset(&sc->periodic_callout, hz,
12240                           bxe_periodic_callout_func, sc);
12241         }
12242
12243         return;
12244     }
12245
12246     if ((sc->state != BXE_STATE_OPEN) ||
12247         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12248         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12249         BXE_CORE_UNLOCK(sc);
12250         return;
12251     }
12252
12253 #if __FreeBSD_version >= 800000
12254
12255     FOR_EACH_QUEUE(sc, i) {
12256         fp = &sc->fp[i];
12257
12258         if (BXE_FP_TX_TRYLOCK(fp)) {
12259             struct ifnet *ifp = sc->ifnet;
12260             /*
12261              * If interface was stopped due to unavailable
12262              * bds, try to process some tx completions
12263              */
12264             (void) bxe_txeof(sc, fp);
12265            
12266             tx_bd_avail = bxe_tx_avail(sc, fp);
12267             if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12268                 bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
12269             }
12270             BXE_FP_TX_UNLOCK(fp);
12271         }
12272     }
12273
12274 #else
12275
12276     fp = &sc->fp[0];
12277     if (BXE_FP_TX_TRYLOCK(fp)) {
12278         struct ifnet *ifp = sc->ifnet;
12279         /*
12280          * If interface was stopped due to unavailable
12281          * bds, try to process some tx completions
12282          */
12283         (void) bxe_txeof(sc, fp);
12284            
12285         tx_bd_avail = bxe_tx_avail(sc, fp);
12286         if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12287             bxe_tx_start_locked(sc, ifp, fp);
12288         }
12289  
12290         BXE_FP_TX_UNLOCK(fp);
12291     }
12292
12293 #endif /* #if __FreeBSD_version >= 800000 */
12294
12295     /* Check for TX timeouts on any fastpath. */
12296     FOR_EACH_QUEUE(sc, i) {
12297         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12298             /* Ruh-Roh, chip was reset! */
12299             break;
12300         }
12301     }
12302
12303     if (!CHIP_REV_IS_SLOW(sc)) {
12304         /*
12305          * This barrier is needed to ensure the ordering between the writing
12306          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12307          * the reading here.
12308          */
12309         mb();
12310         if (sc->port.pmf) {
12311             bxe_acquire_phy_lock(sc);
12312             elink_period_func(&sc->link_params, &sc->link_vars);
12313             bxe_release_phy_lock(sc);
12314         }
12315     }
12316
12317     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12318         int mb_idx = SC_FW_MB_IDX(sc);
12319         uint32_t drv_pulse;
12320         uint32_t mcp_pulse;
12321
12322         ++sc->fw_drv_pulse_wr_seq;
12323         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12324
12325         drv_pulse = sc->fw_drv_pulse_wr_seq;
12326         bxe_drv_pulse(sc);
12327
12328         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12329                      MCP_PULSE_SEQ_MASK);
12330
12331         /*
12332          * The delta between driver pulse and mcp response should
12333          * be 1 (before mcp response) or 0 (after mcp response).
12334          */
12335         if ((drv_pulse != mcp_pulse) &&
12336             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12337             /* someone lost a heartbeat... */
12338             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12339                   drv_pulse, mcp_pulse);
12340         }
12341     }
12342
12343     /* state is BXE_STATE_OPEN */
12344     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12345
12346     BXE_CORE_UNLOCK(sc);
12347
12348     if ((sc->state == BXE_STATE_OPEN) &&
12349         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12350         /* schedule the next periodic callout */
12351         callout_reset(&sc->periodic_callout, hz,
12352                       bxe_periodic_callout_func, sc);
12353     }
12354 }
12355
12356 static void
12357 bxe_periodic_start(struct bxe_softc *sc)
12358 {
12359     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12360     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12361 }
12362
12363 static void
12364 bxe_periodic_stop(struct bxe_softc *sc)
12365 {
12366     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12367     callout_drain(&sc->periodic_callout);
12368 }
12369
12370 /* start the controller */
12371 static __noinline int
12372 bxe_nic_load(struct bxe_softc *sc,
12373              int              load_mode)
12374 {
12375     uint32_t val;
12376     int load_code = 0;
12377     int i, rc = 0;
12378
12379     BXE_CORE_LOCK_ASSERT(sc);
12380
12381     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12382
12383     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12384
12385     if (IS_PF(sc)) {
12386         /* must be called before memory allocation and HW init */
12387         bxe_ilt_set_info(sc);
12388     }
12389
12390     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12391
12392     bxe_set_fp_rx_buf_size(sc);
12393
12394     if (bxe_alloc_fp_buffers(sc) != 0) {
12395         BLOGE(sc, "Failed to allocate fastpath memory\n");
12396         sc->state = BXE_STATE_CLOSED;
12397         rc = ENOMEM;
12398         goto bxe_nic_load_error0;
12399     }
12400
12401     if (bxe_alloc_mem(sc) != 0) {
12402         sc->state = BXE_STATE_CLOSED;
12403         rc = ENOMEM;
12404         goto bxe_nic_load_error0;
12405     }
12406
12407     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12408         sc->state = BXE_STATE_CLOSED;
12409         rc = ENOMEM;
12410         goto bxe_nic_load_error0;
12411     }
12412
12413     if (IS_PF(sc)) {
12414         /* set pf load just before approaching the MCP */
12415         bxe_set_pf_load(sc);
12416
12417         /* if MCP exists send load request and analyze response */
12418         if (!BXE_NOMCP(sc)) {
12419             /* attempt to load pf */
12420             if (bxe_nic_load_request(sc, &load_code) != 0) {
12421                 sc->state = BXE_STATE_CLOSED;
12422                 rc = ENXIO;
12423                 goto bxe_nic_load_error1;
12424             }
12425
12426             /* what did the MCP say? */
12427             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12428                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12429                 sc->state = BXE_STATE_CLOSED;
12430                 rc = ENXIO;
12431                 goto bxe_nic_load_error2;
12432             }
12433         } else {
12434             BLOGI(sc, "Device has no MCP!\n");
12435             load_code = bxe_nic_load_no_mcp(sc);
12436         }
12437
12438         /* mark PMF if applicable */
12439         bxe_nic_load_pmf(sc, load_code);
12440
12441         /* Init Function state controlling object */
12442         bxe_init_func_obj(sc);
12443
12444         /* Initialize HW */
12445         if (bxe_init_hw(sc, load_code) != 0) {
12446             BLOGE(sc, "HW init failed\n");
12447             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12448             sc->state = BXE_STATE_CLOSED;
12449             rc = ENXIO;
12450             goto bxe_nic_load_error2;
12451         }
12452     }
12453
12454     /* set ALWAYS_ALIVE bit in shmem */
12455     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12456     bxe_drv_pulse(sc);
12457     sc->flags |= BXE_NO_PULSE;
12458
12459     /* attach interrupts */
12460     if (bxe_interrupt_attach(sc) != 0) {
12461         sc->state = BXE_STATE_CLOSED;
12462         rc = ENXIO;
12463         goto bxe_nic_load_error2;
12464     }
12465
12466     bxe_nic_init(sc, load_code);
12467
12468     /* Init per-function objects */
12469     if (IS_PF(sc)) {
12470         bxe_init_objs(sc);
12471         // XXX bxe_iov_nic_init(sc);
12472
12473         /* set AFEX default VLAN tag to an invalid value */
12474         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12475         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12476
12477         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12478         rc = bxe_func_start(sc);
12479         if (rc) {
12480             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12481             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12482             sc->state = BXE_STATE_ERROR;
12483             goto bxe_nic_load_error3;
12484         }
12485
12486         /* send LOAD_DONE command to MCP */
12487         if (!BXE_NOMCP(sc)) {
12488             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12489             if (!load_code) {
12490                 BLOGE(sc, "MCP response failure, aborting\n");
12491                 sc->state = BXE_STATE_ERROR;
12492                 rc = ENXIO;
12493                 goto bxe_nic_load_error3;
12494             }
12495         }
12496
12497         rc = bxe_setup_leading(sc);
12498         if (rc) {
12499             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12500             sc->state = BXE_STATE_ERROR;
12501             goto bxe_nic_load_error3;
12502         }
12503
12504         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12505             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12506             if (rc) {
12507                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12508                 sc->state = BXE_STATE_ERROR;
12509                 goto bxe_nic_load_error3;
12510             }
12511         }
12512
12513         rc = bxe_init_rss_pf(sc);
12514         if (rc) {
12515             BLOGE(sc, "PF RSS init failed\n");
12516             sc->state = BXE_STATE_ERROR;
12517             goto bxe_nic_load_error3;
12518         }
12519     }
12520     /* XXX VF */
12521
12522     /* now when Clients are configured we are ready to work */
12523     sc->state = BXE_STATE_OPEN;
12524
12525     /* Configure a ucast MAC */
12526     if (IS_PF(sc)) {
12527         rc = bxe_set_eth_mac(sc, TRUE);
12528     }
12529     if (rc) {
12530         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12531         sc->state = BXE_STATE_ERROR;
12532         goto bxe_nic_load_error3;
12533     }
12534
12535     if (sc->port.pmf) {
12536         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12537         if (rc) {
12538             sc->state = BXE_STATE_ERROR;
12539             goto bxe_nic_load_error3;
12540         }
12541     }
12542
12543     sc->link_params.feature_config_flags &=
12544         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12545
12546     /* start fast path */
12547
12548     /* Initialize Rx filter */
12549     bxe_set_rx_mode(sc);
12550
12551     /* start the Tx */
12552     switch (/* XXX load_mode */LOAD_OPEN) {
12553     case LOAD_NORMAL:
12554     case LOAD_OPEN:
12555         break;
12556
12557     case LOAD_DIAG:
12558     case LOAD_LOOPBACK_EXT:
12559         sc->state = BXE_STATE_DIAG;
12560         break;
12561
12562     default:
12563         break;
12564     }
12565
12566     if (sc->port.pmf) {
12567         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12568     } else {
12569         bxe_link_status_update(sc);
12570     }
12571
12572     /* start the periodic timer callout */
12573     bxe_periodic_start(sc);
12574
12575     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12576         /* mark driver is loaded in shmem2 */
12577         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12578         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12579                   (val |
12580                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12581                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12582     }
12583
12584     /* wait for all pending SP commands to complete */
12585     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12586         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12587         bxe_periodic_stop(sc);
12588         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12589         return (ENXIO);
12590     }
12591
12592     /* Tell the stack the driver is running! */
12593     sc->ifnet->if_drv_flags = IFF_DRV_RUNNING;
12594
12595     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12596
12597     return (0);
12598
12599 bxe_nic_load_error3:
12600
12601     if (IS_PF(sc)) {
12602         bxe_int_disable_sync(sc, 1);
12603
12604         /* clean out queued objects */
12605         bxe_squeeze_objects(sc);
12606     }
12607
12608     bxe_interrupt_detach(sc);
12609
12610 bxe_nic_load_error2:
12611
12612     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12613         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12614         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12615     }
12616
12617     sc->port.pmf = 0;
12618
12619 bxe_nic_load_error1:
12620
12621     /* clear pf_load status, as it was already set */
12622     if (IS_PF(sc)) {
12623         bxe_clear_pf_load(sc);
12624     }
12625
12626 bxe_nic_load_error0:
12627
12628     bxe_free_fw_stats_mem(sc);
12629     bxe_free_fp_buffers(sc);
12630     bxe_free_mem(sc);
12631
12632     return (rc);
12633 }
12634
12635 static int
12636 bxe_init_locked(struct bxe_softc *sc)
12637 {
12638     int other_engine = SC_PATH(sc) ? 0 : 1;
12639     uint8_t other_load_status, load_status;
12640     uint8_t global = FALSE;
12641     int rc;
12642
12643     BXE_CORE_LOCK_ASSERT(sc);
12644
12645     /* check if the driver is already running */
12646     if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
12647         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12648         return (0);
12649     }
12650
12651     bxe_set_power_state(sc, PCI_PM_D0);
12652
12653     /*
12654      * If parity occurred during the unload, then attentions and/or
12655      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12656      * loaded on the current engine to complete the recovery. Parity recovery
12657      * is only relevant for PF driver.
12658      */
12659     if (IS_PF(sc)) {
12660         other_load_status = bxe_get_load_status(sc, other_engine);
12661         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12662
12663         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12664             bxe_chk_parity_attn(sc, &global, TRUE)) {
12665             do {
12666                 /*
12667                  * If there are attentions and they are in global blocks, set
12668                  * the GLOBAL_RESET bit regardless whether it will be this
12669                  * function that will complete the recovery or not.
12670                  */
12671                 if (global) {
12672                     bxe_set_reset_global(sc);
12673                 }
12674
12675                 /*
12676                  * Only the first function on the current engine should try
12677                  * to recover in open. In case of attentions in global blocks
12678                  * only the first in the chip should try to recover.
12679                  */
12680                 if ((!load_status && (!global || !other_load_status)) &&
12681                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12682                     BLOGI(sc, "Recovered during init\n");
12683                     break;
12684                 }
12685
12686                 /* recovery has failed... */
12687                 bxe_set_power_state(sc, PCI_PM_D3hot);
12688                 sc->recovery_state = BXE_RECOVERY_FAILED;
12689
12690                 BLOGE(sc, "Recovery flow hasn't properly "
12691                           "completed yet, try again later. "
12692                           "If you still see this message after a "
12693                           "few retries then power cycle is required.\n");
12694
12695                 rc = ENXIO;
12696                 goto bxe_init_locked_done;
12697             } while (0);
12698         }
12699     }
12700
12701     sc->recovery_state = BXE_RECOVERY_DONE;
12702
12703     rc = bxe_nic_load(sc, LOAD_OPEN);
12704
12705 bxe_init_locked_done:
12706
12707     if (rc) {
12708         /* Tell the stack the driver is NOT running! */
12709         BLOGE(sc, "Initialization failed, "
12710                   "stack notified driver is NOT running!\n");
12711         sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
12712     }
12713
12714     return (rc);
12715 }
12716
12717 static int
12718 bxe_stop_locked(struct bxe_softc *sc)
12719 {
12720     BXE_CORE_LOCK_ASSERT(sc);
12721     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12722 }
12723
12724 /*
12725  * Handles controller initialization when called from an unlocked routine.
12726  * ifconfig calls this function.
12727  *
12728  * Returns:
12729  *   void
12730  */
12731 static void
12732 bxe_init(void *xsc)
12733 {
12734     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12735
12736     BXE_CORE_LOCK(sc);
12737     bxe_init_locked(sc);
12738     BXE_CORE_UNLOCK(sc);
12739 }
12740
12741 static int
12742 bxe_init_ifnet(struct bxe_softc *sc)
12743 {
12744     struct ifnet *ifp;
12745
12746     /* ifconfig entrypoint for media type/status reporting */
12747     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12748                  bxe_ifmedia_update,
12749                  bxe_ifmedia_status);
12750
12751     /* set the default interface values */
12752     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12753     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12754     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12755
12756     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12757         BLOGI(sc, "IFMEDIA flags : %x\n", sc->ifmedia.ifm_media);
12758
12759     /* allocate the ifnet structure */
12760     if ((ifp = if_alloc(IFT_ETHER)) == NULL) {
12761         BLOGE(sc, "Interface allocation failed!\n");
12762         return (ENXIO);
12763     }
12764
12765     ifp->if_softc = sc;
12766     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12767     ifp->if_flags = (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
12768     ifp->if_ioctl = bxe_ioctl;
12769     ifp->if_start = bxe_tx_start;
12770 #if __FreeBSD_version >= 800000
12771     ifp->if_transmit = bxe_tx_mq_start;
12772     ifp->if_qflush = bxe_mq_flush;
12773 #endif
12774 #ifdef FreeBSD8_0
12775     ifp->if_timer = 0;
12776 #endif
12777     ifp->if_init = bxe_init;
12778     ifp->if_mtu = sc->mtu;
12779     ifp->if_hwassist = (CSUM_IP       |
12780                         CSUM_TCP      |
12781                         CSUM_UDP      |
12782                         CSUM_TSO      |
12783                         CSUM_TCP_IPV6 |
12784                         CSUM_UDP_IPV6);
12785     ifp->if_capabilities =
12786 #if __FreeBSD_version < 700000
12787         (IFCAP_VLAN_MTU       |
12788          IFCAP_VLAN_HWTAGGING |
12789          IFCAP_HWCSUM         |
12790          IFCAP_JUMBO_MTU      |
12791          IFCAP_LRO);
12792 #else
12793         (IFCAP_VLAN_MTU       |
12794          IFCAP_VLAN_HWTAGGING |
12795          IFCAP_VLAN_HWTSO     |
12796          IFCAP_VLAN_HWFILTER  |
12797          IFCAP_VLAN_HWCSUM    |
12798          IFCAP_HWCSUM         |
12799          IFCAP_JUMBO_MTU      |
12800          IFCAP_LRO            |
12801          IFCAP_TSO4           |
12802          IFCAP_TSO6           |
12803          IFCAP_WOL_MAGIC);
12804 #endif
12805     ifp->if_capenable = ifp->if_capabilities;
12806     ifp->if_capenable &= ~IFCAP_WOL_MAGIC; /* XXX not yet... */
12807 #if __FreeBSD_version < 1000025
12808     ifp->if_baudrate = 1000000000;
12809 #else
12810     if_initbaudrate(ifp, IF_Gbps(10));
12811 #endif
12812     ifp->if_snd.ifq_drv_maxlen = sc->tx_ring_size;
12813
12814     IFQ_SET_MAXLEN(&ifp->if_snd, ifp->if_snd.ifq_drv_maxlen);
12815     IFQ_SET_READY(&ifp->if_snd);
12816
12817     sc->ifnet = ifp;
12818
12819     /* attach to the Ethernet interface list */
12820     ether_ifattach(ifp, sc->link_params.mac_addr);
12821
12822     return (0);
12823 }
12824
12825 static void
12826 bxe_deallocate_bars(struct bxe_softc *sc)
12827 {
12828     int i;
12829
12830     for (i = 0; i < MAX_BARS; i++) {
12831         if (sc->bar[i].resource != NULL) {
12832             bus_release_resource(sc->dev,
12833                                  SYS_RES_MEMORY,
12834                                  sc->bar[i].rid,
12835                                  sc->bar[i].resource);
12836             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12837                   i, PCIR_BAR(i));
12838         }
12839     }
12840 }
12841
12842 static int
12843 bxe_allocate_bars(struct bxe_softc *sc)
12844 {
12845     u_int flags;
12846     int i;
12847
12848     memset(sc->bar, 0, sizeof(sc->bar));
12849
12850     for (i = 0; i < MAX_BARS; i++) {
12851
12852         /* memory resources reside at BARs 0, 2, 4 */
12853         /* Run `pciconf -lb` to see mappings */
12854         if ((i != 0) && (i != 2) && (i != 4)) {
12855             continue;
12856         }
12857
12858         sc->bar[i].rid = PCIR_BAR(i);
12859
12860         flags = RF_ACTIVE;
12861         if (i == 0) {
12862             flags |= RF_SHAREABLE;
12863         }
12864
12865         if ((sc->bar[i].resource =
12866              bus_alloc_resource_any(sc->dev,
12867                                     SYS_RES_MEMORY,
12868                                     &sc->bar[i].rid,
12869                                     flags)) == NULL) {
12870             return (0);
12871         }
12872
12873         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12874         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12875         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12876
12877         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%ld) -> %p\n",
12878               i, PCIR_BAR(i),
12879               (void *)rman_get_start(sc->bar[i].resource),
12880               (void *)rman_get_end(sc->bar[i].resource),
12881               rman_get_size(sc->bar[i].resource),
12882               (void *)sc->bar[i].kva);
12883     }
12884
12885     return (0);
12886 }
12887
12888 static void
12889 bxe_get_function_num(struct bxe_softc *sc)
12890 {
12891     uint32_t val = 0;
12892
12893     /*
12894      * Read the ME register to get the function number. The ME register
12895      * holds the relative-function number and absolute-function number. The
12896      * absolute-function number appears only in E2 and above. Before that
12897      * these bits always contained zero, therefore we cannot blindly use them.
12898      */
12899
12900     val = REG_RD(sc, BAR_ME_REGISTER);
12901
12902     sc->pfunc_rel =
12903         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12904     sc->path_id =
12905         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12906
12907     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12908         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12909     } else {
12910         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12911     }
12912
12913     BLOGD(sc, DBG_LOAD,
12914           "Relative function %d, Absolute function %d, Path %d\n",
12915           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12916 }
12917
12918 static uint32_t
12919 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12920 {
12921     uint32_t shmem2_size;
12922     uint32_t offset;
12923     uint32_t mf_cfg_offset_value;
12924
12925     /* Non 57712 */
12926     offset = (SHMEM_RD(sc, func_mb) +
12927               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12928
12929     /* 57712 plus */
12930     if (sc->devinfo.shmem2_base != 0) {
12931         shmem2_size = SHMEM2_RD(sc, size);
12932         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12933             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12934             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12935                 offset = mf_cfg_offset_value;
12936             }
12937         }
12938     }
12939
12940     return (offset);
12941 }
12942
12943 static uint32_t
12944 bxe_pcie_capability_read(struct bxe_softc *sc,
12945                          int    reg,
12946                          int    width)
12947 {
12948     int pcie_reg;
12949
12950     /* ensure PCIe capability is enabled */
12951     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12952         if (pcie_reg != 0) {
12953             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12954             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12955         }
12956     }
12957
12958     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12959
12960     return (0);
12961 }
12962
12963 static uint8_t
12964 bxe_is_pcie_pending(struct bxe_softc *sc)
12965 {
12966     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12967             PCIM_EXP_STA_TRANSACTION_PND);
12968 }
12969
12970 /*
12971  * Walk the PCI capabiites list for the device to find what features are
12972  * supported. These capabilites may be enabled/disabled by firmware so it's
12973  * best to walk the list rather than make assumptions.
12974  */
12975 static void
12976 bxe_probe_pci_caps(struct bxe_softc *sc)
12977 {
12978     uint16_t link_status;
12979     int reg;
12980
12981     /* check if PCI Power Management is enabled */
12982     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
12983         if (reg != 0) {
12984             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
12985
12986             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
12987             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
12988         }
12989     }
12990
12991     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
12992
12993     /* handle PCIe 2.0 workarounds for 57710 */
12994     if (CHIP_IS_E1(sc)) {
12995         /* workaround for 57710 errata E4_57710_27462 */
12996         sc->devinfo.pcie_link_speed =
12997             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
12998
12999         /* workaround for 57710 errata E4_57710_27488 */
13000         sc->devinfo.pcie_link_width =
13001             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13002         if (sc->devinfo.pcie_link_speed > 1) {
13003             sc->devinfo.pcie_link_width =
13004                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
13005         }
13006     } else {
13007         sc->devinfo.pcie_link_speed =
13008             (link_status & PCIM_LINK_STA_SPEED);
13009         sc->devinfo.pcie_link_width =
13010             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13011     }
13012
13013     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
13014           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
13015
13016     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
13017     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
13018
13019     /* check if MSI capability is enabled */
13020     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
13021         if (reg != 0) {
13022             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13023
13024             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13025             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13026         }
13027     }
13028
13029     /* check if MSI-X capability is enabled */
13030     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13031         if (reg != 0) {
13032             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13033
13034             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13035             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13036         }
13037     }
13038 }
13039
13040 static int
13041 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13042 {
13043     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13044     uint32_t val;
13045
13046     /* get the outer vlan if we're in switch-dependent mode */
13047
13048     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13049     mf_info->ext_id = (uint16_t)val;
13050
13051     mf_info->multi_vnics_mode = 1;
13052
13053     if (!VALID_OVLAN(mf_info->ext_id)) {
13054         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13055         return (1);
13056     }
13057
13058     /* get the capabilities */
13059     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13060         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13061         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13062     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13063                FUNC_MF_CFG_PROTOCOL_FCOE) {
13064         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13065     } else {
13066         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13067     }
13068
13069     mf_info->vnics_per_port =
13070         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13071
13072     return (0);
13073 }
13074
13075 static uint32_t
13076 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13077 {
13078     uint32_t retval = 0;
13079     uint32_t val;
13080
13081     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13082
13083     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13084         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13085             retval |= MF_PROTO_SUPPORT_ETHERNET;
13086         }
13087         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13088             retval |= MF_PROTO_SUPPORT_ISCSI;
13089         }
13090         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13091             retval |= MF_PROTO_SUPPORT_FCOE;
13092         }
13093     }
13094
13095     return (retval);
13096 }
13097
13098 static int
13099 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13100 {
13101     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13102     uint32_t val;
13103
13104     /*
13105      * There is no outer vlan if we're in switch-independent mode.
13106      * If the mac is valid then assume multi-function.
13107      */
13108
13109     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13110
13111     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13112
13113     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13114
13115     mf_info->vnics_per_port =
13116         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13117
13118     return (0);
13119 }
13120
13121 static int
13122 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13123 {
13124     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13125     uint32_t e1hov_tag;
13126     uint32_t func_config;
13127     uint32_t niv_config;
13128
13129     mf_info->multi_vnics_mode = 1;
13130
13131     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13132     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13133     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13134
13135     mf_info->ext_id =
13136         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13137                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13138
13139     mf_info->default_vlan =
13140         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13141                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13142
13143     mf_info->niv_allowed_priorities =
13144         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13145                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13146
13147     mf_info->niv_default_cos =
13148         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13149                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13150
13151     mf_info->afex_vlan_mode =
13152         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13153          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13154
13155     mf_info->niv_mba_enabled =
13156         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13157          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13158
13159     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13160
13161     mf_info->vnics_per_port =
13162         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13163
13164     return (0);
13165 }
13166
13167 static int
13168 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13169 {
13170     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13171     uint32_t mf_cfg1;
13172     uint32_t mf_cfg2;
13173     uint32_t ovlan1;
13174     uint32_t ovlan2;
13175     uint8_t i, j;
13176
13177     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13178           SC_PORT(sc));
13179     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13180           mf_info->mf_config[SC_VN(sc)]);
13181     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13182           mf_info->multi_vnics_mode);
13183     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13184           mf_info->vnics_per_port);
13185     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13186           mf_info->ext_id);
13187     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13188           mf_info->min_bw[0], mf_info->min_bw[1],
13189           mf_info->min_bw[2], mf_info->min_bw[3]);
13190     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13191           mf_info->max_bw[0], mf_info->max_bw[1],
13192           mf_info->max_bw[2], mf_info->max_bw[3]);
13193     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13194           sc->mac_addr_str);
13195
13196     /* various MF mode sanity checks... */
13197
13198     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13199         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13200               SC_PORT(sc));
13201         return (1);
13202     }
13203
13204     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13205         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13206               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13207         return (1);
13208     }
13209
13210     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13211         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13212         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13213             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13214                   SC_VN(sc), OVLAN(sc));
13215             return (1);
13216         }
13217
13218         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13219             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13220                   mf_info->multi_vnics_mode, OVLAN(sc));
13221             return (1);
13222         }
13223
13224         /*
13225          * Verify all functions are either MF or SF mode. If MF, make sure
13226          * sure that all non-hidden functions have a valid ovlan. If SF,
13227          * make sure that all non-hidden functions have an invalid ovlan.
13228          */
13229         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13230             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13231             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13232             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13233                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13234                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13235                 BLOGE(sc, "mf_mode=SD function %d MF config "
13236                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13237                       i, mf_info->multi_vnics_mode, ovlan1);
13238                 return (1);
13239             }
13240         }
13241
13242         /* Verify all funcs on the same port each have a different ovlan. */
13243         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13244             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13245             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13246             /* iterate from the next function on the port to the max func */
13247             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13248                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13249                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13250                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13251                     VALID_OVLAN(ovlan1) &&
13252                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13253                     VALID_OVLAN(ovlan2) &&
13254                     (ovlan1 == ovlan2)) {
13255                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13256                               "have the same ovlan (%d)\n",
13257                           i, j, ovlan1);
13258                     return (1);
13259                 }
13260             }
13261         }
13262     } /* MULTI_FUNCTION_SD */
13263
13264     return (0);
13265 }
13266
13267 static int
13268 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13269 {
13270     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13271     uint32_t val, mac_upper;
13272     uint8_t i, vnic;
13273
13274     /* initialize mf_info defaults */
13275     mf_info->vnics_per_port   = 1;
13276     mf_info->multi_vnics_mode = FALSE;
13277     mf_info->path_has_ovlan   = FALSE;
13278     mf_info->mf_mode          = SINGLE_FUNCTION;
13279
13280     if (!CHIP_IS_MF_CAP(sc)) {
13281         return (0);
13282     }
13283
13284     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13285         BLOGE(sc, "Invalid mf_cfg_base!\n");
13286         return (1);
13287     }
13288
13289     /* get the MF mode (switch dependent / independent / single-function) */
13290
13291     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13292
13293     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13294     {
13295     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13296
13297         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13298
13299         /* check for legal upper mac bytes */
13300         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13301             mf_info->mf_mode = MULTI_FUNCTION_SI;
13302         } else {
13303             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13304         }
13305
13306         break;
13307
13308     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13309     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13310
13311         /* get outer vlan configuration */
13312         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13313
13314         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13315             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13316             mf_info->mf_mode = MULTI_FUNCTION_SD;
13317         } else {
13318             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13319         }
13320
13321         break;
13322
13323     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13324
13325         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13326         return (0);
13327
13328     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13329
13330         /*
13331          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13332          * and the MAC address is valid.
13333          */
13334         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13335
13336         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13337             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13338             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13339         } else {
13340             BLOGE(sc, "Invalid config for AFEX mode\n");
13341         }
13342
13343         break;
13344
13345     default:
13346
13347         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13348               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13349
13350         return (1);
13351     }
13352
13353     /* set path mf_mode (which could be different than function mf_mode) */
13354     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13355         mf_info->path_has_ovlan = TRUE;
13356     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13357         /*
13358          * Decide on path multi vnics mode. If we're not in MF mode and in
13359          * 4-port mode, this is good enough to check vnic-0 of the other port
13360          * on the same path
13361          */
13362         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13363             uint8_t other_port = !(PORT_ID(sc) & 1);
13364             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13365
13366             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13367
13368             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13369         }
13370     }
13371
13372     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13373         /* invalid MF config */
13374         if (SC_VN(sc) >= 1) {
13375             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13376             return (1);
13377         }
13378
13379         return (0);
13380     }
13381
13382     /* get the MF configuration */
13383     mf_info->mf_config[SC_VN(sc)] =
13384         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13385
13386     switch(mf_info->mf_mode)
13387     {
13388     case MULTI_FUNCTION_SD:
13389
13390         bxe_get_shmem_mf_cfg_info_sd(sc);
13391         break;
13392
13393     case MULTI_FUNCTION_SI:
13394
13395         bxe_get_shmem_mf_cfg_info_si(sc);
13396         break;
13397
13398     case MULTI_FUNCTION_AFEX:
13399
13400         bxe_get_shmem_mf_cfg_info_niv(sc);
13401         break;
13402
13403     default:
13404
13405         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13406               mf_info->mf_mode);
13407         return (1);
13408     }
13409
13410     /* get the congestion management parameters */
13411
13412     vnic = 0;
13413     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13414         /* get min/max bw */
13415         val = MFCFG_RD(sc, func_mf_config[i].config);
13416         mf_info->min_bw[vnic] =
13417             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13418         mf_info->max_bw[vnic] =
13419             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13420         vnic++;
13421     }
13422
13423     return (bxe_check_valid_mf_cfg(sc));
13424 }
13425
13426 static int
13427 bxe_get_shmem_info(struct bxe_softc *sc)
13428 {
13429     int port;
13430     uint32_t mac_hi, mac_lo, val;
13431
13432     port = SC_PORT(sc);
13433     mac_hi = mac_lo = 0;
13434
13435     sc->link_params.sc   = sc;
13436     sc->link_params.port = port;
13437
13438     /* get the hardware config info */
13439     sc->devinfo.hw_config =
13440         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13441     sc->devinfo.hw_config2 =
13442         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13443
13444     sc->link_params.hw_led_mode =
13445         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13446          SHARED_HW_CFG_LED_MODE_SHIFT);
13447
13448     /* get the port feature config */
13449     sc->port.config =
13450         SHMEM_RD(sc, dev_info.port_feature_config[port].config),
13451
13452     /* get the link params */
13453     sc->link_params.speed_cap_mask[0] =
13454         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13455     sc->link_params.speed_cap_mask[1] =
13456         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13457
13458     /* get the lane config */
13459     sc->link_params.lane_config =
13460         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13461
13462     /* get the link config */
13463     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13464     sc->port.link_config[ELINK_INT_PHY] = val;
13465     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13466     sc->port.link_config[ELINK_EXT_PHY1] =
13467         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13468
13469     /* get the override preemphasis flag and enable it or turn it off */
13470     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13471     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13472         sc->link_params.feature_config_flags |=
13473             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13474     } else {
13475         sc->link_params.feature_config_flags &=
13476             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13477     }
13478
13479     /* get the initial value of the link params */
13480     sc->link_params.multi_phy_config =
13481         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13482
13483     /* get external phy info */
13484     sc->port.ext_phy_config =
13485         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13486
13487     /* get the multifunction configuration */
13488     bxe_get_mf_cfg_info(sc);
13489
13490     /* get the mac address */
13491     if (IS_MF(sc)) {
13492         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13493         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13494     } else {
13495         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13496         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13497     }
13498
13499     if ((mac_lo == 0) && (mac_hi == 0)) {
13500         *sc->mac_addr_str = 0;
13501         BLOGE(sc, "No Ethernet address programmed!\n");
13502     } else {
13503         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13504         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13505         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13506         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13507         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13508         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13509         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13510                  "%02x:%02x:%02x:%02x:%02x:%02x",
13511                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13512                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13513                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13514         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13515     }
13516
13517     return (0);
13518 }
13519
13520 static void
13521 bxe_get_tunable_params(struct bxe_softc *sc)
13522 {
13523     /* sanity checks */
13524
13525     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13526         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13527         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13528         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13529         bxe_interrupt_mode = INTR_MODE_MSIX;
13530     }
13531
13532     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13533         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13534         bxe_queue_count = 0;
13535     }
13536
13537     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13538         if (bxe_max_rx_bufs == 0) {
13539             bxe_max_rx_bufs = RX_BD_USABLE;
13540         } else {
13541             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13542             bxe_max_rx_bufs = 2048;
13543         }
13544     }
13545
13546     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13547         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13548         bxe_hc_rx_ticks = 25;
13549     }
13550
13551     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13552         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13553         bxe_hc_tx_ticks = 50;
13554     }
13555
13556     if (bxe_max_aggregation_size == 0) {
13557         bxe_max_aggregation_size = TPA_AGG_SIZE;
13558     }
13559
13560     if (bxe_max_aggregation_size > 0xffff) {
13561         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13562               bxe_max_aggregation_size);
13563         bxe_max_aggregation_size = TPA_AGG_SIZE;
13564     }
13565
13566     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13567         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13568         bxe_mrrs = -1;
13569     }
13570
13571     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13572         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13573         bxe_autogreeen = 0;
13574     }
13575
13576     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13577         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13578         bxe_udp_rss = 0;
13579     }
13580
13581     /* pull in user settings */
13582
13583     sc->interrupt_mode       = bxe_interrupt_mode;
13584     sc->max_rx_bufs          = bxe_max_rx_bufs;
13585     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13586     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13587     sc->max_aggregation_size = bxe_max_aggregation_size;
13588     sc->mrrs                 = bxe_mrrs;
13589     sc->autogreeen           = bxe_autogreeen;
13590     sc->udp_rss              = bxe_udp_rss;
13591
13592     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13593         sc->num_queues = 1;
13594     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13595         sc->num_queues =
13596             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13597                 MAX_RSS_CHAINS);
13598         if (sc->num_queues > mp_ncpus) {
13599             sc->num_queues = mp_ncpus;
13600         }
13601     }
13602
13603     BLOGD(sc, DBG_LOAD,
13604           "User Config: "
13605           "debug=0x%lx "
13606           "interrupt_mode=%d "
13607           "queue_count=%d "
13608           "hc_rx_ticks=%d "
13609           "hc_tx_ticks=%d "
13610           "rx_budget=%d "
13611           "max_aggregation_size=%d "
13612           "mrrs=%d "
13613           "autogreeen=%d "
13614           "udp_rss=%d\n",
13615           bxe_debug,
13616           sc->interrupt_mode,
13617           sc->num_queues,
13618           sc->hc_rx_ticks,
13619           sc->hc_tx_ticks,
13620           bxe_rx_budget,
13621           sc->max_aggregation_size,
13622           sc->mrrs,
13623           sc->autogreeen,
13624           sc->udp_rss);
13625 }
13626
13627 static int
13628 bxe_media_detect(struct bxe_softc *sc)
13629 {
13630     int port_type;
13631     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13632
13633     switch (sc->link_params.phy[phy_idx].media_type) {
13634     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13635     case ELINK_ETH_PHY_XFP_FIBER:
13636         BLOGI(sc, "Found 10Gb Fiber media.\n");
13637         sc->media = IFM_10G_SR;
13638         port_type = PORT_FIBRE;
13639         break;
13640     case ELINK_ETH_PHY_SFP_1G_FIBER:
13641         BLOGI(sc, "Found 1Gb Fiber media.\n");
13642         sc->media = IFM_1000_SX;
13643         port_type = PORT_FIBRE;
13644         break;
13645     case ELINK_ETH_PHY_KR:
13646     case ELINK_ETH_PHY_CX4:
13647         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13648         sc->media = IFM_10G_CX4;
13649         port_type = PORT_FIBRE;
13650         break;
13651     case ELINK_ETH_PHY_DA_TWINAX:
13652         BLOGI(sc, "Found 10Gb Twinax media.\n");
13653         sc->media = IFM_10G_TWINAX;
13654         port_type = PORT_DA;
13655         break;
13656     case ELINK_ETH_PHY_BASE_T:
13657         if (sc->link_params.speed_cap_mask[0] &
13658             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13659             BLOGI(sc, "Found 10GBase-T media.\n");
13660             sc->media = IFM_10G_T;
13661             port_type = PORT_TP;
13662         } else {
13663             BLOGI(sc, "Found 1000Base-T media.\n");
13664             sc->media = IFM_1000_T;
13665             port_type = PORT_TP;
13666         }
13667         break;
13668     case ELINK_ETH_PHY_NOT_PRESENT:
13669         BLOGI(sc, "Media not present.\n");
13670         sc->media = 0;
13671         port_type = PORT_OTHER;
13672         break;
13673     case ELINK_ETH_PHY_UNSPECIFIED:
13674     default:
13675         BLOGI(sc, "Unknown media!\n");
13676         sc->media = 0;
13677         port_type = PORT_OTHER;
13678         break;
13679     }
13680     return port_type;
13681 }
13682
13683 #define GET_FIELD(value, fname)                     \
13684     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13685 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13686 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13687
13688 static int
13689 bxe_get_igu_cam_info(struct bxe_softc *sc)
13690 {
13691     int pfid = SC_FUNC(sc);
13692     int igu_sb_id;
13693     uint32_t val;
13694     uint8_t fid, igu_sb_cnt = 0;
13695
13696     sc->igu_base_sb = 0xff;
13697
13698     if (CHIP_INT_MODE_IS_BC(sc)) {
13699         int vn = SC_VN(sc);
13700         igu_sb_cnt = sc->igu_sb_cnt;
13701         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13702                            FP_SB_MAX_E1x);
13703         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13704                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13705         return (0);
13706     }
13707
13708     /* IGU in normal mode - read CAM */
13709     for (igu_sb_id = 0;
13710          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13711          igu_sb_id++) {
13712         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13713         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13714             continue;
13715         }
13716         fid = IGU_FID(val);
13717         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13718             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13719                 continue;
13720             }
13721             if (IGU_VEC(val) == 0) {
13722                 /* default status block */
13723                 sc->igu_dsb_id = igu_sb_id;
13724             } else {
13725                 if (sc->igu_base_sb == 0xff) {
13726                     sc->igu_base_sb = igu_sb_id;
13727                 }
13728                 igu_sb_cnt++;
13729             }
13730         }
13731     }
13732
13733     /*
13734      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13735      * that number of CAM entries will not be equal to the value advertised in
13736      * PCI. Driver should use the minimal value of both as the actual status
13737      * block count
13738      */
13739     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13740
13741     if (igu_sb_cnt == 0) {
13742         BLOGE(sc, "CAM configuration error\n");
13743         return (-1);
13744     }
13745
13746     return (0);
13747 }
13748
13749 /*
13750  * Gather various information from the device config space, the device itself,
13751  * shmem, and the user input.
13752  */
13753 static int
13754 bxe_get_device_info(struct bxe_softc *sc)
13755 {
13756     uint32_t val;
13757     int rc;
13758
13759     /* Get the data for the device */
13760     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13761     sc->devinfo.device_id    = pci_get_device(sc->dev);
13762     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13763     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13764
13765     /* get the chip revision (chip metal comes from pci config space) */
13766     sc->devinfo.chip_id     =
13767     sc->link_params.chip_id =
13768         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13769          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13770          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13771          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13772
13773     /* force 57811 according to MISC register */
13774     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13775         if (CHIP_IS_57810(sc)) {
13776             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13777                                    (sc->devinfo.chip_id & 0x0000ffff));
13778         } else if (CHIP_IS_57810_MF(sc)) {
13779             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13780                                    (sc->devinfo.chip_id & 0x0000ffff));
13781         }
13782         sc->devinfo.chip_id |= 0x1;
13783     }
13784
13785     BLOGD(sc, DBG_LOAD,
13786           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13787           sc->devinfo.chip_id,
13788           ((sc->devinfo.chip_id >> 16) & 0xffff),
13789           ((sc->devinfo.chip_id >> 12) & 0xf),
13790           ((sc->devinfo.chip_id >>  4) & 0xff),
13791           ((sc->devinfo.chip_id >>  0) & 0xf));
13792
13793     val = (REG_RD(sc, 0x2874) & 0x55);
13794     if ((sc->devinfo.chip_id & 0x1) ||
13795         (CHIP_IS_E1(sc) && val) ||
13796         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13797         sc->flags |= BXE_ONE_PORT_FLAG;
13798         BLOGD(sc, DBG_LOAD, "single port device\n");
13799     }
13800
13801     /* set the doorbell size */
13802     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13803
13804     /* determine whether the device is in 2 port or 4 port mode */
13805     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13806     if (CHIP_IS_E2E3(sc)) {
13807         /*
13808          * Read port4mode_en_ovwr[0]:
13809          *   If 1, four port mode is in port4mode_en_ovwr[1].
13810          *   If 0, four port mode is in port4mode_en[0].
13811          */
13812         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13813         if (val & 1) {
13814             val = ((val >> 1) & 1);
13815         } else {
13816             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13817         }
13818
13819         sc->devinfo.chip_port_mode =
13820             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13821
13822         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13823     }
13824
13825     /* get the function and path info for the device */
13826     bxe_get_function_num(sc);
13827
13828     /* get the shared memory base address */
13829     sc->devinfo.shmem_base     =
13830     sc->link_params.shmem_base =
13831         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13832     sc->devinfo.shmem2_base =
13833         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13834                                   MISC_REG_GENERIC_CR_0));
13835
13836     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13837           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13838
13839     if (!sc->devinfo.shmem_base) {
13840         /* this should ONLY prevent upcoming shmem reads */
13841         BLOGI(sc, "MCP not active\n");
13842         sc->flags |= BXE_NO_MCP_FLAG;
13843         return (0);
13844     }
13845
13846     /* make sure the shared memory contents are valid */
13847     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13848     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13849         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13850         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13851         return (0);
13852     }
13853     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13854
13855     /* get the bootcode version */
13856     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13857     snprintf(sc->devinfo.bc_ver_str,
13858              sizeof(sc->devinfo.bc_ver_str),
13859              "%d.%d.%d",
13860              ((sc->devinfo.bc_ver >> 24) & 0xff),
13861              ((sc->devinfo.bc_ver >> 16) & 0xff),
13862              ((sc->devinfo.bc_ver >>  8) & 0xff));
13863     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13864
13865     /* get the bootcode shmem address */
13866     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13867     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13868
13869     /* clean indirect addresses as they're not used */
13870     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13871     if (IS_PF(sc)) {
13872         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13873         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13874         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13875         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13876         if (CHIP_IS_E1x(sc)) {
13877             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13878             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13879             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13880             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13881         }
13882
13883         /*
13884          * Enable internal target-read (in case we are probed after PF
13885          * FLR). Must be done prior to any BAR read access. Only for
13886          * 57712 and up
13887          */
13888         if (!CHIP_IS_E1x(sc)) {
13889             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13890         }
13891     }
13892
13893     /* get the nvram size */
13894     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13895     sc->devinfo.flash_size =
13896         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13897     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13898
13899     /* get PCI capabilites */
13900     bxe_probe_pci_caps(sc);
13901
13902     bxe_set_power_state(sc, PCI_PM_D0);
13903
13904     /* get various configuration parameters from shmem */
13905     bxe_get_shmem_info(sc);
13906
13907     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13908         val = pci_read_config(sc->dev,
13909                               (sc->devinfo.pcie_msix_cap_reg +
13910                                PCIR_MSIX_CTRL),
13911                               2);
13912         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13913     } else {
13914         sc->igu_sb_cnt = 1;
13915     }
13916
13917     sc->igu_base_addr = BAR_IGU_INTMEM;
13918
13919     /* initialize IGU parameters */
13920     if (CHIP_IS_E1x(sc)) {
13921         sc->devinfo.int_block = INT_BLOCK_HC;
13922         sc->igu_dsb_id = DEF_SB_IGU_ID;
13923         sc->igu_base_sb = 0;
13924     } else {
13925         sc->devinfo.int_block = INT_BLOCK_IGU;
13926
13927         /* do not allow device reset during IGU info preocessing */
13928         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13929
13930         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13931
13932         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13933             int tout = 5000;
13934
13935             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13936
13937             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13938             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13939             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13940
13941             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13942                 tout--;
13943                 DELAY(1000);
13944             }
13945
13946             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13947                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13948                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13949                 return (-1);
13950             }
13951         }
13952
13953         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13954             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13955             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13956         } else {
13957             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13958         }
13959
13960         rc = bxe_get_igu_cam_info(sc);
13961
13962         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13963
13964         if (rc) {
13965             return (rc);
13966         }
13967     }
13968
13969     /*
13970      * Get base FW non-default (fast path) status block ID. This value is
13971      * used to initialize the fw_sb_id saved on the fp/queue structure to
13972      * determine the id used by the FW.
13973      */
13974     if (CHIP_IS_E1x(sc)) {
13975         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
13976     } else {
13977         /*
13978          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
13979          * the same queue are indicated on the same IGU SB). So we prefer
13980          * FW and IGU SBs to be the same value.
13981          */
13982         sc->base_fw_ndsb = sc->igu_base_sb;
13983     }
13984
13985     BLOGD(sc, DBG_LOAD,
13986           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
13987           sc->igu_dsb_id, sc->igu_base_sb,
13988           sc->igu_sb_cnt, sc->base_fw_ndsb);
13989
13990     elink_phy_probe(&sc->link_params);
13991
13992     return (0);
13993 }
13994
13995 static void
13996 bxe_link_settings_supported(struct bxe_softc *sc,
13997                             uint32_t         switch_cfg)
13998 {
13999     uint32_t cfg_size = 0;
14000     uint32_t idx;
14001     uint8_t port = SC_PORT(sc);
14002
14003     /* aggregation of supported attributes of all external phys */
14004     sc->port.supported[0] = 0;
14005     sc->port.supported[1] = 0;
14006
14007     switch (sc->link_params.num_phys) {
14008     case 1:
14009         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
14010         cfg_size = 1;
14011         break;
14012     case 2:
14013         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
14014         cfg_size = 1;
14015         break;
14016     case 3:
14017         if (sc->link_params.multi_phy_config &
14018             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
14019             sc->port.supported[1] =
14020                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14021             sc->port.supported[0] =
14022                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14023         } else {
14024             sc->port.supported[0] =
14025                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14026             sc->port.supported[1] =
14027                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14028         }
14029         cfg_size = 2;
14030         break;
14031     }
14032
14033     if (!(sc->port.supported[0] || sc->port.supported[1])) {
14034         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14035               SHMEM_RD(sc,
14036                        dev_info.port_hw_config[port].external_phy_config),
14037               SHMEM_RD(sc,
14038                        dev_info.port_hw_config[port].external_phy_config2));
14039         return;
14040     }
14041
14042     if (CHIP_IS_E3(sc))
14043         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14044     else {
14045         switch (switch_cfg) {
14046         case ELINK_SWITCH_CFG_1G:
14047             sc->port.phy_addr =
14048                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14049             break;
14050         case ELINK_SWITCH_CFG_10G:
14051             sc->port.phy_addr =
14052                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14053             break;
14054         default:
14055             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14056                   sc->port.link_config[0]);
14057             return;
14058         }
14059     }
14060
14061     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14062
14063     /* mask what we support according to speed_cap_mask per configuration */
14064     for (idx = 0; idx < cfg_size; idx++) {
14065         if (!(sc->link_params.speed_cap_mask[idx] &
14066               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14067             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14068         }
14069
14070         if (!(sc->link_params.speed_cap_mask[idx] &
14071               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14072             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14073         }
14074
14075         if (!(sc->link_params.speed_cap_mask[idx] &
14076               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14077             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14078         }
14079
14080         if (!(sc->link_params.speed_cap_mask[idx] &
14081               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14082             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14083         }
14084
14085         if (!(sc->link_params.speed_cap_mask[idx] &
14086               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14087             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14088         }
14089
14090         if (!(sc->link_params.speed_cap_mask[idx] &
14091               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14092             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14093         }
14094
14095         if (!(sc->link_params.speed_cap_mask[idx] &
14096               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14097             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14098         }
14099
14100         if (!(sc->link_params.speed_cap_mask[idx] &
14101               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14102             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14103         }
14104     }
14105
14106     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14107           sc->port.supported[0], sc->port.supported[1]);
14108         ELINK_DEBUG_P2(sc, "PHY supported 0=0x%08x 1=0x%08x\n",
14109                                         sc->port.supported[0], sc->port.supported[1]);
14110 }
14111
14112 static void
14113 bxe_link_settings_requested(struct bxe_softc *sc)
14114 {
14115     uint32_t link_config;
14116     uint32_t idx;
14117     uint32_t cfg_size = 0;
14118
14119     sc->port.advertising[0] = 0;
14120     sc->port.advertising[1] = 0;
14121
14122     switch (sc->link_params.num_phys) {
14123     case 1:
14124     case 2:
14125         cfg_size = 1;
14126         break;
14127     case 3:
14128         cfg_size = 2;
14129         break;
14130     }
14131
14132     for (idx = 0; idx < cfg_size; idx++) {
14133         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14134         link_config = sc->port.link_config[idx];
14135
14136         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14137         case PORT_FEATURE_LINK_SPEED_AUTO:
14138             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14139                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14140                 sc->port.advertising[idx] |= sc->port.supported[idx];
14141                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14142                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14143                     sc->port.advertising[idx] |=
14144                         (ELINK_SUPPORTED_100baseT_Half |
14145                          ELINK_SUPPORTED_100baseT_Full);
14146             } else {
14147                 /* force 10G, no AN */
14148                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14149                 sc->port.advertising[idx] |=
14150                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14151                 continue;
14152             }
14153             break;
14154
14155         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14156             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14157                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14158                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14159                                               ADVERTISED_TP);
14160             } else {
14161                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14162                           "speed_cap_mask=0x%08x\n",
14163                       link_config, sc->link_params.speed_cap_mask[idx]);
14164                 return;
14165             }
14166             break;
14167
14168         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14169             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14170                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14171                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14172                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14173                                               ADVERTISED_TP);
14174                                 ELINK_DEBUG_P1(sc, "driver requesting DUPLEX_HALF req_duplex = %x!\n",
14175                                                                 sc->link_params.req_duplex[idx]);
14176             } else {
14177                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14178                           "speed_cap_mask=0x%08x\n",
14179                       link_config, sc->link_params.speed_cap_mask[idx]);
14180                 return;
14181             }
14182             break;
14183
14184         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14185             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14186                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14187                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
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_HALF:
14198             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14199                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14200                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14201                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14202                                               ADVERTISED_TP);
14203             } else {
14204                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14205                           "speed_cap_mask=0x%08x\n",
14206                       link_config, sc->link_params.speed_cap_mask[idx]);
14207                 return;
14208             }
14209             break;
14210
14211         case PORT_FEATURE_LINK_SPEED_1G:
14212             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14213                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14214                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
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_2_5G:
14225             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14226                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14227                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_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_10G_CX4:
14238             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14239                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14240                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14241                                               ADVERTISED_FIBRE);
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_20G:
14251             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14252             break;
14253
14254         default:
14255             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14256                       "speed_cap_mask=0x%08x\n",
14257                   link_config, sc->link_params.speed_cap_mask[idx]);
14258             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14259             sc->port.advertising[idx] = sc->port.supported[idx];
14260             break;
14261         }
14262
14263         sc->link_params.req_flow_ctrl[idx] =
14264             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14265
14266         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14267             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14268                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14269             } else {
14270                 bxe_set_requested_fc(sc);
14271             }
14272         }
14273
14274         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14275                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14276               sc->link_params.req_line_speed[idx],
14277               sc->link_params.req_duplex[idx],
14278               sc->link_params.req_flow_ctrl[idx],
14279               sc->port.advertising[idx]);
14280                 ELINK_DEBUG_P3(sc, "req_line_speed=%d req_duplex=%d "
14281                                                 "advertising=0x%x\n",
14282                                                 sc->link_params.req_line_speed[idx],
14283                                                 sc->link_params.req_duplex[idx],
14284                                                 sc->port.advertising[idx]);
14285     }
14286 }
14287
14288 static void
14289 bxe_get_phy_info(struct bxe_softc *sc)
14290 {
14291     uint8_t port = SC_PORT(sc);
14292     uint32_t config = sc->port.config;
14293     uint32_t eee_mode;
14294
14295     /* shmem data already read in bxe_get_shmem_info() */
14296
14297     ELINK_DEBUG_P3(sc, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14298                         "link_config0=0x%08x\n",
14299                sc->link_params.lane_config,
14300                sc->link_params.speed_cap_mask[0],
14301                sc->port.link_config[0]);
14302      
14303
14304     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14305     bxe_link_settings_requested(sc);
14306
14307     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14308         sc->link_params.feature_config_flags |=
14309             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14310     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14311         sc->link_params.feature_config_flags &=
14312             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14313     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14314         sc->link_params.feature_config_flags |=
14315             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14316     }
14317
14318     /* configure link feature according to nvram value */
14319     eee_mode =
14320         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14321           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14322          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14323     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14324         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14325                                     ELINK_EEE_MODE_ENABLE_LPI |
14326                                     ELINK_EEE_MODE_OUTPUT_TIME);
14327     } else {
14328         sc->link_params.eee_mode = 0;
14329     }
14330
14331     /* get the media type */
14332     bxe_media_detect(sc);
14333         ELINK_DEBUG_P1(sc, "detected media type\n", sc->media);
14334 }
14335
14336 static void
14337 bxe_get_params(struct bxe_softc *sc)
14338 {
14339     /* get user tunable params */
14340     bxe_get_tunable_params(sc);
14341
14342     /* select the RX and TX ring sizes */
14343     sc->tx_ring_size = TX_BD_USABLE;
14344     sc->rx_ring_size = RX_BD_USABLE;
14345
14346     /* XXX disable WoL */
14347     sc->wol = 0;
14348 }
14349
14350 static void
14351 bxe_set_modes_bitmap(struct bxe_softc *sc)
14352 {
14353     uint32_t flags = 0;
14354
14355     if (CHIP_REV_IS_FPGA(sc)) {
14356         SET_FLAGS(flags, MODE_FPGA);
14357     } else if (CHIP_REV_IS_EMUL(sc)) {
14358         SET_FLAGS(flags, MODE_EMUL);
14359     } else {
14360         SET_FLAGS(flags, MODE_ASIC);
14361     }
14362
14363     if (CHIP_IS_MODE_4_PORT(sc)) {
14364         SET_FLAGS(flags, MODE_PORT4);
14365     } else {
14366         SET_FLAGS(flags, MODE_PORT2);
14367     }
14368
14369     if (CHIP_IS_E2(sc)) {
14370         SET_FLAGS(flags, MODE_E2);
14371     } else if (CHIP_IS_E3(sc)) {
14372         SET_FLAGS(flags, MODE_E3);
14373         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14374             SET_FLAGS(flags, MODE_E3_A0);
14375         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14376             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14377         }
14378     }
14379
14380     if (IS_MF(sc)) {
14381         SET_FLAGS(flags, MODE_MF);
14382         switch (sc->devinfo.mf_info.mf_mode) {
14383         case MULTI_FUNCTION_SD:
14384             SET_FLAGS(flags, MODE_MF_SD);
14385             break;
14386         case MULTI_FUNCTION_SI:
14387             SET_FLAGS(flags, MODE_MF_SI);
14388             break;
14389         case MULTI_FUNCTION_AFEX:
14390             SET_FLAGS(flags, MODE_MF_AFEX);
14391             break;
14392         }
14393     } else {
14394         SET_FLAGS(flags, MODE_SF);
14395     }
14396
14397 #if defined(__LITTLE_ENDIAN)
14398     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14399 #else /* __BIG_ENDIAN */
14400     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14401 #endif
14402
14403     INIT_MODE_FLAGS(sc) = flags;
14404 }
14405
14406 static int
14407 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14408 {
14409     struct bxe_fastpath *fp;
14410     bus_addr_t busaddr;
14411     int max_agg_queues;
14412     int max_segments;
14413     bus_size_t max_size;
14414     bus_size_t max_seg_size;
14415     char buf[32];
14416     int rc;
14417     int i, j;
14418
14419     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14420
14421     /* allocate the parent bus DMA tag */
14422     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14423                             1,                        /* alignment */
14424                             0,                        /* boundary limit */
14425                             BUS_SPACE_MAXADDR,        /* restricted low */
14426                             BUS_SPACE_MAXADDR,        /* restricted hi */
14427                             NULL,                     /* addr filter() */
14428                             NULL,                     /* addr filter() arg */
14429                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14430                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14431                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14432                             0,                        /* flags */
14433                             NULL,                     /* lock() */
14434                             NULL,                     /* lock() arg */
14435                             &sc->parent_dma_tag);     /* returned dma tag */
14436     if (rc != 0) {
14437         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14438         return (1);
14439     }
14440
14441     /************************/
14442     /* DEFAULT STATUS BLOCK */
14443     /************************/
14444
14445     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14446                       &sc->def_sb_dma, "default status block") != 0) {
14447         /* XXX */
14448         bus_dma_tag_destroy(sc->parent_dma_tag);
14449         return (1);
14450     }
14451
14452     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14453
14454     /***************/
14455     /* EVENT QUEUE */
14456     /***************/
14457
14458     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14459                       &sc->eq_dma, "event queue") != 0) {
14460         /* XXX */
14461         bxe_dma_free(sc, &sc->def_sb_dma);
14462         sc->def_sb = NULL;
14463         bus_dma_tag_destroy(sc->parent_dma_tag);
14464         return (1);
14465     }
14466
14467     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14468
14469     /*************/
14470     /* SLOW PATH */
14471     /*************/
14472
14473     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14474                       &sc->sp_dma, "slow path") != 0) {
14475         /* XXX */
14476         bxe_dma_free(sc, &sc->eq_dma);
14477         sc->eq = NULL;
14478         bxe_dma_free(sc, &sc->def_sb_dma);
14479         sc->def_sb = NULL;
14480         bus_dma_tag_destroy(sc->parent_dma_tag);
14481         return (1);
14482     }
14483
14484     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14485
14486     /*******************/
14487     /* SLOW PATH QUEUE */
14488     /*******************/
14489
14490     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14491                       &sc->spq_dma, "slow path queue") != 0) {
14492         /* XXX */
14493         bxe_dma_free(sc, &sc->sp_dma);
14494         sc->sp = NULL;
14495         bxe_dma_free(sc, &sc->eq_dma);
14496         sc->eq = NULL;
14497         bxe_dma_free(sc, &sc->def_sb_dma);
14498         sc->def_sb = NULL;
14499         bus_dma_tag_destroy(sc->parent_dma_tag);
14500         return (1);
14501     }
14502
14503     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14504
14505     /***************************/
14506     /* FW DECOMPRESSION BUFFER */
14507     /***************************/
14508
14509     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14510                       "fw decompression buffer") != 0) {
14511         /* XXX */
14512         bxe_dma_free(sc, &sc->spq_dma);
14513         sc->spq = NULL;
14514         bxe_dma_free(sc, &sc->sp_dma);
14515         sc->sp = NULL;
14516         bxe_dma_free(sc, &sc->eq_dma);
14517         sc->eq = NULL;
14518         bxe_dma_free(sc, &sc->def_sb_dma);
14519         sc->def_sb = NULL;
14520         bus_dma_tag_destroy(sc->parent_dma_tag);
14521         return (1);
14522     }
14523
14524     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14525
14526     if ((sc->gz_strm =
14527          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14528         /* XXX */
14529         bxe_dma_free(sc, &sc->gz_buf_dma);
14530         sc->gz_buf = NULL;
14531         bxe_dma_free(sc, &sc->spq_dma);
14532         sc->spq = NULL;
14533         bxe_dma_free(sc, &sc->sp_dma);
14534         sc->sp = NULL;
14535         bxe_dma_free(sc, &sc->eq_dma);
14536         sc->eq = NULL;
14537         bxe_dma_free(sc, &sc->def_sb_dma);
14538         sc->def_sb = NULL;
14539         bus_dma_tag_destroy(sc->parent_dma_tag);
14540         return (1);
14541     }
14542
14543     /*************/
14544     /* FASTPATHS */
14545     /*************/
14546
14547     /* allocate DMA memory for each fastpath structure */
14548     for (i = 0; i < sc->num_queues; i++) {
14549         fp = &sc->fp[i];
14550         fp->sc    = sc;
14551         fp->index = i;
14552
14553         /*******************/
14554         /* FP STATUS BLOCK */
14555         /*******************/
14556
14557         snprintf(buf, sizeof(buf), "fp %d status block", i);
14558         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14559                           &fp->sb_dma, buf) != 0) {
14560             /* XXX unwind and free previous fastpath allocations */
14561             BLOGE(sc, "Failed to alloc %s\n", buf);
14562             return (1);
14563         } else {
14564             if (CHIP_IS_E2E3(sc)) {
14565                 fp->status_block.e2_sb =
14566                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14567             } else {
14568                 fp->status_block.e1x_sb =
14569                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14570             }
14571         }
14572
14573         /******************/
14574         /* FP TX BD CHAIN */
14575         /******************/
14576
14577         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14578         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14579                           &fp->tx_dma, buf) != 0) {
14580             /* XXX unwind and free previous fastpath allocations */
14581             BLOGE(sc, "Failed to alloc %s\n", buf);
14582             return (1);
14583         } else {
14584             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14585         }
14586
14587         /* link together the tx bd chain pages */
14588         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14589             /* index into the tx bd chain array to last entry per page */
14590             struct eth_tx_next_bd *tx_next_bd =
14591                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14592             /* point to the next page and wrap from last page */
14593             busaddr = (fp->tx_dma.paddr +
14594                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14595             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14596             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14597         }
14598
14599         /******************/
14600         /* FP RX BD CHAIN */
14601         /******************/
14602
14603         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14604         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14605                           &fp->rx_dma, buf) != 0) {
14606             /* XXX unwind and free previous fastpath allocations */
14607             BLOGE(sc, "Failed to alloc %s\n", buf);
14608             return (1);
14609         } else {
14610             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14611         }
14612
14613         /* link together the rx bd chain pages */
14614         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14615             /* index into the rx bd chain array to last entry per page */
14616             struct eth_rx_bd *rx_bd =
14617                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14618             /* point to the next page and wrap from last page */
14619             busaddr = (fp->rx_dma.paddr +
14620                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14621             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14622             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14623         }
14624
14625         /*******************/
14626         /* FP RX RCQ CHAIN */
14627         /*******************/
14628
14629         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14630         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14631                           &fp->rcq_dma, buf) != 0) {
14632             /* XXX unwind and free previous fastpath allocations */
14633             BLOGE(sc, "Failed to alloc %s\n", buf);
14634             return (1);
14635         } else {
14636             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14637         }
14638
14639         /* link together the rcq chain pages */
14640         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14641             /* index into the rcq chain array to last entry per page */
14642             struct eth_rx_cqe_next_page *rx_cqe_next =
14643                 (struct eth_rx_cqe_next_page *)
14644                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14645             /* point to the next page and wrap from last page */
14646             busaddr = (fp->rcq_dma.paddr +
14647                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14648             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14649             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14650         }
14651
14652         /*******************/
14653         /* FP RX SGE CHAIN */
14654         /*******************/
14655
14656         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14657         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14658                           &fp->rx_sge_dma, buf) != 0) {
14659             /* XXX unwind and free previous fastpath allocations */
14660             BLOGE(sc, "Failed to alloc %s\n", buf);
14661             return (1);
14662         } else {
14663             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14664         }
14665
14666         /* link together the sge chain pages */
14667         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14668             /* index into the rcq chain array to last entry per page */
14669             struct eth_rx_sge *rx_sge =
14670                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14671             /* point to the next page and wrap from last page */
14672             busaddr = (fp->rx_sge_dma.paddr +
14673                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14674             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14675             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14676         }
14677
14678         /***********************/
14679         /* FP TX MBUF DMA MAPS */
14680         /***********************/
14681
14682         /* set required sizes before mapping to conserve resources */
14683         if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
14684             max_size     = BXE_TSO_MAX_SIZE;
14685             max_segments = BXE_TSO_MAX_SEGMENTS;
14686             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14687         } else {
14688             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14689             max_segments = BXE_MAX_SEGMENTS;
14690             max_seg_size = MCLBYTES;
14691         }
14692
14693         /* create a dma tag for the tx mbufs */
14694         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14695                                 1,                  /* alignment */
14696                                 0,                  /* boundary limit */
14697                                 BUS_SPACE_MAXADDR,  /* restricted low */
14698                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14699                                 NULL,               /* addr filter() */
14700                                 NULL,               /* addr filter() arg */
14701                                 max_size,           /* max map size */
14702                                 max_segments,       /* num discontinuous */
14703                                 max_seg_size,       /* max seg size */
14704                                 0,                  /* flags */
14705                                 NULL,               /* lock() */
14706                                 NULL,               /* lock() arg */
14707                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14708         if (rc != 0) {
14709             /* XXX unwind and free previous fastpath allocations */
14710             BLOGE(sc, "Failed to create dma tag for "
14711                       "'fp %d tx mbufs' (%d)\n", i, rc);
14712             return (1);
14713         }
14714
14715         /* create dma maps for each of the tx mbuf clusters */
14716         for (j = 0; j < TX_BD_TOTAL; j++) {
14717             if (bus_dmamap_create(fp->tx_mbuf_tag,
14718                                   BUS_DMA_NOWAIT,
14719                                   &fp->tx_mbuf_chain[j].m_map)) {
14720                 /* XXX unwind and free previous fastpath allocations */
14721                 BLOGE(sc, "Failed to create dma map for "
14722                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14723                 return (1);
14724             }
14725         }
14726
14727         /***********************/
14728         /* FP RX MBUF DMA MAPS */
14729         /***********************/
14730
14731         /* create a dma tag for the rx mbufs */
14732         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14733                                 1,                  /* alignment */
14734                                 0,                  /* boundary limit */
14735                                 BUS_SPACE_MAXADDR,  /* restricted low */
14736                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14737                                 NULL,               /* addr filter() */
14738                                 NULL,               /* addr filter() arg */
14739                                 MJUM9BYTES,         /* max map size */
14740                                 1,                  /* num discontinuous */
14741                                 MJUM9BYTES,         /* max seg size */
14742                                 0,                  /* flags */
14743                                 NULL,               /* lock() */
14744                                 NULL,               /* lock() arg */
14745                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14746         if (rc != 0) {
14747             /* XXX unwind and free previous fastpath allocations */
14748             BLOGE(sc, "Failed to create dma tag for "
14749                       "'fp %d rx mbufs' (%d)\n", i, rc);
14750             return (1);
14751         }
14752
14753         /* create dma maps for each of the rx mbuf clusters */
14754         for (j = 0; j < RX_BD_TOTAL; j++) {
14755             if (bus_dmamap_create(fp->rx_mbuf_tag,
14756                                   BUS_DMA_NOWAIT,
14757                                   &fp->rx_mbuf_chain[j].m_map)) {
14758                 /* XXX unwind and free previous fastpath allocations */
14759                 BLOGE(sc, "Failed to create dma map for "
14760                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14761                 return (1);
14762             }
14763         }
14764
14765         /* create dma map for the spare rx mbuf cluster */
14766         if (bus_dmamap_create(fp->rx_mbuf_tag,
14767                               BUS_DMA_NOWAIT,
14768                               &fp->rx_mbuf_spare_map)) {
14769             /* XXX unwind and free previous fastpath allocations */
14770             BLOGE(sc, "Failed to create dma map for "
14771                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14772             return (1);
14773         }
14774
14775         /***************************/
14776         /* FP RX SGE MBUF DMA MAPS */
14777         /***************************/
14778
14779         /* create a dma tag for the rx sge mbufs */
14780         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14781                                 1,                  /* alignment */
14782                                 0,                  /* boundary limit */
14783                                 BUS_SPACE_MAXADDR,  /* restricted low */
14784                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14785                                 NULL,               /* addr filter() */
14786                                 NULL,               /* addr filter() arg */
14787                                 BCM_PAGE_SIZE,      /* max map size */
14788                                 1,                  /* num discontinuous */
14789                                 BCM_PAGE_SIZE,      /* max seg size */
14790                                 0,                  /* flags */
14791                                 NULL,               /* lock() */
14792                                 NULL,               /* lock() arg */
14793                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14794         if (rc != 0) {
14795             /* XXX unwind and free previous fastpath allocations */
14796             BLOGE(sc, "Failed to create dma tag for "
14797                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14798             return (1);
14799         }
14800
14801         /* create dma maps for the rx sge mbuf clusters */
14802         for (j = 0; j < RX_SGE_TOTAL; j++) {
14803             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14804                                   BUS_DMA_NOWAIT,
14805                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14806                 /* XXX unwind and free previous fastpath allocations */
14807                 BLOGE(sc, "Failed to create dma map for "
14808                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14809                 return (1);
14810             }
14811         }
14812
14813         /* create dma map for the spare rx sge mbuf cluster */
14814         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14815                               BUS_DMA_NOWAIT,
14816                               &fp->rx_sge_mbuf_spare_map)) {
14817             /* XXX unwind and free previous fastpath allocations */
14818             BLOGE(sc, "Failed to create dma map for "
14819                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14820             return (1);
14821         }
14822
14823         /***************************/
14824         /* FP RX TPA MBUF DMA MAPS */
14825         /***************************/
14826
14827         /* create dma maps for the rx tpa mbuf clusters */
14828         max_agg_queues = MAX_AGG_QS(sc);
14829
14830         for (j = 0; j < max_agg_queues; j++) {
14831             if (bus_dmamap_create(fp->rx_mbuf_tag,
14832                                   BUS_DMA_NOWAIT,
14833                                   &fp->rx_tpa_info[j].bd.m_map)) {
14834                 /* XXX unwind and free previous fastpath allocations */
14835                 BLOGE(sc, "Failed to create dma map for "
14836                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14837                 return (1);
14838             }
14839         }
14840
14841         /* create dma map for the spare rx tpa mbuf cluster */
14842         if (bus_dmamap_create(fp->rx_mbuf_tag,
14843                               BUS_DMA_NOWAIT,
14844                               &fp->rx_tpa_info_mbuf_spare_map)) {
14845             /* XXX unwind and free previous fastpath allocations */
14846             BLOGE(sc, "Failed to create dma map for "
14847                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14848             return (1);
14849         }
14850
14851         bxe_init_sge_ring_bit_mask(fp);
14852     }
14853
14854     return (0);
14855 }
14856
14857 static void
14858 bxe_free_hsi_mem(struct bxe_softc *sc)
14859 {
14860     struct bxe_fastpath *fp;
14861     int max_agg_queues;
14862     int i, j;
14863
14864     if (sc->parent_dma_tag == NULL) {
14865         return; /* assume nothing was allocated */
14866     }
14867
14868     for (i = 0; i < sc->num_queues; i++) {
14869         fp = &sc->fp[i];
14870
14871         /*******************/
14872         /* FP STATUS BLOCK */
14873         /*******************/
14874
14875         bxe_dma_free(sc, &fp->sb_dma);
14876         memset(&fp->status_block, 0, sizeof(fp->status_block));
14877
14878         /******************/
14879         /* FP TX BD CHAIN */
14880         /******************/
14881
14882         bxe_dma_free(sc, &fp->tx_dma);
14883         fp->tx_chain = NULL;
14884
14885         /******************/
14886         /* FP RX BD CHAIN */
14887         /******************/
14888
14889         bxe_dma_free(sc, &fp->rx_dma);
14890         fp->rx_chain = NULL;
14891
14892         /*******************/
14893         /* FP RX RCQ CHAIN */
14894         /*******************/
14895
14896         bxe_dma_free(sc, &fp->rcq_dma);
14897         fp->rcq_chain = NULL;
14898
14899         /*******************/
14900         /* FP RX SGE CHAIN */
14901         /*******************/
14902
14903         bxe_dma_free(sc, &fp->rx_sge_dma);
14904         fp->rx_sge_chain = NULL;
14905
14906         /***********************/
14907         /* FP TX MBUF DMA MAPS */
14908         /***********************/
14909
14910         if (fp->tx_mbuf_tag != NULL) {
14911             for (j = 0; j < TX_BD_TOTAL; j++) {
14912                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14913                     bus_dmamap_unload(fp->tx_mbuf_tag,
14914                                       fp->tx_mbuf_chain[j].m_map);
14915                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14916                                        fp->tx_mbuf_chain[j].m_map);
14917                 }
14918             }
14919
14920             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14921             fp->tx_mbuf_tag = NULL;
14922         }
14923
14924         /***********************/
14925         /* FP RX MBUF DMA MAPS */
14926         /***********************/
14927
14928         if (fp->rx_mbuf_tag != NULL) {
14929             for (j = 0; j < RX_BD_TOTAL; j++) {
14930                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14931                     bus_dmamap_unload(fp->rx_mbuf_tag,
14932                                       fp->rx_mbuf_chain[j].m_map);
14933                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14934                                        fp->rx_mbuf_chain[j].m_map);
14935                 }
14936             }
14937
14938             if (fp->rx_mbuf_spare_map != NULL) {
14939                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14940                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14941             }
14942
14943             /***************************/
14944             /* FP RX TPA MBUF DMA MAPS */
14945             /***************************/
14946
14947             max_agg_queues = MAX_AGG_QS(sc);
14948
14949             for (j = 0; j < max_agg_queues; j++) {
14950                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14951                     bus_dmamap_unload(fp->rx_mbuf_tag,
14952                                       fp->rx_tpa_info[j].bd.m_map);
14953                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14954                                        fp->rx_tpa_info[j].bd.m_map);
14955                 }
14956             }
14957
14958             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14959                 bus_dmamap_unload(fp->rx_mbuf_tag,
14960                                   fp->rx_tpa_info_mbuf_spare_map);
14961                 bus_dmamap_destroy(fp->rx_mbuf_tag,
14962                                    fp->rx_tpa_info_mbuf_spare_map);
14963             }
14964
14965             bus_dma_tag_destroy(fp->rx_mbuf_tag);
14966             fp->rx_mbuf_tag = NULL;
14967         }
14968
14969         /***************************/
14970         /* FP RX SGE MBUF DMA MAPS */
14971         /***************************/
14972
14973         if (fp->rx_sge_mbuf_tag != NULL) {
14974             for (j = 0; j < RX_SGE_TOTAL; j++) {
14975                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14976                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14977                                       fp->rx_sge_mbuf_chain[j].m_map);
14978                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14979                                        fp->rx_sge_mbuf_chain[j].m_map);
14980                 }
14981             }
14982
14983             if (fp->rx_sge_mbuf_spare_map != NULL) {
14984                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14985                                   fp->rx_sge_mbuf_spare_map);
14986                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14987                                    fp->rx_sge_mbuf_spare_map);
14988             }
14989
14990             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
14991             fp->rx_sge_mbuf_tag = NULL;
14992         }
14993     }
14994
14995     /***************************/
14996     /* FW DECOMPRESSION BUFFER */
14997     /***************************/
14998
14999     bxe_dma_free(sc, &sc->gz_buf_dma);
15000     sc->gz_buf = NULL;
15001     free(sc->gz_strm, M_DEVBUF);
15002     sc->gz_strm = NULL;
15003
15004     /*******************/
15005     /* SLOW PATH QUEUE */
15006     /*******************/
15007
15008     bxe_dma_free(sc, &sc->spq_dma);
15009     sc->spq = NULL;
15010
15011     /*************/
15012     /* SLOW PATH */
15013     /*************/
15014
15015     bxe_dma_free(sc, &sc->sp_dma);
15016     sc->sp = NULL;
15017
15018     /***************/
15019     /* EVENT QUEUE */
15020     /***************/
15021
15022     bxe_dma_free(sc, &sc->eq_dma);
15023     sc->eq = NULL;
15024
15025     /************************/
15026     /* DEFAULT STATUS BLOCK */
15027     /************************/
15028
15029     bxe_dma_free(sc, &sc->def_sb_dma);
15030     sc->def_sb = NULL;
15031
15032     bus_dma_tag_destroy(sc->parent_dma_tag);
15033     sc->parent_dma_tag = NULL;
15034 }
15035
15036 /*
15037  * Previous driver DMAE transaction may have occurred when pre-boot stage
15038  * ended and boot began. This would invalidate the addresses of the
15039  * transaction, resulting in was-error bit set in the PCI causing all
15040  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15041  * the interrupt which detected this from the pglueb and the was-done bit
15042  */
15043 static void
15044 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15045 {
15046     uint32_t val;
15047
15048     if (!CHIP_IS_E1x(sc)) {
15049         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15050         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15051             BLOGD(sc, DBG_LOAD,
15052                   "Clearing 'was-error' bit that was set in pglueb");
15053             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15054         }
15055     }
15056 }
15057
15058 static int
15059 bxe_prev_mcp_done(struct bxe_softc *sc)
15060 {
15061     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15062                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15063     if (!rc) {
15064         BLOGE(sc, "MCP response failure, aborting\n");
15065         return (-1);
15066     }
15067
15068     return (0);
15069 }
15070
15071 static struct bxe_prev_list_node *
15072 bxe_prev_path_get_entry(struct bxe_softc *sc)
15073 {
15074     struct bxe_prev_list_node *tmp;
15075
15076     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15077         if ((sc->pcie_bus == tmp->bus) &&
15078             (sc->pcie_device == tmp->slot) &&
15079             (SC_PATH(sc) == tmp->path)) {
15080             return (tmp);
15081         }
15082     }
15083
15084     return (NULL);
15085 }
15086
15087 static uint8_t
15088 bxe_prev_is_path_marked(struct bxe_softc *sc)
15089 {
15090     struct bxe_prev_list_node *tmp;
15091     int rc = FALSE;
15092
15093     mtx_lock(&bxe_prev_mtx);
15094
15095     tmp = bxe_prev_path_get_entry(sc);
15096     if (tmp) {
15097         if (tmp->aer) {
15098             BLOGD(sc, DBG_LOAD,
15099                   "Path %d/%d/%d was marked by AER\n",
15100                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15101         } else {
15102             rc = TRUE;
15103             BLOGD(sc, DBG_LOAD,
15104                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15105                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15106         }
15107     }
15108
15109     mtx_unlock(&bxe_prev_mtx);
15110
15111     return (rc);
15112 }
15113
15114 static int
15115 bxe_prev_mark_path(struct bxe_softc *sc,
15116                    uint8_t          after_undi)
15117 {
15118     struct bxe_prev_list_node *tmp;
15119
15120     mtx_lock(&bxe_prev_mtx);
15121
15122     /* Check whether the entry for this path already exists */
15123     tmp = bxe_prev_path_get_entry(sc);
15124     if (tmp) {
15125         if (!tmp->aer) {
15126             BLOGD(sc, DBG_LOAD,
15127                   "Re-marking AER in path %d/%d/%d\n",
15128                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15129         } else {
15130             BLOGD(sc, DBG_LOAD,
15131                   "Removing AER indication from path %d/%d/%d\n",
15132                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15133             tmp->aer = 0;
15134         }
15135
15136         mtx_unlock(&bxe_prev_mtx);
15137         return (0);
15138     }
15139
15140     mtx_unlock(&bxe_prev_mtx);
15141
15142     /* Create an entry for this path and add it */
15143     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15144                  (M_NOWAIT | M_ZERO));
15145     if (!tmp) {
15146         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15147         return (-1);
15148     }
15149
15150     tmp->bus  = sc->pcie_bus;
15151     tmp->slot = sc->pcie_device;
15152     tmp->path = SC_PATH(sc);
15153     tmp->aer  = 0;
15154     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15155
15156     mtx_lock(&bxe_prev_mtx);
15157
15158     BLOGD(sc, DBG_LOAD,
15159           "Marked path %d/%d/%d - finished previous unload\n",
15160           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15161     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15162
15163     mtx_unlock(&bxe_prev_mtx);
15164
15165     return (0);
15166 }
15167
15168 static int
15169 bxe_do_flr(struct bxe_softc *sc)
15170 {
15171     int i;
15172
15173     /* only E2 and onwards support FLR */
15174     if (CHIP_IS_E1x(sc)) {
15175         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15176         return (-1);
15177     }
15178
15179     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15180     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15181         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15182               sc->devinfo.bc_ver);
15183         return (-1);
15184     }
15185
15186     /* Wait for Transaction Pending bit clean */
15187     for (i = 0; i < 4; i++) {
15188         if (i) {
15189             DELAY(((1 << (i - 1)) * 100) * 1000);
15190         }
15191
15192         if (!bxe_is_pcie_pending(sc)) {
15193             goto clear;
15194         }
15195     }
15196
15197     BLOGE(sc, "PCIE transaction is not cleared, "
15198               "proceeding with reset anyway\n");
15199
15200 clear:
15201
15202     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15203     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15204
15205     return (0);
15206 }
15207
15208 struct bxe_mac_vals {
15209     uint32_t xmac_addr;
15210     uint32_t xmac_val;
15211     uint32_t emac_addr;
15212     uint32_t emac_val;
15213     uint32_t umac_addr;
15214     uint32_t umac_val;
15215     uint32_t bmac_addr;
15216     uint32_t bmac_val[2];
15217 };
15218
15219 static void
15220 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15221                           struct bxe_mac_vals *vals)
15222 {
15223     uint32_t val, base_addr, offset, mask, reset_reg;
15224     uint8_t mac_stopped = FALSE;
15225     uint8_t port = SC_PORT(sc);
15226     uint32_t wb_data[2];
15227
15228     /* reset addresses as they also mark which values were changed */
15229     vals->bmac_addr = 0;
15230     vals->umac_addr = 0;
15231     vals->xmac_addr = 0;
15232     vals->emac_addr = 0;
15233
15234     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15235
15236     if (!CHIP_IS_E3(sc)) {
15237         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15238         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15239         if ((mask & reset_reg) && val) {
15240             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15241             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15242                                     : NIG_REG_INGRESS_BMAC0_MEM;
15243             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15244                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15245
15246             /*
15247              * use rd/wr since we cannot use dmae. This is safe
15248              * since MCP won't access the bus due to the request
15249              * to unload, and no function on the path can be
15250              * loaded at this time.
15251              */
15252             wb_data[0] = REG_RD(sc, base_addr + offset);
15253             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15254             vals->bmac_addr = base_addr + offset;
15255             vals->bmac_val[0] = wb_data[0];
15256             vals->bmac_val[1] = wb_data[1];
15257             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15258             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15259             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15260         }
15261
15262         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15263         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15264         vals->emac_val = REG_RD(sc, vals->emac_addr);
15265         REG_WR(sc, vals->emac_addr, 0);
15266         mac_stopped = TRUE;
15267     } else {
15268         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15269             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15270             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15271             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15272             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15273             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15274             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15275             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15276             REG_WR(sc, vals->xmac_addr, 0);
15277             mac_stopped = TRUE;
15278         }
15279
15280         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15281         if (mask & reset_reg) {
15282             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15283             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15284             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15285             vals->umac_val = REG_RD(sc, vals->umac_addr);
15286             REG_WR(sc, vals->umac_addr, 0);
15287             mac_stopped = TRUE;
15288         }
15289     }
15290
15291     if (mac_stopped) {
15292         DELAY(20000);
15293     }
15294 }
15295
15296 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15297 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15298 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15299 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15300
15301 static void
15302 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15303                          uint8_t          port,
15304                          uint8_t          inc)
15305 {
15306     uint16_t rcq, bd;
15307     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15308
15309     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15310     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15311
15312     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15313     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15314
15315     BLOGD(sc, DBG_LOAD,
15316           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15317           port, bd, rcq);
15318 }
15319
15320 static int
15321 bxe_prev_unload_common(struct bxe_softc *sc)
15322 {
15323     uint32_t reset_reg, tmp_reg = 0, rc;
15324     uint8_t prev_undi = FALSE;
15325     struct bxe_mac_vals mac_vals;
15326     uint32_t timer_count = 1000;
15327     uint32_t prev_brb;
15328
15329     /*
15330      * It is possible a previous function received 'common' answer,
15331      * but hasn't loaded yet, therefore creating a scenario of
15332      * multiple functions receiving 'common' on the same path.
15333      */
15334     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15335
15336     memset(&mac_vals, 0, sizeof(mac_vals));
15337
15338     if (bxe_prev_is_path_marked(sc)) {
15339         return (bxe_prev_mcp_done(sc));
15340     }
15341
15342     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15343
15344     /* Reset should be performed after BRB is emptied */
15345     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15346         /* Close the MAC Rx to prevent BRB from filling up */
15347         bxe_prev_unload_close_mac(sc, &mac_vals);
15348
15349         /* close LLH filters towards the BRB */
15350         elink_set_rx_filter(&sc->link_params, 0);
15351
15352         /*
15353          * Check if the UNDI driver was previously loaded.
15354          * UNDI driver initializes CID offset for normal bell to 0x7
15355          */
15356         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15357             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15358             if (tmp_reg == 0x7) {
15359                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15360                 prev_undi = TRUE;
15361                 /* clear the UNDI indication */
15362                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15363                 /* clear possible idle check errors */
15364                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15365             }
15366         }
15367
15368         /* wait until BRB is empty */
15369         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15370         while (timer_count) {
15371             prev_brb = tmp_reg;
15372
15373             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15374             if (!tmp_reg) {
15375                 break;
15376             }
15377
15378             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15379
15380             /* reset timer as long as BRB actually gets emptied */
15381             if (prev_brb > tmp_reg) {
15382                 timer_count = 1000;
15383             } else {
15384                 timer_count--;
15385             }
15386
15387             /* If UNDI resides in memory, manually increment it */
15388             if (prev_undi) {
15389                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15390             }
15391
15392             DELAY(10);
15393         }
15394
15395         if (!timer_count) {
15396             BLOGE(sc, "Failed to empty BRB\n");
15397         }
15398     }
15399
15400     /* No packets are in the pipeline, path is ready for reset */
15401     bxe_reset_common(sc);
15402
15403     if (mac_vals.xmac_addr) {
15404         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15405     }
15406     if (mac_vals.umac_addr) {
15407         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15408     }
15409     if (mac_vals.emac_addr) {
15410         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15411     }
15412     if (mac_vals.bmac_addr) {
15413         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15414         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15415     }
15416
15417     rc = bxe_prev_mark_path(sc, prev_undi);
15418     if (rc) {
15419         bxe_prev_mcp_done(sc);
15420         return (rc);
15421     }
15422
15423     return (bxe_prev_mcp_done(sc));
15424 }
15425
15426 static int
15427 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15428 {
15429     int rc;
15430
15431     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15432
15433     /* Test if previous unload process was already finished for this path */
15434     if (bxe_prev_is_path_marked(sc)) {
15435         return (bxe_prev_mcp_done(sc));
15436     }
15437
15438     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15439
15440     /*
15441      * If function has FLR capabilities, and existing FW version matches
15442      * the one required, then FLR will be sufficient to clean any residue
15443      * left by previous driver
15444      */
15445     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15446     if (!rc) {
15447         /* fw version is good */
15448         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15449         rc = bxe_do_flr(sc);
15450     }
15451
15452     if (!rc) {
15453         /* FLR was performed */
15454         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15455         return (0);
15456     }
15457
15458     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15459
15460     /* Close the MCP request, return failure*/
15461     rc = bxe_prev_mcp_done(sc);
15462     if (!rc) {
15463         rc = BXE_PREV_WAIT_NEEDED;
15464     }
15465
15466     return (rc);
15467 }
15468
15469 static int
15470 bxe_prev_unload(struct bxe_softc *sc)
15471 {
15472     int time_counter = 10;
15473     uint32_t fw, hw_lock_reg, hw_lock_val;
15474     uint32_t rc = 0;
15475
15476     /*
15477      * Clear HW from errors which may have resulted from an interrupted
15478      * DMAE transaction.
15479      */
15480     bxe_prev_interrupted_dmae(sc);
15481
15482     /* Release previously held locks */
15483     hw_lock_reg =
15484         (SC_FUNC(sc) <= 5) ?
15485             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15486             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15487
15488     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15489     if (hw_lock_val) {
15490         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15491             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15492             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15493                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15494         }
15495         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15496         REG_WR(sc, hw_lock_reg, 0xffffffff);
15497     } else {
15498         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15499     }
15500
15501     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15502         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15503         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15504     }
15505
15506     do {
15507         /* Lock MCP using an unload request */
15508         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15509         if (!fw) {
15510             BLOGE(sc, "MCP response failure, aborting\n");
15511             rc = -1;
15512             break;
15513         }
15514
15515         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15516             rc = bxe_prev_unload_common(sc);
15517             break;
15518         }
15519
15520         /* non-common reply from MCP night require looping */
15521         rc = bxe_prev_unload_uncommon(sc);
15522         if (rc != BXE_PREV_WAIT_NEEDED) {
15523             break;
15524         }
15525
15526         DELAY(20000);
15527     } while (--time_counter);
15528
15529     if (!time_counter || rc) {
15530         BLOGE(sc, "Failed to unload previous driver!"
15531             " time_counter %d rc %d\n", time_counter, rc);
15532         rc = -1;
15533     }
15534
15535     return (rc);
15536 }
15537
15538 void
15539 bxe_dcbx_set_state(struct bxe_softc *sc,
15540                    uint8_t          dcb_on,
15541                    uint32_t         dcbx_enabled)
15542 {
15543     if (!CHIP_IS_E1x(sc)) {
15544         sc->dcb_state = dcb_on;
15545         sc->dcbx_enabled = dcbx_enabled;
15546     } else {
15547         sc->dcb_state = FALSE;
15548         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15549     }
15550     BLOGD(sc, DBG_LOAD,
15551           "DCB state [%s:%s]\n",
15552           dcb_on ? "ON" : "OFF",
15553           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15554           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15555           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15556           "on-chip with negotiation" : "invalid");
15557 }
15558
15559 /* must be called after sriov-enable */
15560 static int
15561 bxe_set_qm_cid_count(struct bxe_softc *sc)
15562 {
15563     int cid_count = BXE_L2_MAX_CID(sc);
15564
15565     if (IS_SRIOV(sc)) {
15566         cid_count += BXE_VF_CIDS;
15567     }
15568
15569     if (CNIC_SUPPORT(sc)) {
15570         cid_count += CNIC_CID_MAX;
15571     }
15572
15573     return (roundup(cid_count, QM_CID_ROUND));
15574 }
15575
15576 static void
15577 bxe_init_multi_cos(struct bxe_softc *sc)
15578 {
15579     int pri, cos;
15580
15581     uint32_t pri_map = 0; /* XXX change to user config */
15582
15583     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15584         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15585         if (cos < sc->max_cos) {
15586             sc->prio_to_cos[pri] = cos;
15587         } else {
15588             BLOGW(sc, "Invalid COS %d for priority %d "
15589                       "(max COS is %d), setting to 0\n",
15590                   cos, pri, (sc->max_cos - 1));
15591             sc->prio_to_cos[pri] = 0;
15592         }
15593     }
15594 }
15595
15596 static int
15597 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15598 {
15599     struct bxe_softc *sc;
15600     int error, result;
15601
15602     result = 0;
15603     error = sysctl_handle_int(oidp, &result, 0, req);
15604
15605     if (error || !req->newptr) {
15606         return (error);
15607     }
15608
15609     if (result == 1) {
15610         uint32_t  temp;
15611         sc = (struct bxe_softc *)arg1;
15612
15613         BLOGI(sc, "... dumping driver state ...\n");
15614         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15615         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15616     }
15617
15618     return (error);
15619 }
15620
15621 static int
15622 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15623 {
15624     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15625     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15626     uint32_t *offset;
15627     uint64_t value = 0;
15628     int index = (int)arg2;
15629
15630     if (index >= BXE_NUM_ETH_STATS) {
15631         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15632         return (-1);
15633     }
15634
15635     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15636
15637     switch (bxe_eth_stats_arr[index].size) {
15638     case 4:
15639         value = (uint64_t)*offset;
15640         break;
15641     case 8:
15642         value = HILO_U64(*offset, *(offset + 1));
15643         break;
15644     default:
15645         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15646               index, bxe_eth_stats_arr[index].size);
15647         return (-1);
15648     }
15649
15650     return (sysctl_handle_64(oidp, &value, 0, req));
15651 }
15652
15653 static int
15654 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15655 {
15656     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15657     uint32_t *eth_stats;
15658     uint32_t *offset;
15659     uint64_t value = 0;
15660     uint32_t q_stat = (uint32_t)arg2;
15661     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15662     uint32_t index = (q_stat & 0xffff);
15663
15664     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15665
15666     if (index >= BXE_NUM_ETH_Q_STATS) {
15667         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15668         return (-1);
15669     }
15670
15671     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15672
15673     switch (bxe_eth_q_stats_arr[index].size) {
15674     case 4:
15675         value = (uint64_t)*offset;
15676         break;
15677     case 8:
15678         value = HILO_U64(*offset, *(offset + 1));
15679         break;
15680     default:
15681         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15682               index, bxe_eth_q_stats_arr[index].size);
15683         return (-1);
15684     }
15685
15686     return (sysctl_handle_64(oidp, &value, 0, req));
15687 }
15688
15689 static void bxe_force_link_reset(struct bxe_softc *sc)
15690 {
15691
15692         bxe_acquire_phy_lock(sc);
15693         elink_link_reset(&sc->link_params, &sc->link_vars, 1);
15694         bxe_release_phy_lock(sc);
15695 }
15696
15697 static int
15698 bxe_sysctl_pauseparam(SYSCTL_HANDLER_ARGS)
15699 {
15700         struct bxe_softc *sc = (struct bxe_softc *)arg1;;
15701         uint32_t cfg_idx = bxe_get_link_cfg_idx(sc);
15702         int rc = 0;
15703         int error;
15704         int result;
15705
15706
15707         error = sysctl_handle_int(oidp, &sc->bxe_pause_param, 0, req);
15708
15709         if (error || !req->newptr) {
15710                 return (error);
15711         }
15712         if ((sc->bxe_pause_param < 0) ||  (sc->bxe_pause_param > 8)) {
15713                 BLOGW(sc, "invalid pause param (%d) - use intergers between 1 & 8\n",sc->bxe_pause_param);
15714                 sc->bxe_pause_param = 8;
15715         }
15716
15717         result = (sc->bxe_pause_param << PORT_FEATURE_FLOW_CONTROL_SHIFT);
15718
15719
15720         if((result & 0x400) && !(sc->port.supported[cfg_idx] & ELINK_SUPPORTED_Autoneg))  {
15721                         BLOGW(sc, "Does not support Autoneg pause_param %d\n", sc->bxe_pause_param);
15722                         return -EINVAL;
15723         }
15724
15725         if(IS_MF(sc))
15726                 return 0;
15727        sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_AUTO;
15728         if(result & ELINK_FLOW_CTRL_RX)
15729                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_RX;
15730
15731         if(result & ELINK_FLOW_CTRL_TX)
15732                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_TX;
15733         if(sc->link_params.req_flow_ctrl[cfg_idx] == ELINK_FLOW_CTRL_AUTO)
15734                 sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_NONE;
15735
15736         if(result & 0x400) {
15737                 if (sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG) {
15738                         sc->link_params.req_flow_ctrl[cfg_idx] =
15739                                 ELINK_FLOW_CTRL_AUTO;
15740                 }
15741                 sc->link_params.req_fc_auto_adv = 0;
15742                 if (result & ELINK_FLOW_CTRL_RX)
15743                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_RX;
15744
15745                 if (result & ELINK_FLOW_CTRL_TX)
15746                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_TX;
15747                 if (!sc->link_params.req_fc_auto_adv)
15748                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_NONE;
15749         }
15750          if (IS_PF(sc)) {
15751                         if (sc->link_vars.link_up) {
15752                                 bxe_stats_handle(sc, STATS_EVENT_STOP);
15753                         }
15754                         if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
15755                         bxe_force_link_reset(sc);
15756                         bxe_acquire_phy_lock(sc);
15757
15758                         rc = elink_phy_init(&sc->link_params, &sc->link_vars);
15759
15760                         bxe_release_phy_lock(sc);
15761
15762                         bxe_calc_fc_adv(sc);
15763                         }
15764         }
15765         return rc;
15766 }
15767
15768
15769 static void
15770 bxe_add_sysctls(struct bxe_softc *sc)
15771 {
15772     struct sysctl_ctx_list *ctx;
15773     struct sysctl_oid_list *children;
15774     struct sysctl_oid *queue_top, *queue;
15775     struct sysctl_oid_list *queue_top_children, *queue_children;
15776     char queue_num_buf[32];
15777     uint32_t q_stat;
15778     int i, j;
15779
15780     ctx = device_get_sysctl_ctx(sc->dev);
15781     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15782
15783     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15784                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15785                       "version");
15786
15787     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15788              BCM_5710_FW_MAJOR_VERSION,
15789              BCM_5710_FW_MINOR_VERSION,
15790              BCM_5710_FW_REVISION_VERSION,
15791              BCM_5710_FW_ENGINEERING_VERSION);
15792
15793     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15794         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15795          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15796          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15797          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15798                                                                 "Unknown"));
15799     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15800                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15801                     "multifunction vnics per port");
15802
15803     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15804         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15805          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15806          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15807                                               "???GT/s"),
15808         sc->devinfo.pcie_link_width);
15809
15810     sc->debug = bxe_debug;
15811
15812 #if __FreeBSD_version >= 900000
15813     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15814                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15815                       "bootcode version");
15816     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15817                       CTLFLAG_RD, sc->fw_ver_str, 0,
15818                       "firmware version");
15819     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15820                       CTLFLAG_RD, sc->mf_mode_str, 0,
15821                       "multifunction mode");
15822     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15823                       CTLFLAG_RD, sc->mac_addr_str, 0,
15824                       "mac address");
15825     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15826                       CTLFLAG_RD, &sc->pci_link_str, 0,
15827                       "pci link status");
15828     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15829                     CTLFLAG_RW, &sc->debug, 0,
15830                     "debug logging mode");
15831 #else
15832     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15833                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15834                       "bootcode version");
15835     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15836                       CTLFLAG_RD, &sc->fw_ver_str, 0,
15837                       "firmware version");
15838     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15839                       CTLFLAG_RD, &sc->mf_mode_str, 0,
15840                       "multifunction mode");
15841     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15842                       CTLFLAG_RD, &sc->mac_addr_str, 0,
15843                       "mac address");
15844     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15845                       CTLFLAG_RD, &sc->pci_link_str, 0,
15846                       "pci link status");
15847     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15848                     CTLFLAG_RW, &sc->debug, 0,
15849                     "debug logging mode");
15850 #endif /* #if __FreeBSD_version >= 900000 */
15851
15852     sc->trigger_grcdump = 0;
15853     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
15854                    CTLFLAG_RW, &sc->trigger_grcdump, 0,
15855                    "trigger grcdump should be invoked"
15856                    "  before collecting grcdump");
15857
15858     sc->grcdump_started = 0;
15859     sc->grcdump_done = 0;
15860     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15861                    CTLFLAG_RD, &sc->grcdump_done, 0,
15862                    "set by driver when grcdump is done");
15863
15864     sc->rx_budget = bxe_rx_budget;
15865     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15866                     CTLFLAG_RW, &sc->rx_budget, 0,
15867                     "rx processing budget");
15868
15869    SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_param",
15870                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15871                     bxe_sysctl_pauseparam, "IU",
15872                     "need pause frames- DEF:0/TX:1/RX:2/BOTH:3/AUTO:4/AUTOTX:5/AUTORX:6/AUTORXTX:7/NONE:8");
15873
15874
15875     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15876                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15877                     bxe_sysctl_state, "IU", "dump driver state");
15878
15879     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15880         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15881                         bxe_eth_stats_arr[i].string,
15882                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15883                         bxe_sysctl_eth_stat, "LU",
15884                         bxe_eth_stats_arr[i].string);
15885     }
15886
15887     /* add a new parent node for all queues "dev.bxe.#.queue" */
15888     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15889                                 CTLFLAG_RD, NULL, "queue");
15890     queue_top_children = SYSCTL_CHILDREN(queue_top);
15891
15892     for (i = 0; i < sc->num_queues; i++) {
15893         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15894         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15895         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15896                                 queue_num_buf, CTLFLAG_RD, NULL,
15897                                 "single queue");
15898         queue_children = SYSCTL_CHILDREN(queue);
15899
15900         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15901             q_stat = ((i << 16) | j);
15902             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15903                             bxe_eth_q_stats_arr[j].string,
15904                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15905                             bxe_sysctl_eth_q_stat, "LU",
15906                             bxe_eth_q_stats_arr[j].string);
15907         }
15908     }
15909 }
15910
15911 static int
15912 bxe_alloc_buf_rings(struct bxe_softc *sc)
15913 {
15914 #if __FreeBSD_version >= 800000
15915
15916     int i;
15917     struct bxe_fastpath *fp;
15918
15919     for (i = 0; i < sc->num_queues; i++) {
15920
15921         fp = &sc->fp[i];
15922
15923         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15924                                    M_NOWAIT, &fp->tx_mtx);
15925         if (fp->tx_br == NULL)
15926             return (-1);
15927     }
15928 #endif
15929     return (0);
15930 }
15931
15932 static void
15933 bxe_free_buf_rings(struct bxe_softc *sc)
15934 {
15935 #if __FreeBSD_version >= 800000
15936
15937     int i;
15938     struct bxe_fastpath *fp;
15939
15940     for (i = 0; i < sc->num_queues; i++) {
15941
15942         fp = &sc->fp[i];
15943
15944         if (fp->tx_br) {
15945             buf_ring_free(fp->tx_br, M_DEVBUF);
15946             fp->tx_br = NULL;
15947         }
15948     }
15949
15950 #endif
15951 }
15952
15953 static void
15954 bxe_init_fp_mutexs(struct bxe_softc *sc)
15955 {
15956     int i;
15957     struct bxe_fastpath *fp;
15958
15959     for (i = 0; i < sc->num_queues; i++) {
15960
15961         fp = &sc->fp[i];
15962
15963         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15964             "bxe%d_fp%d_tx_lock", sc->unit, i);
15965         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15966
15967         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15968             "bxe%d_fp%d_rx_lock", sc->unit, i);
15969         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15970     }
15971 }
15972
15973 static void
15974 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15975 {
15976     int i;
15977     struct bxe_fastpath *fp;
15978
15979     for (i = 0; i < sc->num_queues; i++) {
15980
15981         fp = &sc->fp[i];
15982
15983         if (mtx_initialized(&fp->tx_mtx)) {
15984             mtx_destroy(&fp->tx_mtx);
15985         }
15986
15987         if (mtx_initialized(&fp->rx_mtx)) {
15988             mtx_destroy(&fp->rx_mtx);
15989         }
15990     }
15991 }
15992
15993
15994 /*
15995  * Device attach function.
15996  *
15997  * Allocates device resources, performs secondary chip identification, and
15998  * initializes driver instance variables. This function is called from driver
15999  * load after a successful probe.
16000  *
16001  * Returns:
16002  *   0 = Success, >0 = Failure
16003  */
16004 static int
16005 bxe_attach(device_t dev)
16006 {
16007     struct bxe_softc *sc;
16008
16009     sc = device_get_softc(dev);
16010
16011     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
16012
16013     sc->state = BXE_STATE_CLOSED;
16014
16015     sc->dev  = dev;
16016     sc->unit = device_get_unit(dev);
16017
16018     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
16019
16020     sc->pcie_bus    = pci_get_bus(dev);
16021     sc->pcie_device = pci_get_slot(dev);
16022     sc->pcie_func   = pci_get_function(dev);
16023
16024     /* enable bus master capability */
16025     pci_enable_busmaster(dev);
16026
16027     /* get the BARs */
16028     if (bxe_allocate_bars(sc) != 0) {
16029         return (ENXIO);
16030     }
16031
16032     /* initialize the mutexes */
16033     bxe_init_mutexes(sc);
16034
16035     /* prepare the periodic callout */
16036     callout_init(&sc->periodic_callout, 0);
16037
16038     /* prepare the chip taskqueue */
16039     sc->chip_tq_flags = CHIP_TQ_NONE;
16040     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
16041              "bxe%d_chip_tq", sc->unit);
16042     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
16043     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
16044                                    taskqueue_thread_enqueue,
16045                                    &sc->chip_tq);
16046     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
16047                             "%s", sc->chip_tq_name);
16048
16049     /* get device info and set params */
16050     if (bxe_get_device_info(sc) != 0) {
16051         BLOGE(sc, "getting device info\n");
16052         bxe_deallocate_bars(sc);
16053         pci_disable_busmaster(dev);
16054         return (ENXIO);
16055     }
16056
16057     /* get final misc params */
16058     bxe_get_params(sc);
16059
16060     /* set the default MTU (changed via ifconfig) */
16061     sc->mtu = ETHERMTU;
16062
16063     bxe_set_modes_bitmap(sc);
16064
16065     /* XXX
16066      * If in AFEX mode and the function is configured for FCoE
16067      * then bail... no L2 allowed.
16068      */
16069
16070     /* get phy settings from shmem and 'and' against admin settings */
16071     bxe_get_phy_info(sc);
16072
16073     /* initialize the FreeBSD ifnet interface */
16074     if (bxe_init_ifnet(sc) != 0) {
16075         bxe_release_mutexes(sc);
16076         bxe_deallocate_bars(sc);
16077         pci_disable_busmaster(dev);
16078         return (ENXIO);
16079     }
16080
16081     if (bxe_add_cdev(sc) != 0) {
16082         if (sc->ifnet != NULL) {
16083             ether_ifdetach(sc->ifnet);
16084         }
16085         ifmedia_removeall(&sc->ifmedia);
16086         bxe_release_mutexes(sc);
16087         bxe_deallocate_bars(sc);
16088         pci_disable_busmaster(dev);
16089         return (ENXIO);
16090     }
16091
16092     /* allocate device interrupts */
16093     if (bxe_interrupt_alloc(sc) != 0) {
16094         bxe_del_cdev(sc);
16095         if (sc->ifnet != NULL) {
16096             ether_ifdetach(sc->ifnet);
16097         }
16098         ifmedia_removeall(&sc->ifmedia);
16099         bxe_release_mutexes(sc);
16100         bxe_deallocate_bars(sc);
16101         pci_disable_busmaster(dev);
16102         return (ENXIO);
16103     }
16104
16105     bxe_init_fp_mutexs(sc);
16106
16107     if (bxe_alloc_buf_rings(sc) != 0) {
16108         bxe_free_buf_rings(sc);
16109         bxe_interrupt_free(sc);
16110         bxe_del_cdev(sc);
16111         if (sc->ifnet != NULL) {
16112             ether_ifdetach(sc->ifnet);
16113         }
16114         ifmedia_removeall(&sc->ifmedia);
16115         bxe_release_mutexes(sc);
16116         bxe_deallocate_bars(sc);
16117         pci_disable_busmaster(dev);
16118         return (ENXIO);
16119     }
16120
16121     /* allocate ilt */
16122     if (bxe_alloc_ilt_mem(sc) != 0) {
16123         bxe_free_buf_rings(sc);
16124         bxe_interrupt_free(sc);
16125         bxe_del_cdev(sc);
16126         if (sc->ifnet != NULL) {
16127             ether_ifdetach(sc->ifnet);
16128         }
16129         ifmedia_removeall(&sc->ifmedia);
16130         bxe_release_mutexes(sc);
16131         bxe_deallocate_bars(sc);
16132         pci_disable_busmaster(dev);
16133         return (ENXIO);
16134     }
16135
16136     /* allocate the host hardware/software hsi structures */
16137     if (bxe_alloc_hsi_mem(sc) != 0) {
16138         bxe_free_ilt_mem(sc);
16139         bxe_free_buf_rings(sc);
16140         bxe_interrupt_free(sc);
16141         bxe_del_cdev(sc);
16142         if (sc->ifnet != NULL) {
16143             ether_ifdetach(sc->ifnet);
16144         }
16145         ifmedia_removeall(&sc->ifmedia);
16146         bxe_release_mutexes(sc);
16147         bxe_deallocate_bars(sc);
16148         pci_disable_busmaster(dev);
16149         return (ENXIO);
16150     }
16151
16152     /* need to reset chip if UNDI was active */
16153     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16154         /* init fw_seq */
16155         sc->fw_seq =
16156             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16157              DRV_MSG_SEQ_NUMBER_MASK);
16158         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16159         bxe_prev_unload(sc);
16160     }
16161
16162 #if 1
16163     /* XXX */
16164     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16165 #else
16166     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16167         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16168         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16169         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16170         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16171         bxe_dcbx_init_params(sc);
16172     } else {
16173         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16174     }
16175 #endif
16176
16177     /* calculate qm_cid_count */
16178     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16179     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16180
16181     sc->max_cos = 1;
16182     bxe_init_multi_cos(sc);
16183
16184     bxe_add_sysctls(sc);
16185
16186     return (0);
16187 }
16188
16189 /*
16190  * Device detach function.
16191  *
16192  * Stops the controller, resets the controller, and releases resources.
16193  *
16194  * Returns:
16195  *   0 = Success, >0 = Failure
16196  */
16197 static int
16198 bxe_detach(device_t dev)
16199 {
16200     struct bxe_softc *sc;
16201     struct ifnet *ifp;
16202
16203     sc = device_get_softc(dev);
16204
16205     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16206
16207     ifp = sc->ifnet;
16208     if (ifp != NULL && ifp->if_vlantrunk != NULL) {
16209         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16210         return(EBUSY);
16211     }
16212
16213     bxe_del_cdev(sc);
16214
16215     /* stop the periodic callout */
16216     bxe_periodic_stop(sc);
16217
16218     /* stop the chip taskqueue */
16219     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16220     if (sc->chip_tq) {
16221         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16222         taskqueue_free(sc->chip_tq);
16223         sc->chip_tq = NULL;
16224     }
16225
16226     /* stop and reset the controller if it was open */
16227     if (sc->state != BXE_STATE_CLOSED) {
16228         BXE_CORE_LOCK(sc);
16229         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16230         sc->state = BXE_STATE_DISABLED;
16231         BXE_CORE_UNLOCK(sc);
16232     }
16233
16234     /* release the network interface */
16235     if (ifp != NULL) {
16236         ether_ifdetach(ifp);
16237     }
16238     ifmedia_removeall(&sc->ifmedia);
16239
16240     /* XXX do the following based on driver state... */
16241
16242     /* free the host hardware/software hsi structures */
16243     bxe_free_hsi_mem(sc);
16244
16245     /* free ilt */
16246     bxe_free_ilt_mem(sc);
16247
16248     bxe_free_buf_rings(sc);
16249
16250     /* release the interrupts */
16251     bxe_interrupt_free(sc);
16252
16253     /* Release the mutexes*/
16254     bxe_destroy_fp_mutexs(sc);
16255     bxe_release_mutexes(sc);
16256
16257
16258     /* Release the PCIe BAR mapped memory */
16259     bxe_deallocate_bars(sc);
16260
16261     /* Release the FreeBSD interface. */
16262     if (sc->ifnet != NULL) {
16263         if_free(sc->ifnet);
16264     }
16265
16266     pci_disable_busmaster(dev);
16267
16268     return (0);
16269 }
16270
16271 /*
16272  * Device shutdown function.
16273  *
16274  * Stops and resets the controller.
16275  *
16276  * Returns:
16277  *   Nothing
16278  */
16279 static int
16280 bxe_shutdown(device_t dev)
16281 {
16282     struct bxe_softc *sc;
16283
16284     sc = device_get_softc(dev);
16285
16286     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16287
16288     /* stop the periodic callout */
16289     bxe_periodic_stop(sc);
16290
16291     BXE_CORE_LOCK(sc);
16292     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16293     BXE_CORE_UNLOCK(sc);
16294
16295     return (0);
16296 }
16297
16298 void
16299 bxe_igu_ack_sb(struct bxe_softc *sc,
16300                uint8_t          igu_sb_id,
16301                uint8_t          segment,
16302                uint16_t         index,
16303                uint8_t          op,
16304                uint8_t          update)
16305 {
16306     uint32_t igu_addr = sc->igu_base_addr;
16307     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16308     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16309 }
16310
16311 static void
16312 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16313                      uint8_t          func,
16314                      uint8_t          idu_sb_id,
16315                      uint8_t          is_pf)
16316 {
16317     uint32_t data, ctl, cnt = 100;
16318     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16319     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16320     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16321     uint32_t sb_bit =  1 << (idu_sb_id%32);
16322     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16323     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16324
16325     /* Not supported in BC mode */
16326     if (CHIP_INT_MODE_IS_BC(sc)) {
16327         return;
16328     }
16329
16330     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16331              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16332             IGU_REGULAR_CLEANUP_SET |
16333             IGU_REGULAR_BCLEANUP);
16334
16335     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16336            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16337            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16338
16339     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16340             data, igu_addr_data);
16341     REG_WR(sc, igu_addr_data, data);
16342
16343     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16344                       BUS_SPACE_BARRIER_WRITE);
16345     mb();
16346
16347     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16348             ctl, igu_addr_ctl);
16349     REG_WR(sc, igu_addr_ctl, ctl);
16350
16351     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16352                       BUS_SPACE_BARRIER_WRITE);
16353     mb();
16354
16355     /* wait for clean up to finish */
16356     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16357         DELAY(20000);
16358     }
16359
16360     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16361         BLOGD(sc, DBG_LOAD,
16362               "Unable to finish IGU cleanup: "
16363               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16364               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16365     }
16366 }
16367
16368 static void
16369 bxe_igu_clear_sb(struct bxe_softc *sc,
16370                  uint8_t          idu_sb_id)
16371 {
16372     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16373 }
16374
16375
16376
16377
16378
16379
16380
16381 /*******************/
16382 /* ECORE CALLBACKS */
16383 /*******************/
16384
16385 static void
16386 bxe_reset_common(struct bxe_softc *sc)
16387 {
16388     uint32_t val = 0x1400;
16389
16390     /* reset_common */
16391     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16392
16393     if (CHIP_IS_E3(sc)) {
16394         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16395         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16396     }
16397
16398     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16399 }
16400
16401 static void
16402 bxe_common_init_phy(struct bxe_softc *sc)
16403 {
16404     uint32_t shmem_base[2];
16405     uint32_t shmem2_base[2];
16406
16407     /* Avoid common init in case MFW supports LFA */
16408     if (SHMEM2_RD(sc, size) >
16409         (uint32_t)offsetof(struct shmem2_region,
16410                            lfa_host_addr[SC_PORT(sc)])) {
16411         return;
16412     }
16413
16414     shmem_base[0]  = sc->devinfo.shmem_base;
16415     shmem2_base[0] = sc->devinfo.shmem2_base;
16416
16417     if (!CHIP_IS_E1x(sc)) {
16418         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16419         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16420     }
16421
16422     bxe_acquire_phy_lock(sc);
16423     elink_common_init_phy(sc, shmem_base, shmem2_base,
16424                           sc->devinfo.chip_id, 0);
16425     bxe_release_phy_lock(sc);
16426 }
16427
16428 static void
16429 bxe_pf_disable(struct bxe_softc *sc)
16430 {
16431     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16432
16433     val &= ~IGU_PF_CONF_FUNC_EN;
16434
16435     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16436     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16437     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16438 }
16439
16440 static void
16441 bxe_init_pxp(struct bxe_softc *sc)
16442 {
16443     uint16_t devctl;
16444     int r_order, w_order;
16445
16446     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16447
16448     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16449
16450     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16451
16452     if (sc->mrrs == -1) {
16453         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16454     } else {
16455         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16456         r_order = sc->mrrs;
16457     }
16458
16459     ecore_init_pxp_arb(sc, r_order, w_order);
16460 }
16461
16462 static uint32_t
16463 bxe_get_pretend_reg(struct bxe_softc *sc)
16464 {
16465     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16466     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16467     return (base + (SC_ABS_FUNC(sc)) * stride);
16468 }
16469
16470 /*
16471  * Called only on E1H or E2.
16472  * When pretending to be PF, the pretend value is the function number 0..7.
16473  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16474  * combination.
16475  */
16476 static int
16477 bxe_pretend_func(struct bxe_softc *sc,
16478                  uint16_t         pretend_func_val)
16479 {
16480     uint32_t pretend_reg;
16481
16482     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16483         return (-1);
16484     }
16485
16486     /* get my own pretend register */
16487     pretend_reg = bxe_get_pretend_reg(sc);
16488     REG_WR(sc, pretend_reg, pretend_func_val);
16489     REG_RD(sc, pretend_reg);
16490     return (0);
16491 }
16492
16493 static void
16494 bxe_iov_init_dmae(struct bxe_softc *sc)
16495 {
16496     return;
16497 }
16498
16499 static void
16500 bxe_iov_init_dq(struct bxe_softc *sc)
16501 {
16502     return;
16503 }
16504
16505 /* send a NIG loopback debug packet */
16506 static void
16507 bxe_lb_pckt(struct bxe_softc *sc)
16508 {
16509     uint32_t wb_write[3];
16510
16511     /* Ethernet source and destination addresses */
16512     wb_write[0] = 0x55555555;
16513     wb_write[1] = 0x55555555;
16514     wb_write[2] = 0x20;     /* SOP */
16515     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16516
16517     /* NON-IP protocol */
16518     wb_write[0] = 0x09000000;
16519     wb_write[1] = 0x55555555;
16520     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16521     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16522 }
16523
16524 /*
16525  * Some of the internal memories are not directly readable from the driver.
16526  * To test them we send debug packets.
16527  */
16528 static int
16529 bxe_int_mem_test(struct bxe_softc *sc)
16530 {
16531     int factor;
16532     int count, i;
16533     uint32_t val = 0;
16534
16535     if (CHIP_REV_IS_FPGA(sc)) {
16536         factor = 120;
16537     } else if (CHIP_REV_IS_EMUL(sc)) {
16538         factor = 200;
16539     } else {
16540         factor = 1;
16541     }
16542
16543     /* disable inputs of parser neighbor blocks */
16544     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16545     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16546     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16547     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16548
16549     /*  write 0 to parser credits for CFC search request */
16550     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16551
16552     /* send Ethernet packet */
16553     bxe_lb_pckt(sc);
16554
16555     /* TODO do i reset NIG statistic? */
16556     /* Wait until NIG register shows 1 packet of size 0x10 */
16557     count = 1000 * factor;
16558     while (count) {
16559         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16560         val = *BXE_SP(sc, wb_data[0]);
16561         if (val == 0x10) {
16562             break;
16563         }
16564
16565         DELAY(10000);
16566         count--;
16567     }
16568
16569     if (val != 0x10) {
16570         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16571         return (-1);
16572     }
16573
16574     /* wait until PRS register shows 1 packet */
16575     count = (1000 * factor);
16576     while (count) {
16577         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16578         if (val == 1) {
16579             break;
16580         }
16581
16582         DELAY(10000);
16583         count--;
16584     }
16585
16586     if (val != 0x1) {
16587         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16588         return (-2);
16589     }
16590
16591     /* Reset and init BRB, PRS */
16592     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16593     DELAY(50000);
16594     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16595     DELAY(50000);
16596     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16597     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16598
16599     /* Disable inputs of parser neighbor blocks */
16600     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16601     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16602     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16603     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16604
16605     /* Write 0 to parser credits for CFC search request */
16606     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16607
16608     /* send 10 Ethernet packets */
16609     for (i = 0; i < 10; i++) {
16610         bxe_lb_pckt(sc);
16611     }
16612
16613     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16614     count = (1000 * factor);
16615     while (count) {
16616         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16617         val = *BXE_SP(sc, wb_data[0]);
16618         if (val == 0xb0) {
16619             break;
16620         }
16621
16622         DELAY(10000);
16623         count--;
16624     }
16625
16626     if (val != 0xb0) {
16627         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16628         return (-3);
16629     }
16630
16631     /* Wait until PRS register shows 2 packets */
16632     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16633     if (val != 2) {
16634         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16635     }
16636
16637     /* Write 1 to parser credits for CFC search request */
16638     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16639
16640     /* Wait until PRS register shows 3 packets */
16641     DELAY(10000 * factor);
16642
16643     /* Wait until NIG register shows 1 packet of size 0x10 */
16644     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16645     if (val != 3) {
16646         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16647     }
16648
16649     /* clear NIG EOP FIFO */
16650     for (i = 0; i < 11; i++) {
16651         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16652     }
16653
16654     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16655     if (val != 1) {
16656         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16657         return (-4);
16658     }
16659
16660     /* Reset and init BRB, PRS, NIG */
16661     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16662     DELAY(50000);
16663     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16664     DELAY(50000);
16665     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16666     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16667     if (!CNIC_SUPPORT(sc)) {
16668         /* set NIC mode */
16669         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16670     }
16671
16672     /* Enable inputs of parser neighbor blocks */
16673     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16674     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16675     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16676     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16677
16678     return (0);
16679 }
16680
16681 static void
16682 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16683 {
16684     int is_required;
16685     uint32_t val;
16686     int port;
16687
16688     is_required = 0;
16689     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16690            SHARED_HW_CFG_FAN_FAILURE_MASK);
16691
16692     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16693         is_required = 1;
16694     }
16695     /*
16696      * The fan failure mechanism is usually related to the PHY type since
16697      * the power consumption of the board is affected by the PHY. Currently,
16698      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16699      */
16700     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16701         for (port = PORT_0; port < PORT_MAX; port++) {
16702             is_required |= elink_fan_failure_det_req(sc,
16703                                                      sc->devinfo.shmem_base,
16704                                                      sc->devinfo.shmem2_base,
16705                                                      port);
16706         }
16707     }
16708
16709     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16710
16711     if (is_required == 0) {
16712         return;
16713     }
16714
16715     /* Fan failure is indicated by SPIO 5 */
16716     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16717
16718     /* set to active low mode */
16719     val = REG_RD(sc, MISC_REG_SPIO_INT);
16720     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16721     REG_WR(sc, MISC_REG_SPIO_INT, val);
16722
16723     /* enable interrupt to signal the IGU */
16724     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16725     val |= MISC_SPIO_SPIO5;
16726     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16727 }
16728
16729 static void
16730 bxe_enable_blocks_attention(struct bxe_softc *sc)
16731 {
16732     uint32_t val;
16733
16734     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16735     if (!CHIP_IS_E1x(sc)) {
16736         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16737     } else {
16738         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16739     }
16740     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16741     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16742     /*
16743      * mask read length error interrupts in brb for parser
16744      * (parsing unit and 'checksum and crc' unit)
16745      * these errors are legal (PU reads fixed length and CAC can cause
16746      * read length error on truncated packets)
16747      */
16748     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16749     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16750     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16751     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16752     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16753     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16754 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16755 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16756     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16757     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16758     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16759 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16760 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16761     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16762     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16763     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16764     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16765 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16766 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16767
16768     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16769            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16770            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16771     if (!CHIP_IS_E1x(sc)) {
16772         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16773                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16774     }
16775     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16776
16777     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16778     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16779     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16780 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16781
16782     if (!CHIP_IS_E1x(sc)) {
16783         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16784         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16785     }
16786
16787     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16788     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16789 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16790     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16791 }
16792
16793 /**
16794  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16795  *
16796  * @sc:     driver handle
16797  */
16798 static int
16799 bxe_init_hw_common(struct bxe_softc *sc)
16800 {
16801     uint8_t abs_func_id;
16802     uint32_t val;
16803
16804     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16805           SC_ABS_FUNC(sc));
16806
16807     /*
16808      * take the RESET lock to protect undi_unload flow from accessing
16809      * registers while we are resetting the chip
16810      */
16811     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16812
16813     bxe_reset_common(sc);
16814
16815     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16816
16817     val = 0xfffc;
16818     if (CHIP_IS_E3(sc)) {
16819         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16820         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16821     }
16822
16823     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16824
16825     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16826
16827     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16828     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16829
16830     if (!CHIP_IS_E1x(sc)) {
16831         /*
16832          * 4-port mode or 2-port mode we need to turn off master-enable for
16833          * everyone. After that we turn it back on for self. So, we disregard
16834          * multi-function, and always disable all functions on the given path,
16835          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16836          */
16837         for (abs_func_id = SC_PATH(sc);
16838              abs_func_id < (E2_FUNC_MAX * 2);
16839              abs_func_id += 2) {
16840             if (abs_func_id == SC_ABS_FUNC(sc)) {
16841                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16842                 continue;
16843             }
16844
16845             bxe_pretend_func(sc, abs_func_id);
16846
16847             /* clear pf enable */
16848             bxe_pf_disable(sc);
16849
16850             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16851         }
16852     }
16853
16854     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16855
16856     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16857
16858     if (CHIP_IS_E1(sc)) {
16859         /*
16860          * enable HW interrupt from PXP on USDM overflow
16861          * bit 16 on INT_MASK_0
16862          */
16863         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16864     }
16865
16866     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16867     bxe_init_pxp(sc);
16868
16869 #ifdef __BIG_ENDIAN
16870     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16871     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16872     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16873     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16874     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16875     /* make sure this value is 0 */
16876     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16877
16878     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16879     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16880     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16881     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16882     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16883 #endif
16884
16885     ecore_ilt_init_page_size(sc, INITOP_SET);
16886
16887     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16888         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16889     }
16890
16891     /* let the HW do it's magic... */
16892     DELAY(100000);
16893
16894     /* finish PXP init */
16895     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16896     if (val != 1) {
16897         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16898             val);
16899         return (-1);
16900     }
16901     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16902     if (val != 1) {
16903         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16904         return (-1);
16905     }
16906
16907     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16908
16909     /*
16910      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16911      * entries with value "0" and valid bit on. This needs to be done by the
16912      * first PF that is loaded in a path (i.e. common phase)
16913      */
16914     if (!CHIP_IS_E1x(sc)) {
16915 /*
16916  * In E2 there is a bug in the timers block that can cause function 6 / 7
16917  * (i.e. vnic3) to start even if it is marked as "scan-off".
16918  * This occurs when a different function (func2,3) is being marked
16919  * as "scan-off". Real-life scenario for example: if a driver is being
16920  * load-unloaded while func6,7 are down. This will cause the timer to access
16921  * the ilt, translate to a logical address and send a request to read/write.
16922  * Since the ilt for the function that is down is not valid, this will cause
16923  * a translation error which is unrecoverable.
16924  * The Workaround is intended to make sure that when this happens nothing
16925  * fatal will occur. The workaround:
16926  *  1.  First PF driver which loads on a path will:
16927  *      a.  After taking the chip out of reset, by using pretend,
16928  *          it will write "0" to the following registers of
16929  *          the other vnics.
16930  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16931  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16932  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16933  *          And for itself it will write '1' to
16934  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16935  *          dmae-operations (writing to pram for example.)
16936  *          note: can be done for only function 6,7 but cleaner this
16937  *            way.
16938  *      b.  Write zero+valid to the entire ILT.
16939  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16940  *          VNIC3 (of that port). The range allocated will be the
16941  *          entire ILT. This is needed to prevent  ILT range error.
16942  *  2.  Any PF driver load flow:
16943  *      a.  ILT update with the physical addresses of the allocated
16944  *          logical pages.
16945  *      b.  Wait 20msec. - note that this timeout is needed to make
16946  *          sure there are no requests in one of the PXP internal
16947  *          queues with "old" ILT addresses.
16948  *      c.  PF enable in the PGLC.
16949  *      d.  Clear the was_error of the PF in the PGLC. (could have
16950  *          occurred while driver was down)
16951  *      e.  PF enable in the CFC (WEAK + STRONG)
16952  *      f.  Timers scan enable
16953  *  3.  PF driver unload flow:
16954  *      a.  Clear the Timers scan_en.
16955  *      b.  Polling for scan_on=0 for that PF.
16956  *      c.  Clear the PF enable bit in the PXP.
16957  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16958  *      e.  Write zero+valid to all ILT entries (The valid bit must
16959  *          stay set)
16960  *      f.  If this is VNIC 3 of a port then also init
16961  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16962  *          to the last enrty in the ILT.
16963  *
16964  *      Notes:
16965  *      Currently the PF error in the PGLC is non recoverable.
16966  *      In the future the there will be a recovery routine for this error.
16967  *      Currently attention is masked.
16968  *      Having an MCP lock on the load/unload process does not guarantee that
16969  *      there is no Timer disable during Func6/7 enable. This is because the
16970  *      Timers scan is currently being cleared by the MCP on FLR.
16971  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16972  *      there is error before clearing it. But the flow above is simpler and
16973  *      more general.
16974  *      All ILT entries are written by zero+valid and not just PF6/7
16975  *      ILT entries since in the future the ILT entries allocation for
16976  *      PF-s might be dynamic.
16977  */
16978         struct ilt_client_info ilt_cli;
16979         struct ecore_ilt ilt;
16980
16981         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16982         memset(&ilt, 0, sizeof(struct ecore_ilt));
16983
16984         /* initialize dummy TM client */
16985         ilt_cli.start      = 0;
16986         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16987         ilt_cli.client_num = ILT_CLIENT_TM;
16988
16989         /*
16990          * Step 1: set zeroes to all ilt page entries with valid bit on
16991          * Step 2: set the timers first/last ilt entry to point
16992          * to the entire range to prevent ILT range error for 3rd/4th
16993          * vnic (this code assumes existence of the vnic)
16994          *
16995          * both steps performed by call to ecore_ilt_client_init_op()
16996          * with dummy TM client
16997          *
16998          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16999          * and his brother are split registers
17000          */
17001
17002         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
17003         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
17004         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
17005
17006         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
17007         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
17008         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
17009     }
17010
17011     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
17012     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
17013
17014     if (!CHIP_IS_E1x(sc)) {
17015         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
17016                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
17017
17018         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
17019         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
17020
17021         /* let the HW do it's magic... */
17022         do {
17023             DELAY(200000);
17024             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
17025         } while (factor-- && (val != 1));
17026
17027         if (val != 1) {
17028             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
17029             return (-1);
17030         }
17031     }
17032
17033     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
17034
17035     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
17036
17037     bxe_iov_init_dmae(sc);
17038
17039     /* clean the DMAE memory */
17040     sc->dmae_ready = 1;
17041     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
17042
17043     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
17044
17045     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
17046
17047     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
17048
17049     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
17050
17051     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
17052     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17053     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17054     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17055
17056     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17057
17058     /* QM queues pointers table */
17059     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17060
17061     /* soft reset pulse */
17062     REG_WR(sc, QM_REG_SOFT_RESET, 1);
17063     REG_WR(sc, QM_REG_SOFT_RESET, 0);
17064
17065     if (CNIC_SUPPORT(sc))
17066         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17067
17068     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17069     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17070     if (!CHIP_REV_IS_SLOW(sc)) {
17071         /* enable hw interrupt from doorbell Q */
17072         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17073     }
17074
17075     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17076
17077     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17078     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17079
17080     if (!CHIP_IS_E1(sc)) {
17081         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17082     }
17083
17084     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17085         if (IS_MF_AFEX(sc)) {
17086             /*
17087              * configure that AFEX and VLAN headers must be
17088              * received in AFEX mode
17089              */
17090             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17091             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17092             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17093             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17094             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17095         } else {
17096             /*
17097              * Bit-map indicating which L2 hdrs may appear
17098              * after the basic Ethernet header
17099              */
17100             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17101                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17102         }
17103     }
17104
17105     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17106     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17107     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17108     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17109
17110     if (!CHIP_IS_E1x(sc)) {
17111         /* reset VFC memories */
17112         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17113                VFC_MEMORIES_RST_REG_CAM_RST |
17114                VFC_MEMORIES_RST_REG_RAM_RST);
17115         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17116                VFC_MEMORIES_RST_REG_CAM_RST |
17117                VFC_MEMORIES_RST_REG_RAM_RST);
17118
17119         DELAY(20000);
17120     }
17121
17122     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17123     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17124     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17125     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17126
17127     /* sync semi rtc */
17128     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17129            0x80000000);
17130     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17131            0x80000000);
17132
17133     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17134     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17135     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17136
17137     if (!CHIP_IS_E1x(sc)) {
17138         if (IS_MF_AFEX(sc)) {
17139             /*
17140              * configure that AFEX and VLAN headers must be
17141              * sent in AFEX mode
17142              */
17143             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17144             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17145             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17146             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17147             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17148         } else {
17149             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17150                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17151         }
17152     }
17153
17154     REG_WR(sc, SRC_REG_SOFT_RST, 1);
17155
17156     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17157
17158     if (CNIC_SUPPORT(sc)) {
17159         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17160         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17161         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17162         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17163         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17164         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17165         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17166         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17167         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17168         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17169     }
17170     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17171
17172     if (sizeof(union cdu_context) != 1024) {
17173         /* we currently assume that a context is 1024 bytes */
17174         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17175               (long)sizeof(union cdu_context));
17176     }
17177
17178     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17179     val = (4 << 24) + (0 << 12) + 1024;
17180     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17181
17182     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17183
17184     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17185     /* enable context validation interrupt from CFC */
17186     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17187
17188     /* set the thresholds to prevent CFC/CDU race */
17189     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17190     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17191
17192     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17193         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17194     }
17195
17196     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17197     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17198
17199     /* Reset PCIE errors for debug */
17200     REG_WR(sc, 0x2814, 0xffffffff);
17201     REG_WR(sc, 0x3820, 0xffffffff);
17202
17203     if (!CHIP_IS_E1x(sc)) {
17204         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17205                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17206                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17207         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17208                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17209                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17210                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17211         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17212                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17213                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17214                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17215     }
17216
17217     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17218
17219     if (!CHIP_IS_E1(sc)) {
17220         /* in E3 this done in per-port section */
17221         if (!CHIP_IS_E3(sc))
17222             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17223     }
17224
17225     if (CHIP_IS_E1H(sc)) {
17226         /* not applicable for E2 (and above ...) */
17227         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17228     }
17229
17230     if (CHIP_REV_IS_SLOW(sc)) {
17231         DELAY(200000);
17232     }
17233
17234     /* finish CFC init */
17235     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17236     if (val != 1) {
17237         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17238         return (-1);
17239     }
17240     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17241     if (val != 1) {
17242         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17243         return (-1);
17244     }
17245     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17246     if (val != 1) {
17247         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17248         return (-1);
17249     }
17250     REG_WR(sc, CFC_REG_DEBUG0, 0);
17251
17252     if (CHIP_IS_E1(sc)) {
17253         /* read NIG statistic to see if this is our first up since powerup */
17254         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17255         val = *BXE_SP(sc, wb_data[0]);
17256
17257         /* do internal memory self test */
17258         if ((val == 0) && bxe_int_mem_test(sc)) {
17259             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17260             return (-1);
17261         }
17262     }
17263
17264     bxe_setup_fan_failure_detection(sc);
17265
17266     /* clear PXP2 attentions */
17267     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17268
17269     bxe_enable_blocks_attention(sc);
17270
17271     if (!CHIP_REV_IS_SLOW(sc)) {
17272         ecore_enable_blocks_parity(sc);
17273     }
17274
17275     if (!BXE_NOMCP(sc)) {
17276         if (CHIP_IS_E1x(sc)) {
17277             bxe_common_init_phy(sc);
17278         }
17279     }
17280
17281     return (0);
17282 }
17283
17284 /**
17285  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17286  *
17287  * @sc:     driver handle
17288  */
17289 static int
17290 bxe_init_hw_common_chip(struct bxe_softc *sc)
17291 {
17292     int rc = bxe_init_hw_common(sc);
17293
17294     if (rc) {
17295         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17296         return (rc);
17297     }
17298
17299     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17300     if (!BXE_NOMCP(sc)) {
17301         bxe_common_init_phy(sc);
17302     }
17303
17304     return (0);
17305 }
17306
17307 static int
17308 bxe_init_hw_port(struct bxe_softc *sc)
17309 {
17310     int port = SC_PORT(sc);
17311     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17312     uint32_t low, high;
17313     uint32_t val;
17314
17315     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17316
17317     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17318
17319     ecore_init_block(sc, BLOCK_MISC, init_phase);
17320     ecore_init_block(sc, BLOCK_PXP, init_phase);
17321     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17322
17323     /*
17324      * Timers bug workaround: disables the pf_master bit in pglue at
17325      * common phase, we need to enable it here before any dmae access are
17326      * attempted. Therefore we manually added the enable-master to the
17327      * port phase (it also happens in the function phase)
17328      */
17329     if (!CHIP_IS_E1x(sc)) {
17330         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17331     }
17332
17333     ecore_init_block(sc, BLOCK_ATC, init_phase);
17334     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17335     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17336     ecore_init_block(sc, BLOCK_QM, init_phase);
17337
17338     ecore_init_block(sc, BLOCK_TCM, init_phase);
17339     ecore_init_block(sc, BLOCK_UCM, init_phase);
17340     ecore_init_block(sc, BLOCK_CCM, init_phase);
17341     ecore_init_block(sc, BLOCK_XCM, init_phase);
17342
17343     /* QM cid (connection) count */
17344     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17345
17346     if (CNIC_SUPPORT(sc)) {
17347         ecore_init_block(sc, BLOCK_TM, init_phase);
17348         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17349         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17350     }
17351
17352     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17353
17354     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17355
17356     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17357         if (IS_MF(sc)) {
17358             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17359         } else if (sc->mtu > 4096) {
17360             if (BXE_ONE_PORT(sc)) {
17361                 low = 160;
17362             } else {
17363                 val = sc->mtu;
17364                 /* (24*1024 + val*4)/256 */
17365                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17366             }
17367         } else {
17368             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17369         }
17370         high = (low + 56); /* 14*1024/256 */
17371         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17372         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17373     }
17374
17375     if (CHIP_IS_MODE_4_PORT(sc)) {
17376         REG_WR(sc, SC_PORT(sc) ?
17377                BRB1_REG_MAC_GUARANTIED_1 :
17378                BRB1_REG_MAC_GUARANTIED_0, 40);
17379     }
17380
17381     ecore_init_block(sc, BLOCK_PRS, init_phase);
17382     if (CHIP_IS_E3B0(sc)) {
17383         if (IS_MF_AFEX(sc)) {
17384             /* configure headers for AFEX mode */
17385             REG_WR(sc, SC_PORT(sc) ?
17386                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17387                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17388             REG_WR(sc, SC_PORT(sc) ?
17389                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17390                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17391             REG_WR(sc, SC_PORT(sc) ?
17392                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17393                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17394         } else {
17395             /* Ovlan exists only if we are in multi-function +
17396              * switch-dependent mode, in switch-independent there
17397              * is no ovlan headers
17398              */
17399             REG_WR(sc, SC_PORT(sc) ?
17400                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17401                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17402                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17403         }
17404     }
17405
17406     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17407     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17408     ecore_init_block(sc, BLOCK_USDM, init_phase);
17409     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17410
17411     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17412     ecore_init_block(sc, BLOCK_USEM, init_phase);
17413     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17414     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17415
17416     ecore_init_block(sc, BLOCK_UPB, init_phase);
17417     ecore_init_block(sc, BLOCK_XPB, init_phase);
17418
17419     ecore_init_block(sc, BLOCK_PBF, init_phase);
17420
17421     if (CHIP_IS_E1x(sc)) {
17422         /* configure PBF to work without PAUSE mtu 9000 */
17423         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17424
17425         /* update threshold */
17426         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17427         /* update init credit */
17428         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17429
17430         /* probe changes */
17431         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17432         DELAY(50);
17433         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17434     }
17435
17436     if (CNIC_SUPPORT(sc)) {
17437         ecore_init_block(sc, BLOCK_SRC, init_phase);
17438     }
17439
17440     ecore_init_block(sc, BLOCK_CDU, init_phase);
17441     ecore_init_block(sc, BLOCK_CFC, init_phase);
17442
17443     if (CHIP_IS_E1(sc)) {
17444         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17445         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17446     }
17447     ecore_init_block(sc, BLOCK_HC, init_phase);
17448
17449     ecore_init_block(sc, BLOCK_IGU, init_phase);
17450
17451     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17452     /* init aeu_mask_attn_func_0/1:
17453      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17454      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17455      *             bits 4-7 are used for "per vn group attention" */
17456     val = IS_MF(sc) ? 0xF7 : 0x7;
17457     /* Enable DCBX attention for all but E1 */
17458     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17459     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17460
17461     ecore_init_block(sc, BLOCK_NIG, init_phase);
17462
17463     if (!CHIP_IS_E1x(sc)) {
17464         /* Bit-map indicating which L2 hdrs may appear after the
17465          * basic Ethernet header
17466          */
17467         if (IS_MF_AFEX(sc)) {
17468             REG_WR(sc, SC_PORT(sc) ?
17469                    NIG_REG_P1_HDRS_AFTER_BASIC :
17470                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17471         } else {
17472             REG_WR(sc, SC_PORT(sc) ?
17473                    NIG_REG_P1_HDRS_AFTER_BASIC :
17474                    NIG_REG_P0_HDRS_AFTER_BASIC,
17475                    IS_MF_SD(sc) ? 7 : 6);
17476         }
17477
17478         if (CHIP_IS_E3(sc)) {
17479             REG_WR(sc, SC_PORT(sc) ?
17480                    NIG_REG_LLH1_MF_MODE :
17481                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17482         }
17483     }
17484     if (!CHIP_IS_E3(sc)) {
17485         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17486     }
17487
17488     if (!CHIP_IS_E1(sc)) {
17489         /* 0x2 disable mf_ov, 0x1 enable */
17490         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17491                (IS_MF_SD(sc) ? 0x1 : 0x2));
17492
17493         if (!CHIP_IS_E1x(sc)) {
17494             val = 0;
17495             switch (sc->devinfo.mf_info.mf_mode) {
17496             case MULTI_FUNCTION_SD:
17497                 val = 1;
17498                 break;
17499             case MULTI_FUNCTION_SI:
17500             case MULTI_FUNCTION_AFEX:
17501                 val = 2;
17502                 break;
17503             }
17504
17505             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17506                         NIG_REG_LLH0_CLS_TYPE), val);
17507         }
17508         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17509         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17510         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17511     }
17512
17513     /* If SPIO5 is set to generate interrupts, enable it for this port */
17514     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17515     if (val & MISC_SPIO_SPIO5) {
17516         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17517                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17518         val = REG_RD(sc, reg_addr);
17519         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17520         REG_WR(sc, reg_addr, val);
17521     }
17522
17523     return (0);
17524 }
17525
17526 static uint32_t
17527 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17528                        uint32_t         reg,
17529                        uint32_t         expected,
17530                        uint32_t         poll_count)
17531 {
17532     uint32_t cur_cnt = poll_count;
17533     uint32_t val;
17534
17535     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17536         DELAY(FLR_WAIT_INTERVAL);
17537     }
17538
17539     return (val);
17540 }
17541
17542 static int
17543 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17544                               uint32_t         reg,
17545                               char             *msg,
17546                               uint32_t         poll_cnt)
17547 {
17548     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17549
17550     if (val != 0) {
17551         BLOGE(sc, "%s usage count=%d\n", msg, val);
17552         return (1);
17553     }
17554
17555     return (0);
17556 }
17557
17558 /* Common routines with VF FLR cleanup */
17559 static uint32_t
17560 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17561 {
17562     /* adjust polling timeout */
17563     if (CHIP_REV_IS_EMUL(sc)) {
17564         return (FLR_POLL_CNT * 2000);
17565     }
17566
17567     if (CHIP_REV_IS_FPGA(sc)) {
17568         return (FLR_POLL_CNT * 120);
17569     }
17570
17571     return (FLR_POLL_CNT);
17572 }
17573
17574 static int
17575 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17576                            uint32_t         poll_cnt)
17577 {
17578     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17579     if (bxe_flr_clnup_poll_hw_counter(sc,
17580                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17581                                       "CFC PF usage counter timed out",
17582                                       poll_cnt)) {
17583         return (1);
17584     }
17585
17586     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17587     if (bxe_flr_clnup_poll_hw_counter(sc,
17588                                       DORQ_REG_PF_USAGE_CNT,
17589                                       "DQ PF usage counter timed out",
17590                                       poll_cnt)) {
17591         return (1);
17592     }
17593
17594     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17595     if (bxe_flr_clnup_poll_hw_counter(sc,
17596                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17597                                       "QM PF usage counter timed out",
17598                                       poll_cnt)) {
17599         return (1);
17600     }
17601
17602     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17603     if (bxe_flr_clnup_poll_hw_counter(sc,
17604                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17605                                       "Timers VNIC usage counter timed out",
17606                                       poll_cnt)) {
17607         return (1);
17608     }
17609
17610     if (bxe_flr_clnup_poll_hw_counter(sc,
17611                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17612                                       "Timers NUM_SCANS usage counter timed out",
17613                                       poll_cnt)) {
17614         return (1);
17615     }
17616
17617     /* Wait DMAE PF usage counter to zero */
17618     if (bxe_flr_clnup_poll_hw_counter(sc,
17619                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17620                                       "DMAE dommand register timed out",
17621                                       poll_cnt)) {
17622         return (1);
17623     }
17624
17625     return (0);
17626 }
17627
17628 #define OP_GEN_PARAM(param)                                            \
17629     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17630 #define OP_GEN_TYPE(type)                                           \
17631     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17632 #define OP_GEN_AGG_VECT(index)                                             \
17633     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17634
17635 static int
17636 bxe_send_final_clnup(struct bxe_softc *sc,
17637                      uint8_t          clnup_func,
17638                      uint32_t         poll_cnt)
17639 {
17640     uint32_t op_gen_command = 0;
17641     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17642                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17643     int ret = 0;
17644
17645     if (REG_RD(sc, comp_addr)) {
17646         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17647         return (1);
17648     }
17649
17650     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17651     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17652     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17653     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17654
17655     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17656     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17657
17658     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17659         BLOGE(sc, "FW final cleanup did not succeed\n");
17660         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17661               (REG_RD(sc, comp_addr)));
17662         bxe_panic(sc, ("FLR cleanup failed\n"));
17663         return (1);
17664     }
17665
17666     /* Zero completion for nxt FLR */
17667     REG_WR(sc, comp_addr, 0);
17668
17669     return (ret);
17670 }
17671
17672 static void
17673 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17674                        struct pbf_pN_buf_regs *regs,
17675                        uint32_t               poll_count)
17676 {
17677     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17678     uint32_t cur_cnt = poll_count;
17679
17680     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17681     crd = crd_start = REG_RD(sc, regs->crd);
17682     init_crd = REG_RD(sc, regs->init_crd);
17683
17684     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17685     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17686     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17687
17688     while ((crd != init_crd) &&
17689            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17690             (init_crd - crd_start))) {
17691         if (cur_cnt--) {
17692             DELAY(FLR_WAIT_INTERVAL);
17693             crd = REG_RD(sc, regs->crd);
17694             crd_freed = REG_RD(sc, regs->crd_freed);
17695         } else {
17696             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17697             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17698             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17699             break;
17700         }
17701     }
17702
17703     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17704           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17705 }
17706
17707 static void
17708 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17709                        struct pbf_pN_cmd_regs *regs,
17710                        uint32_t               poll_count)
17711 {
17712     uint32_t occup, to_free, freed, freed_start;
17713     uint32_t cur_cnt = poll_count;
17714
17715     occup = to_free = REG_RD(sc, regs->lines_occup);
17716     freed = freed_start = REG_RD(sc, regs->lines_freed);
17717
17718     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17719     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17720
17721     while (occup &&
17722            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17723         if (cur_cnt--) {
17724             DELAY(FLR_WAIT_INTERVAL);
17725             occup = REG_RD(sc, regs->lines_occup);
17726             freed = REG_RD(sc, regs->lines_freed);
17727         } else {
17728             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17729             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17730             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17731             break;
17732         }
17733     }
17734
17735     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17736           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17737 }
17738
17739 static void
17740 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17741 {
17742     struct pbf_pN_cmd_regs cmd_regs[] = {
17743         {0, (CHIP_IS_E3B0(sc)) ?
17744             PBF_REG_TQ_OCCUPANCY_Q0 :
17745             PBF_REG_P0_TQ_OCCUPANCY,
17746             (CHIP_IS_E3B0(sc)) ?
17747             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17748             PBF_REG_P0_TQ_LINES_FREED_CNT},
17749         {1, (CHIP_IS_E3B0(sc)) ?
17750             PBF_REG_TQ_OCCUPANCY_Q1 :
17751             PBF_REG_P1_TQ_OCCUPANCY,
17752             (CHIP_IS_E3B0(sc)) ?
17753             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17754             PBF_REG_P1_TQ_LINES_FREED_CNT},
17755         {4, (CHIP_IS_E3B0(sc)) ?
17756             PBF_REG_TQ_OCCUPANCY_LB_Q :
17757             PBF_REG_P4_TQ_OCCUPANCY,
17758             (CHIP_IS_E3B0(sc)) ?
17759             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17760             PBF_REG_P4_TQ_LINES_FREED_CNT}
17761     };
17762
17763     struct pbf_pN_buf_regs buf_regs[] = {
17764         {0, (CHIP_IS_E3B0(sc)) ?
17765             PBF_REG_INIT_CRD_Q0 :
17766             PBF_REG_P0_INIT_CRD ,
17767             (CHIP_IS_E3B0(sc)) ?
17768             PBF_REG_CREDIT_Q0 :
17769             PBF_REG_P0_CREDIT,
17770             (CHIP_IS_E3B0(sc)) ?
17771             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17772             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17773         {1, (CHIP_IS_E3B0(sc)) ?
17774             PBF_REG_INIT_CRD_Q1 :
17775             PBF_REG_P1_INIT_CRD,
17776             (CHIP_IS_E3B0(sc)) ?
17777             PBF_REG_CREDIT_Q1 :
17778             PBF_REG_P1_CREDIT,
17779             (CHIP_IS_E3B0(sc)) ?
17780             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17781             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17782         {4, (CHIP_IS_E3B0(sc)) ?
17783             PBF_REG_INIT_CRD_LB_Q :
17784             PBF_REG_P4_INIT_CRD,
17785             (CHIP_IS_E3B0(sc)) ?
17786             PBF_REG_CREDIT_LB_Q :
17787             PBF_REG_P4_CREDIT,
17788             (CHIP_IS_E3B0(sc)) ?
17789             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17790             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17791     };
17792
17793     int i;
17794
17795     /* Verify the command queues are flushed P0, P1, P4 */
17796     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17797         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17798     }
17799
17800     /* Verify the transmission buffers are flushed P0, P1, P4 */
17801     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17802         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17803     }
17804 }
17805
17806 static void
17807 bxe_hw_enable_status(struct bxe_softc *sc)
17808 {
17809     uint32_t val;
17810
17811     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17812     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17813
17814     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17815     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17816
17817     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17818     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17819
17820     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17821     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17822
17823     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17824     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17825
17826     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17827     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17828
17829     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17830     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17831
17832     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17833     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17834 }
17835
17836 static int
17837 bxe_pf_flr_clnup(struct bxe_softc *sc)
17838 {
17839     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17840
17841     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17842
17843     /* Re-enable PF target read access */
17844     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17845
17846     /* Poll HW usage counters */
17847     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17848     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17849         return (-1);
17850     }
17851
17852     /* Zero the igu 'trailing edge' and 'leading edge' */
17853
17854     /* Send the FW cleanup command */
17855     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17856         return (-1);
17857     }
17858
17859     /* ATC cleanup */
17860
17861     /* Verify TX hw is flushed */
17862     bxe_tx_hw_flushed(sc, poll_cnt);
17863
17864     /* Wait 100ms (not adjusted according to platform) */
17865     DELAY(100000);
17866
17867     /* Verify no pending pci transactions */
17868     if (bxe_is_pcie_pending(sc)) {
17869         BLOGE(sc, "PCIE Transactions still pending\n");
17870     }
17871
17872     /* Debug */
17873     bxe_hw_enable_status(sc);
17874
17875     /*
17876      * Master enable - Due to WB DMAE writes performed before this
17877      * register is re-initialized as part of the regular function init
17878      */
17879     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17880
17881     return (0);
17882 }
17883
17884 static int
17885 bxe_init_hw_func(struct bxe_softc *sc)
17886 {
17887     int port = SC_PORT(sc);
17888     int func = SC_FUNC(sc);
17889     int init_phase = PHASE_PF0 + func;
17890     struct ecore_ilt *ilt = sc->ilt;
17891     uint16_t cdu_ilt_start;
17892     uint32_t addr, val;
17893     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17894     int i, main_mem_width, rc;
17895
17896     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17897
17898     /* FLR cleanup */
17899     if (!CHIP_IS_E1x(sc)) {
17900         rc = bxe_pf_flr_clnup(sc);
17901         if (rc) {
17902             BLOGE(sc, "FLR cleanup failed!\n");
17903             // XXX bxe_fw_dump(sc);
17904             // XXX bxe_idle_chk(sc);
17905             return (rc);
17906         }
17907     }
17908
17909     /* set MSI reconfigure capability */
17910     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17911         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17912         val = REG_RD(sc, addr);
17913         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17914         REG_WR(sc, addr, val);
17915     }
17916
17917     ecore_init_block(sc, BLOCK_PXP, init_phase);
17918     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17919
17920     ilt = sc->ilt;
17921     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17922
17923     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17924         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17925         ilt->lines[cdu_ilt_start + i].page_mapping =
17926             sc->context[i].vcxt_dma.paddr;
17927         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17928     }
17929     ecore_ilt_init_op(sc, INITOP_SET);
17930
17931     /* Set NIC mode */
17932     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17933     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17934
17935     if (!CHIP_IS_E1x(sc)) {
17936         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17937
17938         /* Turn on a single ISR mode in IGU if driver is going to use
17939          * INT#x or MSI
17940          */
17941         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17942             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17943         }
17944
17945         /*
17946          * Timers workaround bug: function init part.
17947          * Need to wait 20msec after initializing ILT,
17948          * needed to make sure there are no requests in
17949          * one of the PXP internal queues with "old" ILT addresses
17950          */
17951         DELAY(20000);
17952
17953         /*
17954          * Master enable - Due to WB DMAE writes performed before this
17955          * register is re-initialized as part of the regular function
17956          * init
17957          */
17958         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17959         /* Enable the function in IGU */
17960         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17961     }
17962
17963     sc->dmae_ready = 1;
17964
17965     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17966
17967     if (!CHIP_IS_E1x(sc))
17968         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17969
17970     ecore_init_block(sc, BLOCK_ATC, init_phase);
17971     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17972     ecore_init_block(sc, BLOCK_NIG, init_phase);
17973     ecore_init_block(sc, BLOCK_SRC, init_phase);
17974     ecore_init_block(sc, BLOCK_MISC, init_phase);
17975     ecore_init_block(sc, BLOCK_TCM, init_phase);
17976     ecore_init_block(sc, BLOCK_UCM, init_phase);
17977     ecore_init_block(sc, BLOCK_CCM, init_phase);
17978     ecore_init_block(sc, BLOCK_XCM, init_phase);
17979     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17980     ecore_init_block(sc, BLOCK_USEM, init_phase);
17981     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17982     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17983
17984     if (!CHIP_IS_E1x(sc))
17985         REG_WR(sc, QM_REG_PF_EN, 1);
17986
17987     if (!CHIP_IS_E1x(sc)) {
17988         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17989         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17990         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17991         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17992     }
17993     ecore_init_block(sc, BLOCK_QM, init_phase);
17994
17995     ecore_init_block(sc, BLOCK_TM, init_phase);
17996     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17997
17998     bxe_iov_init_dq(sc);
17999
18000     ecore_init_block(sc, BLOCK_BRB1, init_phase);
18001     ecore_init_block(sc, BLOCK_PRS, init_phase);
18002     ecore_init_block(sc, BLOCK_TSDM, init_phase);
18003     ecore_init_block(sc, BLOCK_CSDM, init_phase);
18004     ecore_init_block(sc, BLOCK_USDM, init_phase);
18005     ecore_init_block(sc, BLOCK_XSDM, init_phase);
18006     ecore_init_block(sc, BLOCK_UPB, init_phase);
18007     ecore_init_block(sc, BLOCK_XPB, init_phase);
18008     ecore_init_block(sc, BLOCK_PBF, init_phase);
18009     if (!CHIP_IS_E1x(sc))
18010         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
18011
18012     ecore_init_block(sc, BLOCK_CDU, init_phase);
18013
18014     ecore_init_block(sc, BLOCK_CFC, init_phase);
18015
18016     if (!CHIP_IS_E1x(sc))
18017         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
18018
18019     if (IS_MF(sc)) {
18020         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
18021         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
18022     }
18023
18024     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
18025
18026     /* HC init per function */
18027     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18028         if (CHIP_IS_E1H(sc)) {
18029             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18030
18031             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18032             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18033         }
18034         ecore_init_block(sc, BLOCK_HC, init_phase);
18035
18036     } else {
18037         int num_segs, sb_idx, prod_offset;
18038
18039         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18040
18041         if (!CHIP_IS_E1x(sc)) {
18042             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18043             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18044         }
18045
18046         ecore_init_block(sc, BLOCK_IGU, init_phase);
18047
18048         if (!CHIP_IS_E1x(sc)) {
18049             int dsb_idx = 0;
18050             /**
18051              * Producer memory:
18052              * E2 mode: address 0-135 match to the mapping memory;
18053              * 136 - PF0 default prod; 137 - PF1 default prod;
18054              * 138 - PF2 default prod; 139 - PF3 default prod;
18055              * 140 - PF0 attn prod;    141 - PF1 attn prod;
18056              * 142 - PF2 attn prod;    143 - PF3 attn prod;
18057              * 144-147 reserved.
18058              *
18059              * E1.5 mode - In backward compatible mode;
18060              * for non default SB; each even line in the memory
18061              * holds the U producer and each odd line hold
18062              * the C producer. The first 128 producers are for
18063              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18064              * producers are for the DSB for each PF.
18065              * Each PF has five segments: (the order inside each
18066              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18067              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18068              * 144-147 attn prods;
18069              */
18070             /* non-default-status-blocks */
18071             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18072                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18073             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18074                 prod_offset = (sc->igu_base_sb + sb_idx) *
18075                     num_segs;
18076
18077                 for (i = 0; i < num_segs; i++) {
18078                     addr = IGU_REG_PROD_CONS_MEMORY +
18079                             (prod_offset + i) * 4;
18080                     REG_WR(sc, addr, 0);
18081                 }
18082                 /* send consumer update with value 0 */
18083                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18084                            USTORM_ID, 0, IGU_INT_NOP, 1);
18085                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18086             }
18087
18088             /* default-status-blocks */
18089             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18090                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18091
18092             if (CHIP_IS_MODE_4_PORT(sc))
18093                 dsb_idx = SC_FUNC(sc);
18094             else
18095                 dsb_idx = SC_VN(sc);
18096
18097             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18098                        IGU_BC_BASE_DSB_PROD + dsb_idx :
18099                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
18100
18101             /*
18102              * igu prods come in chunks of E1HVN_MAX (4) -
18103              * does not matters what is the current chip mode
18104              */
18105             for (i = 0; i < (num_segs * E1HVN_MAX);
18106                  i += E1HVN_MAX) {
18107                 addr = IGU_REG_PROD_CONS_MEMORY +
18108                             (prod_offset + i)*4;
18109                 REG_WR(sc, addr, 0);
18110             }
18111             /* send consumer update with 0 */
18112             if (CHIP_INT_MODE_IS_BC(sc)) {
18113                 bxe_ack_sb(sc, sc->igu_dsb_id,
18114                            USTORM_ID, 0, IGU_INT_NOP, 1);
18115                 bxe_ack_sb(sc, sc->igu_dsb_id,
18116                            CSTORM_ID, 0, IGU_INT_NOP, 1);
18117                 bxe_ack_sb(sc, sc->igu_dsb_id,
18118                            XSTORM_ID, 0, IGU_INT_NOP, 1);
18119                 bxe_ack_sb(sc, sc->igu_dsb_id,
18120                            TSTORM_ID, 0, IGU_INT_NOP, 1);
18121                 bxe_ack_sb(sc, sc->igu_dsb_id,
18122                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18123             } else {
18124                 bxe_ack_sb(sc, sc->igu_dsb_id,
18125                            USTORM_ID, 0, IGU_INT_NOP, 1);
18126                 bxe_ack_sb(sc, sc->igu_dsb_id,
18127                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18128             }
18129             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18130
18131             /* !!! these should become driver const once
18132                rf-tool supports split-68 const */
18133             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18134             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18135             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18136             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18137             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18138             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18139         }
18140     }
18141
18142     /* Reset PCIE errors for debug */
18143     REG_WR(sc, 0x2114, 0xffffffff);
18144     REG_WR(sc, 0x2120, 0xffffffff);
18145
18146     if (CHIP_IS_E1x(sc)) {
18147         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18148         main_mem_base = HC_REG_MAIN_MEMORY +
18149                 SC_PORT(sc) * (main_mem_size * 4);
18150         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18151         main_mem_width = 8;
18152
18153         val = REG_RD(sc, main_mem_prty_clr);
18154         if (val) {
18155             BLOGD(sc, DBG_LOAD,
18156                   "Parity errors in HC block during function init (0x%x)!\n",
18157                   val);
18158         }
18159
18160         /* Clear "false" parity errors in MSI-X table */
18161         for (i = main_mem_base;
18162              i < main_mem_base + main_mem_size * 4;
18163              i += main_mem_width) {
18164             bxe_read_dmae(sc, i, main_mem_width / 4);
18165             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18166                            i, main_mem_width / 4);
18167         }
18168         /* Clear HC parity attention */
18169         REG_RD(sc, main_mem_prty_clr);
18170     }
18171
18172 #if 1
18173     /* Enable STORMs SP logging */
18174     REG_WR8(sc, BAR_USTRORM_INTMEM +
18175            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18176     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18177            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18178     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18179            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18180     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18181            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18182 #endif
18183
18184     elink_phy_probe(&sc->link_params);
18185
18186     return (0);
18187 }
18188
18189 static void
18190 bxe_link_reset(struct bxe_softc *sc)
18191 {
18192     if (!BXE_NOMCP(sc)) {
18193         bxe_acquire_phy_lock(sc);
18194         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18195         bxe_release_phy_lock(sc);
18196     } else {
18197         if (!CHIP_REV_IS_SLOW(sc)) {
18198             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18199         }
18200     }
18201 }
18202
18203 static void
18204 bxe_reset_port(struct bxe_softc *sc)
18205 {
18206     int port = SC_PORT(sc);
18207     uint32_t val;
18208
18209         ELINK_DEBUG_P0(sc, "bxe_reset_port called\n");
18210     /* reset physical Link */
18211     bxe_link_reset(sc);
18212
18213     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18214
18215     /* Do not rcv packets to BRB */
18216     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18217     /* Do not direct rcv packets that are not for MCP to the BRB */
18218     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18219                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18220
18221     /* Configure AEU */
18222     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18223
18224     DELAY(100000);
18225
18226     /* Check for BRB port occupancy */
18227     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18228     if (val) {
18229         BLOGD(sc, DBG_LOAD,
18230               "BRB1 is not empty, %d blocks are occupied\n", val);
18231     }
18232
18233     /* TODO: Close Doorbell port? */
18234 }
18235
18236 static void
18237 bxe_ilt_wr(struct bxe_softc *sc,
18238            uint32_t         index,
18239            bus_addr_t       addr)
18240 {
18241     int reg;
18242     uint32_t wb_write[2];
18243
18244     if (CHIP_IS_E1(sc)) {
18245         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18246     } else {
18247         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18248     }
18249
18250     wb_write[0] = ONCHIP_ADDR1(addr);
18251     wb_write[1] = ONCHIP_ADDR2(addr);
18252     REG_WR_DMAE(sc, reg, wb_write, 2);
18253 }
18254
18255 static void
18256 bxe_clear_func_ilt(struct bxe_softc *sc,
18257                    uint32_t         func)
18258 {
18259     uint32_t i, base = FUNC_ILT_BASE(func);
18260     for (i = base; i < base + ILT_PER_FUNC; i++) {
18261         bxe_ilt_wr(sc, i, 0);
18262     }
18263 }
18264
18265 static void
18266 bxe_reset_func(struct bxe_softc *sc)
18267 {
18268     struct bxe_fastpath *fp;
18269     int port = SC_PORT(sc);
18270     int func = SC_FUNC(sc);
18271     int i;
18272
18273     /* Disable the function in the FW */
18274     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18275     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18276     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18277     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18278
18279     /* FP SBs */
18280     FOR_EACH_ETH_QUEUE(sc, i) {
18281         fp = &sc->fp[i];
18282         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18283                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18284                 SB_DISABLED);
18285     }
18286
18287     /* SP SB */
18288     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18289             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18290             SB_DISABLED);
18291
18292     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18293         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18294     }
18295
18296     /* Configure IGU */
18297     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18298         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18299         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18300     } else {
18301         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18302         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18303     }
18304
18305     if (CNIC_LOADED(sc)) {
18306         /* Disable Timer scan */
18307         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18308         /*
18309          * Wait for at least 10ms and up to 2 second for the timers
18310          * scan to complete
18311          */
18312         for (i = 0; i < 200; i++) {
18313             DELAY(10000);
18314             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18315                 break;
18316         }
18317     }
18318
18319     /* Clear ILT */
18320     bxe_clear_func_ilt(sc, func);
18321
18322     /*
18323      * Timers workaround bug for E2: if this is vnic-3,
18324      * we need to set the entire ilt range for this timers.
18325      */
18326     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18327         struct ilt_client_info ilt_cli;
18328         /* use dummy TM client */
18329         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18330         ilt_cli.start = 0;
18331         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18332         ilt_cli.client_num = ILT_CLIENT_TM;
18333
18334         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18335     }
18336
18337     /* this assumes that reset_port() called before reset_func()*/
18338     if (!CHIP_IS_E1x(sc)) {
18339         bxe_pf_disable(sc);
18340     }
18341
18342     sc->dmae_ready = 0;
18343 }
18344
18345 static int
18346 bxe_gunzip_init(struct bxe_softc *sc)
18347 {
18348     return (0);
18349 }
18350
18351 static void
18352 bxe_gunzip_end(struct bxe_softc *sc)
18353 {
18354     return;
18355 }
18356
18357 static int
18358 bxe_init_firmware(struct bxe_softc *sc)
18359 {
18360     if (CHIP_IS_E1(sc)) {
18361         ecore_init_e1_firmware(sc);
18362         sc->iro_array = e1_iro_arr;
18363     } else if (CHIP_IS_E1H(sc)) {
18364         ecore_init_e1h_firmware(sc);
18365         sc->iro_array = e1h_iro_arr;
18366     } else if (!CHIP_IS_E1x(sc)) {
18367         ecore_init_e2_firmware(sc);
18368         sc->iro_array = e2_iro_arr;
18369     } else {
18370         BLOGE(sc, "Unsupported chip revision\n");
18371         return (-1);
18372     }
18373
18374     return (0);
18375 }
18376
18377 static void
18378 bxe_release_firmware(struct bxe_softc *sc)
18379 {
18380     /* Do nothing */
18381     return;
18382 }
18383
18384 static int
18385 ecore_gunzip(struct bxe_softc *sc,
18386              const uint8_t    *zbuf,
18387              int              len)
18388 {
18389     /* XXX : Implement... */
18390     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18391     return (FALSE);
18392 }
18393
18394 static void
18395 ecore_reg_wr_ind(struct bxe_softc *sc,
18396                  uint32_t         addr,
18397                  uint32_t         val)
18398 {
18399     bxe_reg_wr_ind(sc, addr, val);
18400 }
18401
18402 static void
18403 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18404                           bus_addr_t       phys_addr,
18405                           uint32_t         addr,
18406                           uint32_t         len)
18407 {
18408     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18409 }
18410
18411 void
18412 ecore_storm_memset_struct(struct bxe_softc *sc,
18413                           uint32_t         addr,
18414                           size_t           size,
18415                           uint32_t         *data)
18416 {
18417     uint8_t i;
18418     for (i = 0; i < size/4; i++) {
18419         REG_WR(sc, addr + (i * 4), data[i]);
18420     }
18421 }
18422
18423
18424 /*
18425  * character device - ioctl interface definitions
18426  */
18427
18428
18429 #include "bxe_dump.h"
18430 #include "bxe_ioctl.h"
18431 #include <sys/conf.h>
18432
18433 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18434                 struct thread *td);
18435
18436 static struct cdevsw bxe_cdevsw = {
18437     .d_version = D_VERSION,
18438     .d_ioctl = bxe_eioctl,
18439     .d_name = "bxecnic",
18440 };
18441
18442 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18443
18444
18445 #define DUMP_ALL_PRESETS        0x1FFF
18446 #define DUMP_MAX_PRESETS        13
18447 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18448 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18449 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18450 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18451 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18452
18453 #define IS_REG_IN_PRESET(presets, idx)  \
18454                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18455
18456
18457 static int
18458 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18459 {
18460     if (CHIP_IS_E1(sc))
18461         return dump_num_registers[0][preset-1];
18462     else if (CHIP_IS_E1H(sc))
18463         return dump_num_registers[1][preset-1];
18464     else if (CHIP_IS_E2(sc))
18465         return dump_num_registers[2][preset-1];
18466     else if (CHIP_IS_E3A0(sc))
18467         return dump_num_registers[3][preset-1];
18468     else if (CHIP_IS_E3B0(sc))
18469         return dump_num_registers[4][preset-1];
18470     else
18471         return 0;
18472 }
18473
18474 static int
18475 bxe_get_total_regs_len32(struct bxe_softc *sc)
18476 {
18477     uint32_t preset_idx;
18478     int regdump_len32 = 0;
18479
18480
18481     /* Calculate the total preset regs length */
18482     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18483         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18484     }
18485
18486     return regdump_len32;
18487 }
18488
18489 static const uint32_t *
18490 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18491 {
18492     if (CHIP_IS_E2(sc))
18493         return page_vals_e2;
18494     else if (CHIP_IS_E3(sc))
18495         return page_vals_e3;
18496     else
18497         return NULL;
18498 }
18499
18500 static uint32_t
18501 __bxe_get_page_reg_num(struct bxe_softc *sc)
18502 {
18503     if (CHIP_IS_E2(sc))
18504         return PAGE_MODE_VALUES_E2;
18505     else if (CHIP_IS_E3(sc))
18506         return PAGE_MODE_VALUES_E3;
18507     else
18508         return 0;
18509 }
18510
18511 static const uint32_t *
18512 __bxe_get_page_write_ar(struct bxe_softc *sc)
18513 {
18514     if (CHIP_IS_E2(sc))
18515         return page_write_regs_e2;
18516     else if (CHIP_IS_E3(sc))
18517         return page_write_regs_e3;
18518     else
18519         return NULL;
18520 }
18521
18522 static uint32_t
18523 __bxe_get_page_write_num(struct bxe_softc *sc)
18524 {
18525     if (CHIP_IS_E2(sc))
18526         return PAGE_WRITE_REGS_E2;
18527     else if (CHIP_IS_E3(sc))
18528         return PAGE_WRITE_REGS_E3;
18529     else
18530         return 0;
18531 }
18532
18533 static const struct reg_addr *
18534 __bxe_get_page_read_ar(struct bxe_softc *sc)
18535 {
18536     if (CHIP_IS_E2(sc))
18537         return page_read_regs_e2;
18538     else if (CHIP_IS_E3(sc))
18539         return page_read_regs_e3;
18540     else
18541         return NULL;
18542 }
18543
18544 static uint32_t
18545 __bxe_get_page_read_num(struct bxe_softc *sc)
18546 {
18547     if (CHIP_IS_E2(sc))
18548         return PAGE_READ_REGS_E2;
18549     else if (CHIP_IS_E3(sc))
18550         return PAGE_READ_REGS_E3;
18551     else
18552         return 0;
18553 }
18554
18555 static bool
18556 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18557 {
18558     if (CHIP_IS_E1(sc))
18559         return IS_E1_REG(reg_info->chips);
18560     else if (CHIP_IS_E1H(sc))
18561         return IS_E1H_REG(reg_info->chips);
18562     else if (CHIP_IS_E2(sc))
18563         return IS_E2_REG(reg_info->chips);
18564     else if (CHIP_IS_E3A0(sc))
18565         return IS_E3A0_REG(reg_info->chips);
18566     else if (CHIP_IS_E3B0(sc))
18567         return IS_E3B0_REG(reg_info->chips);
18568     else
18569         return 0;
18570 }
18571
18572 static bool
18573 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18574 {
18575     if (CHIP_IS_E1(sc))
18576         return IS_E1_REG(wreg_info->chips);
18577     else if (CHIP_IS_E1H(sc))
18578         return IS_E1H_REG(wreg_info->chips);
18579     else if (CHIP_IS_E2(sc))
18580         return IS_E2_REG(wreg_info->chips);
18581     else if (CHIP_IS_E3A0(sc))
18582         return IS_E3A0_REG(wreg_info->chips);
18583     else if (CHIP_IS_E3B0(sc))
18584         return IS_E3B0_REG(wreg_info->chips);
18585     else
18586         return 0;
18587 }
18588
18589 /**
18590  * bxe_read_pages_regs - read "paged" registers
18591  *
18592  * @bp          device handle
18593  * @p           output buffer
18594  *
18595  * Reads "paged" memories: memories that may only be read by first writing to a
18596  * specific address ("write address") and then reading from a specific address
18597  * ("read address"). There may be more than one write address per "page" and
18598  * more than one read address per write address.
18599  */
18600 static void
18601 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18602 {
18603     uint32_t i, j, k, n;
18604
18605     /* addresses of the paged registers */
18606     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18607     /* number of paged registers */
18608     int num_pages = __bxe_get_page_reg_num(sc);
18609     /* write addresses */
18610     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18611     /* number of write addresses */
18612     int write_num = __bxe_get_page_write_num(sc);
18613     /* read addresses info */
18614     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18615     /* number of read addresses */
18616     int read_num = __bxe_get_page_read_num(sc);
18617     uint32_t addr, size;
18618
18619     for (i = 0; i < num_pages; i++) {
18620         for (j = 0; j < write_num; j++) {
18621             REG_WR(sc, write_addr[j], page_addr[i]);
18622
18623             for (k = 0; k < read_num; k++) {
18624                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18625                     size = read_addr[k].size;
18626                     for (n = 0; n < size; n++) {
18627                         addr = read_addr[k].addr + n*4;
18628                         *p++ = REG_RD(sc, addr);
18629                     }
18630                 }
18631             }
18632         }
18633     }
18634     return;
18635 }
18636
18637
18638 static int
18639 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18640 {
18641     uint32_t i, j, addr;
18642     const struct wreg_addr *wreg_addr_p = NULL;
18643
18644     if (CHIP_IS_E1(sc))
18645         wreg_addr_p = &wreg_addr_e1;
18646     else if (CHIP_IS_E1H(sc))
18647         wreg_addr_p = &wreg_addr_e1h;
18648     else if (CHIP_IS_E2(sc))
18649         wreg_addr_p = &wreg_addr_e2;
18650     else if (CHIP_IS_E3A0(sc))
18651         wreg_addr_p = &wreg_addr_e3;
18652     else if (CHIP_IS_E3B0(sc))
18653         wreg_addr_p = &wreg_addr_e3b0;
18654     else
18655         return (-1);
18656
18657     /* Read the idle_chk registers */
18658     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18659         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18660             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18661             for (j = 0; j < idle_reg_addrs[i].size; j++)
18662                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18663         }
18664     }
18665
18666     /* Read the regular registers */
18667     for (i = 0; i < REGS_COUNT; i++) {
18668         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18669             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18670             for (j = 0; j < reg_addrs[i].size; j++)
18671                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18672         }
18673     }
18674
18675     /* Read the CAM registers */
18676     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18677         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18678         for (i = 0; i < wreg_addr_p->size; i++) {
18679             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18680
18681             /* In case of wreg_addr register, read additional
18682                registers from read_regs array
18683              */
18684             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18685                 addr = *(wreg_addr_p->read_regs);
18686                 *p++ = REG_RD(sc, addr + j*4);
18687             }
18688         }
18689     }
18690
18691     /* Paged registers are supported in E2 & E3 only */
18692     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18693         /* Read "paged" registers */
18694         bxe_read_pages_regs(sc, p, preset);
18695     }
18696
18697     return 0;
18698 }
18699
18700 int
18701 bxe_grc_dump(struct bxe_softc *sc)
18702 {
18703     int rval = 0;
18704     uint32_t preset_idx;
18705     uint8_t *buf;
18706     uint32_t size;
18707     struct  dump_header *d_hdr;
18708     uint32_t i;
18709     uint32_t reg_val;
18710     uint32_t reg_addr;
18711     uint32_t cmd_offset;
18712     struct ecore_ilt *ilt = SC_ILT(sc);
18713     struct bxe_fastpath *fp;
18714     struct ilt_client_info *ilt_cli;
18715     int grc_dump_size;
18716
18717
18718     if (sc->grcdump_done || sc->grcdump_started)
18719         return (rval);
18720     
18721     sc->grcdump_started = 1;
18722     BLOGI(sc, "Started collecting grcdump\n");
18723
18724     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18725                 sizeof(struct  dump_header);
18726
18727     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18728
18729     if (sc->grc_dump == NULL) {
18730         BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
18731         return(ENOMEM);
18732     }
18733
18734
18735
18736     /* Disable parity attentions as long as following dump may
18737      * cause false alarms by reading never written registers. We
18738      * will re-enable parity attentions right after the dump.
18739      */
18740
18741     /* Disable parity on path 0 */
18742     bxe_pretend_func(sc, 0);
18743
18744     ecore_disable_blocks_parity(sc);
18745
18746     /* Disable parity on path 1 */
18747     bxe_pretend_func(sc, 1);
18748     ecore_disable_blocks_parity(sc);
18749
18750     /* Return to current function */
18751     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18752
18753     buf = sc->grc_dump;
18754     d_hdr = sc->grc_dump;
18755
18756     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18757     d_hdr->version = BNX2X_DUMP_VERSION;
18758     d_hdr->preset = DUMP_ALL_PRESETS;
18759
18760     if (CHIP_IS_E1(sc)) {
18761         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18762     } else if (CHIP_IS_E1H(sc)) {
18763         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18764     } else if (CHIP_IS_E2(sc)) {
18765         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18766                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18767     } else if (CHIP_IS_E3A0(sc)) {
18768         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18769                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18770     } else if (CHIP_IS_E3B0(sc)) {
18771         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18772                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18773     }
18774
18775     buf += sizeof(struct  dump_header);
18776
18777     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18778
18779         /* Skip presets with IOR */
18780         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18781             (preset_idx == 11))
18782             continue;
18783
18784         rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
18785
18786         if (rval)
18787             break;
18788
18789         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18790
18791         buf += size;
18792     }
18793
18794     bxe_pretend_func(sc, 0);
18795     ecore_clear_blocks_parity(sc);
18796     ecore_enable_blocks_parity(sc);
18797
18798     bxe_pretend_func(sc, 1);
18799     ecore_clear_blocks_parity(sc);
18800     ecore_enable_blocks_parity(sc);
18801
18802     /* Return to current function */
18803     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18804
18805
18806
18807     if(sc->state == BXE_STATE_OPEN) {
18808         if(sc->fw_stats_req  != NULL) {
18809                 BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
18810                                 (uintmax_t)sc->fw_stats_req_mapping,
18811                                 (uintmax_t)sc->fw_stats_data_mapping,
18812                                 sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
18813                 }       
18814                 if(sc->def_sb != NULL) {
18815                         BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
18816                                 (void *)sc->def_sb_dma.paddr, sc->def_sb,
18817                                 sizeof(struct host_sp_status_block));
18818                 }
18819                 if(sc->eq_dma.vaddr != NULL) {
18820                 BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
18821                                 (uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
18822                 }
18823                 if(sc->sp_dma.vaddr != NULL) {
18824                 BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
18825                                 (uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
18826                                 sizeof(struct bxe_slowpath));
18827                 }
18828                 if(sc->spq_dma.vaddr != NULL) {
18829                 BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
18830                                 (uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
18831                 }
18832                 if(sc->gz_buf_dma.vaddr != NULL) {
18833                 BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
18834                                 (uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
18835                                 FW_BUF_SIZE);
18836                 }
18837         for (i = 0; i < sc->num_queues; i++) {
18838                 fp = &sc->fp[i];
18839                         if(fp->sb_dma.vaddr != NULL && fp->tx_dma.vaddr != NULL &&
18840                         fp->rx_dma.vaddr != NULL && fp->rcq_dma.vaddr != NULL &&
18841                         fp->rx_sge_dma.vaddr != NULL) {
18842
18843                                 BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18844                                 (uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
18845                                 sizeof(union bxe_host_hc_status_block));
18846                                 BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18847                                 (uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
18848                                 (BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
18849                         BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18850                                 (uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
18851                                 (BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
18852                         BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18853                                 (uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
18854                                 (BCM_PAGE_SIZE * RCQ_NUM_PAGES));
18855                         BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18856                                 (uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
18857                                 (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
18858                 }
18859                 }
18860                 if(ilt != NULL ) {
18861                 ilt_cli = &ilt->clients[1];
18862                         if(ilt->lines != NULL) {
18863                 for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
18864                         BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
18865                                 (uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
18866                                 ((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
18867                 }
18868                         }
18869                 }
18870
18871
18872         cmd_offset = DMAE_REG_CMD_MEM;
18873         for (i = 0; i < 224; i++) {
18874                 reg_addr = (cmd_offset +(i * 4));
18875                 reg_val = REG_RD(sc, reg_addr);
18876                 BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
18877                                 reg_addr, reg_val);
18878         }
18879         }
18880
18881     BLOGI(sc, "Collection of grcdump done\n");
18882     sc->grcdump_done = 1;
18883     return(rval);
18884 }
18885
18886 static int
18887 bxe_add_cdev(struct bxe_softc *sc)
18888 {
18889     sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
18890
18891     if (sc->eeprom == NULL) {
18892         BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
18893         return (-1);
18894     }
18895
18896     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18897                             sc->ifnet->if_dunit,
18898                             UID_ROOT,
18899                             GID_WHEEL,
18900                             0600,
18901                             "%s",
18902                             if_name(sc->ifnet));
18903
18904     if (sc->ioctl_dev == NULL) {
18905         free(sc->eeprom, M_DEVBUF);
18906         sc->eeprom = NULL;
18907         return (-1);
18908     }
18909
18910     sc->ioctl_dev->si_drv1 = sc;
18911
18912     return (0);
18913 }
18914
18915 static void
18916 bxe_del_cdev(struct bxe_softc *sc)
18917 {
18918     if (sc->ioctl_dev != NULL)
18919         destroy_dev(sc->ioctl_dev);
18920
18921     if (sc->eeprom != NULL) {
18922         free(sc->eeprom, M_DEVBUF);
18923         sc->eeprom = NULL;
18924     }
18925     sc->ioctl_dev = NULL;
18926
18927     return;
18928 }
18929
18930 static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
18931 {
18932
18933     if ((sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) == 0)
18934         return FALSE;
18935
18936     return TRUE;
18937 }
18938
18939
18940 static int
18941 bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18942 {
18943     int rval = 0;
18944
18945     if(!bxe_is_nvram_accessible(sc)) {
18946         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18947         return (-EAGAIN);
18948     }
18949     rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
18950
18951
18952    return (rval);
18953 }
18954
18955 static int
18956 bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18957 {
18958     int rval = 0;
18959
18960     if(!bxe_is_nvram_accessible(sc)) {
18961         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18962         return (-EAGAIN);
18963     }
18964     rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
18965
18966    return (rval);
18967 }
18968
18969 static int
18970 bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
18971 {
18972     int rval = 0;
18973
18974     switch (eeprom->eeprom_cmd) {
18975
18976     case BXE_EEPROM_CMD_SET_EEPROM:
18977
18978         rval = copyin(eeprom->eeprom_data, sc->eeprom,
18979                        eeprom->eeprom_data_len);
18980
18981         if (rval)
18982             break;
18983
18984         rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18985                        eeprom->eeprom_data_len);
18986         break;
18987
18988     case BXE_EEPROM_CMD_GET_EEPROM:
18989
18990         rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18991                        eeprom->eeprom_data_len);
18992
18993         if (rval) {
18994             break;
18995         }
18996
18997         rval = copyout(sc->eeprom, eeprom->eeprom_data,
18998                        eeprom->eeprom_data_len);
18999         break;
19000
19001     default:
19002             rval = EINVAL;
19003             break;
19004     }
19005
19006     if (rval) {
19007         BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
19008     }
19009
19010     return (rval);
19011 }
19012
19013 static int
19014 bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
19015 {
19016     uint32_t ext_phy_config;
19017     int port = SC_PORT(sc);
19018     int cfg_idx = bxe_get_link_cfg_idx(sc);
19019
19020     dev_p->supported = sc->port.supported[cfg_idx] |
19021             (sc->port.supported[cfg_idx ^ 1] &
19022             (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
19023     dev_p->advertising = sc->port.advertising[cfg_idx];
19024     if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
19025         ELINK_ETH_PHY_SFP_1G_FIBER) {
19026         dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
19027         dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
19028     }
19029     if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
19030         !(sc->flags & BXE_MF_FUNC_DIS)) {
19031         dev_p->duplex = sc->link_vars.duplex;
19032         if (IS_MF(sc) && !BXE_NOMCP(sc))
19033             dev_p->speed = bxe_get_mf_speed(sc);
19034         else
19035             dev_p->speed = sc->link_vars.line_speed;
19036     } else {
19037         dev_p->duplex = DUPLEX_UNKNOWN;
19038         dev_p->speed = SPEED_UNKNOWN;
19039     }
19040
19041     dev_p->port = bxe_media_detect(sc);
19042
19043     ext_phy_config = SHMEM_RD(sc,
19044                          dev_info.port_hw_config[port].external_phy_config);
19045     if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
19046         PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
19047         dev_p->phy_address =  sc->port.phy_addr;
19048     else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19049             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
19050         ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19051             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
19052         dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
19053     else
19054         dev_p->phy_address = 0;
19055
19056     if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
19057         dev_p->autoneg = AUTONEG_ENABLE;
19058     else
19059        dev_p->autoneg = AUTONEG_DISABLE;
19060
19061
19062     return 0;
19063 }
19064
19065 static int
19066 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
19067         struct thread *td)
19068 {
19069     struct bxe_softc    *sc;
19070     int                 rval = 0;
19071     device_t            pci_dev;
19072     bxe_grcdump_t       *dump = NULL;
19073     int grc_dump_size;
19074     bxe_drvinfo_t   *drv_infop = NULL;
19075     bxe_dev_setting_t  *dev_p;
19076     bxe_dev_setting_t  dev_set;
19077     bxe_get_regs_t  *reg_p;
19078     bxe_reg_rdw_t *reg_rdw_p;
19079     bxe_pcicfg_rdw_t *cfg_rdw_p;
19080     bxe_perm_mac_addr_t *mac_addr_p;
19081
19082
19083     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
19084         return ENXIO;
19085
19086     pci_dev= sc->dev;
19087
19088     dump = (bxe_grcdump_t *)data;
19089
19090     switch(cmd) {
19091
19092         case BXE_GRC_DUMP_SIZE:
19093             dump->pci_func = sc->pcie_func;
19094             dump->grcdump_size =
19095                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19096                      sizeof(struct  dump_header);
19097             break;
19098
19099         case BXE_GRC_DUMP:
19100             
19101             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19102                                 sizeof(struct  dump_header);
19103             if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
19104                 (dump->grcdump_size < grc_dump_size)) {
19105                 rval = EINVAL;
19106                 break;
19107             }
19108
19109             if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
19110                 (!sc->grcdump_started)) {
19111                 rval =  bxe_grc_dump(sc);
19112             }
19113
19114             if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
19115                 (sc->grc_dump != NULL))  {
19116                 dump->grcdump_dwords = grc_dump_size >> 2;
19117                 rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
19118                 free(sc->grc_dump, M_DEVBUF);
19119                 sc->grc_dump = NULL;
19120                 sc->grcdump_started = 0;
19121                 sc->grcdump_done = 0;
19122             }
19123
19124             break;
19125
19126         case BXE_DRV_INFO:
19127             drv_infop = (bxe_drvinfo_t *)data;
19128             snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
19129             snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
19130                 BXE_DRIVER_VERSION);
19131             snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
19132                 sc->devinfo.bc_ver_str);
19133             snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
19134                 "%s", sc->fw_ver_str);
19135             drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
19136             drv_infop->reg_dump_len =
19137                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
19138                     + sizeof(struct  dump_header);
19139             snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
19140                 sc->pcie_bus, sc->pcie_device, sc->pcie_func);
19141             break;
19142
19143         case BXE_DEV_SETTING:
19144             dev_p = (bxe_dev_setting_t *)data;
19145             bxe_get_settings(sc, &dev_set);
19146             dev_p->supported = dev_set.supported;
19147             dev_p->advertising = dev_set.advertising;
19148             dev_p->speed = dev_set.speed;
19149             dev_p->duplex = dev_set.duplex;
19150             dev_p->port = dev_set.port;
19151             dev_p->phy_address = dev_set.phy_address;
19152             dev_p->autoneg = dev_set.autoneg;
19153
19154             break;
19155
19156         case BXE_GET_REGS:
19157
19158             reg_p = (bxe_get_regs_t *)data;
19159             grc_dump_size = reg_p->reg_buf_len;
19160
19161             if((!sc->grcdump_done) && (!sc->grcdump_started)) {
19162                 bxe_grc_dump(sc);
19163             }
19164             if((sc->grcdump_done) && (sc->grcdump_started) &&
19165                 (sc->grc_dump != NULL))  {
19166                 rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
19167                 free(sc->grc_dump, M_DEVBUF);
19168                 sc->grc_dump = NULL;
19169                 sc->grcdump_started = 0;
19170                 sc->grcdump_done = 0;
19171             }
19172
19173             break;
19174
19175         case BXE_RDW_REG:
19176             reg_rdw_p = (bxe_reg_rdw_t *)data;
19177             if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
19178                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19179                 reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
19180
19181             if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
19182                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19183                 REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
19184
19185             break;
19186
19187         case BXE_RDW_PCICFG:
19188             cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
19189             if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
19190
19191                 cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
19192                                          cfg_rdw_p->cfg_width);
19193
19194             } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
19195                 pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
19196                             cfg_rdw_p->cfg_width);
19197             } else {
19198                 BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
19199             }
19200             break;
19201
19202         case BXE_MAC_ADDR:
19203             mac_addr_p = (bxe_perm_mac_addr_t *)data;
19204             snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
19205                 sc->mac_addr_str);
19206             break;
19207
19208         case BXE_EEPROM:
19209             rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
19210             break;
19211
19212
19213         default:
19214             break;
19215     }
19216
19217     return (rval);
19218 }