]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/dev/bxe/bxe.c
MFC r338734
[FreeBSD/stable/9.git] / sys / dev / bxe / bxe.c
1 /*-
2  * Copyright (c) 2007-2014 QLogic Corporation. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS'
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #define BXE_DRIVER_VERSION "1.78.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 };
646
647 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
648 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
649
650
651 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
652                                  uint8_t          read_cfg,
653                                  uint8_t          cmng_type);
654 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
655 static void    storm_memset_cmng(struct bxe_softc *sc,
656                                  struct cmng_init *cmng,
657                                  uint8_t          port);
658 static void    bxe_set_reset_global(struct bxe_softc *sc);
659 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
660 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
661                                  int              engine);
662 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
663 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
664                                    uint8_t          *global,
665                                    uint8_t          print);
666 static void    bxe_int_disable(struct bxe_softc *sc);
667 static int     bxe_release_leader_lock(struct bxe_softc *sc);
668 static void    bxe_pf_disable(struct bxe_softc *sc);
669 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
670 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
671                                       struct bxe_fastpath *fp,
672                                       uint16_t            rx_bd_prod,
673                                       uint16_t            rx_cq_prod,
674                                       uint16_t            rx_sge_prod);
675 static void    bxe_link_report_locked(struct bxe_softc *sc);
676 static void    bxe_link_report(struct bxe_softc *sc);
677 static void    bxe_link_status_update(struct bxe_softc *sc);
678 static void    bxe_periodic_callout_func(void *xsc);
679 static void    bxe_periodic_start(struct bxe_softc *sc);
680 static void    bxe_periodic_stop(struct bxe_softc *sc);
681 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
682                                     uint16_t prev_index,
683                                     uint16_t index);
684 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
685                                      int                 queue);
686 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
687                                      uint16_t            index);
688 static uint8_t bxe_txeof(struct bxe_softc *sc,
689                          struct bxe_fastpath *fp);
690 static void    bxe_task_fp(struct bxe_fastpath *fp);
691 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
692                                      struct mbuf      *m,
693                                      uint8_t          contents);
694 static int     bxe_alloc_mem(struct bxe_softc *sc);
695 static void    bxe_free_mem(struct bxe_softc *sc);
696 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
697 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
698 static int     bxe_interrupt_attach(struct bxe_softc *sc);
699 static void    bxe_interrupt_detach(struct bxe_softc *sc);
700 static void    bxe_set_rx_mode(struct bxe_softc *sc);
701 static int     bxe_init_locked(struct bxe_softc *sc);
702 static int     bxe_stop_locked(struct bxe_softc *sc);
703 static __noinline int bxe_nic_load(struct bxe_softc *sc,
704                                    int              load_mode);
705 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
706                                      uint32_t         unload_mode,
707                                      uint8_t          keep_link);
708
709 static void bxe_handle_sp_tq(void *context, int pending);
710 static void bxe_handle_fp_tq(void *context, int pending);
711
712 static int bxe_add_cdev(struct bxe_softc *sc);
713 static void bxe_del_cdev(struct bxe_softc *sc);
714 int bxe_grc_dump(struct bxe_softc *sc);
715 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
716 static void bxe_free_buf_rings(struct bxe_softc *sc);
717
718 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
719 uint32_t
720 calc_crc32(uint8_t  *crc32_packet,
721            uint32_t crc32_length,
722            uint32_t crc32_seed,
723            uint8_t  complement)
724 {
725    uint32_t byte         = 0;
726    uint32_t bit          = 0;
727    uint8_t  msb          = 0;
728    uint32_t temp         = 0;
729    uint32_t shft         = 0;
730    uint8_t  current_byte = 0;
731    uint32_t crc32_result = crc32_seed;
732    const uint32_t CRC32_POLY = 0x1edc6f41;
733
734    if ((crc32_packet == NULL) ||
735        (crc32_length == 0) ||
736        ((crc32_length % 8) != 0))
737     {
738         return (crc32_result);
739     }
740
741     for (byte = 0; byte < crc32_length; byte = byte + 1)
742     {
743         current_byte = crc32_packet[byte];
744         for (bit = 0; bit < 8; bit = bit + 1)
745         {
746             /* msb = crc32_result[31]; */
747             msb = (uint8_t)(crc32_result >> 31);
748
749             crc32_result = crc32_result << 1;
750
751             /* it (msb != current_byte[bit]) */
752             if (msb != (0x1 & (current_byte >> bit)))
753             {
754                 crc32_result = crc32_result ^ CRC32_POLY;
755                 /* crc32_result[0] = 1 */
756                 crc32_result |= 1;
757             }
758         }
759     }
760
761     /* Last step is to:
762      * 1. "mirror" every bit
763      * 2. swap the 4 bytes
764      * 3. complement each bit
765      */
766
767     /* Mirror */
768     temp = crc32_result;
769     shft = sizeof(crc32_result) * 8 - 1;
770
771     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
772     {
773         temp <<= 1;
774         temp |= crc32_result & 1;
775         shft-- ;
776     }
777
778     /* temp[31-bit] = crc32_result[bit] */
779     temp <<= shft;
780
781     /* Swap */
782     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
783     {
784         uint32_t t0, t1, t2, t3;
785         t0 = (0x000000ff & (temp >> 24));
786         t1 = (0x0000ff00 & (temp >> 8));
787         t2 = (0x00ff0000 & (temp << 8));
788         t3 = (0xff000000 & (temp << 24));
789         crc32_result = t0 | t1 | t2 | t3;
790     }
791
792     /* Complement */
793     if (complement)
794     {
795         crc32_result = ~crc32_result;
796     }
797
798     return (crc32_result);
799 }
800
801 int
802 bxe_test_bit(int                    nr,
803              volatile unsigned long *addr)
804 {
805     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
806 }
807
808 void
809 bxe_set_bit(unsigned int           nr,
810             volatile unsigned long *addr)
811 {
812     atomic_set_acq_long(addr, (1 << nr));
813 }
814
815 void
816 bxe_clear_bit(int                    nr,
817               volatile unsigned long *addr)
818 {
819     atomic_clear_acq_long(addr, (1 << nr));
820 }
821
822 int
823 bxe_test_and_set_bit(int                    nr,
824                        volatile unsigned long *addr)
825 {
826     unsigned long x;
827     nr = (1 << nr);
828     do {
829         x = *addr;
830     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
831     // if (x & nr) bit_was_set; else bit_was_not_set;
832     return (x & nr);
833 }
834
835 int
836 bxe_test_and_clear_bit(int                    nr,
837                        volatile unsigned long *addr)
838 {
839     unsigned long x;
840     nr = (1 << nr);
841     do {
842         x = *addr;
843     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
844     // if (x & nr) bit_was_set; else bit_was_not_set;
845     return (x & nr);
846 }
847
848 int
849 bxe_cmpxchg(volatile int *addr,
850             int          old,
851             int          new)
852 {
853     int x;
854     do {
855         x = *addr;
856     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
857     return (x);
858 }
859
860 /*
861  * Get DMA memory from the OS.
862  *
863  * Validates that the OS has provided DMA buffers in response to a
864  * bus_dmamap_load call and saves the physical address of those buffers.
865  * When the callback is used the OS will return 0 for the mapping function
866  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
867  * failures back to the caller.
868  *
869  * Returns:
870  *   Nothing.
871  */
872 static void
873 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
874 {
875     struct bxe_dma *dma = arg;
876
877     if (error) {
878         dma->paddr = 0;
879         dma->nseg  = 0;
880         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
881     } else {
882         dma->paddr = segs->ds_addr;
883         dma->nseg  = nseg;
884     }
885 }
886
887 /*
888  * Allocate a block of memory and map it for DMA. No partial completions
889  * allowed and release any resources acquired if we can't acquire all
890  * resources.
891  *
892  * Returns:
893  *   0 = Success, !0 = Failure
894  */
895 int
896 bxe_dma_alloc(struct bxe_softc *sc,
897               bus_size_t       size,
898               struct bxe_dma   *dma,
899               const char       *msg)
900 {
901     int rc;
902
903     if (dma->size > 0) {
904         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
905               (unsigned long)dma->size);
906         return (1);
907     }
908
909     memset(dma, 0, sizeof(*dma)); /* sanity */
910     dma->sc   = sc;
911     dma->size = size;
912     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
913
914     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
915                             BCM_PAGE_SIZE,      /* alignment */
916                             0,                  /* boundary limit */
917                             BUS_SPACE_MAXADDR,  /* restricted low */
918                             BUS_SPACE_MAXADDR,  /* restricted hi */
919                             NULL,               /* addr filter() */
920                             NULL,               /* addr filter() arg */
921                             size,               /* max map size */
922                             1,                  /* num discontinuous */
923                             size,               /* max seg size */
924                             BUS_DMA_ALLOCNOW,   /* flags */
925                             NULL,               /* lock() */
926                             NULL,               /* lock() arg */
927                             &dma->tag);         /* returned dma tag */
928     if (rc != 0) {
929         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
930         memset(dma, 0, sizeof(*dma));
931         return (1);
932     }
933
934     rc = bus_dmamem_alloc(dma->tag,
935                           (void **)&dma->vaddr,
936                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
937                           &dma->map);
938     if (rc != 0) {
939         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
940         bus_dma_tag_destroy(dma->tag);
941         memset(dma, 0, sizeof(*dma));
942         return (1);
943     }
944
945     rc = bus_dmamap_load(dma->tag,
946                          dma->map,
947                          dma->vaddr,
948                          size,
949                          bxe_dma_map_addr, /* BLOGD in here */
950                          dma,
951                          BUS_DMA_NOWAIT);
952     if (rc != 0) {
953         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
954         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
955         bus_dma_tag_destroy(dma->tag);
956         memset(dma, 0, sizeof(*dma));
957         return (1);
958     }
959
960     return (0);
961 }
962
963 void
964 bxe_dma_free(struct bxe_softc *sc,
965              struct bxe_dma   *dma)
966 {
967     if (dma->size > 0) {
968         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
969
970         bus_dmamap_sync(dma->tag, dma->map,
971                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
972         bus_dmamap_unload(dma->tag, dma->map);
973         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
974         bus_dma_tag_destroy(dma->tag);
975     }
976
977     memset(dma, 0, sizeof(*dma));
978 }
979
980 /*
981  * These indirect read and write routines are only during init.
982  * The locking is handled by the MCP.
983  */
984
985 void
986 bxe_reg_wr_ind(struct bxe_softc *sc,
987                uint32_t         addr,
988                uint32_t         val)
989 {
990     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
991     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
992     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
993 }
994
995 uint32_t
996 bxe_reg_rd_ind(struct bxe_softc *sc,
997                uint32_t         addr)
998 {
999     uint32_t val;
1000
1001     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1002     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
1003     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1004
1005     return (val);
1006 }
1007
1008 static int
1009 bxe_acquire_hw_lock(struct bxe_softc *sc,
1010                     uint32_t         resource)
1011 {
1012     uint32_t lock_status;
1013     uint32_t resource_bit = (1 << resource);
1014     int func = SC_FUNC(sc);
1015     uint32_t hw_lock_control_reg;
1016     int cnt;
1017
1018     /* validate the resource is within range */
1019     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1020         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1021             " resource_bit 0x%x\n", resource, resource_bit);
1022         return (-1);
1023     }
1024
1025     if (func <= 5) {
1026         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1027     } else {
1028         hw_lock_control_reg =
1029                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1030     }
1031
1032     /* validate the resource is not already taken */
1033     lock_status = REG_RD(sc, hw_lock_control_reg);
1034     if (lock_status & resource_bit) {
1035         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1036               resource, lock_status, resource_bit);
1037         return (-1);
1038     }
1039
1040     /* try every 5ms for 5 seconds */
1041     for (cnt = 0; cnt < 1000; cnt++) {
1042         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1043         lock_status = REG_RD(sc, hw_lock_control_reg);
1044         if (lock_status & resource_bit) {
1045             return (0);
1046         }
1047         DELAY(5000);
1048     }
1049
1050     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1051         resource, resource_bit);
1052     return (-1);
1053 }
1054
1055 static int
1056 bxe_release_hw_lock(struct bxe_softc *sc,
1057                     uint32_t         resource)
1058 {
1059     uint32_t lock_status;
1060     uint32_t resource_bit = (1 << resource);
1061     int func = SC_FUNC(sc);
1062     uint32_t hw_lock_control_reg;
1063
1064     /* validate the resource is within range */
1065     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1066         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1067             " resource_bit 0x%x\n", resource, resource_bit);
1068         return (-1);
1069     }
1070
1071     if (func <= 5) {
1072         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1073     } else {
1074         hw_lock_control_reg =
1075                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1076     }
1077
1078     /* validate the resource is currently taken */
1079     lock_status = REG_RD(sc, hw_lock_control_reg);
1080     if (!(lock_status & resource_bit)) {
1081         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1082               resource, lock_status, resource_bit);
1083         return (-1);
1084     }
1085
1086     REG_WR(sc, hw_lock_control_reg, resource_bit);
1087     return (0);
1088 }
1089 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1090 {
1091         BXE_PHY_LOCK(sc);
1092         bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1093 }
1094
1095 static void bxe_release_phy_lock(struct bxe_softc *sc)
1096 {
1097         bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1098         BXE_PHY_UNLOCK(sc);
1099 }
1100 /*
1101  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1102  * had we done things the other way around, if two pfs from the same port
1103  * would attempt to access nvram at the same time, we could run into a
1104  * scenario such as:
1105  * pf A takes the port lock.
1106  * pf B succeeds in taking the same lock since they are from the same port.
1107  * pf A takes the per pf misc lock. Performs eeprom access.
1108  * pf A finishes. Unlocks the per pf misc lock.
1109  * Pf B takes the lock and proceeds to perform it's own access.
1110  * pf A unlocks the per port lock, while pf B is still working (!).
1111  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1112  * access corrupted by pf B).*
1113  */
1114 static int
1115 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1116 {
1117     int port = SC_PORT(sc);
1118     int count, i;
1119     uint32_t val = 0;
1120
1121     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1122     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1123
1124     /* adjust timeout for emulation/FPGA */
1125     count = NVRAM_TIMEOUT_COUNT;
1126     if (CHIP_REV_IS_SLOW(sc)) {
1127         count *= 100;
1128     }
1129
1130     /* request access to nvram interface */
1131     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1132            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1133
1134     for (i = 0; i < count*10; i++) {
1135         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1136         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1137             break;
1138         }
1139
1140         DELAY(5);
1141     }
1142
1143     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1144         BLOGE(sc, "Cannot get access to nvram interface "
1145             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1146             port, val);
1147         return (-1);
1148     }
1149
1150     return (0);
1151 }
1152
1153 static int
1154 bxe_release_nvram_lock(struct bxe_softc *sc)
1155 {
1156     int port = SC_PORT(sc);
1157     int count, i;
1158     uint32_t val = 0;
1159
1160     /* adjust timeout for emulation/FPGA */
1161     count = NVRAM_TIMEOUT_COUNT;
1162     if (CHIP_REV_IS_SLOW(sc)) {
1163         count *= 100;
1164     }
1165
1166     /* relinquish nvram interface */
1167     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1168            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1169
1170     for (i = 0; i < count*10; i++) {
1171         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1172         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1173             break;
1174         }
1175
1176         DELAY(5);
1177     }
1178
1179     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1180         BLOGE(sc, "Cannot free access to nvram interface "
1181             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1182             port, val);
1183         return (-1);
1184     }
1185
1186     /* release HW lock: protect against other PFs in PF Direct Assignment */
1187     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1188
1189     return (0);
1190 }
1191
1192 static void
1193 bxe_enable_nvram_access(struct bxe_softc *sc)
1194 {
1195     uint32_t val;
1196
1197     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1198
1199     /* enable both bits, even on read */
1200     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1201            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1202 }
1203
1204 static void
1205 bxe_disable_nvram_access(struct bxe_softc *sc)
1206 {
1207     uint32_t val;
1208
1209     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1210
1211     /* disable both bits, even after read */
1212     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1213            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1214                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1215 }
1216
1217 static int
1218 bxe_nvram_read_dword(struct bxe_softc *sc,
1219                      uint32_t         offset,
1220                      uint32_t         *ret_val,
1221                      uint32_t         cmd_flags)
1222 {
1223     int count, i, rc;
1224     uint32_t val;
1225
1226     /* build the command word */
1227     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1228
1229     /* need to clear DONE bit separately */
1230     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1231
1232     /* address of the NVRAM to read from */
1233     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1234            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1235
1236     /* issue a read command */
1237     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1238
1239     /* adjust timeout for emulation/FPGA */
1240     count = NVRAM_TIMEOUT_COUNT;
1241     if (CHIP_REV_IS_SLOW(sc)) {
1242         count *= 100;
1243     }
1244
1245     /* wait for completion */
1246     *ret_val = 0;
1247     rc = -1;
1248     for (i = 0; i < count; i++) {
1249         DELAY(5);
1250         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1251
1252         if (val & MCPR_NVM_COMMAND_DONE) {
1253             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1254             /* we read nvram data in cpu order
1255              * but ethtool sees it as an array of bytes
1256              * converting to big-endian will do the work
1257              */
1258             *ret_val = htobe32(val);
1259             rc = 0;
1260             break;
1261         }
1262     }
1263
1264     if (rc == -1) {
1265         BLOGE(sc, "nvram read timeout expired "
1266             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1267             offset, cmd_flags, val);
1268     }
1269
1270     return (rc);
1271 }
1272
1273 static int
1274 bxe_nvram_read(struct bxe_softc *sc,
1275                uint32_t         offset,
1276                uint8_t          *ret_buf,
1277                int              buf_size)
1278 {
1279     uint32_t cmd_flags;
1280     uint32_t val;
1281     int rc;
1282
1283     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1284         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1285               offset, buf_size);
1286         return (-1);
1287     }
1288
1289     if ((offset + buf_size) > sc->devinfo.flash_size) {
1290         BLOGE(sc, "Invalid parameter, "
1291                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1292               offset, buf_size, sc->devinfo.flash_size);
1293         return (-1);
1294     }
1295
1296     /* request access to nvram interface */
1297     rc = bxe_acquire_nvram_lock(sc);
1298     if (rc) {
1299         return (rc);
1300     }
1301
1302     /* enable access to nvram interface */
1303     bxe_enable_nvram_access(sc);
1304
1305     /* read the first word(s) */
1306     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1307     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1308         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1309         memcpy(ret_buf, &val, 4);
1310
1311         /* advance to the next dword */
1312         offset += sizeof(uint32_t);
1313         ret_buf += sizeof(uint32_t);
1314         buf_size -= sizeof(uint32_t);
1315         cmd_flags = 0;
1316     }
1317
1318     if (rc == 0) {
1319         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1320         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1321         memcpy(ret_buf, &val, 4);
1322     }
1323
1324     /* disable access to nvram interface */
1325     bxe_disable_nvram_access(sc);
1326     bxe_release_nvram_lock(sc);
1327
1328     return (rc);
1329 }
1330
1331 static int
1332 bxe_nvram_write_dword(struct bxe_softc *sc,
1333                       uint32_t         offset,
1334                       uint32_t         val,
1335                       uint32_t         cmd_flags)
1336 {
1337     int count, i, rc;
1338
1339     /* build the command word */
1340     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1341
1342     /* need to clear DONE bit separately */
1343     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1344
1345     /* write the data */
1346     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1347
1348     /* address of the NVRAM to write to */
1349     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1350            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1351
1352     /* issue the write command */
1353     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1354
1355     /* adjust timeout for emulation/FPGA */
1356     count = NVRAM_TIMEOUT_COUNT;
1357     if (CHIP_REV_IS_SLOW(sc)) {
1358         count *= 100;
1359     }
1360
1361     /* wait for completion */
1362     rc = -1;
1363     for (i = 0; i < count; i++) {
1364         DELAY(5);
1365         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1366         if (val & MCPR_NVM_COMMAND_DONE) {
1367             rc = 0;
1368             break;
1369         }
1370     }
1371
1372     if (rc == -1) {
1373         BLOGE(sc, "nvram write timeout expired "
1374             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1375             offset, cmd_flags, val);
1376     }
1377
1378     return (rc);
1379 }
1380
1381 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1382
1383 static int
1384 bxe_nvram_write1(struct bxe_softc *sc,
1385                  uint32_t         offset,
1386                  uint8_t          *data_buf,
1387                  int              buf_size)
1388 {
1389     uint32_t cmd_flags;
1390     uint32_t align_offset;
1391     uint32_t val;
1392     int rc;
1393
1394     if ((offset + buf_size) > sc->devinfo.flash_size) {
1395         BLOGE(sc, "Invalid parameter, "
1396                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1397               offset, buf_size, sc->devinfo.flash_size);
1398         return (-1);
1399     }
1400
1401     /* request access to nvram interface */
1402     rc = bxe_acquire_nvram_lock(sc);
1403     if (rc) {
1404         return (rc);
1405     }
1406
1407     /* enable access to nvram interface */
1408     bxe_enable_nvram_access(sc);
1409
1410     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1411     align_offset = (offset & ~0x03);
1412     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1413
1414     if (rc == 0) {
1415         val &= ~(0xff << BYTE_OFFSET(offset));
1416         val |= (*data_buf << BYTE_OFFSET(offset));
1417
1418         /* nvram data is returned as an array of bytes
1419          * convert it back to cpu order
1420          */
1421         val = be32toh(val);
1422
1423         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1424     }
1425
1426     /* disable access to nvram interface */
1427     bxe_disable_nvram_access(sc);
1428     bxe_release_nvram_lock(sc);
1429
1430     return (rc);
1431 }
1432
1433 static int
1434 bxe_nvram_write(struct bxe_softc *sc,
1435                 uint32_t         offset,
1436                 uint8_t          *data_buf,
1437                 int              buf_size)
1438 {
1439     uint32_t cmd_flags;
1440     uint32_t val;
1441     uint32_t written_so_far;
1442     int rc;
1443
1444     if (buf_size == 1) {
1445         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1446     }
1447
1448     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1449         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1450               offset, buf_size);
1451         return (-1);
1452     }
1453
1454     if (buf_size == 0) {
1455         return (0); /* nothing to do */
1456     }
1457
1458     if ((offset + buf_size) > sc->devinfo.flash_size) {
1459         BLOGE(sc, "Invalid parameter, "
1460                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1461               offset, buf_size, sc->devinfo.flash_size);
1462         return (-1);
1463     }
1464
1465     /* request access to nvram interface */
1466     rc = bxe_acquire_nvram_lock(sc);
1467     if (rc) {
1468         return (rc);
1469     }
1470
1471     /* enable access to nvram interface */
1472     bxe_enable_nvram_access(sc);
1473
1474     written_so_far = 0;
1475     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1476     while ((written_so_far < buf_size) && (rc == 0)) {
1477         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1478             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1479         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1480             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1481         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1482             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1483         }
1484
1485         memcpy(&val, data_buf, 4);
1486
1487         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1488
1489         /* advance to the next dword */
1490         offset += sizeof(uint32_t);
1491         data_buf += sizeof(uint32_t);
1492         written_so_far += sizeof(uint32_t);
1493         cmd_flags = 0;
1494     }
1495
1496     /* disable access to nvram interface */
1497     bxe_disable_nvram_access(sc);
1498     bxe_release_nvram_lock(sc);
1499
1500     return (rc);
1501 }
1502
1503 /* copy command into DMAE command memory and set DMAE command Go */
1504 void
1505 bxe_post_dmae(struct bxe_softc    *sc,
1506               struct dmae_cmd *dmae,
1507               int                 idx)
1508 {
1509     uint32_t cmd_offset;
1510     int i;
1511
1512     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1513     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1514         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1515     }
1516
1517     REG_WR(sc, dmae_reg_go_c[idx], 1);
1518 }
1519
1520 uint32_t
1521 bxe_dmae_opcode_add_comp(uint32_t opcode,
1522                          uint8_t  comp_type)
1523 {
1524     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1525                       DMAE_CMD_C_TYPE_ENABLE));
1526 }
1527
1528 uint32_t
1529 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1530 {
1531     return (opcode & ~DMAE_CMD_SRC_RESET);
1532 }
1533
1534 uint32_t
1535 bxe_dmae_opcode(struct bxe_softc *sc,
1536                 uint8_t          src_type,
1537                 uint8_t          dst_type,
1538                 uint8_t          with_comp,
1539                 uint8_t          comp_type)
1540 {
1541     uint32_t opcode = 0;
1542
1543     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1544                (dst_type << DMAE_CMD_DST_SHIFT));
1545
1546     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1547
1548     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1549
1550     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1551                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1552
1553     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1554
1555 #ifdef __BIG_ENDIAN
1556     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1557 #else
1558     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1559 #endif
1560
1561     if (with_comp) {
1562         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1563     }
1564
1565     return (opcode);
1566 }
1567
1568 static void
1569 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1570                         struct dmae_cmd *dmae,
1571                         uint8_t             src_type,
1572                         uint8_t             dst_type)
1573 {
1574     memset(dmae, 0, sizeof(struct dmae_cmd));
1575
1576     /* set the opcode */
1577     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1578                                    TRUE, DMAE_COMP_PCI);
1579
1580     /* fill in the completion parameters */
1581     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1582     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1583     dmae->comp_val     = DMAE_COMP_VAL;
1584 }
1585
1586 /* issue a DMAE command over the init channel and wait for completion */
1587 static int
1588 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1589                          struct dmae_cmd *dmae)
1590 {
1591     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1592     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1593
1594     BXE_DMAE_LOCK(sc);
1595
1596     /* reset completion */
1597     *wb_comp = 0;
1598
1599     /* post the command on the channel used for initializations */
1600     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1601
1602     /* wait for completion */
1603     DELAY(5);
1604
1605     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1606         if (!timeout ||
1607             (sc->recovery_state != BXE_RECOVERY_DONE &&
1608              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1609             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1610                 *wb_comp, sc->recovery_state);
1611             BXE_DMAE_UNLOCK(sc);
1612             return (DMAE_TIMEOUT);
1613         }
1614
1615         timeout--;
1616         DELAY(50);
1617     }
1618
1619     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1620         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1621                 *wb_comp, sc->recovery_state);
1622         BXE_DMAE_UNLOCK(sc);
1623         return (DMAE_PCI_ERROR);
1624     }
1625
1626     BXE_DMAE_UNLOCK(sc);
1627     return (0);
1628 }
1629
1630 void
1631 bxe_read_dmae(struct bxe_softc *sc,
1632               uint32_t         src_addr,
1633               uint32_t         len32)
1634 {
1635     struct dmae_cmd dmae;
1636     uint32_t *data;
1637     int i, rc;
1638
1639     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1640
1641     if (!sc->dmae_ready) {
1642         data = BXE_SP(sc, wb_data[0]);
1643
1644         for (i = 0; i < len32; i++) {
1645             data[i] = (CHIP_IS_E1(sc)) ?
1646                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1647                           REG_RD(sc, (src_addr + (i * 4)));
1648         }
1649
1650         return;
1651     }
1652
1653     /* set opcode and fixed command fields */
1654     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1655
1656     /* fill in addresses and len */
1657     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1658     dmae.src_addr_hi = 0;
1659     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1660     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1661     dmae.len         = len32;
1662
1663     /* issue the command and wait for completion */
1664     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1665         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1666     };
1667 }
1668
1669 void
1670 bxe_write_dmae(struct bxe_softc *sc,
1671                bus_addr_t       dma_addr,
1672                uint32_t         dst_addr,
1673                uint32_t         len32)
1674 {
1675     struct dmae_cmd dmae;
1676     int rc;
1677
1678     if (!sc->dmae_ready) {
1679         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1680
1681         if (CHIP_IS_E1(sc)) {
1682             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1683         } else {
1684             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1685         }
1686
1687         return;
1688     }
1689
1690     /* set opcode and fixed command fields */
1691     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1692
1693     /* fill in addresses and len */
1694     dmae.src_addr_lo = U64_LO(dma_addr);
1695     dmae.src_addr_hi = U64_HI(dma_addr);
1696     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1697     dmae.dst_addr_hi = 0;
1698     dmae.len         = len32;
1699
1700     /* issue the command and wait for completion */
1701     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1702         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1703     }
1704 }
1705
1706 void
1707 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1708                         bus_addr_t       phys_addr,
1709                         uint32_t         addr,
1710                         uint32_t         len)
1711 {
1712     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1713     int offset = 0;
1714
1715     while (len > dmae_wr_max) {
1716         bxe_write_dmae(sc,
1717                        (phys_addr + offset), /* src DMA address */
1718                        (addr + offset),      /* dst GRC address */
1719                        dmae_wr_max);
1720         offset += (dmae_wr_max * 4);
1721         len -= dmae_wr_max;
1722     }
1723
1724     bxe_write_dmae(sc,
1725                    (phys_addr + offset), /* src DMA address */
1726                    (addr + offset),      /* dst GRC address */
1727                    len);
1728 }
1729
1730 void
1731 bxe_set_ctx_validation(struct bxe_softc   *sc,
1732                        struct eth_context *cxt,
1733                        uint32_t           cid)
1734 {
1735     /* ustorm cxt validation */
1736     cxt->ustorm_ag_context.cdu_usage =
1737         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1738             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1739     /* xcontext validation */
1740     cxt->xstorm_ag_context.cdu_reserved =
1741         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1742             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1743 }
1744
1745 static void
1746 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1747                             uint8_t          port,
1748                             uint8_t          fw_sb_id,
1749                             uint8_t          sb_index,
1750                             uint8_t          ticks)
1751 {
1752     uint32_t addr =
1753         (BAR_CSTRORM_INTMEM +
1754          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1755
1756     REG_WR8(sc, addr, ticks);
1757
1758     BLOGD(sc, DBG_LOAD,
1759           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1760           port, fw_sb_id, sb_index, ticks);
1761 }
1762
1763 static void
1764 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1765                             uint8_t          port,
1766                             uint16_t         fw_sb_id,
1767                             uint8_t          sb_index,
1768                             uint8_t          disable)
1769 {
1770     uint32_t enable_flag =
1771         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1772     uint32_t addr =
1773         (BAR_CSTRORM_INTMEM +
1774          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1775     uint8_t flags;
1776
1777     /* clear and set */
1778     flags = REG_RD8(sc, addr);
1779     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1780     flags |= enable_flag;
1781     REG_WR8(sc, addr, flags);
1782
1783     BLOGD(sc, DBG_LOAD,
1784           "port %d fw_sb_id %d sb_index %d disable %d\n",
1785           port, fw_sb_id, sb_index, disable);
1786 }
1787
1788 void
1789 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1790                              uint8_t          fw_sb_id,
1791                              uint8_t          sb_index,
1792                              uint8_t          disable,
1793                              uint16_t         usec)
1794 {
1795     int port = SC_PORT(sc);
1796     uint8_t ticks = (usec / 4); /* XXX ??? */
1797
1798     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1799
1800     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1801     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1802 }
1803
1804 void
1805 elink_cb_udelay(struct bxe_softc *sc,
1806                 uint32_t         usecs)
1807 {
1808     DELAY(usecs);
1809 }
1810
1811 uint32_t
1812 elink_cb_reg_read(struct bxe_softc *sc,
1813                   uint32_t         reg_addr)
1814 {
1815     return (REG_RD(sc, reg_addr));
1816 }
1817
1818 void
1819 elink_cb_reg_write(struct bxe_softc *sc,
1820                    uint32_t         reg_addr,
1821                    uint32_t         val)
1822 {
1823     REG_WR(sc, reg_addr, val);
1824 }
1825
1826 void
1827 elink_cb_reg_wb_write(struct bxe_softc *sc,
1828                       uint32_t         offset,
1829                       uint32_t         *wb_write,
1830                       uint16_t         len)
1831 {
1832     REG_WR_DMAE(sc, offset, wb_write, len);
1833 }
1834
1835 void
1836 elink_cb_reg_wb_read(struct bxe_softc *sc,
1837                      uint32_t         offset,
1838                      uint32_t         *wb_write,
1839                      uint16_t         len)
1840 {
1841     REG_RD_DMAE(sc, offset, wb_write, len);
1842 }
1843
1844 uint8_t
1845 elink_cb_path_id(struct bxe_softc *sc)
1846 {
1847     return (SC_PATH(sc));
1848 }
1849
1850 void
1851 elink_cb_event_log(struct bxe_softc     *sc,
1852                    const elink_log_id_t elink_log_id,
1853                    ...)
1854 {
1855     /* XXX */
1856     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1857 }
1858
1859 static int
1860 bxe_set_spio(struct bxe_softc *sc,
1861              int              spio,
1862              uint32_t         mode)
1863 {
1864     uint32_t spio_reg;
1865
1866     /* Only 2 SPIOs are configurable */
1867     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1868         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1869         return (-1);
1870     }
1871
1872     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1873
1874     /* read SPIO and mask except the float bits */
1875     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1876
1877     switch (mode) {
1878     case MISC_SPIO_OUTPUT_LOW:
1879         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1880         /* clear FLOAT and set CLR */
1881         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1882         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1883         break;
1884
1885     case MISC_SPIO_OUTPUT_HIGH:
1886         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1887         /* clear FLOAT and set SET */
1888         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1889         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1890         break;
1891
1892     case MISC_SPIO_INPUT_HI_Z:
1893         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1894         /* set FLOAT */
1895         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1896         break;
1897
1898     default:
1899         break;
1900     }
1901
1902     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1903     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1904
1905     return (0);
1906 }
1907
1908 static int
1909 bxe_gpio_read(struct bxe_softc *sc,
1910               int              gpio_num,
1911               uint8_t          port)
1912 {
1913     /* The GPIO should be swapped if swap register is set and active */
1914     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1915                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1916     int gpio_shift = (gpio_num +
1917                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1918     uint32_t gpio_mask = (1 << gpio_shift);
1919     uint32_t gpio_reg;
1920
1921     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1922         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1923             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1924             gpio_mask);
1925         return (-1);
1926     }
1927
1928     /* read GPIO value */
1929     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1930
1931     /* get the requested pin value */
1932     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1933 }
1934
1935 static int
1936 bxe_gpio_write(struct bxe_softc *sc,
1937                int              gpio_num,
1938                uint32_t         mode,
1939                uint8_t          port)
1940 {
1941     /* The GPIO should be swapped if swap register is set and active */
1942     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1943                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1944     int gpio_shift = (gpio_num +
1945                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1946     uint32_t gpio_mask = (1 << gpio_shift);
1947     uint32_t gpio_reg;
1948
1949     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1950         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1951             " gpio_shift %d gpio_mask 0x%x\n",
1952             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1953         return (-1);
1954     }
1955
1956     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1957
1958     /* read GPIO and mask except the float bits */
1959     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1960
1961     switch (mode) {
1962     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1963         BLOGD(sc, DBG_PHY,
1964               "Set GPIO %d (shift %d) -> output low\n",
1965               gpio_num, gpio_shift);
1966         /* clear FLOAT and set CLR */
1967         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1968         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1969         break;
1970
1971     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1972         BLOGD(sc, DBG_PHY,
1973               "Set GPIO %d (shift %d) -> output high\n",
1974               gpio_num, gpio_shift);
1975         /* clear FLOAT and set SET */
1976         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1977         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1978         break;
1979
1980     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1981         BLOGD(sc, DBG_PHY,
1982               "Set GPIO %d (shift %d) -> input\n",
1983               gpio_num, gpio_shift);
1984         /* set FLOAT */
1985         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1986         break;
1987
1988     default:
1989         break;
1990     }
1991
1992     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1993     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1994
1995     return (0);
1996 }
1997
1998 static int
1999 bxe_gpio_mult_write(struct bxe_softc *sc,
2000                     uint8_t          pins,
2001                     uint32_t         mode)
2002 {
2003     uint32_t gpio_reg;
2004
2005     /* any port swapping should be handled by caller */
2006
2007     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2008
2009     /* read GPIO and mask except the float bits */
2010     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
2011     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2012     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
2013     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
2014
2015     switch (mode) {
2016     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2017         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
2018         /* set CLR */
2019         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
2020         break;
2021
2022     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2023         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
2024         /* set SET */
2025         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2026         break;
2027
2028     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2029         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2030         /* set FLOAT */
2031         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2032         break;
2033
2034     default:
2035         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2036             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2037         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2038         return (-1);
2039     }
2040
2041     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2042     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2043
2044     return (0);
2045 }
2046
2047 static int
2048 bxe_gpio_int_write(struct bxe_softc *sc,
2049                    int              gpio_num,
2050                    uint32_t         mode,
2051                    uint8_t          port)
2052 {
2053     /* The GPIO should be swapped if swap register is set and active */
2054     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2055                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2056     int gpio_shift = (gpio_num +
2057                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2058     uint32_t gpio_mask = (1 << gpio_shift);
2059     uint32_t gpio_reg;
2060
2061     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2062         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2063             " gpio_shift %d gpio_mask 0x%x\n",
2064             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2065         return (-1);
2066     }
2067
2068     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2069
2070     /* read GPIO int */
2071     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2072
2073     switch (mode) {
2074     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2075         BLOGD(sc, DBG_PHY,
2076               "Clear GPIO INT %d (shift %d) -> output low\n",
2077               gpio_num, gpio_shift);
2078         /* clear SET and set CLR */
2079         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2080         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2081         break;
2082
2083     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2084         BLOGD(sc, DBG_PHY,
2085               "Set GPIO INT %d (shift %d) -> output high\n",
2086               gpio_num, gpio_shift);
2087         /* clear CLR and set SET */
2088         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2089         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2090         break;
2091
2092     default:
2093         break;
2094     }
2095
2096     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2097     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2098
2099     return (0);
2100 }
2101
2102 uint32_t
2103 elink_cb_gpio_read(struct bxe_softc *sc,
2104                    uint16_t         gpio_num,
2105                    uint8_t          port)
2106 {
2107     return (bxe_gpio_read(sc, gpio_num, port));
2108 }
2109
2110 uint8_t
2111 elink_cb_gpio_write(struct bxe_softc *sc,
2112                     uint16_t         gpio_num,
2113                     uint8_t          mode, /* 0=low 1=high */
2114                     uint8_t          port)
2115 {
2116     return (bxe_gpio_write(sc, gpio_num, mode, port));
2117 }
2118
2119 uint8_t
2120 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2121                          uint8_t          pins,
2122                          uint8_t          mode) /* 0=low 1=high */
2123 {
2124     return (bxe_gpio_mult_write(sc, pins, mode));
2125 }
2126
2127 uint8_t
2128 elink_cb_gpio_int_write(struct bxe_softc *sc,
2129                         uint16_t         gpio_num,
2130                         uint8_t          mode, /* 0=low 1=high */
2131                         uint8_t          port)
2132 {
2133     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2134 }
2135
2136 void
2137 elink_cb_notify_link_changed(struct bxe_softc *sc)
2138 {
2139     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2140                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2141 }
2142
2143 /* send the MCP a request, block until there is a reply */
2144 uint32_t
2145 elink_cb_fw_command(struct bxe_softc *sc,
2146                     uint32_t         command,
2147                     uint32_t         param)
2148 {
2149     int mb_idx = SC_FW_MB_IDX(sc);
2150     uint32_t seq;
2151     uint32_t rc = 0;
2152     uint32_t cnt = 1;
2153     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2154
2155     BXE_FWMB_LOCK(sc);
2156
2157     seq = ++sc->fw_seq;
2158     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2159     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2160
2161     BLOGD(sc, DBG_PHY,
2162           "wrote command 0x%08x to FW MB param 0x%08x\n",
2163           (command | seq), param);
2164
2165     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2166     do {
2167         DELAY(delay * 1000);
2168         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2169     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2170
2171     BLOGD(sc, DBG_PHY,
2172           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2173           cnt*delay, rc, seq);
2174
2175     /* is this a reply to our command? */
2176     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2177         rc &= FW_MSG_CODE_MASK;
2178     } else {
2179         /* Ruh-roh! */
2180         BLOGE(sc, "FW failed to respond!\n");
2181         // XXX bxe_fw_dump(sc);
2182         rc = 0;
2183     }
2184
2185     BXE_FWMB_UNLOCK(sc);
2186     return (rc);
2187 }
2188
2189 static uint32_t
2190 bxe_fw_command(struct bxe_softc *sc,
2191                uint32_t         command,
2192                uint32_t         param)
2193 {
2194     return (elink_cb_fw_command(sc, command, param));
2195 }
2196
2197 static void
2198 __storm_memset_dma_mapping(struct bxe_softc *sc,
2199                            uint32_t         addr,
2200                            bus_addr_t       mapping)
2201 {
2202     REG_WR(sc, addr, U64_LO(mapping));
2203     REG_WR(sc, (addr + 4), U64_HI(mapping));
2204 }
2205
2206 static void
2207 storm_memset_spq_addr(struct bxe_softc *sc,
2208                       bus_addr_t       mapping,
2209                       uint16_t         abs_fid)
2210 {
2211     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2212                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2213     __storm_memset_dma_mapping(sc, addr, mapping);
2214 }
2215
2216 static void
2217 storm_memset_vf_to_pf(struct bxe_softc *sc,
2218                       uint16_t         abs_fid,
2219                       uint16_t         pf_id)
2220 {
2221     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2222     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2223     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2224     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2225 }
2226
2227 static void
2228 storm_memset_func_en(struct bxe_softc *sc,
2229                      uint16_t         abs_fid,
2230                      uint8_t          enable)
2231 {
2232     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2233     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2234     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2235     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2236 }
2237
2238 static void
2239 storm_memset_eq_data(struct bxe_softc       *sc,
2240                      struct event_ring_data *eq_data,
2241                      uint16_t               pfid)
2242 {
2243     uint32_t addr;
2244     size_t size;
2245
2246     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2247     size = sizeof(struct event_ring_data);
2248     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2249 }
2250
2251 static void
2252 storm_memset_eq_prod(struct bxe_softc *sc,
2253                      uint16_t         eq_prod,
2254                      uint16_t         pfid)
2255 {
2256     uint32_t addr = (BAR_CSTRORM_INTMEM +
2257                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2258     REG_WR16(sc, addr, eq_prod);
2259 }
2260
2261 /*
2262  * Post a slowpath command.
2263  *
2264  * A slowpath command is used to propogate a configuration change through
2265  * the controller in a controlled manner, allowing each STORM processor and
2266  * other H/W blocks to phase in the change.  The commands sent on the
2267  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2268  * completion of the ramrod will occur in different ways.  Here's a
2269  * breakdown of ramrods and how they complete:
2270  *
2271  * RAMROD_CMD_ID_ETH_PORT_SETUP
2272  *   Used to setup the leading connection on a port.  Completes on the
2273  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2274  *
2275  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2276  *   Used to setup an additional connection on a port.  Completes on the
2277  *   RCQ of the multi-queue/RSS connection being initialized.
2278  *
2279  * RAMROD_CMD_ID_ETH_STAT_QUERY
2280  *   Used to force the storm processors to update the statistics database
2281  *   in host memory.  This ramrod is send on the leading connection CID and
2282  *   completes as an index increment of the CSTORM on the default status
2283  *   block.
2284  *
2285  * RAMROD_CMD_ID_ETH_UPDATE
2286  *   Used to update the state of the leading connection, usually to udpate
2287  *   the RSS indirection table.  Completes on the RCQ of the leading
2288  *   connection. (Not currently used under FreeBSD until OS support becomes
2289  *   available.)
2290  *
2291  * RAMROD_CMD_ID_ETH_HALT
2292  *   Used when tearing down a connection prior to driver unload.  Completes
2293  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2294  *   use this on the leading connection.
2295  *
2296  * RAMROD_CMD_ID_ETH_SET_MAC
2297  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2298  *   the RCQ of the leading connection.
2299  *
2300  * RAMROD_CMD_ID_ETH_CFC_DEL
2301  *   Used when tearing down a conneciton prior to driver unload.  Completes
2302  *   on the RCQ of the leading connection (since the current connection
2303  *   has been completely removed from controller memory).
2304  *
2305  * RAMROD_CMD_ID_ETH_PORT_DEL
2306  *   Used to tear down the leading connection prior to driver unload,
2307  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2308  *   default status block.
2309  *
2310  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2311  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2312  *   RSS connection that is being offloaded.  (Not currently used under
2313  *   FreeBSD.)
2314  *
2315  * There can only be one command pending per function.
2316  *
2317  * Returns:
2318  *   0 = Success, !0 = Failure.
2319  */
2320
2321 /* must be called under the spq lock */
2322 static inline
2323 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2324 {
2325     struct eth_spe *next_spe = sc->spq_prod_bd;
2326
2327     if (sc->spq_prod_bd == sc->spq_last_bd) {
2328         /* wrap back to the first eth_spq */
2329         sc->spq_prod_bd = sc->spq;
2330         sc->spq_prod_idx = 0;
2331     } else {
2332         sc->spq_prod_bd++;
2333         sc->spq_prod_idx++;
2334     }
2335
2336     return (next_spe);
2337 }
2338
2339 /* must be called under the spq lock */
2340 static inline
2341 void bxe_sp_prod_update(struct bxe_softc *sc)
2342 {
2343     int func = SC_FUNC(sc);
2344
2345     /*
2346      * Make sure that BD data is updated before writing the producer.
2347      * BD data is written to the memory, the producer is read from the
2348      * memory, thus we need a full memory barrier to ensure the ordering.
2349      */
2350     mb();
2351
2352     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2353              sc->spq_prod_idx);
2354
2355     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2356                       BUS_SPACE_BARRIER_WRITE);
2357 }
2358
2359 /**
2360  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2361  *
2362  * @cmd:      command to check
2363  * @cmd_type: command type
2364  */
2365 static inline
2366 int bxe_is_contextless_ramrod(int cmd,
2367                               int cmd_type)
2368 {
2369     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2370         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2371         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2372         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2373         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2374         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2375         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2376         return (TRUE);
2377     } else {
2378         return (FALSE);
2379     }
2380 }
2381
2382 /**
2383  * bxe_sp_post - place a single command on an SP ring
2384  *
2385  * @sc:         driver handle
2386  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2387  * @cid:        SW CID the command is related to
2388  * @data_hi:    command private data address (high 32 bits)
2389  * @data_lo:    command private data address (low 32 bits)
2390  * @cmd_type:   command type (e.g. NONE, ETH)
2391  *
2392  * SP data is handled as if it's always an address pair, thus data fields are
2393  * not swapped to little endian in upper functions. Instead this function swaps
2394  * data as if it's two uint32 fields.
2395  */
2396 int
2397 bxe_sp_post(struct bxe_softc *sc,
2398             int              command,
2399             int              cid,
2400             uint32_t         data_hi,
2401             uint32_t         data_lo,
2402             int              cmd_type)
2403 {
2404     struct eth_spe *spe;
2405     uint16_t type;
2406     int common;
2407
2408     common = bxe_is_contextless_ramrod(command, cmd_type);
2409
2410     BXE_SP_LOCK(sc);
2411
2412     if (common) {
2413         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2414             BLOGE(sc, "EQ ring is full!\n");
2415             BXE_SP_UNLOCK(sc);
2416             return (-1);
2417         }
2418     } else {
2419         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2420             BLOGE(sc, "SPQ ring is full!\n");
2421             BXE_SP_UNLOCK(sc);
2422             return (-1);
2423         }
2424     }
2425
2426     spe = bxe_sp_get_next(sc);
2427
2428     /* CID needs port number to be encoded int it */
2429     spe->hdr.conn_and_cmd_data =
2430         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2431
2432     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2433
2434     /* TBD: Check if it works for VFs */
2435     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2436              SPE_HDR_T_FUNCTION_ID);
2437
2438     spe->hdr.type = htole16(type);
2439
2440     spe->data.update_data_addr.hi = htole32(data_hi);
2441     spe->data.update_data_addr.lo = htole32(data_lo);
2442
2443     /*
2444      * It's ok if the actual decrement is issued towards the memory
2445      * somewhere between the lock and unlock. Thus no more explict
2446      * memory barrier is needed.
2447      */
2448     if (common) {
2449         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2450     } else {
2451         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2452     }
2453
2454     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2455     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2456           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2457     BLOGD(sc, DBG_SP,
2458           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2459           sc->spq_prod_idx,
2460           (uint32_t)U64_HI(sc->spq_dma.paddr),
2461           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2462           command,
2463           common,
2464           HW_CID(sc, cid),
2465           data_hi,
2466           data_lo,
2467           type,
2468           atomic_load_acq_long(&sc->cq_spq_left),
2469           atomic_load_acq_long(&sc->eq_spq_left));
2470
2471     bxe_sp_prod_update(sc);
2472
2473     BXE_SP_UNLOCK(sc);
2474     return (0);
2475 }
2476
2477 /**
2478  * bxe_debug_print_ind_table - prints the indirection table configuration.
2479  *
2480  * @sc: driver hanlde
2481  * @p:  pointer to rss configuration
2482  */
2483
2484 /*
2485  * FreeBSD Device probe function.
2486  *
2487  * Compares the device found to the driver's list of supported devices and
2488  * reports back to the bsd loader whether this is the right driver for the device.
2489  * This is the driver entry function called from the "kldload" command.
2490  *
2491  * Returns:
2492  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2493  */
2494 static int
2495 bxe_probe(device_t dev)
2496 {
2497     struct bxe_softc *sc;
2498     struct bxe_device_type *t;
2499     char *descbuf;
2500     uint16_t did, sdid, svid, vid;
2501
2502     /* Find our device structure */
2503     sc = device_get_softc(dev);
2504     sc->dev = dev;
2505     t = bxe_devs;
2506
2507     /* Get the data for the device to be probed. */
2508     vid  = pci_get_vendor(dev);
2509     did  = pci_get_device(dev);
2510     svid = pci_get_subvendor(dev);
2511     sdid = pci_get_subdevice(dev);
2512
2513     BLOGD(sc, DBG_LOAD,
2514           "%s(); VID = 0x%04X, DID = 0x%04X, SVID = 0x%04X, "
2515           "SDID = 0x%04X\n", __FUNCTION__, vid, did, svid, sdid);
2516
2517     /* Look through the list of known devices for a match. */
2518     while (t->bxe_name != NULL) {
2519         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2520             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2521             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2522             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2523             if (descbuf == NULL)
2524                 return (ENOMEM);
2525
2526             /* Print out the device identity. */
2527             snprintf(descbuf, BXE_DEVDESC_MAX,
2528                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2529                      (((pci_read_config(dev, PCIR_REVID, 4) &
2530                         0xf0) >> 4) + 'A'),
2531                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2532                      BXE_DRIVER_VERSION);
2533
2534             device_set_desc_copy(dev, descbuf);
2535             free(descbuf, M_TEMP);
2536             return (BUS_PROBE_DEFAULT);
2537         }
2538         t++;
2539     }
2540
2541     return (ENXIO);
2542 }
2543
2544 static void
2545 bxe_init_mutexes(struct bxe_softc *sc)
2546 {
2547 #ifdef BXE_CORE_LOCK_SX
2548     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2549              "bxe%d_core_lock", sc->unit);
2550     sx_init(&sc->core_sx, sc->core_sx_name);
2551 #else
2552     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2553              "bxe%d_core_lock", sc->unit);
2554     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2555 #endif
2556
2557     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2558              "bxe%d_sp_lock", sc->unit);
2559     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2560
2561     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2562              "bxe%d_dmae_lock", sc->unit);
2563     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2564
2565     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2566              "bxe%d_phy_lock", sc->unit);
2567     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2568
2569     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2570              "bxe%d_fwmb_lock", sc->unit);
2571     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2572
2573     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2574              "bxe%d_print_lock", sc->unit);
2575     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2576
2577     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2578              "bxe%d_stats_lock", sc->unit);
2579     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2580
2581     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2582              "bxe%d_mcast_lock", sc->unit);
2583     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2584 }
2585
2586 static void
2587 bxe_release_mutexes(struct bxe_softc *sc)
2588 {
2589 #ifdef BXE_CORE_LOCK_SX
2590     sx_destroy(&sc->core_sx);
2591 #else
2592     if (mtx_initialized(&sc->core_mtx)) {
2593         mtx_destroy(&sc->core_mtx);
2594     }
2595 #endif
2596
2597     if (mtx_initialized(&sc->sp_mtx)) {
2598         mtx_destroy(&sc->sp_mtx);
2599     }
2600
2601     if (mtx_initialized(&sc->dmae_mtx)) {
2602         mtx_destroy(&sc->dmae_mtx);
2603     }
2604
2605     if (mtx_initialized(&sc->port.phy_mtx)) {
2606         mtx_destroy(&sc->port.phy_mtx);
2607     }
2608
2609     if (mtx_initialized(&sc->fwmb_mtx)) {
2610         mtx_destroy(&sc->fwmb_mtx);
2611     }
2612
2613     if (mtx_initialized(&sc->print_mtx)) {
2614         mtx_destroy(&sc->print_mtx);
2615     }
2616
2617     if (mtx_initialized(&sc->stats_mtx)) {
2618         mtx_destroy(&sc->stats_mtx);
2619     }
2620
2621     if (mtx_initialized(&sc->mcast_mtx)) {
2622         mtx_destroy(&sc->mcast_mtx);
2623     }
2624 }
2625
2626 static void
2627 bxe_tx_disable(struct bxe_softc* sc)
2628 {
2629     struct ifnet *ifp = sc->ifnet;
2630
2631     /* tell the stack the driver is stopped and TX queue is full */
2632     if (ifp != NULL) {
2633         ifp->if_drv_flags = 0;
2634     }
2635 }
2636
2637 static void
2638 bxe_drv_pulse(struct bxe_softc *sc)
2639 {
2640     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2641              sc->fw_drv_pulse_wr_seq);
2642 }
2643
2644 static inline uint16_t
2645 bxe_tx_avail(struct bxe_softc *sc,
2646              struct bxe_fastpath *fp)
2647 {
2648     int16_t  used;
2649     uint16_t prod;
2650     uint16_t cons;
2651
2652     prod = fp->tx_bd_prod;
2653     cons = fp->tx_bd_cons;
2654
2655     used = SUB_S16(prod, cons);
2656
2657     return (int16_t)(sc->tx_ring_size) - used;
2658 }
2659
2660 static inline int
2661 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2662 {
2663     uint16_t hw_cons;
2664
2665     mb(); /* status block fields can change */
2666     hw_cons = le16toh(*fp->tx_cons_sb);
2667     return (hw_cons != fp->tx_pkt_cons);
2668 }
2669
2670 static inline uint8_t
2671 bxe_has_tx_work(struct bxe_fastpath *fp)
2672 {
2673     /* expand this for multi-cos if ever supported */
2674     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2675 }
2676
2677 static inline int
2678 bxe_has_rx_work(struct bxe_fastpath *fp)
2679 {
2680     uint16_t rx_cq_cons_sb;
2681
2682     mb(); /* status block fields can change */
2683     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2684     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2685         rx_cq_cons_sb++;
2686     return (fp->rx_cq_cons != rx_cq_cons_sb);
2687 }
2688
2689 static void
2690 bxe_sp_event(struct bxe_softc    *sc,
2691              struct bxe_fastpath *fp,
2692              union eth_rx_cqe    *rr_cqe)
2693 {
2694     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2695     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2696     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2697     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2698
2699     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2700           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2701
2702     switch (command) {
2703     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2704         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2705         drv_cmd = ECORE_Q_CMD_UPDATE;
2706         break;
2707
2708     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2709         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2710         drv_cmd = ECORE_Q_CMD_SETUP;
2711         break;
2712
2713     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2714         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2715         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2716         break;
2717
2718     case (RAMROD_CMD_ID_ETH_HALT):
2719         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2720         drv_cmd = ECORE_Q_CMD_HALT;
2721         break;
2722
2723     case (RAMROD_CMD_ID_ETH_TERMINATE):
2724         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2725         drv_cmd = ECORE_Q_CMD_TERMINATE;
2726         break;
2727
2728     case (RAMROD_CMD_ID_ETH_EMPTY):
2729         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2730         drv_cmd = ECORE_Q_CMD_EMPTY;
2731         break;
2732
2733     default:
2734         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2735               command, fp->index);
2736         return;
2737     }
2738
2739     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2740         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2741         /*
2742          * q_obj->complete_cmd() failure means that this was
2743          * an unexpected completion.
2744          *
2745          * In this case we don't want to increase the sc->spq_left
2746          * because apparently we haven't sent this command the first
2747          * place.
2748          */
2749         // bxe_panic(sc, ("Unexpected SP completion\n"));
2750         return;
2751     }
2752
2753     atomic_add_acq_long(&sc->cq_spq_left, 1);
2754
2755     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2756           atomic_load_acq_long(&sc->cq_spq_left));
2757 }
2758
2759 /*
2760  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2761  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2762  * the current aggregation queue as in-progress.
2763  */
2764 static void
2765 bxe_tpa_start(struct bxe_softc            *sc,
2766               struct bxe_fastpath         *fp,
2767               uint16_t                    queue,
2768               uint16_t                    cons,
2769               uint16_t                    prod,
2770               struct eth_fast_path_rx_cqe *cqe)
2771 {
2772     struct bxe_sw_rx_bd tmp_bd;
2773     struct bxe_sw_rx_bd *rx_buf;
2774     struct eth_rx_bd *rx_bd;
2775     int max_agg_queues;
2776     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2777     uint16_t index;
2778
2779     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2780                        "cons=%d prod=%d\n",
2781           fp->index, queue, cons, prod);
2782
2783     max_agg_queues = MAX_AGG_QS(sc);
2784
2785     KASSERT((queue < max_agg_queues),
2786             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2787              fp->index, queue, max_agg_queues));
2788
2789     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2790             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2791              fp->index, queue));
2792
2793     /* copy the existing mbuf and mapping from the TPA pool */
2794     tmp_bd = tpa_info->bd;
2795
2796     if (tmp_bd.m == NULL) {
2797         uint32_t *tmp;
2798
2799         tmp = (uint32_t *)cqe;
2800
2801         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2802               fp->index, queue, cons, prod);
2803         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2804             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2805             
2806         /* XXX Error handling? */
2807         return;
2808     }
2809
2810     /* change the TPA queue to the start state */
2811     tpa_info->state            = BXE_TPA_STATE_START;
2812     tpa_info->placement_offset = cqe->placement_offset;
2813     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2814     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2815     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2816
2817     fp->rx_tpa_queue_used |= (1 << queue);
2818
2819     /*
2820      * If all the buffer descriptors are filled with mbufs then fill in
2821      * the current consumer index with a new BD. Else if a maximum Rx
2822      * buffer limit is imposed then fill in the next producer index.
2823      */
2824     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2825                 prod : cons;
2826
2827     /* move the received mbuf and mapping to TPA pool */
2828     tpa_info->bd = fp->rx_mbuf_chain[cons];
2829
2830     /* release any existing RX BD mbuf mappings */
2831     if (cons != index) {
2832         rx_buf = &fp->rx_mbuf_chain[cons];
2833
2834         if (rx_buf->m_map != NULL) {
2835             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2836                             BUS_DMASYNC_POSTREAD);
2837             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2838         }
2839
2840         /*
2841          * We get here when the maximum number of rx buffers is less than
2842          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2843          * it out here without concern of a memory leak.
2844          */
2845         fp->rx_mbuf_chain[cons].m = NULL;
2846     }
2847
2848     /* update the Rx SW BD with the mbuf info from the TPA pool */
2849     fp->rx_mbuf_chain[index] = tmp_bd;
2850
2851     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2852     rx_bd = &fp->rx_chain[index];
2853     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2854     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2855 }
2856
2857 /*
2858  * When a TPA aggregation is completed, loop through the individual mbufs
2859  * of the aggregation, combining them into a single mbuf which will be sent
2860  * up the stack. Refill all freed SGEs with mbufs as we go along.
2861  */
2862 static int
2863 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2864                    struct bxe_fastpath       *fp,
2865                    struct bxe_sw_tpa_info    *tpa_info,
2866                    uint16_t                  queue,
2867                    uint16_t                  pages,
2868                    struct mbuf               *m,
2869                                struct eth_end_agg_rx_cqe *cqe,
2870                    uint16_t                  cqe_idx)
2871 {
2872     struct mbuf *m_frag;
2873     uint32_t frag_len, frag_size, i;
2874     uint16_t sge_idx;
2875     int rc = 0;
2876     int j;
2877
2878     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2879
2880     BLOGD(sc, DBG_LRO,
2881           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2882           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2883
2884     /* make sure the aggregated frame is not too big to handle */
2885     if (pages > 8 * PAGES_PER_SGE) {
2886
2887         uint32_t *tmp = (uint32_t *)cqe;
2888
2889         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2890                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2891               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2892               tpa_info->len_on_bd, frag_size);
2893
2894         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2895             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2896
2897         bxe_panic(sc, ("sge page count error\n"));
2898         return (EINVAL);
2899     }
2900
2901     /*
2902      * Scan through the scatter gather list pulling individual mbufs into a
2903      * single mbuf for the host stack.
2904      */
2905     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2906         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2907
2908         /*
2909          * Firmware gives the indices of the SGE as if the ring is an array
2910          * (meaning that the "next" element will consume 2 indices).
2911          */
2912         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2913
2914         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2915                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2916               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2917
2918         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2919
2920         /* allocate a new mbuf for the SGE */
2921         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2922         if (rc) {
2923             /* Leave all remaining SGEs in the ring! */
2924             return (rc);
2925         }
2926
2927         /* update the fragment length */
2928         m_frag->m_len = frag_len;
2929
2930         /* concatenate the fragment to the head mbuf */
2931         m_cat(m, m_frag);
2932         fp->eth_q_stats.mbuf_alloc_sge--;
2933
2934         /* update the TPA mbuf size and remaining fragment size */
2935         m->m_pkthdr.len += frag_len;
2936         frag_size -= frag_len;
2937     }
2938
2939     BLOGD(sc, DBG_LRO,
2940           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2941           fp->index, queue, frag_size);
2942
2943     return (rc);
2944 }
2945
2946 static inline void
2947 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2948 {
2949     int i, j;
2950
2951     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2952         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2953
2954         for (j = 0; j < 2; j++) {
2955             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2956             idx--;
2957         }
2958     }
2959 }
2960
2961 static inline void
2962 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2963 {
2964     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2965     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2966
2967     /*
2968      * Clear the two last indices in the page to 1. These are the indices that
2969      * correspond to the "next" element, hence will never be indicated and
2970      * should be removed from the calculations.
2971      */
2972     bxe_clear_sge_mask_next_elems(fp);
2973 }
2974
2975 static inline void
2976 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2977                         uint16_t            idx)
2978 {
2979     uint16_t last_max = fp->last_max_sge;
2980
2981     if (SUB_S16(idx, last_max) > 0) {
2982         fp->last_max_sge = idx;
2983     }
2984 }
2985
2986 static inline void
2987 bxe_update_sge_prod(struct bxe_softc          *sc,
2988                     struct bxe_fastpath       *fp,
2989                     uint16_t                  sge_len,
2990                     union eth_sgl_or_raw_data *cqe)
2991 {
2992     uint16_t last_max, last_elem, first_elem;
2993     uint16_t delta = 0;
2994     uint16_t i;
2995
2996     if (!sge_len) {
2997         return;
2998     }
2999
3000     /* first mark all used pages */
3001     for (i = 0; i < sge_len; i++) {
3002         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
3003                             RX_SGE(le16toh(cqe->sgl[i])));
3004     }
3005
3006     BLOGD(sc, DBG_LRO,
3007           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
3008           fp->index, sge_len - 1,
3009           le16toh(cqe->sgl[sge_len - 1]));
3010
3011     /* assume that the last SGE index is the biggest */
3012     bxe_update_last_max_sge(fp,
3013                             le16toh(cqe->sgl[sge_len - 1]));
3014
3015     last_max = RX_SGE(fp->last_max_sge);
3016     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
3017     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
3018
3019     /* if ring is not full */
3020     if (last_elem + 1 != first_elem) {
3021         last_elem++;
3022     }
3023
3024     /* now update the prod */
3025     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
3026         if (__predict_true(fp->sge_mask[i])) {
3027             break;
3028         }
3029
3030         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3031         delta += BIT_VEC64_ELEM_SZ;
3032     }
3033
3034     if (delta > 0) {
3035         fp->rx_sge_prod += delta;
3036         /* clear page-end entries */
3037         bxe_clear_sge_mask_next_elems(fp);
3038     }
3039
3040     BLOGD(sc, DBG_LRO,
3041           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3042           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3043 }
3044
3045 /*
3046  * The aggregation on the current TPA queue has completed. Pull the individual
3047  * mbuf fragments together into a single mbuf, perform all necessary checksum
3048  * calculations, and send the resuting mbuf to the stack.
3049  */
3050 static void
3051 bxe_tpa_stop(struct bxe_softc          *sc,
3052              struct bxe_fastpath       *fp,
3053              struct bxe_sw_tpa_info    *tpa_info,
3054              uint16_t                  queue,
3055              uint16_t                  pages,
3056                          struct eth_end_agg_rx_cqe *cqe,
3057              uint16_t                  cqe_idx)
3058 {
3059     struct ifnet *ifp = sc->ifnet;
3060     struct mbuf *m;
3061     int rc = 0;
3062
3063     BLOGD(sc, DBG_LRO,
3064           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3065           fp->index, queue, tpa_info->placement_offset,
3066           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3067
3068     m = tpa_info->bd.m;
3069
3070     /* allocate a replacement before modifying existing mbuf */
3071     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3072     if (rc) {
3073         /* drop the frame and log an error */
3074         fp->eth_q_stats.rx_soft_errors++;
3075         goto bxe_tpa_stop_exit;
3076     }
3077
3078     /* we have a replacement, fixup the current mbuf */
3079     m_adj(m, tpa_info->placement_offset);
3080     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3081
3082     /* mark the checksums valid (taken care of by the firmware) */
3083     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3084     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3085     m->m_pkthdr.csum_data = 0xffff;
3086     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3087                                CSUM_IP_VALID   |
3088                                CSUM_DATA_VALID |
3089                                CSUM_PSEUDO_HDR);
3090
3091     /* aggregate all of the SGEs into a single mbuf */
3092     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3093     if (rc) {
3094         /* drop the packet and log an error */
3095         fp->eth_q_stats.rx_soft_errors++;
3096         m_freem(m);
3097     } else {
3098         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3099             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3100             m->m_flags |= M_VLANTAG;
3101         }
3102
3103         /* assign packet to this interface interface */
3104         m->m_pkthdr.rcvif = ifp;
3105
3106 #if __FreeBSD_version >= 800000
3107         /* specify what RSS queue was used for this flow */
3108         m->m_pkthdr.flowid = fp->index;
3109         BXE_SET_FLOWID(m);
3110 #endif
3111
3112         ifp->if_ipackets++;
3113         fp->eth_q_stats.rx_tpa_pkts++;
3114
3115         /* pass the frame to the stack */
3116         (*ifp->if_input)(ifp, m);
3117     }
3118
3119     /* we passed an mbuf up the stack or dropped the frame */
3120     fp->eth_q_stats.mbuf_alloc_tpa--;
3121
3122 bxe_tpa_stop_exit:
3123
3124     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3125     fp->rx_tpa_queue_used &= ~(1 << queue);
3126 }
3127
3128 static uint8_t
3129 bxe_service_rxsgl(
3130                  struct bxe_fastpath *fp,
3131                  uint16_t len,
3132                  uint16_t lenonbd,
3133                  struct mbuf *m,
3134                  struct eth_fast_path_rx_cqe *cqe_fp)
3135 {
3136     struct mbuf *m_frag;
3137     uint16_t frags, frag_len;
3138     uint16_t sge_idx = 0;
3139     uint16_t j;
3140     uint8_t i, rc = 0;
3141     uint32_t frag_size;
3142
3143     /* adjust the mbuf */
3144     m->m_len = lenonbd;
3145
3146     frag_size =  len - lenonbd;
3147     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3148
3149     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3150         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3151
3152         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3153         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3154         m_frag->m_len = frag_len;
3155
3156        /* allocate a new mbuf for the SGE */
3157         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3158         if (rc) {
3159             /* Leave all remaining SGEs in the ring! */
3160             return (rc);
3161         }
3162         fp->eth_q_stats.mbuf_alloc_sge--;
3163
3164         /* concatenate the fragment to the head mbuf */
3165         m_cat(m, m_frag);
3166
3167         frag_size -= frag_len;
3168     }
3169
3170     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3171
3172     return rc;
3173 }
3174
3175 static uint8_t
3176 bxe_rxeof(struct bxe_softc    *sc,
3177           struct bxe_fastpath *fp)
3178 {
3179     struct ifnet *ifp = sc->ifnet;
3180     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3181     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3182     int rx_pkts = 0;
3183     int rc = 0;
3184
3185     BXE_FP_RX_LOCK(fp);
3186
3187     /* CQ "next element" is of the size of the regular element */
3188     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3189     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3190         hw_cq_cons++;
3191     }
3192
3193     bd_cons = fp->rx_bd_cons;
3194     bd_prod = fp->rx_bd_prod;
3195     bd_prod_fw = bd_prod;
3196     sw_cq_cons = fp->rx_cq_cons;
3197     sw_cq_prod = fp->rx_cq_prod;
3198
3199     /*
3200      * Memory barrier necessary as speculative reads of the rx
3201      * buffer can be ahead of the index in the status block
3202      */
3203     rmb();
3204
3205     BLOGD(sc, DBG_RX,
3206           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3207           fp->index, hw_cq_cons, sw_cq_cons);
3208
3209     while (sw_cq_cons != hw_cq_cons) {
3210         struct bxe_sw_rx_bd *rx_buf = NULL;
3211         union eth_rx_cqe *cqe;
3212         struct eth_fast_path_rx_cqe *cqe_fp;
3213         uint8_t cqe_fp_flags;
3214         enum eth_rx_cqe_type cqe_fp_type;
3215         uint16_t len, lenonbd,  pad;
3216         struct mbuf *m = NULL;
3217
3218         comp_ring_cons = RCQ(sw_cq_cons);
3219         bd_prod = RX_BD(bd_prod);
3220         bd_cons = RX_BD(bd_cons);
3221
3222         cqe          = &fp->rcq_chain[comp_ring_cons];
3223         cqe_fp       = &cqe->fast_path_cqe;
3224         cqe_fp_flags = cqe_fp->type_error_flags;
3225         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3226
3227         BLOGD(sc, DBG_RX,
3228               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3229               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3230               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3231               fp->index,
3232               hw_cq_cons,
3233               sw_cq_cons,
3234               bd_prod,
3235               bd_cons,
3236               CQE_TYPE(cqe_fp_flags),
3237               cqe_fp_flags,
3238               cqe_fp->status_flags,
3239               le32toh(cqe_fp->rss_hash_result),
3240               le16toh(cqe_fp->vlan_tag),
3241               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3242               le16toh(cqe_fp->len_on_bd));
3243
3244         /* is this a slowpath msg? */
3245         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3246             bxe_sp_event(sc, fp, cqe);
3247             goto next_cqe;
3248         }
3249
3250         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3251
3252         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3253             struct bxe_sw_tpa_info *tpa_info;
3254             uint16_t frag_size, pages;
3255             uint8_t queue;
3256
3257             if (CQE_TYPE_START(cqe_fp_type)) {
3258                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3259                               bd_cons, bd_prod, cqe_fp);
3260                 m = NULL; /* packet not ready yet */
3261                 goto next_rx;
3262             }
3263
3264             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3265                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3266
3267             queue = cqe->end_agg_cqe.queue_index;
3268             tpa_info = &fp->rx_tpa_info[queue];
3269
3270             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3271                   fp->index, queue);
3272
3273             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3274                          tpa_info->len_on_bd);
3275             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3276
3277             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3278                          &cqe->end_agg_cqe, comp_ring_cons);
3279
3280             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3281
3282             goto next_cqe;
3283         }
3284
3285         /* non TPA */
3286
3287         /* is this an error packet? */
3288         if (__predict_false(cqe_fp_flags &
3289                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3290             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3291             fp->eth_q_stats.rx_soft_errors++;
3292             goto next_rx;
3293         }
3294
3295         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3296         lenonbd = le16toh(cqe_fp->len_on_bd);
3297         pad = cqe_fp->placement_offset;
3298
3299         m = rx_buf->m;
3300
3301         if (__predict_false(m == NULL)) {
3302             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3303                   bd_cons, fp->index);
3304             goto next_rx;
3305         }
3306
3307         /* XXX double copy if packet length under a threshold */
3308
3309         /*
3310          * If all the buffer descriptors are filled with mbufs then fill in
3311          * the current consumer index with a new BD. Else if a maximum Rx
3312          * buffer limit is imposed then fill in the next producer index.
3313          */
3314         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3315                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3316                                       bd_prod : bd_cons);
3317         if (rc != 0) {
3318
3319             /* we simply reuse the received mbuf and don't post it to the stack */
3320             m = NULL;
3321
3322             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3323                   fp->index, rc);
3324             fp->eth_q_stats.rx_soft_errors++;
3325
3326             if (sc->max_rx_bufs != RX_BD_USABLE) {
3327                 /* copy this consumer index to the producer index */
3328                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3329                        sizeof(struct bxe_sw_rx_bd));
3330                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3331             }
3332
3333             goto next_rx;
3334         }
3335
3336         /* current mbuf was detached from the bd */
3337         fp->eth_q_stats.mbuf_alloc_rx--;
3338
3339         /* we allocated a replacement mbuf, fixup the current one */
3340         m_adj(m, pad);
3341         m->m_pkthdr.len = m->m_len = len;
3342
3343         if ((len > 60) && (len > lenonbd)) {
3344             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3345             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3346             if (rc)
3347                 break;
3348             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3349         } else if (lenonbd < len) {
3350             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3351         }
3352
3353         /* assign packet to this interface interface */
3354         m->m_pkthdr.rcvif = ifp;
3355
3356         /* assume no hardware checksum has complated */
3357         m->m_pkthdr.csum_flags = 0;
3358
3359         /* validate checksum if offload enabled */
3360         if (ifp->if_capenable & IFCAP_RXCSUM) {
3361             /* check for a valid IP frame */
3362             if (!(cqe->fast_path_cqe.status_flags &
3363                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3364                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3365                 if (__predict_false(cqe_fp_flags &
3366                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3367                     fp->eth_q_stats.rx_hw_csum_errors++;
3368                 } else {
3369                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3370                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3371                 }
3372             }
3373
3374             /* check for a valid TCP/UDP frame */
3375             if (!(cqe->fast_path_cqe.status_flags &
3376                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3377                 if (__predict_false(cqe_fp_flags &
3378                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3379                     fp->eth_q_stats.rx_hw_csum_errors++;
3380                 } else {
3381                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3382                     m->m_pkthdr.csum_data = 0xFFFF;
3383                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3384                                                CSUM_PSEUDO_HDR);
3385                 }
3386             }
3387         }
3388
3389         /* if there is a VLAN tag then flag that info */
3390         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3391             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3392             m->m_flags |= M_VLANTAG;
3393         }
3394
3395 #if __FreeBSD_version >= 800000
3396         /* specify what RSS queue was used for this flow */
3397         m->m_pkthdr.flowid = fp->index;
3398         BXE_SET_FLOWID(m);
3399 #endif
3400
3401 next_rx:
3402
3403         bd_cons    = RX_BD_NEXT(bd_cons);
3404         bd_prod    = RX_BD_NEXT(bd_prod);
3405         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3406
3407         /* pass the frame to the stack */
3408         if (__predict_true(m != NULL)) {
3409             ifp->if_ipackets++;
3410             rx_pkts++;
3411             (*ifp->if_input)(ifp, m);
3412         }
3413
3414 next_cqe:
3415
3416         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3417         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3418
3419         /* limit spinning on the queue */
3420         if (rc != 0)
3421             break;
3422
3423         if (rx_pkts == sc->rx_budget) {
3424             fp->eth_q_stats.rx_budget_reached++;
3425             break;
3426         }
3427     } /* while work to do */
3428
3429     fp->rx_bd_cons = bd_cons;
3430     fp->rx_bd_prod = bd_prod_fw;
3431     fp->rx_cq_cons = sw_cq_cons;
3432     fp->rx_cq_prod = sw_cq_prod;
3433
3434     /* Update producers */
3435     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3436
3437     fp->eth_q_stats.rx_pkts += rx_pkts;
3438     fp->eth_q_stats.rx_calls++;
3439
3440     BXE_FP_RX_UNLOCK(fp);
3441
3442     return (sw_cq_cons != hw_cq_cons);
3443 }
3444
3445 static uint16_t
3446 bxe_free_tx_pkt(struct bxe_softc    *sc,
3447                 struct bxe_fastpath *fp,
3448                 uint16_t            idx)
3449 {
3450     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3451     struct eth_tx_start_bd *tx_start_bd;
3452     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3453     uint16_t new_cons;
3454     int nbd;
3455
3456     /* unmap the mbuf from non-paged memory */
3457     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3458
3459     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3460     nbd = le16toh(tx_start_bd->nbd) - 1;
3461
3462     new_cons = (tx_buf->first_bd + nbd);
3463
3464     /* free the mbuf */
3465     if (__predict_true(tx_buf->m != NULL)) {
3466         m_freem(tx_buf->m);
3467         fp->eth_q_stats.mbuf_alloc_tx--;
3468     } else {
3469         fp->eth_q_stats.tx_chain_lost_mbuf++;
3470     }
3471
3472     tx_buf->m = NULL;
3473     tx_buf->first_bd = 0;
3474
3475     return (new_cons);
3476 }
3477
3478 /* transmit timeout watchdog */
3479 static int
3480 bxe_watchdog(struct bxe_softc    *sc,
3481              struct bxe_fastpath *fp)
3482 {
3483     BXE_FP_TX_LOCK(fp);
3484
3485     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3486         BXE_FP_TX_UNLOCK(fp);
3487         return (0);
3488     }
3489
3490     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3491     if(sc->trigger_grcdump) {
3492          /* taking grcdump */
3493          bxe_grc_dump(sc);
3494     }
3495
3496     BXE_FP_TX_UNLOCK(fp);
3497
3498     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3499     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3500
3501     return (-1);
3502 }
3503
3504 /* processes transmit completions */
3505 static uint8_t
3506 bxe_txeof(struct bxe_softc    *sc,
3507           struct bxe_fastpath *fp)
3508 {
3509     struct ifnet *ifp = sc->ifnet;
3510     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3511     uint16_t tx_bd_avail;
3512
3513     BXE_FP_TX_LOCK_ASSERT(fp);
3514
3515     bd_cons = fp->tx_bd_cons;
3516     hw_cons = le16toh(*fp->tx_cons_sb);
3517     sw_cons = fp->tx_pkt_cons;
3518
3519     while (sw_cons != hw_cons) {
3520         pkt_cons = TX_BD(sw_cons);
3521
3522         BLOGD(sc, DBG_TX,
3523               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3524               fp->index, hw_cons, sw_cons, pkt_cons);
3525
3526         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3527
3528         sw_cons++;
3529     }
3530
3531     fp->tx_pkt_cons = sw_cons;
3532     fp->tx_bd_cons  = bd_cons;
3533
3534     BLOGD(sc, DBG_TX,
3535           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3536           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3537
3538     mb();
3539
3540     tx_bd_avail = bxe_tx_avail(sc, fp);
3541
3542     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3543         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3544     } else {
3545         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3546     }
3547
3548     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3549         /* reset the watchdog timer if there are pending transmits */
3550         fp->watchdog_timer = BXE_TX_TIMEOUT;
3551         return (TRUE);
3552     } else {
3553         /* clear watchdog when there are no pending transmits */
3554         fp->watchdog_timer = 0;
3555         return (FALSE);
3556     }
3557 }
3558
3559 static void
3560 bxe_drain_tx_queues(struct bxe_softc *sc)
3561 {
3562     struct bxe_fastpath *fp;
3563     int i, count;
3564
3565     /* wait until all TX fastpath tasks have completed */
3566     for (i = 0; i < sc->num_queues; i++) {
3567         fp = &sc->fp[i];
3568
3569         count = 1000;
3570
3571         while (bxe_has_tx_work(fp)) {
3572
3573             BXE_FP_TX_LOCK(fp);
3574             bxe_txeof(sc, fp);
3575             BXE_FP_TX_UNLOCK(fp);
3576
3577             if (count == 0) {
3578                 BLOGE(sc, "Timeout waiting for fp[%d] "
3579                           "transmits to complete!\n", i);
3580                 bxe_panic(sc, ("tx drain failure\n"));
3581                 return;
3582             }
3583
3584             count--;
3585             DELAY(1000);
3586             rmb();
3587         }
3588     }
3589
3590     return;
3591 }
3592
3593 static int
3594 bxe_del_all_macs(struct bxe_softc          *sc,
3595                  struct ecore_vlan_mac_obj *mac_obj,
3596                  int                       mac_type,
3597                  uint8_t                   wait_for_comp)
3598 {
3599     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3600     int rc;
3601
3602     /* wait for completion of requested */
3603     if (wait_for_comp) {
3604         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3605     }
3606
3607     /* Set the mac type of addresses we want to clear */
3608     bxe_set_bit(mac_type, &vlan_mac_flags);
3609
3610     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3611     if (rc < 0) {
3612         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3613             rc, mac_type, wait_for_comp);
3614     }
3615
3616     return (rc);
3617 }
3618
3619 static int
3620 bxe_fill_accept_flags(struct bxe_softc *sc,
3621                       uint32_t         rx_mode,
3622                       unsigned long    *rx_accept_flags,
3623                       unsigned long    *tx_accept_flags)
3624 {
3625     /* Clear the flags first */
3626     *rx_accept_flags = 0;
3627     *tx_accept_flags = 0;
3628
3629     switch (rx_mode) {
3630     case BXE_RX_MODE_NONE:
3631         /*
3632          * 'drop all' supersedes any accept flags that may have been
3633          * passed to the function.
3634          */
3635         break;
3636
3637     case BXE_RX_MODE_NORMAL:
3638         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3639         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3640         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3641
3642         /* internal switching mode */
3643         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3644         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3645         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3646
3647         break;
3648
3649     case BXE_RX_MODE_ALLMULTI:
3650         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3651         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3652         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3653
3654         /* internal switching mode */
3655         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3656         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3657         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3658
3659         break;
3660
3661     case BXE_RX_MODE_PROMISC:
3662         /*
3663          * According to deffinition of SI mode, iface in promisc mode
3664          * should receive matched and unmatched (in resolution of port)
3665          * unicast packets.
3666          */
3667         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3668         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3669         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3670         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3671
3672         /* internal switching mode */
3673         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3674         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3675
3676         if (IS_MF_SI(sc)) {
3677             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3678         } else {
3679             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3680         }
3681
3682         break;
3683
3684     default:
3685         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3686         return (-1);
3687     }
3688
3689     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3690     if (rx_mode != BXE_RX_MODE_NONE) {
3691         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3692         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3693     }
3694
3695     return (0);
3696 }
3697
3698 static int
3699 bxe_set_q_rx_mode(struct bxe_softc *sc,
3700                   uint8_t          cl_id,
3701                   unsigned long    rx_mode_flags,
3702                   unsigned long    rx_accept_flags,
3703                   unsigned long    tx_accept_flags,
3704                   unsigned long    ramrod_flags)
3705 {
3706     struct ecore_rx_mode_ramrod_params ramrod_param;
3707     int rc;
3708
3709     memset(&ramrod_param, 0, sizeof(ramrod_param));
3710
3711     /* Prepare ramrod parameters */
3712     ramrod_param.cid = 0;
3713     ramrod_param.cl_id = cl_id;
3714     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3715     ramrod_param.func_id = SC_FUNC(sc);
3716
3717     ramrod_param.pstate = &sc->sp_state;
3718     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3719
3720     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3721     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3722
3723     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3724
3725     ramrod_param.ramrod_flags = ramrod_flags;
3726     ramrod_param.rx_mode_flags = rx_mode_flags;
3727
3728     ramrod_param.rx_accept_flags = rx_accept_flags;
3729     ramrod_param.tx_accept_flags = tx_accept_flags;
3730
3731     rc = ecore_config_rx_mode(sc, &ramrod_param);
3732     if (rc < 0) {
3733         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3734             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3735             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3736             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3737             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3738         return (rc);
3739     }
3740
3741     return (0);
3742 }
3743
3744 static int
3745 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3746 {
3747     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3748     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3749     int rc;
3750
3751     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3752                                &tx_accept_flags);
3753     if (rc) {
3754         return (rc);
3755     }
3756
3757     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3758     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3759
3760     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3761     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3762                               rx_accept_flags, tx_accept_flags,
3763                               ramrod_flags));
3764 }
3765
3766 /* returns the "mcp load_code" according to global load_count array */
3767 static int
3768 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3769 {
3770     int path = SC_PATH(sc);
3771     int port = SC_PORT(sc);
3772
3773     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3774           path, load_count[path][0], load_count[path][1],
3775           load_count[path][2]);
3776     load_count[path][0]++;
3777     load_count[path][1 + port]++;
3778     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3779           path, load_count[path][0], load_count[path][1],
3780           load_count[path][2]);
3781     if (load_count[path][0] == 1) {
3782         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3783     } else if (load_count[path][1 + port] == 1) {
3784         return (FW_MSG_CODE_DRV_LOAD_PORT);
3785     } else {
3786         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3787     }
3788 }
3789
3790 /* returns the "mcp load_code" according to global load_count array */
3791 static int
3792 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3793 {
3794     int port = SC_PORT(sc);
3795     int path = SC_PATH(sc);
3796
3797     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3798           path, load_count[path][0], load_count[path][1],
3799           load_count[path][2]);
3800     load_count[path][0]--;
3801     load_count[path][1 + port]--;
3802     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3803           path, load_count[path][0], load_count[path][1],
3804           load_count[path][2]);
3805     if (load_count[path][0] == 0) {
3806         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3807     } else if (load_count[path][1 + port] == 0) {
3808         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3809     } else {
3810         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3811     }
3812 }
3813
3814 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3815 static uint32_t
3816 bxe_send_unload_req(struct bxe_softc *sc,
3817                     int              unload_mode)
3818 {
3819     uint32_t reset_code = 0;
3820
3821     /* Select the UNLOAD request mode */
3822     if (unload_mode == UNLOAD_NORMAL) {
3823         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3824     } else {
3825         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3826     }
3827
3828     /* Send the request to the MCP */
3829     if (!BXE_NOMCP(sc)) {
3830         reset_code = bxe_fw_command(sc, reset_code, 0);
3831     } else {
3832         reset_code = bxe_nic_unload_no_mcp(sc);
3833     }
3834
3835     return (reset_code);
3836 }
3837
3838 /* send UNLOAD_DONE command to the MCP */
3839 static void
3840 bxe_send_unload_done(struct bxe_softc *sc,
3841                      uint8_t          keep_link)
3842 {
3843     uint32_t reset_param =
3844         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3845
3846     /* Report UNLOAD_DONE to MCP */
3847     if (!BXE_NOMCP(sc)) {
3848         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3849     }
3850 }
3851
3852 static int
3853 bxe_func_wait_started(struct bxe_softc *sc)
3854 {
3855     int tout = 50;
3856
3857     if (!sc->port.pmf) {
3858         return (0);
3859     }
3860
3861     /*
3862      * (assumption: No Attention from MCP at this stage)
3863      * PMF probably in the middle of TX disable/enable transaction
3864      * 1. Sync IRS for default SB
3865      * 2. Sync SP queue - this guarantees us that attention handling started
3866      * 3. Wait, that TX disable/enable transaction completes
3867      *
3868      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3869      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3870      * received completion for the transaction the state is TX_STOPPED.
3871      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3872      * transaction.
3873      */
3874
3875     /* XXX make sure default SB ISR is done */
3876     /* need a way to synchronize an irq (intr_mtx?) */
3877
3878     /* XXX flush any work queues */
3879
3880     while (ecore_func_get_state(sc, &sc->func_obj) !=
3881            ECORE_F_STATE_STARTED && tout--) {
3882         DELAY(20000);
3883     }
3884
3885     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3886         /*
3887          * Failed to complete the transaction in a "good way"
3888          * Force both transactions with CLR bit.
3889          */
3890         struct ecore_func_state_params func_params = { NULL };
3891
3892         BLOGE(sc, "Unexpected function state! "
3893                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3894
3895         func_params.f_obj = &sc->func_obj;
3896         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3897
3898         /* STARTED-->TX_STOPPED */
3899         func_params.cmd = ECORE_F_CMD_TX_STOP;
3900         ecore_func_state_change(sc, &func_params);
3901
3902         /* TX_STOPPED-->STARTED */
3903         func_params.cmd = ECORE_F_CMD_TX_START;
3904         return (ecore_func_state_change(sc, &func_params));
3905     }
3906
3907     return (0);
3908 }
3909
3910 static int
3911 bxe_stop_queue(struct bxe_softc *sc,
3912                int              index)
3913 {
3914     struct bxe_fastpath *fp = &sc->fp[index];
3915     struct ecore_queue_state_params q_params = { NULL };
3916     int rc;
3917
3918     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3919
3920     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3921     /* We want to wait for completion in this context */
3922     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3923
3924     /* Stop the primary connection: */
3925
3926     /* ...halt the connection */
3927     q_params.cmd = ECORE_Q_CMD_HALT;
3928     rc = ecore_queue_state_change(sc, &q_params);
3929     if (rc) {
3930         return (rc);
3931     }
3932
3933     /* ...terminate the connection */
3934     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3935     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3936     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3937     rc = ecore_queue_state_change(sc, &q_params);
3938     if (rc) {
3939         return (rc);
3940     }
3941
3942     /* ...delete cfc entry */
3943     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3944     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3945     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3946     return (ecore_queue_state_change(sc, &q_params));
3947 }
3948
3949 /* wait for the outstanding SP commands */
3950 static inline uint8_t
3951 bxe_wait_sp_comp(struct bxe_softc *sc,
3952                  unsigned long    mask)
3953 {
3954     unsigned long tmp;
3955     int tout = 5000; /* wait for 5 secs tops */
3956
3957     while (tout--) {
3958         mb();
3959         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3960             return (TRUE);
3961         }
3962
3963         DELAY(1000);
3964     }
3965
3966     mb();
3967
3968     tmp = atomic_load_acq_long(&sc->sp_state);
3969     if (tmp & mask) {
3970         BLOGE(sc, "Filtering completion timed out: "
3971                   "sp_state 0x%lx, mask 0x%lx\n",
3972               tmp, mask);
3973         return (FALSE);
3974     }
3975
3976     return (FALSE);
3977 }
3978
3979 static int
3980 bxe_func_stop(struct bxe_softc *sc)
3981 {
3982     struct ecore_func_state_params func_params = { NULL };
3983     int rc;
3984
3985     /* prepare parameters for function state transitions */
3986     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3987     func_params.f_obj = &sc->func_obj;
3988     func_params.cmd = ECORE_F_CMD_STOP;
3989
3990     /*
3991      * Try to stop the function the 'good way'. If it fails (in case
3992      * of a parity error during bxe_chip_cleanup()) and we are
3993      * not in a debug mode, perform a state transaction in order to
3994      * enable further HW_RESET transaction.
3995      */
3996     rc = ecore_func_state_change(sc, &func_params);
3997     if (rc) {
3998         BLOGE(sc, "FUNC_STOP ramrod failed. "
3999                   "Running a dry transaction (%d)\n", rc);
4000         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
4001         return (ecore_func_state_change(sc, &func_params));
4002     }
4003
4004     return (0);
4005 }
4006
4007 static int
4008 bxe_reset_hw(struct bxe_softc *sc,
4009              uint32_t         load_code)
4010 {
4011     struct ecore_func_state_params func_params = { NULL };
4012
4013     /* Prepare parameters for function state transitions */
4014     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4015
4016     func_params.f_obj = &sc->func_obj;
4017     func_params.cmd = ECORE_F_CMD_HW_RESET;
4018
4019     func_params.params.hw_init.load_phase = load_code;
4020
4021     return (ecore_func_state_change(sc, &func_params));
4022 }
4023
4024 static void
4025 bxe_int_disable_sync(struct bxe_softc *sc,
4026                      int              disable_hw)
4027 {
4028     if (disable_hw) {
4029         /* prevent the HW from sending interrupts */
4030         bxe_int_disable(sc);
4031     }
4032
4033     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4034     /* make sure all ISRs are done */
4035
4036     /* XXX make sure sp_task is not running */
4037     /* cancel and flush work queues */
4038 }
4039
4040 static void
4041 bxe_chip_cleanup(struct bxe_softc *sc,
4042                  uint32_t         unload_mode,
4043                  uint8_t          keep_link)
4044 {
4045     int port = SC_PORT(sc);
4046     struct ecore_mcast_ramrod_params rparam = { NULL };
4047     uint32_t reset_code;
4048     int i, rc = 0;
4049
4050     bxe_drain_tx_queues(sc);
4051
4052     /* give HW time to discard old tx messages */
4053     DELAY(1000);
4054
4055     /* Clean all ETH MACs */
4056     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4057     if (rc < 0) {
4058         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4059     }
4060
4061     /* Clean up UC list  */
4062     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4063     if (rc < 0) {
4064         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4065     }
4066
4067     /* Disable LLH */
4068     if (!CHIP_IS_E1(sc)) {
4069         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4070     }
4071
4072     /* Set "drop all" to stop Rx */
4073
4074     /*
4075      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4076      * a race between the completion code and this code.
4077      */
4078     BXE_MCAST_LOCK(sc);
4079
4080     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4081         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4082     } else {
4083         bxe_set_storm_rx_mode(sc);
4084     }
4085
4086     /* Clean up multicast configuration */
4087     rparam.mcast_obj = &sc->mcast_obj;
4088     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4089     if (rc < 0) {
4090         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4091     }
4092
4093     BXE_MCAST_UNLOCK(sc);
4094
4095     // XXX bxe_iov_chip_cleanup(sc);
4096
4097     /*
4098      * Send the UNLOAD_REQUEST to the MCP. This will return if
4099      * this function should perform FUNCTION, PORT, or COMMON HW
4100      * reset.
4101      */
4102     reset_code = bxe_send_unload_req(sc, unload_mode);
4103
4104     /*
4105      * (assumption: No Attention from MCP at this stage)
4106      * PMF probably in the middle of TX disable/enable transaction
4107      */
4108     rc = bxe_func_wait_started(sc);
4109     if (rc) {
4110         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4111     }
4112
4113     /*
4114      * Close multi and leading connections
4115      * Completions for ramrods are collected in a synchronous way
4116      */
4117     for (i = 0; i < sc->num_queues; i++) {
4118         if (bxe_stop_queue(sc, i)) {
4119             goto unload_error;
4120         }
4121     }
4122
4123     /*
4124      * If SP settings didn't get completed so far - something
4125      * very wrong has happen.
4126      */
4127     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4128         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4129     }
4130
4131 unload_error:
4132
4133     rc = bxe_func_stop(sc);
4134     if (rc) {
4135         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4136     }
4137
4138     /* disable HW interrupts */
4139     bxe_int_disable_sync(sc, TRUE);
4140
4141     /* detach interrupts */
4142     bxe_interrupt_detach(sc);
4143
4144     /* Reset the chip */
4145     rc = bxe_reset_hw(sc, reset_code);
4146     if (rc) {
4147         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4148     }
4149
4150     /* Report UNLOAD_DONE to MCP */
4151     bxe_send_unload_done(sc, keep_link);
4152 }
4153
4154 static void
4155 bxe_disable_close_the_gate(struct bxe_softc *sc)
4156 {
4157     uint32_t val;
4158     int port = SC_PORT(sc);
4159
4160     BLOGD(sc, DBG_LOAD,
4161           "Disabling 'close the gates'\n");
4162
4163     if (CHIP_IS_E1(sc)) {
4164         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4165                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4166         val = REG_RD(sc, addr);
4167         val &= ~(0x300);
4168         REG_WR(sc, addr, val);
4169     } else {
4170         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4171         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4172                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4173         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4174     }
4175 }
4176
4177 /*
4178  * Cleans the object that have internal lists without sending
4179  * ramrods. Should be run when interrutps are disabled.
4180  */
4181 static void
4182 bxe_squeeze_objects(struct bxe_softc *sc)
4183 {
4184     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4185     struct ecore_mcast_ramrod_params rparam = { NULL };
4186     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4187     int rc;
4188
4189     /* Cleanup MACs' object first... */
4190
4191     /* Wait for completion of requested */
4192     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4193     /* Perform a dry cleanup */
4194     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4195
4196     /* Clean ETH primary MAC */
4197     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4198     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4199                              &ramrod_flags);
4200     if (rc != 0) {
4201         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4202     }
4203
4204     /* Cleanup UC list */
4205     vlan_mac_flags = 0;
4206     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4207     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4208                              &ramrod_flags);
4209     if (rc != 0) {
4210         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4211     }
4212
4213     /* Now clean mcast object... */
4214
4215     rparam.mcast_obj = &sc->mcast_obj;
4216     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4217
4218     /* Add a DEL command... */
4219     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4220     if (rc < 0) {
4221         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4222     }
4223
4224     /* now wait until all pending commands are cleared */
4225
4226     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4227     while (rc != 0) {
4228         if (rc < 0) {
4229             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4230             return;
4231         }
4232
4233         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4234     }
4235 }
4236
4237 /* stop the controller */
4238 static __noinline int
4239 bxe_nic_unload(struct bxe_softc *sc,
4240                uint32_t         unload_mode,
4241                uint8_t          keep_link)
4242 {
4243     uint8_t global = FALSE;
4244     uint32_t val;
4245     int i;
4246
4247     BXE_CORE_LOCK_ASSERT(sc);
4248
4249     sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
4250
4251     for (i = 0; i < sc->num_queues; i++) {
4252         struct bxe_fastpath *fp;
4253
4254         fp = &sc->fp[i];
4255         BXE_FP_TX_LOCK(fp);
4256         BXE_FP_TX_UNLOCK(fp);
4257     }
4258
4259     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4260
4261     /* mark driver as unloaded in shmem2 */
4262     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4263         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4264         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4265                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4266     }
4267
4268     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4269         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4270         /*
4271          * We can get here if the driver has been unloaded
4272          * during parity error recovery and is either waiting for a
4273          * leader to complete or for other functions to unload and
4274          * then ifconfig down has been issued. In this case we want to
4275          * unload and let other functions to complete a recovery
4276          * process.
4277          */
4278         sc->recovery_state = BXE_RECOVERY_DONE;
4279         sc->is_leader = 0;
4280         bxe_release_leader_lock(sc);
4281         mb();
4282
4283         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4284         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4285             " state = 0x%x\n", sc->recovery_state, sc->state);
4286         return (-1);
4287     }
4288
4289     /*
4290      * Nothing to do during unload if previous bxe_nic_load()
4291      * did not completed succesfully - all resourses are released.
4292      */
4293     if ((sc->state == BXE_STATE_CLOSED) ||
4294         (sc->state == BXE_STATE_ERROR)) {
4295         return (0);
4296     }
4297
4298     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4299     mb();
4300
4301     /* stop tx */
4302     bxe_tx_disable(sc);
4303
4304     sc->rx_mode = BXE_RX_MODE_NONE;
4305     /* XXX set rx mode ??? */
4306
4307     if (IS_PF(sc) && !sc->grcdump_done) {
4308         /* set ALWAYS_ALIVE bit in shmem */
4309         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4310
4311         bxe_drv_pulse(sc);
4312
4313         bxe_stats_handle(sc, STATS_EVENT_STOP);
4314         bxe_save_statistics(sc);
4315     }
4316
4317     /* wait till consumers catch up with producers in all queues */
4318     bxe_drain_tx_queues(sc);
4319
4320     /* if VF indicate to PF this function is going down (PF will delete sp
4321      * elements and clear initializations
4322      */
4323     if (IS_VF(sc)) {
4324         ; /* bxe_vfpf_close_vf(sc); */
4325     } else if (unload_mode != UNLOAD_RECOVERY) {
4326         /* if this is a normal/close unload need to clean up chip */
4327         if (!sc->grcdump_done)
4328             bxe_chip_cleanup(sc, unload_mode, keep_link);
4329     } else {
4330         /* Send the UNLOAD_REQUEST to the MCP */
4331         bxe_send_unload_req(sc, unload_mode);
4332
4333         /*
4334          * Prevent transactions to host from the functions on the
4335          * engine that doesn't reset global blocks in case of global
4336          * attention once gloabl blocks are reset and gates are opened
4337          * (the engine which leader will perform the recovery
4338          * last).
4339          */
4340         if (!CHIP_IS_E1x(sc)) {
4341             bxe_pf_disable(sc);
4342         }
4343
4344         /* disable HW interrupts */
4345         bxe_int_disable_sync(sc, TRUE);
4346
4347         /* detach interrupts */
4348         bxe_interrupt_detach(sc);
4349
4350         /* Report UNLOAD_DONE to MCP */
4351         bxe_send_unload_done(sc, FALSE);
4352     }
4353
4354     /*
4355      * At this stage no more interrupts will arrive so we may safely clean
4356      * the queue'able objects here in case they failed to get cleaned so far.
4357      */
4358     if (IS_PF(sc)) {
4359         bxe_squeeze_objects(sc);
4360     }
4361
4362     /* There should be no more pending SP commands at this stage */
4363     sc->sp_state = 0;
4364
4365     sc->port.pmf = 0;
4366
4367     bxe_free_fp_buffers(sc);
4368
4369     if (IS_PF(sc)) {
4370         bxe_free_mem(sc);
4371     }
4372
4373     bxe_free_fw_stats_mem(sc);
4374
4375     sc->state = BXE_STATE_CLOSED;
4376
4377     /*
4378      * Check if there are pending parity attentions. If there are - set
4379      * RECOVERY_IN_PROGRESS.
4380      */
4381     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4382         bxe_set_reset_in_progress(sc);
4383
4384         /* Set RESET_IS_GLOBAL if needed */
4385         if (global) {
4386             bxe_set_reset_global(sc);
4387         }
4388     }
4389
4390     /*
4391      * The last driver must disable a "close the gate" if there is no
4392      * parity attention or "process kill" pending.
4393      */
4394     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4395         bxe_reset_is_done(sc, SC_PATH(sc))) {
4396         bxe_disable_close_the_gate(sc);
4397     }
4398
4399     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4400
4401     bxe_link_report(sc);
4402
4403     return (0);
4404 }
4405
4406 /*
4407  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4408  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4409  */
4410 static int
4411 bxe_ifmedia_update(struct ifnet *ifp)
4412 {
4413     struct bxe_softc *sc = (struct bxe_softc *)ifp->if_softc;
4414     struct ifmedia *ifm;
4415
4416     ifm = &sc->ifmedia;
4417
4418     /* We only support Ethernet media type. */
4419     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4420         return (EINVAL);
4421     }
4422
4423     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4424     case IFM_AUTO:
4425          break;
4426     case IFM_10G_CX4:
4427     case IFM_10G_SR:
4428     case IFM_10G_T:
4429     case IFM_10G_TWINAX:
4430     default:
4431         /* We don't support changing the media type. */
4432         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4433               IFM_SUBTYPE(ifm->ifm_media));
4434         return (EINVAL);
4435     }
4436
4437     return (0);
4438 }
4439
4440 /*
4441  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4442  */
4443 static void
4444 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4445 {
4446     struct bxe_softc *sc = ifp->if_softc;
4447
4448     /* Bug 165447: the 'ifconfig' tool skips printing of the "status: ..."
4449        line if the IFM_AVALID flag is *NOT* set. So we need to set this
4450        flag unconditionally (irrespective of the admininistrative
4451        'up/down' state of the interface) to ensure that that line is always
4452        displayed.
4453     */
4454     ifmr->ifm_status = IFM_AVALID;
4455
4456     /* Setup the default interface info. */
4457     ifmr->ifm_active = IFM_ETHER;
4458
4459     /* Report link down if the driver isn't running. */
4460     if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4461         ifmr->ifm_active |= IFM_NONE;
4462         BLOGD(sc, DBG_PHY, "in %s : nic still not loaded fully\n", __func__);
4463         BLOGD(sc, DBG_PHY, "in %s : link_up (1) : %d\n",
4464                 __func__, sc->link_vars.link_up);
4465         return;
4466     }
4467
4468
4469     if (sc->link_vars.link_up) {
4470         ifmr->ifm_status |= IFM_ACTIVE;
4471         ifmr->ifm_active |= IFM_FDX;
4472     } else {
4473         ifmr->ifm_active |= IFM_NONE;
4474         BLOGD(sc, DBG_PHY, "in %s : setting IFM_NONE\n",
4475                 __func__);
4476         return;
4477     }
4478
4479     ifmr->ifm_active |= sc->media;
4480     return;
4481 }
4482
4483 static void
4484 bxe_handle_chip_tq(void *context,
4485                    int  pending)
4486 {
4487     struct bxe_softc *sc = (struct bxe_softc *)context;
4488     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4489
4490     switch (work)
4491     {
4492     case CHIP_TQ_REINIT:
4493         if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
4494             /* restart the interface */
4495             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4496             bxe_periodic_stop(sc);
4497             BXE_CORE_LOCK(sc);
4498             bxe_stop_locked(sc);
4499             bxe_init_locked(sc);
4500             BXE_CORE_UNLOCK(sc);
4501         }
4502         break;
4503
4504     default:
4505         break;
4506     }
4507 }
4508
4509 /*
4510  * Handles any IOCTL calls from the operating system.
4511  *
4512  * Returns:
4513  *   0 = Success, >0 Failure
4514  */
4515 static int
4516 bxe_ioctl(struct ifnet *ifp,
4517           u_long       command,
4518           caddr_t      data)
4519 {
4520     struct bxe_softc *sc = ifp->if_softc;
4521     struct ifreq *ifr = (struct ifreq *)data;
4522     int mask = 0;
4523     int reinit = 0;
4524     int error = 0;
4525
4526     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4527     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4528
4529     switch (command)
4530     {
4531     case SIOCSIFMTU:
4532         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4533               ifr->ifr_mtu);
4534
4535         if (sc->mtu == ifr->ifr_mtu) {
4536             /* nothing to change */
4537             break;
4538         }
4539
4540         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4541             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4542                   ifr->ifr_mtu, mtu_min, mtu_max);
4543             error = EINVAL;
4544             break;
4545         }
4546
4547         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4548                              (unsigned long)ifr->ifr_mtu);
4549         atomic_store_rel_long((volatile unsigned long *)&ifp->if_mtu,
4550                               (unsigned long)ifr->ifr_mtu);
4551
4552         reinit = 1;
4553         break;
4554
4555     case SIOCSIFFLAGS:
4556         /* toggle the interface state up or down */
4557         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4558
4559         BXE_CORE_LOCK(sc);
4560         /* check if the interface is up */
4561         if (ifp->if_flags & IFF_UP) {
4562             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4563                 /* set the receive mode flags */
4564                 bxe_set_rx_mode(sc);
4565             } else if(sc->state != BXE_STATE_DISABLED) {
4566                 bxe_init_locked(sc);
4567             }
4568         } else {
4569             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4570                 bxe_periodic_stop(sc);
4571                 bxe_stop_locked(sc);
4572             }
4573         }
4574         BXE_CORE_UNLOCK(sc);
4575
4576         break;
4577
4578     case SIOCADDMULTI:
4579     case SIOCDELMULTI:
4580         /* add/delete multicast addresses */
4581         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4582
4583         /* check if the interface is up */
4584         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4585             /* set the receive mode flags */
4586             BXE_CORE_LOCK(sc);
4587             bxe_set_rx_mode(sc);
4588             BXE_CORE_UNLOCK(sc); 
4589         }
4590
4591         break;
4592
4593     case SIOCSIFCAP:
4594         /* find out which capabilities have changed */
4595         mask = (ifr->ifr_reqcap ^ ifp->if_capenable);
4596
4597         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4598               mask);
4599
4600         /* toggle the LRO capabilites enable flag */
4601         if (mask & IFCAP_LRO) {
4602             ifp->if_capenable ^= IFCAP_LRO;
4603             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4604                   (ifp->if_capenable & IFCAP_LRO) ? "ON" : "OFF");
4605             reinit = 1;
4606         }
4607
4608         /* toggle the TXCSUM checksum capabilites enable flag */
4609         if (mask & IFCAP_TXCSUM) {
4610             ifp->if_capenable ^= IFCAP_TXCSUM;
4611             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4612                   (ifp->if_capenable & IFCAP_TXCSUM) ? "ON" : "OFF");
4613             if (ifp->if_capenable & IFCAP_TXCSUM) {
4614                 ifp->if_hwassist = (CSUM_IP       |
4615                                     CSUM_TCP      |
4616                                     CSUM_UDP      |
4617                                     CSUM_TSO      |
4618                                     CSUM_TCP_IPV6 |
4619                                     CSUM_UDP_IPV6);
4620             } else {
4621                 ifp->if_hwassist = 0;
4622             }
4623         }
4624
4625         /* toggle the RXCSUM checksum capabilities enable flag */
4626         if (mask & IFCAP_RXCSUM) {
4627             ifp->if_capenable ^= IFCAP_RXCSUM;
4628             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4629                   (ifp->if_capenable & IFCAP_RXCSUM) ? "ON" : "OFF");
4630             if (ifp->if_capenable & IFCAP_RXCSUM) {
4631                 ifp->if_hwassist = (CSUM_IP       |
4632                                     CSUM_TCP      |
4633                                     CSUM_UDP      |
4634                                     CSUM_TSO      |
4635                                     CSUM_TCP_IPV6 |
4636                                     CSUM_UDP_IPV6);
4637             } else {
4638                 ifp->if_hwassist = 0;
4639             }
4640         }
4641
4642         /* toggle TSO4 capabilities enabled flag */
4643         if (mask & IFCAP_TSO4) {
4644             ifp->if_capenable ^= IFCAP_TSO4;
4645             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4646                   (ifp->if_capenable & IFCAP_TSO4) ? "ON" : "OFF");
4647         }
4648
4649         /* toggle TSO6 capabilities enabled flag */
4650         if (mask & IFCAP_TSO6) {
4651             ifp->if_capenable ^= IFCAP_TSO6;
4652             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4653                   (ifp->if_capenable & IFCAP_TSO6) ? "ON" : "OFF");
4654         }
4655
4656         /* toggle VLAN_HWTSO capabilities enabled flag */
4657         if (mask & IFCAP_VLAN_HWTSO) {
4658             ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
4659             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4660                   (ifp->if_capenable & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4661         }
4662
4663         /* toggle VLAN_HWCSUM capabilities enabled flag */
4664         if (mask & IFCAP_VLAN_HWCSUM) {
4665             /* XXX investigate this... */
4666             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4667             error = EINVAL;
4668         }
4669
4670         /* toggle VLAN_MTU capabilities enable flag */
4671         if (mask & IFCAP_VLAN_MTU) {
4672             /* XXX investigate this... */
4673             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4674             error = EINVAL;
4675         }
4676
4677         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4678         if (mask & IFCAP_VLAN_HWTAGGING) {
4679             /* XXX investigate this... */
4680             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4681             error = EINVAL;
4682         }
4683
4684         /* toggle VLAN_HWFILTER capabilities enabled flag */
4685         if (mask & IFCAP_VLAN_HWFILTER) {
4686             /* XXX investigate this... */
4687             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4688             error = EINVAL;
4689         }
4690
4691         /* XXX not yet...
4692          * IFCAP_WOL_MAGIC
4693          */
4694
4695         break;
4696
4697     case SIOCSIFMEDIA:
4698     case SIOCGIFMEDIA:
4699         /* set/get interface media */
4700         BLOGD(sc, DBG_IOCTL,
4701               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4702               (command & 0xff));
4703         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4704         break;
4705
4706     default:
4707         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4708               (command & 0xff));
4709         error = ether_ioctl(ifp, command, data);
4710         break;
4711     }
4712
4713     if (reinit && (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
4714         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4715               "Re-initializing hardware from IOCTL change\n");
4716         bxe_periodic_stop(sc);
4717         BXE_CORE_LOCK(sc);
4718         bxe_stop_locked(sc);
4719         bxe_init_locked(sc);
4720         BXE_CORE_UNLOCK(sc);
4721     }
4722
4723     return (error);
4724 }
4725
4726 static __noinline void
4727 bxe_dump_mbuf(struct bxe_softc *sc,
4728               struct mbuf      *m,
4729               uint8_t          contents)
4730 {
4731     char * type;
4732     int i = 0;
4733
4734     if (!(sc->debug & DBG_MBUF)) {
4735         return;
4736     }
4737
4738     if (m == NULL) {
4739         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4740         return;
4741     }
4742
4743     while (m) {
4744
4745 #if __FreeBSD_version >= 1000000
4746         BLOGD(sc, DBG_MBUF,
4747               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4748               i, m, m->m_len, m->m_flags,
4749               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4750
4751         if (m->m_flags & M_PKTHDR) {
4752              BLOGD(sc, DBG_MBUF,
4753                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4754                    i, m->m_pkthdr.len, m->m_flags,
4755                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4756                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4757                    "\22M_PROMISC\23M_NOFREE",
4758                    (int)m->m_pkthdr.csum_flags,
4759                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4760                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4761                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4762                    "\14CSUM_PSEUDO_HDR");
4763         }
4764 #else
4765         BLOGD(sc, DBG_MBUF,
4766               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4767               i, m, m->m_len, m->m_flags,
4768               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4769
4770         if (m->m_flags & M_PKTHDR) {
4771              BLOGD(sc, DBG_MBUF,
4772                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4773                    i, m->m_pkthdr.len, m->m_flags,
4774                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4775                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4776                    "\22M_PROMISC\23M_NOFREE",
4777                    (int)m->m_pkthdr.csum_flags,
4778                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4779                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4780                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4781                    "\14CSUM_PSEUDO_HDR");
4782         }
4783 #endif /* #if __FreeBSD_version >= 1000000 */
4784
4785         if (m->m_flags & M_EXT) {
4786             switch (m->m_ext.ext_type) {
4787             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4788             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4789             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4790             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4791             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4792             case EXT_PACKET:     type = "EXT_PACKET";     break;
4793             case EXT_MBUF:       type = "EXT_MBUF";       break;
4794             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4795             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4796             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4797             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4798             default:             type = "UNKNOWN";        break;
4799             }
4800
4801             BLOGD(sc, DBG_MBUF,
4802                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4803                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4804         }
4805
4806         if (contents) {
4807             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4808         }
4809
4810         m = m->m_next;
4811         i++;
4812     }
4813 }
4814
4815 /*
4816  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4817  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4818  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4819  * The headers comes in a seperate bd in FreeBSD so 13-3=10.
4820  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4821  */
4822 static int
4823 bxe_chktso_window(struct bxe_softc  *sc,
4824                   int               nsegs,
4825                   bus_dma_segment_t *segs,
4826                   struct mbuf       *m)
4827 {
4828     uint32_t num_wnds, wnd_size, wnd_sum;
4829     int32_t frag_idx, wnd_idx;
4830     unsigned short lso_mss;
4831     int defrag;
4832
4833     defrag = 0;
4834     wnd_sum = 0;
4835     wnd_size = 10;
4836     num_wnds = nsegs - wnd_size;
4837     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4838
4839     /*
4840      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4841      * first window sum of data while skipping the first assuming it is the
4842      * header in FreeBSD.
4843      */
4844     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4845         wnd_sum += htole16(segs[frag_idx].ds_len);
4846     }
4847
4848     /* check the first 10 bd window size */
4849     if (wnd_sum < lso_mss) {
4850         return (1);
4851     }
4852
4853     /* run through the windows */
4854     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4855         /* subtract the first mbuf->m_len of the last wndw(-header) */
4856         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4857         /* add the next mbuf len to the len of our new window */
4858         wnd_sum += htole16(segs[frag_idx].ds_len);
4859         if (wnd_sum < lso_mss) {
4860             return (1);
4861         }
4862     }
4863
4864     return (0);
4865 }
4866
4867 static uint8_t
4868 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4869                     struct mbuf         *m,
4870                     uint32_t            *parsing_data)
4871 {
4872     struct ether_vlan_header *eh = NULL;
4873     struct ip *ip4 = NULL;
4874     struct ip6_hdr *ip6 = NULL;
4875     caddr_t ip = NULL;
4876     struct tcphdr *th = NULL;
4877     int e_hlen, ip_hlen, l4_off;
4878     uint16_t proto;
4879
4880     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4881         /* no L4 checksum offload needed */
4882         return (0);
4883     }
4884
4885     /* get the Ethernet header */
4886     eh = mtod(m, struct ether_vlan_header *);
4887
4888     /* handle VLAN encapsulation if present */
4889     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4890         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4891         proto  = ntohs(eh->evl_proto);
4892     } else {
4893         e_hlen = ETHER_HDR_LEN;
4894         proto  = ntohs(eh->evl_encap_proto);
4895     }
4896
4897     switch (proto) {
4898     case ETHERTYPE_IP:
4899         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4900         ip4 = (m->m_len < sizeof(struct ip)) ?
4901                   (struct ip *)m->m_next->m_data :
4902                   (struct ip *)(m->m_data + e_hlen);
4903         /* ip_hl is number of 32-bit words */
4904         ip_hlen = (ip4->ip_hl << 2);
4905         ip = (caddr_t)ip4;
4906         break;
4907     case ETHERTYPE_IPV6:
4908         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4909         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4910                   (struct ip6_hdr *)m->m_next->m_data :
4911                   (struct ip6_hdr *)(m->m_data + e_hlen);
4912         /* XXX cannot support offload with IPv6 extensions */
4913         ip_hlen = sizeof(struct ip6_hdr);
4914         ip = (caddr_t)ip6;
4915         break;
4916     default:
4917         /* We can't offload in this case... */
4918         /* XXX error stat ??? */
4919         return (0);
4920     }
4921
4922     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4923     l4_off = (e_hlen + ip_hlen);
4924
4925     *parsing_data |=
4926         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4927          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4928
4929     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4930                                   CSUM_TSO |
4931                                   CSUM_TCP_IPV6)) {
4932         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4933         th = (struct tcphdr *)(ip + ip_hlen);
4934         /* th_off is number of 32-bit words */
4935         *parsing_data |= ((th->th_off <<
4936                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4937                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4938         return (l4_off + (th->th_off << 2)); /* entire header length */
4939     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4940                                          CSUM_UDP_IPV6)) {
4941         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4942         return (l4_off + sizeof(struct udphdr)); /* entire header length */
4943     } else {
4944         /* XXX error stat ??? */
4945         return (0);
4946     }
4947 }
4948
4949 static uint8_t
4950 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4951                  struct mbuf                *m,
4952                  struct eth_tx_parse_bd_e1x *pbd)
4953 {
4954     struct ether_vlan_header *eh = NULL;
4955     struct ip *ip4 = NULL;
4956     struct ip6_hdr *ip6 = NULL;
4957     caddr_t ip = NULL;
4958     struct tcphdr *th = NULL;
4959     struct udphdr *uh = NULL;
4960     int e_hlen, ip_hlen;
4961     uint16_t proto;
4962     uint8_t hlen;
4963     uint16_t tmp_csum;
4964     uint32_t *tmp_uh;
4965
4966     /* get the Ethernet header */
4967     eh = mtod(m, struct ether_vlan_header *);
4968
4969     /* handle VLAN encapsulation if present */
4970     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4971         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4972         proto  = ntohs(eh->evl_proto);
4973     } else {
4974         e_hlen = ETHER_HDR_LEN;
4975         proto  = ntohs(eh->evl_encap_proto);
4976     }
4977
4978     switch (proto) {
4979     case ETHERTYPE_IP:
4980         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4981         ip4 = (m->m_len < sizeof(struct ip)) ?
4982                   (struct ip *)m->m_next->m_data :
4983                   (struct ip *)(m->m_data + e_hlen);
4984         /* ip_hl is number of 32-bit words */
4985         ip_hlen = (ip4->ip_hl << 1);
4986         ip = (caddr_t)ip4;
4987         break;
4988     case ETHERTYPE_IPV6:
4989         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4990         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4991                   (struct ip6_hdr *)m->m_next->m_data :
4992                   (struct ip6_hdr *)(m->m_data + e_hlen);
4993         /* XXX cannot support offload with IPv6 extensions */
4994         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4995         ip = (caddr_t)ip6;
4996         break;
4997     default:
4998         /* We can't offload in this case... */
4999         /* XXX error stat ??? */
5000         return (0);
5001     }
5002
5003     hlen = (e_hlen >> 1);
5004
5005     /* note that rest of global_data is indirectly zeroed here */
5006     if (m->m_flags & M_VLANTAG) {
5007         pbd->global_data =
5008             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
5009     } else {
5010         pbd->global_data = htole16(hlen);
5011     }
5012
5013     pbd->ip_hlen_w = ip_hlen;
5014
5015     hlen += pbd->ip_hlen_w;
5016
5017     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5018
5019     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5020                                   CSUM_TSO |
5021                                   CSUM_TCP_IPV6)) {
5022         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5023         /* th_off is number of 32-bit words */
5024         hlen += (uint16_t)(th->th_off << 1);
5025     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5026                                          CSUM_UDP_IPV6)) {
5027         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5028         hlen += (sizeof(struct udphdr) / 2);
5029     } else {
5030         /* valid case as only CSUM_IP was set */
5031         return (0);
5032     }
5033
5034     pbd->total_hlen_w = htole16(hlen);
5035
5036     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5037                                   CSUM_TSO |
5038                                   CSUM_TCP_IPV6)) {
5039         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5040         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5041     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5042                                          CSUM_UDP_IPV6)) {
5043         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5044
5045         /*
5046          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5047          * checksums and does not know anything about the UDP header and where
5048          * the checksum field is located. It only knows about TCP. Therefore
5049          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5050          * offload. Since the checksum field offset for TCP is 16 bytes and
5051          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5052          * bytes less than the start of the UDP header. This allows the
5053          * hardware to write the checksum in the correct spot. But the
5054          * hardware will compute a checksum which includes the last 10 bytes
5055          * of the IP header. To correct this we tweak the stack computed
5056          * pseudo checksum by folding in the calculation of the inverse
5057          * checksum for those final 10 bytes of the IP header. This allows
5058          * the correct checksum to be computed by the hardware.
5059          */
5060
5061         /* set pointer 10 bytes before UDP header */
5062         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5063
5064         /* calculate a pseudo header checksum over the first 10 bytes */
5065         tmp_csum = in_pseudo(*tmp_uh,
5066                              *(tmp_uh + 1),
5067                              *(uint16_t *)(tmp_uh + 2));
5068
5069         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5070     }
5071
5072     return (hlen * 2); /* entire header length, number of bytes */
5073 }
5074
5075 static void
5076 bxe_set_pbd_lso_e2(struct mbuf *m,
5077                    uint32_t    *parsing_data)
5078 {
5079     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5080                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5081                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5082
5083     /* XXX test for IPv6 with extension header... */
5084 }
5085
5086 static void
5087 bxe_set_pbd_lso(struct mbuf                *m,
5088                 struct eth_tx_parse_bd_e1x *pbd)
5089 {
5090     struct ether_vlan_header *eh = NULL;
5091     struct ip *ip = NULL;
5092     struct tcphdr *th = NULL;
5093     int e_hlen;
5094
5095     /* get the Ethernet header */
5096     eh = mtod(m, struct ether_vlan_header *);
5097
5098     /* handle VLAN encapsulation if present */
5099     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5100                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5101
5102     /* get the IP and TCP header, with LSO entire header in first mbuf */
5103     /* XXX assuming IPv4 */
5104     ip = (struct ip *)(m->m_data + e_hlen);
5105     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5106
5107     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5108     pbd->tcp_send_seq = ntohl(th->th_seq);
5109     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5110
5111 #if 1
5112         /* XXX IPv4 */
5113         pbd->ip_id = ntohs(ip->ip_id);
5114         pbd->tcp_pseudo_csum =
5115             ntohs(in_pseudo(ip->ip_src.s_addr,
5116                             ip->ip_dst.s_addr,
5117                             htons(IPPROTO_TCP)));
5118 #else
5119         /* XXX IPv6 */
5120         pbd->tcp_pseudo_csum =
5121             ntohs(in_pseudo(&ip6->ip6_src,
5122                             &ip6->ip6_dst,
5123                             htons(IPPROTO_TCP)));
5124 #endif
5125
5126     pbd->global_data |=
5127         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5128 }
5129
5130 /*
5131  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5132  * visible to the controller.
5133  *
5134  * If an mbuf is submitted to this routine and cannot be given to the
5135  * controller (e.g. it has too many fragments) then the function may free
5136  * the mbuf and return to the caller.
5137  *
5138  * Returns:
5139  *   0 = Success, !0 = Failure
5140  *   Note the side effect that an mbuf may be freed if it causes a problem.
5141  */
5142 static int
5143 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5144 {
5145     bus_dma_segment_t segs[32];
5146     struct mbuf *m0;
5147     struct bxe_sw_tx_bd *tx_buf;
5148     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5149     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5150     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5151     struct eth_tx_bd *tx_data_bd;
5152     struct eth_tx_bd *tx_total_pkt_size_bd;
5153     struct eth_tx_start_bd *tx_start_bd;
5154     uint16_t bd_prod, pkt_prod, total_pkt_size;
5155     uint8_t mac_type;
5156     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5157     struct bxe_softc *sc;
5158     uint16_t tx_bd_avail;
5159     struct ether_vlan_header *eh;
5160     uint32_t pbd_e2_parsing_data = 0;
5161     uint8_t hlen = 0;
5162     int tmp_bd;
5163     int i;
5164
5165     sc = fp->sc;
5166
5167 #if __FreeBSD_version >= 800000
5168     M_ASSERTPKTHDR(*m_head);
5169 #endif /* #if __FreeBSD_version >= 800000 */
5170
5171     m0 = *m_head;
5172     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5173     tx_start_bd = NULL;
5174     tx_data_bd = NULL;
5175     tx_total_pkt_size_bd = NULL;
5176
5177     /* get the H/W pointer for packets and BDs */
5178     pkt_prod = fp->tx_pkt_prod;
5179     bd_prod = fp->tx_bd_prod;
5180
5181     mac_type = UNICAST_ADDRESS;
5182
5183     /* map the mbuf into the next open DMAable memory */
5184     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5185     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5186                                     tx_buf->m_map, m0,
5187                                     segs, &nsegs, BUS_DMA_NOWAIT);
5188
5189     /* mapping errors */
5190     if(__predict_false(error != 0)) {
5191         fp->eth_q_stats.tx_dma_mapping_failure++;
5192         if (error == ENOMEM) {
5193             /* resource issue, try again later */
5194             rc = ENOMEM;
5195         } else if (error == EFBIG) {
5196             /* possibly recoverable with defragmentation */
5197             fp->eth_q_stats.mbuf_defrag_attempts++;
5198             m0 = m_defrag(*m_head, M_DONTWAIT);
5199             if (m0 == NULL) {
5200                 fp->eth_q_stats.mbuf_defrag_failures++;
5201                 rc = ENOBUFS;
5202             } else {
5203                 /* defrag successful, try mapping again */
5204                 *m_head = m0;
5205                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5206                                                 tx_buf->m_map, m0,
5207                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5208                 if (error) {
5209                     fp->eth_q_stats.tx_dma_mapping_failure++;
5210                     rc = error;
5211                 }
5212             }
5213         } else {
5214             /* unknown, unrecoverable mapping error */
5215             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5216             bxe_dump_mbuf(sc, m0, FALSE);
5217             rc = error;
5218         }
5219
5220         goto bxe_tx_encap_continue;
5221     }
5222
5223     tx_bd_avail = bxe_tx_avail(sc, fp);
5224
5225     /* make sure there is enough room in the send queue */
5226     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5227         /* Recoverable, try again later. */
5228         fp->eth_q_stats.tx_hw_queue_full++;
5229         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5230         rc = ENOMEM;
5231         goto bxe_tx_encap_continue;
5232     }
5233
5234     /* capture the current H/W TX chain high watermark */
5235     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5236                         (TX_BD_USABLE - tx_bd_avail))) {
5237         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5238     }
5239
5240     /* make sure it fits in the packet window */
5241     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5242         /*
5243          * The mbuf may be to big for the controller to handle. If the frame
5244          * is a TSO frame we'll need to do an additional check.
5245          */
5246         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5247             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5248                 goto bxe_tx_encap_continue; /* OK to send */
5249             } else {
5250                 fp->eth_q_stats.tx_window_violation_tso++;
5251             }
5252         } else {
5253             fp->eth_q_stats.tx_window_violation_std++;
5254         }
5255
5256         /* lets try to defragment this mbuf and remap it */
5257         fp->eth_q_stats.mbuf_defrag_attempts++;
5258         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5259
5260         m0 = m_defrag(*m_head, M_DONTWAIT);
5261         if (m0 == NULL) {
5262             fp->eth_q_stats.mbuf_defrag_failures++;
5263             /* Ugh, just drop the frame... :( */
5264             rc = ENOBUFS;
5265         } else {
5266             /* defrag successful, try mapping again */
5267             *m_head = m0;
5268             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5269                                             tx_buf->m_map, m0,
5270                                             segs, &nsegs, BUS_DMA_NOWAIT);
5271             if (error) {
5272                 fp->eth_q_stats.tx_dma_mapping_failure++;
5273                 /* No sense in trying to defrag/copy chain, drop it. :( */
5274                 rc = error;
5275             } else {
5276                /* if the chain is still too long then drop it */
5277                 if(m0->m_pkthdr.csum_flags & CSUM_TSO) {
5278                     /*
5279                      * in case TSO is enabled nsegs should be checked against
5280                      * BXE_TSO_MAX_SEGMENTS
5281                      */
5282                     if (__predict_false(nsegs > BXE_TSO_MAX_SEGMENTS)) {
5283                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5284                         fp->eth_q_stats.nsegs_path1_errors++;
5285                         rc = ENODEV;
5286                     }
5287                 } else {
5288                     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5289                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5290                         fp->eth_q_stats.nsegs_path2_errors++;
5291                         rc = ENODEV;
5292                     }
5293                 }
5294             }
5295         }
5296     }
5297
5298 bxe_tx_encap_continue:
5299
5300     /* Check for errors */
5301     if (rc) {
5302         if (rc == ENOMEM) {
5303             /* recoverable try again later  */
5304         } else {
5305             fp->eth_q_stats.tx_soft_errors++;
5306             fp->eth_q_stats.mbuf_alloc_tx--;
5307             m_freem(*m_head);
5308             *m_head = NULL;
5309         }
5310
5311         return (rc);
5312     }
5313
5314     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5315     if (m0->m_flags & M_BCAST) {
5316         mac_type = BROADCAST_ADDRESS;
5317     } else if (m0->m_flags & M_MCAST) {
5318         mac_type = MULTICAST_ADDRESS;
5319     }
5320
5321     /* store the mbuf into the mbuf ring */
5322     tx_buf->m        = m0;
5323     tx_buf->first_bd = fp->tx_bd_prod;
5324     tx_buf->flags    = 0;
5325
5326     /* prepare the first transmit (start) BD for the mbuf */
5327     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5328
5329     BLOGD(sc, DBG_TX,
5330           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5331           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5332
5333     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5334     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5335     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5336     total_pkt_size += tx_start_bd->nbytes;
5337     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5338
5339     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5340
5341     /* all frames have at least Start BD + Parsing BD */
5342     nbds = nsegs + 1;
5343     tx_start_bd->nbd = htole16(nbds);
5344
5345     if (m0->m_flags & M_VLANTAG) {
5346         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5347         tx_start_bd->bd_flags.as_bitfield |=
5348             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5349     } else {
5350         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5351         if (IS_VF(sc)) {
5352             /* map ethernet header to find type and header length */
5353             eh = mtod(m0, struct ether_vlan_header *);
5354             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5355         } else {
5356             /* used by FW for packet accounting */
5357             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5358         }
5359     }
5360
5361     /*
5362      * add a parsing BD from the chain. The parsing BD is always added
5363      * though it is only used for TSO and chksum
5364      */
5365     bd_prod = TX_BD_NEXT(bd_prod);
5366
5367     if (m0->m_pkthdr.csum_flags) {
5368         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5369             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5370             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5371         }
5372
5373         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5374             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5375                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5376         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5377             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5378                                                   ETH_TX_BD_FLAGS_IS_UDP |
5379                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5380         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5381                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5382             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5383         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5384             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5385                                                   ETH_TX_BD_FLAGS_IS_UDP);
5386         }
5387     }
5388
5389     if (!CHIP_IS_E1x(sc)) {
5390         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5391         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5392
5393         if (m0->m_pkthdr.csum_flags) {
5394             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5395         }
5396
5397         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5398                  mac_type);
5399     } else {
5400         uint16_t global_data = 0;
5401
5402         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5403         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5404
5405         if (m0->m_pkthdr.csum_flags) {
5406             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5407         }
5408
5409         SET_FLAG(global_data,
5410                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5411         pbd_e1x->global_data |= htole16(global_data);
5412     }
5413
5414     /* setup the parsing BD with TSO specific info */
5415     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5416         fp->eth_q_stats.tx_ofld_frames_lso++;
5417         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5418
5419         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5420             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5421
5422             /* split the first BD into header/data making the fw job easy */
5423             nbds++;
5424             tx_start_bd->nbd = htole16(nbds);
5425             tx_start_bd->nbytes = htole16(hlen);
5426
5427             bd_prod = TX_BD_NEXT(bd_prod);
5428
5429             /* new transmit BD after the tx_parse_bd */
5430             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5431             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5432             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5433             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5434             if (tx_total_pkt_size_bd == NULL) {
5435                 tx_total_pkt_size_bd = tx_data_bd;
5436             }
5437
5438             BLOGD(sc, DBG_TX,
5439                   "TSO split header size is %d (%x:%x) nbds %d\n",
5440                   le16toh(tx_start_bd->nbytes),
5441                   le32toh(tx_start_bd->addr_hi),
5442                   le32toh(tx_start_bd->addr_lo),
5443                   nbds);
5444         }
5445
5446         if (!CHIP_IS_E1x(sc)) {
5447             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5448         } else {
5449             bxe_set_pbd_lso(m0, pbd_e1x);
5450         }
5451     }
5452
5453     if (pbd_e2_parsing_data) {
5454         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5455     }
5456
5457     /* prepare remaining BDs, start tx bd contains first seg/frag */
5458     for (i = 1; i < nsegs ; i++) {
5459         bd_prod = TX_BD_NEXT(bd_prod);
5460         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5461         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5462         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5463         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5464         if (tx_total_pkt_size_bd == NULL) {
5465             tx_total_pkt_size_bd = tx_data_bd;
5466         }
5467         total_pkt_size += tx_data_bd->nbytes;
5468     }
5469
5470     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5471
5472     if (tx_total_pkt_size_bd != NULL) {
5473         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5474     }
5475
5476     if (__predict_false(sc->debug & DBG_TX)) {
5477         tmp_bd = tx_buf->first_bd;
5478         for (i = 0; i < nbds; i++)
5479         {
5480             if (i == 0) {
5481                 BLOGD(sc, DBG_TX,
5482                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5483                       "bd_flags=0x%x hdr_nbds=%d\n",
5484                       tx_start_bd,
5485                       tmp_bd,
5486                       le16toh(tx_start_bd->nbd),
5487                       le16toh(tx_start_bd->vlan_or_ethertype),
5488                       tx_start_bd->bd_flags.as_bitfield,
5489                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5490             } else if (i == 1) {
5491                 if (pbd_e1x) {
5492                     BLOGD(sc, DBG_TX,
5493                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5494                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5495                           "tcp_seq=%u total_hlen_w=%u\n",
5496                           pbd_e1x,
5497                           tmp_bd,
5498                           pbd_e1x->global_data,
5499                           pbd_e1x->ip_hlen_w,
5500                           pbd_e1x->ip_id,
5501                           pbd_e1x->lso_mss,
5502                           pbd_e1x->tcp_flags,
5503                           pbd_e1x->tcp_pseudo_csum,
5504                           pbd_e1x->tcp_send_seq,
5505                           le16toh(pbd_e1x->total_hlen_w));
5506                 } else { /* if (pbd_e2) */
5507                     BLOGD(sc, DBG_TX,
5508                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5509                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5510                           pbd_e2,
5511                           tmp_bd,
5512                           pbd_e2->data.mac_addr.dst_hi,
5513                           pbd_e2->data.mac_addr.dst_mid,
5514                           pbd_e2->data.mac_addr.dst_lo,
5515                           pbd_e2->data.mac_addr.src_hi,
5516                           pbd_e2->data.mac_addr.src_mid,
5517                           pbd_e2->data.mac_addr.src_lo,
5518                           pbd_e2->parsing_data);
5519                 }
5520             }
5521
5522             if (i != 1) { /* skip parse db as it doesn't hold data */
5523                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5524                 BLOGD(sc, DBG_TX,
5525                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5526                       tx_data_bd,
5527                       tmp_bd,
5528                       le16toh(tx_data_bd->nbytes),
5529                       le32toh(tx_data_bd->addr_hi),
5530                       le32toh(tx_data_bd->addr_lo));
5531             }
5532
5533             tmp_bd = TX_BD_NEXT(tmp_bd);
5534         }
5535     }
5536
5537     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5538
5539     /* update TX BD producer index value for next TX */
5540     bd_prod = TX_BD_NEXT(bd_prod);
5541
5542     /*
5543      * If the chain of tx_bd's describing this frame is adjacent to or spans
5544      * an eth_tx_next_bd element then we need to increment the nbds value.
5545      */
5546     if (TX_BD_IDX(bd_prod) < nbds) {
5547         nbds++;
5548     }
5549
5550     /* don't allow reordering of writes for nbd and packets */
5551     mb();
5552
5553     fp->tx_db.data.prod += nbds;
5554
5555     /* producer points to the next free tx_bd at this point */
5556     fp->tx_pkt_prod++;
5557     fp->tx_bd_prod = bd_prod;
5558
5559     DOORBELL(sc, fp->index, fp->tx_db.raw);
5560
5561     fp->eth_q_stats.tx_pkts++;
5562
5563     /* Prevent speculative reads from getting ahead of the status block. */
5564     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5565                       0, 0, BUS_SPACE_BARRIER_READ);
5566
5567     /* Prevent speculative reads from getting ahead of the doorbell. */
5568     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5569                       0, 0, BUS_SPACE_BARRIER_READ);
5570
5571     return (0);
5572 }
5573
5574 static void
5575 bxe_tx_start_locked(struct bxe_softc    *sc,
5576                     struct ifnet        *ifp,
5577                     struct bxe_fastpath *fp)
5578 {
5579     struct mbuf *m = NULL;
5580     int tx_count = 0;
5581     uint16_t tx_bd_avail;
5582
5583     BXE_FP_TX_LOCK_ASSERT(fp);
5584
5585     /* keep adding entries while there are frames to send */
5586     while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
5587
5588         /*
5589          * check for any frames to send
5590          * dequeue can still be NULL even if queue is not empty
5591          */
5592         IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
5593         if (__predict_false(m == NULL)) {
5594             break;
5595         }
5596
5597         /* the mbuf now belongs to us */
5598         fp->eth_q_stats.mbuf_alloc_tx++;
5599
5600         /*
5601          * Put the frame into the transmit ring. If we don't have room,
5602          * place the mbuf back at the head of the TX queue, set the
5603          * OACTIVE flag, and wait for the NIC to drain the chain.
5604          */
5605         if (__predict_false(bxe_tx_encap(fp, &m))) {
5606             fp->eth_q_stats.tx_encap_failures++;
5607             if (m != NULL) {
5608                 /* mark the TX queue as full and return the frame */
5609                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5610                 IFQ_DRV_PREPEND(&ifp->if_snd, m);
5611                 fp->eth_q_stats.mbuf_alloc_tx--;
5612                 fp->eth_q_stats.tx_queue_xoff++;
5613             }
5614
5615             /* stop looking for more work */
5616             break;
5617         }
5618
5619         /* the frame was enqueued successfully */
5620         tx_count++;
5621
5622         /* send a copy of the frame to any BPF listeners. */
5623         BPF_MTAP(ifp, m);
5624
5625         tx_bd_avail = bxe_tx_avail(sc, fp);
5626
5627         /* handle any completions if we're running low */
5628         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5629             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5630             bxe_txeof(sc, fp);
5631             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5632                 break;
5633             }
5634         }
5635     }
5636
5637     /* all TX packets were dequeued and/or the tx ring is full */
5638     if (tx_count > 0) {
5639         /* reset the TX watchdog timeout timer */
5640         fp->watchdog_timer = BXE_TX_TIMEOUT;
5641     }
5642 }
5643
5644 /* Legacy (non-RSS) dispatch routine */
5645 static void
5646 bxe_tx_start(struct ifnet *ifp)
5647 {
5648     struct bxe_softc *sc;
5649     struct bxe_fastpath *fp;
5650
5651     sc = ifp->if_softc;
5652
5653     if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5654         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5655         return;
5656     }
5657
5658     if (!sc->link_vars.link_up) {
5659         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5660         return;
5661     }
5662
5663     fp = &sc->fp[0];
5664
5665     if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5666         fp->eth_q_stats.tx_queue_full_return++;
5667         return;
5668     }
5669
5670     BXE_FP_TX_LOCK(fp);
5671     bxe_tx_start_locked(sc, ifp, fp);
5672     BXE_FP_TX_UNLOCK(fp);
5673 }
5674
5675 #if __FreeBSD_version >= 901504
5676
5677 static int
5678 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5679                        struct ifnet        *ifp,
5680                        struct bxe_fastpath *fp,
5681                        struct mbuf         *m)
5682 {
5683     struct buf_ring *tx_br = fp->tx_br;
5684     struct mbuf *next;
5685     int depth, rc, tx_count;
5686     uint16_t tx_bd_avail;
5687
5688     rc = tx_count = 0;
5689
5690     BXE_FP_TX_LOCK_ASSERT(fp);
5691
5692     if (sc->state != BXE_STATE_OPEN)  {
5693         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5694         return ENETDOWN;
5695     }
5696
5697     if (!tx_br) {
5698         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5699         return (EINVAL);
5700     }
5701
5702     if (m != NULL) {
5703         rc = drbr_enqueue(ifp, tx_br, m);
5704         if (rc != 0) {
5705             fp->eth_q_stats.tx_soft_errors++;
5706             goto bxe_tx_mq_start_locked_exit;
5707         }
5708     }
5709
5710     if (!sc->link_vars.link_up || !(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5711         fp->eth_q_stats.tx_request_link_down_failures++;
5712         goto bxe_tx_mq_start_locked_exit;
5713     }
5714
5715     /* fetch the depth of the driver queue */
5716     depth = drbr_inuse(ifp, tx_br);
5717     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5718         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5719     }
5720
5721     /* keep adding entries while there are frames to send */
5722     while ((next = drbr_peek(ifp, tx_br)) != NULL) {
5723         /* handle any completions if we're running low */
5724         tx_bd_avail = bxe_tx_avail(sc, fp);
5725         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5726             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5727             bxe_txeof(sc, fp);
5728             tx_bd_avail = bxe_tx_avail(sc, fp);
5729             if (tx_bd_avail < (BXE_TSO_MAX_SEGMENTS + 1)) {
5730                 fp->eth_q_stats.bd_avail_too_less_failures++;
5731                 m_freem(next);
5732                 drbr_advance(ifp, tx_br);
5733                 rc = ENOBUFS;
5734                 break;
5735             }
5736         }
5737
5738         /* the mbuf now belongs to us */
5739         fp->eth_q_stats.mbuf_alloc_tx++;
5740
5741         /*
5742          * Put the frame into the transmit ring. If we don't have room,
5743          * place the mbuf back at the head of the TX queue, set the
5744          * OACTIVE flag, and wait for the NIC to drain the chain.
5745          */
5746         rc = bxe_tx_encap(fp, &next);
5747         if (__predict_false(rc != 0)) {
5748             fp->eth_q_stats.tx_encap_failures++;
5749             if (next != NULL) {
5750                 /* mark the TX queue as full and save the frame */
5751                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5752                 drbr_putback(ifp, tx_br, next);
5753                 fp->eth_q_stats.mbuf_alloc_tx--;
5754                 fp->eth_q_stats.tx_frames_deferred++;
5755             } else
5756                 drbr_advance(ifp, tx_br);
5757
5758             /* stop looking for more work */
5759             break;
5760         }
5761
5762         /* the transmit frame was enqueued successfully */
5763         tx_count++;
5764
5765         /* send a copy of the frame to any BPF listeners */
5766         BPF_MTAP(ifp, next);
5767
5768         drbr_advance(ifp, tx_br);
5769     }
5770
5771     /* all TX packets were dequeued and/or the tx ring is full */
5772     if (tx_count > 0) {
5773         /* reset the TX watchdog timeout timer */
5774         fp->watchdog_timer = BXE_TX_TIMEOUT;
5775     }
5776
5777 bxe_tx_mq_start_locked_exit:
5778     /* If we didn't drain the drbr, enqueue a task in the future to do it. */
5779     if (!drbr_empty(ifp, tx_br)) {
5780         fp->eth_q_stats.tx_mq_not_empty++;
5781         taskqueue_enqueue_timeout(fp->tq, &fp->tx_timeout_task, 1);
5782     }
5783
5784     return (rc);
5785 }
5786
5787 static void
5788 bxe_tx_mq_start_deferred(void *arg,
5789                          int pending)
5790 {
5791     struct bxe_fastpath *fp = (struct bxe_fastpath *)arg;
5792     struct bxe_softc *sc = fp->sc;
5793     struct ifnet *ifp = sc->ifnet;
5794
5795     BXE_FP_TX_LOCK(fp);
5796     bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
5797     BXE_FP_TX_UNLOCK(fp);
5798 }
5799
5800 /* Multiqueue (TSS) dispatch routine. */
5801 static int
5802 bxe_tx_mq_start(struct ifnet *ifp,
5803                 struct mbuf  *m)
5804 {
5805     struct bxe_softc *sc = ifp->if_softc;
5806     struct bxe_fastpath *fp;
5807     int fp_index, rc;
5808
5809     fp_index = 0; /* default is the first queue */
5810
5811     /* check if flowid is set */
5812
5813     if (BXE_VALID_FLOWID(m))
5814         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5815
5816     fp = &sc->fp[fp_index];
5817
5818     if (sc->state != BXE_STATE_OPEN)  {
5819         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5820         return ENETDOWN;
5821     }
5822
5823     if (BXE_FP_TX_TRYLOCK(fp)) {
5824         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5825         BXE_FP_TX_UNLOCK(fp);
5826     } else {
5827         rc = drbr_enqueue(ifp, fp->tx_br, m);
5828         taskqueue_enqueue(fp->tq, &fp->tx_task);
5829     }
5830
5831     return (rc);
5832 }
5833
5834 static void
5835 bxe_mq_flush(struct ifnet *ifp)
5836 {
5837     struct bxe_softc *sc = ifp->if_softc;
5838     struct bxe_fastpath *fp;
5839     struct mbuf *m;
5840     int i;
5841
5842     for (i = 0; i < sc->num_queues; i++) {
5843         fp = &sc->fp[i];
5844
5845         if (fp->state != BXE_FP_STATE_IRQ) {
5846             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5847                   fp->index, fp->state);
5848             continue;
5849         }
5850
5851         if (fp->tx_br != NULL) {
5852             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5853             BXE_FP_TX_LOCK(fp);
5854             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5855                 m_freem(m);
5856             }
5857             BXE_FP_TX_UNLOCK(fp);
5858         }
5859     }
5860
5861     if_qflush(ifp);
5862 }
5863
5864 #endif /* FreeBSD_version >= 901504 */
5865
5866 static uint16_t
5867 bxe_cid_ilt_lines(struct bxe_softc *sc)
5868 {
5869     if (IS_SRIOV(sc)) {
5870         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5871     }
5872     return (L2_ILT_LINES(sc));
5873 }
5874
5875 static void
5876 bxe_ilt_set_info(struct bxe_softc *sc)
5877 {
5878     struct ilt_client_info *ilt_client;
5879     struct ecore_ilt *ilt = sc->ilt;
5880     uint16_t line = 0;
5881
5882     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5883     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5884
5885     /* CDU */
5886     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5887     ilt_client->client_num = ILT_CLIENT_CDU;
5888     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5889     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5890     ilt_client->start = line;
5891     line += bxe_cid_ilt_lines(sc);
5892
5893     if (CNIC_SUPPORT(sc)) {
5894         line += CNIC_ILT_LINES;
5895     }
5896
5897     ilt_client->end = (line - 1);
5898
5899     BLOGD(sc, DBG_LOAD,
5900           "ilt client[CDU]: start %d, end %d, "
5901           "psz 0x%x, flags 0x%x, hw psz %d\n",
5902           ilt_client->start, ilt_client->end,
5903           ilt_client->page_size,
5904           ilt_client->flags,
5905           ilog2(ilt_client->page_size >> 12));
5906
5907     /* QM */
5908     if (QM_INIT(sc->qm_cid_count)) {
5909         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5910         ilt_client->client_num = ILT_CLIENT_QM;
5911         ilt_client->page_size = QM_ILT_PAGE_SZ;
5912         ilt_client->flags = 0;
5913         ilt_client->start = line;
5914
5915         /* 4 bytes for each cid */
5916         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5917                              QM_ILT_PAGE_SZ);
5918
5919         ilt_client->end = (line - 1);
5920
5921         BLOGD(sc, DBG_LOAD,
5922               "ilt client[QM]: start %d, end %d, "
5923               "psz 0x%x, flags 0x%x, hw psz %d\n",
5924               ilt_client->start, ilt_client->end,
5925               ilt_client->page_size, ilt_client->flags,
5926               ilog2(ilt_client->page_size >> 12));
5927     }
5928
5929     if (CNIC_SUPPORT(sc)) {
5930         /* SRC */
5931         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5932         ilt_client->client_num = ILT_CLIENT_SRC;
5933         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5934         ilt_client->flags = 0;
5935         ilt_client->start = line;
5936         line += SRC_ILT_LINES;
5937         ilt_client->end = (line - 1);
5938
5939         BLOGD(sc, DBG_LOAD,
5940               "ilt client[SRC]: start %d, end %d, "
5941               "psz 0x%x, flags 0x%x, hw psz %d\n",
5942               ilt_client->start, ilt_client->end,
5943               ilt_client->page_size, ilt_client->flags,
5944               ilog2(ilt_client->page_size >> 12));
5945
5946         /* TM */
5947         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5948         ilt_client->client_num = ILT_CLIENT_TM;
5949         ilt_client->page_size = TM_ILT_PAGE_SZ;
5950         ilt_client->flags = 0;
5951         ilt_client->start = line;
5952         line += TM_ILT_LINES;
5953         ilt_client->end = (line - 1);
5954
5955         BLOGD(sc, DBG_LOAD,
5956               "ilt client[TM]: start %d, end %d, "
5957               "psz 0x%x, flags 0x%x, hw psz %d\n",
5958               ilt_client->start, ilt_client->end,
5959               ilt_client->page_size, ilt_client->flags,
5960               ilog2(ilt_client->page_size >> 12));
5961     }
5962
5963     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5964 }
5965
5966 static void
5967 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5968 {
5969     int i;
5970     uint32_t rx_buf_size;
5971
5972     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5973
5974     for (i = 0; i < sc->num_queues; i++) {
5975         if(rx_buf_size <= MCLBYTES){
5976             sc->fp[i].rx_buf_size = rx_buf_size;
5977             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5978         }else if (rx_buf_size <= MJUMPAGESIZE){
5979             sc->fp[i].rx_buf_size = rx_buf_size;
5980             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5981         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5982             sc->fp[i].rx_buf_size = MCLBYTES;
5983             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5984         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5985             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5986             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5987         }else {
5988             sc->fp[i].rx_buf_size = MCLBYTES;
5989             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5990         }
5991     }
5992 }
5993
5994 static int
5995 bxe_alloc_ilt_mem(struct bxe_softc *sc)
5996 {
5997     int rc = 0;
5998
5999     if ((sc->ilt =
6000          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
6001                                     M_BXE_ILT,
6002                                     (M_NOWAIT | M_ZERO))) == NULL) {
6003         rc = 1;
6004     }
6005
6006     return (rc);
6007 }
6008
6009 static int
6010 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
6011 {
6012     int rc = 0;
6013
6014     if ((sc->ilt->lines =
6015          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6016                                     M_BXE_ILT,
6017                                     (M_NOWAIT | M_ZERO))) == NULL) {
6018         rc = 1;
6019     }
6020
6021     return (rc);
6022 }
6023
6024 static void
6025 bxe_free_ilt_mem(struct bxe_softc *sc)
6026 {
6027     if (sc->ilt != NULL) {
6028         free(sc->ilt, M_BXE_ILT);
6029         sc->ilt = NULL;
6030     }
6031 }
6032
6033 static void
6034 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6035 {
6036     if (sc->ilt->lines != NULL) {
6037         free(sc->ilt->lines, M_BXE_ILT);
6038         sc->ilt->lines = NULL;
6039     }
6040 }
6041
6042 static void
6043 bxe_free_mem(struct bxe_softc *sc)
6044 {
6045     int i;
6046
6047     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6048         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6049         sc->context[i].vcxt = NULL;
6050         sc->context[i].size = 0;
6051     }
6052
6053     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6054
6055     bxe_free_ilt_lines_mem(sc);
6056
6057 }
6058
6059 static int
6060 bxe_alloc_mem(struct bxe_softc *sc)
6061 {
6062
6063     int context_size;
6064     int allocated;
6065     int i;
6066
6067     /*
6068      * Allocate memory for CDU context:
6069      * This memory is allocated separately and not in the generic ILT
6070      * functions because CDU differs in few aspects:
6071      * 1. There can be multiple entities allocating memory for context -
6072      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6073      * its own ILT lines.
6074      * 2. Since CDU page-size is not a single 4KB page (which is the case
6075      * for the other ILT clients), to be efficient we want to support
6076      * allocation of sub-page-size in the last entry.
6077      * 3. Context pointers are used by the driver to pass to FW / update
6078      * the context (for the other ILT clients the pointers are used just to
6079      * free the memory during unload).
6080      */
6081     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6082     for (i = 0, allocated = 0; allocated < context_size; i++) {
6083         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6084                                   (context_size - allocated));
6085
6086         if (bxe_dma_alloc(sc, sc->context[i].size,
6087                           &sc->context[i].vcxt_dma,
6088                           "cdu context") != 0) {
6089             bxe_free_mem(sc);
6090             return (-1);
6091         }
6092
6093         sc->context[i].vcxt =
6094             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6095
6096         allocated += sc->context[i].size;
6097     }
6098
6099     bxe_alloc_ilt_lines_mem(sc);
6100
6101     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6102           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6103     {
6104         for (i = 0; i < 4; i++) {
6105             BLOGD(sc, DBG_LOAD,
6106                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6107                   i,
6108                   sc->ilt->clients[i].page_size,
6109                   sc->ilt->clients[i].start,
6110                   sc->ilt->clients[i].end,
6111                   sc->ilt->clients[i].client_num,
6112                   sc->ilt->clients[i].flags);
6113         }
6114     }
6115     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6116         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6117         bxe_free_mem(sc);
6118         return (-1);
6119     }
6120
6121     return (0);
6122 }
6123
6124 static void
6125 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6126 {
6127     struct bxe_softc *sc;
6128     int i;
6129
6130     sc = fp->sc;
6131
6132     if (fp->rx_mbuf_tag == NULL) {
6133         return;
6134     }
6135
6136     /* free all mbufs and unload all maps */
6137     for (i = 0; i < RX_BD_TOTAL; i++) {
6138         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6139             bus_dmamap_sync(fp->rx_mbuf_tag,
6140                             fp->rx_mbuf_chain[i].m_map,
6141                             BUS_DMASYNC_POSTREAD);
6142             bus_dmamap_unload(fp->rx_mbuf_tag,
6143                               fp->rx_mbuf_chain[i].m_map);
6144         }
6145
6146         if (fp->rx_mbuf_chain[i].m != NULL) {
6147             m_freem(fp->rx_mbuf_chain[i].m);
6148             fp->rx_mbuf_chain[i].m = NULL;
6149             fp->eth_q_stats.mbuf_alloc_rx--;
6150         }
6151     }
6152 }
6153
6154 static void
6155 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6156 {
6157     struct bxe_softc *sc;
6158     int i, max_agg_queues;
6159
6160     sc = fp->sc;
6161
6162     if (fp->rx_mbuf_tag == NULL) {
6163         return;
6164     }
6165
6166     max_agg_queues = MAX_AGG_QS(sc);
6167
6168     /* release all mbufs and unload all DMA maps in the TPA pool */
6169     for (i = 0; i < max_agg_queues; i++) {
6170         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6171             bus_dmamap_sync(fp->rx_mbuf_tag,
6172                             fp->rx_tpa_info[i].bd.m_map,
6173                             BUS_DMASYNC_POSTREAD);
6174             bus_dmamap_unload(fp->rx_mbuf_tag,
6175                               fp->rx_tpa_info[i].bd.m_map);
6176         }
6177
6178         if (fp->rx_tpa_info[i].bd.m != NULL) {
6179             m_freem(fp->rx_tpa_info[i].bd.m);
6180             fp->rx_tpa_info[i].bd.m = NULL;
6181             fp->eth_q_stats.mbuf_alloc_tpa--;
6182         }
6183     }
6184 }
6185
6186 static void
6187 bxe_free_sge_chain(struct bxe_fastpath *fp)
6188 {
6189     struct bxe_softc *sc;
6190     int i;
6191
6192     sc = fp->sc;
6193
6194     if (fp->rx_sge_mbuf_tag == NULL) {
6195         return;
6196     }
6197
6198     /* rree all mbufs and unload all maps */
6199     for (i = 0; i < RX_SGE_TOTAL; i++) {
6200         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6201             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6202                             fp->rx_sge_mbuf_chain[i].m_map,
6203                             BUS_DMASYNC_POSTREAD);
6204             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6205                               fp->rx_sge_mbuf_chain[i].m_map);
6206         }
6207
6208         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6209             m_freem(fp->rx_sge_mbuf_chain[i].m);
6210             fp->rx_sge_mbuf_chain[i].m = NULL;
6211             fp->eth_q_stats.mbuf_alloc_sge--;
6212         }
6213     }
6214 }
6215
6216 static void
6217 bxe_free_fp_buffers(struct bxe_softc *sc)
6218 {
6219     struct bxe_fastpath *fp;
6220     int i;
6221
6222     for (i = 0; i < sc->num_queues; i++) {
6223         fp = &sc->fp[i];
6224
6225 #if __FreeBSD_version >= 901504
6226         if (fp->tx_br != NULL) {
6227             /* just in case bxe_mq_flush() wasn't called */
6228             if (mtx_initialized(&fp->tx_mtx)) {
6229                 struct mbuf *m;
6230
6231                 BXE_FP_TX_LOCK(fp);
6232                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6233                     m_freem(m);
6234                 BXE_FP_TX_UNLOCK(fp);
6235             }
6236         }
6237 #endif
6238
6239         /* free all RX buffers */
6240         bxe_free_rx_bd_chain(fp);
6241         bxe_free_tpa_pool(fp);
6242         bxe_free_sge_chain(fp);
6243
6244         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6245             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6246                   fp->eth_q_stats.mbuf_alloc_rx);
6247         }
6248
6249         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6250             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6251                   fp->eth_q_stats.mbuf_alloc_sge);
6252         }
6253
6254         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6255             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6256                   fp->eth_q_stats.mbuf_alloc_tpa);
6257         }
6258
6259         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6260             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6261                   fp->eth_q_stats.mbuf_alloc_tx);
6262         }
6263
6264         /* XXX verify all mbufs were reclaimed */
6265     }
6266 }
6267
6268 static int
6269 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6270                      uint16_t            prev_index,
6271                      uint16_t            index)
6272 {
6273     struct bxe_sw_rx_bd *rx_buf;
6274     struct eth_rx_bd *rx_bd;
6275     bus_dma_segment_t segs[1];
6276     bus_dmamap_t map;
6277     struct mbuf *m;
6278     int nsegs, rc;
6279
6280     rc = 0;
6281
6282     /* allocate the new RX BD mbuf */
6283     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6284     if (__predict_false(m == NULL)) {
6285         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6286         return (ENOBUFS);
6287     }
6288
6289     fp->eth_q_stats.mbuf_alloc_rx++;
6290
6291     /* initialize the mbuf buffer length */
6292     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6293
6294     /* map the mbuf into non-paged pool */
6295     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6296                                  fp->rx_mbuf_spare_map,
6297                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6298     if (__predict_false(rc != 0)) {
6299         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6300         m_freem(m);
6301         fp->eth_q_stats.mbuf_alloc_rx--;
6302         return (rc);
6303     }
6304
6305     /* all mbufs must map to a single segment */
6306     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6307
6308     /* release any existing RX BD mbuf mappings */
6309
6310     if (prev_index != index) {
6311         rx_buf = &fp->rx_mbuf_chain[prev_index];
6312
6313         if (rx_buf->m_map != NULL) {
6314             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6315                             BUS_DMASYNC_POSTREAD);
6316             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6317         }
6318
6319         /*
6320          * We only get here from bxe_rxeof() when the maximum number
6321          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6322          * holds the mbuf in the prev_index so it's OK to NULL it out
6323          * here without concern of a memory leak.
6324          */
6325         fp->rx_mbuf_chain[prev_index].m = NULL;
6326     }
6327
6328     rx_buf = &fp->rx_mbuf_chain[index];
6329
6330     if (rx_buf->m_map != NULL) {
6331         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6332                         BUS_DMASYNC_POSTREAD);
6333         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6334     }
6335
6336     /* save the mbuf and mapping info for a future packet */
6337     map = (prev_index != index) ?
6338               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6339     rx_buf->m_map = fp->rx_mbuf_spare_map;
6340     fp->rx_mbuf_spare_map = map;
6341     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6342                     BUS_DMASYNC_PREREAD);
6343     rx_buf->m = m;
6344
6345     rx_bd = &fp->rx_chain[index];
6346     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6347     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6348
6349     return (rc);
6350 }
6351
6352 static int
6353 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6354                       int                 queue)
6355 {
6356     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6357     bus_dma_segment_t segs[1];
6358     bus_dmamap_t map;
6359     struct mbuf *m;
6360     int nsegs;
6361     int rc = 0;
6362
6363     /* allocate the new TPA mbuf */
6364     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6365     if (__predict_false(m == NULL)) {
6366         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6367         return (ENOBUFS);
6368     }
6369
6370     fp->eth_q_stats.mbuf_alloc_tpa++;
6371
6372     /* initialize the mbuf buffer length */
6373     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6374
6375     /* map the mbuf into non-paged pool */
6376     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6377                                  fp->rx_tpa_info_mbuf_spare_map,
6378                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6379     if (__predict_false(rc != 0)) {
6380         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6381         m_free(m);
6382         fp->eth_q_stats.mbuf_alloc_tpa--;
6383         return (rc);
6384     }
6385
6386     /* all mbufs must map to a single segment */
6387     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6388
6389     /* release any existing TPA mbuf mapping */
6390     if (tpa_info->bd.m_map != NULL) {
6391         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6392                         BUS_DMASYNC_POSTREAD);
6393         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6394     }
6395
6396     /* save the mbuf and mapping info for the TPA mbuf */
6397     map = tpa_info->bd.m_map;
6398     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6399     fp->rx_tpa_info_mbuf_spare_map = map;
6400     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6401                     BUS_DMASYNC_PREREAD);
6402     tpa_info->bd.m = m;
6403     tpa_info->seg = segs[0];
6404
6405     return (rc);
6406 }
6407
6408 /*
6409  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6410  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6411  * chain.
6412  */
6413 static int
6414 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6415                       uint16_t            index)
6416 {
6417     struct bxe_sw_rx_bd *sge_buf;
6418     struct eth_rx_sge *sge;
6419     bus_dma_segment_t segs[1];
6420     bus_dmamap_t map;
6421     struct mbuf *m;
6422     int nsegs;
6423     int rc = 0;
6424
6425     /* allocate a new SGE mbuf */
6426     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6427     if (__predict_false(m == NULL)) {
6428         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6429         return (ENOMEM);
6430     }
6431
6432     fp->eth_q_stats.mbuf_alloc_sge++;
6433
6434     /* initialize the mbuf buffer length */
6435     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6436
6437     /* map the SGE mbuf into non-paged pool */
6438     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6439                                  fp->rx_sge_mbuf_spare_map,
6440                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6441     if (__predict_false(rc != 0)) {
6442         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6443         m_freem(m);
6444         fp->eth_q_stats.mbuf_alloc_sge--;
6445         return (rc);
6446     }
6447
6448     /* all mbufs must map to a single segment */
6449     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6450
6451     sge_buf = &fp->rx_sge_mbuf_chain[index];
6452
6453     /* release any existing SGE mbuf mapping */
6454     if (sge_buf->m_map != NULL) {
6455         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6456                         BUS_DMASYNC_POSTREAD);
6457         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6458     }
6459
6460     /* save the mbuf and mapping info for a future packet */
6461     map = sge_buf->m_map;
6462     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6463     fp->rx_sge_mbuf_spare_map = map;
6464     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6465                     BUS_DMASYNC_PREREAD);
6466     sge_buf->m = m;
6467
6468     sge = &fp->rx_sge_chain[index];
6469     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6470     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6471
6472     return (rc);
6473 }
6474
6475 static __noinline int
6476 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6477 {
6478     struct bxe_fastpath *fp;
6479     int i, j, rc = 0;
6480     int ring_prod, cqe_ring_prod;
6481     int max_agg_queues;
6482
6483     for (i = 0; i < sc->num_queues; i++) {
6484         fp = &sc->fp[i];
6485
6486         ring_prod = cqe_ring_prod = 0;
6487         fp->rx_bd_cons = 0;
6488         fp->rx_cq_cons = 0;
6489
6490         /* allocate buffers for the RX BDs in RX BD chain */
6491         for (j = 0; j < sc->max_rx_bufs; j++) {
6492             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6493             if (rc != 0) {
6494                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6495                       i, rc);
6496                 goto bxe_alloc_fp_buffers_error;
6497             }
6498
6499             ring_prod     = RX_BD_NEXT(ring_prod);
6500             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6501         }
6502
6503         fp->rx_bd_prod = ring_prod;
6504         fp->rx_cq_prod = cqe_ring_prod;
6505         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6506
6507         max_agg_queues = MAX_AGG_QS(sc);
6508
6509         fp->tpa_enable = TRUE;
6510
6511         /* fill the TPA pool */
6512         for (j = 0; j < max_agg_queues; j++) {
6513             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6514             if (rc != 0) {
6515                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6516                           i, j);
6517                 fp->tpa_enable = FALSE;
6518                 goto bxe_alloc_fp_buffers_error;
6519             }
6520
6521             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6522         }
6523
6524         if (fp->tpa_enable) {
6525             /* fill the RX SGE chain */
6526             ring_prod = 0;
6527             for (j = 0; j < RX_SGE_USABLE; j++) {
6528                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6529                 if (rc != 0) {
6530                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6531                               i, ring_prod);
6532                     fp->tpa_enable = FALSE;
6533                     ring_prod = 0;
6534                     goto bxe_alloc_fp_buffers_error;
6535                 }
6536
6537                 ring_prod = RX_SGE_NEXT(ring_prod);
6538             }
6539
6540             fp->rx_sge_prod = ring_prod;
6541         }
6542     }
6543
6544     return (0);
6545
6546 bxe_alloc_fp_buffers_error:
6547
6548     /* unwind what was already allocated */
6549     bxe_free_rx_bd_chain(fp);
6550     bxe_free_tpa_pool(fp);
6551     bxe_free_sge_chain(fp);
6552
6553     return (ENOBUFS);
6554 }
6555
6556 static void
6557 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6558 {
6559     bxe_dma_free(sc, &sc->fw_stats_dma);
6560
6561     sc->fw_stats_num = 0;
6562
6563     sc->fw_stats_req_size = 0;
6564     sc->fw_stats_req = NULL;
6565     sc->fw_stats_req_mapping = 0;
6566
6567     sc->fw_stats_data_size = 0;
6568     sc->fw_stats_data = NULL;
6569     sc->fw_stats_data_mapping = 0;
6570 }
6571
6572 static int
6573 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6574 {
6575     uint8_t num_queue_stats;
6576     int num_groups;
6577
6578     /* number of queues for statistics is number of eth queues */
6579     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6580
6581     /*
6582      * Total number of FW statistics requests =
6583      *   1 for port stats + 1 for PF stats + num of queues
6584      */
6585     sc->fw_stats_num = (2 + num_queue_stats);
6586
6587     /*
6588      * Request is built from stats_query_header and an array of
6589      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6590      * rules. The real number or requests is configured in the
6591      * stats_query_header.
6592      */
6593     num_groups =
6594         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6595          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6596
6597     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6598           sc->fw_stats_num, num_groups);
6599
6600     sc->fw_stats_req_size =
6601         (sizeof(struct stats_query_header) +
6602          (num_groups * sizeof(struct stats_query_cmd_group)));
6603
6604     /*
6605      * Data for statistics requests + stats_counter.
6606      * stats_counter holds per-STORM counters that are incremented when
6607      * STORM has finished with the current request. Memory for FCoE
6608      * offloaded statistics are counted anyway, even if they will not be sent.
6609      * VF stats are not accounted for here as the data of VF stats is stored
6610      * in memory allocated by the VF, not here.
6611      */
6612     sc->fw_stats_data_size =
6613         (sizeof(struct stats_counter) +
6614          sizeof(struct per_port_stats) +
6615          sizeof(struct per_pf_stats) +
6616          /* sizeof(struct fcoe_statistics_params) + */
6617          (sizeof(struct per_queue_stats) * num_queue_stats));
6618
6619     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6620                       &sc->fw_stats_dma, "fw stats") != 0) {
6621         bxe_free_fw_stats_mem(sc);
6622         return (-1);
6623     }
6624
6625     /* set up the shortcuts */
6626
6627     sc->fw_stats_req =
6628         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6629     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6630
6631     sc->fw_stats_data =
6632         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6633                                      sc->fw_stats_req_size);
6634     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6635                                  sc->fw_stats_req_size);
6636
6637     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6638           (uintmax_t)sc->fw_stats_req_mapping);
6639
6640     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6641           (uintmax_t)sc->fw_stats_data_mapping);
6642
6643     return (0);
6644 }
6645
6646 /*
6647  * Bits map:
6648  * 0-7  - Engine0 load counter.
6649  * 8-15 - Engine1 load counter.
6650  * 16   - Engine0 RESET_IN_PROGRESS bit.
6651  * 17   - Engine1 RESET_IN_PROGRESS bit.
6652  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6653  *        function on the engine
6654  * 19   - Engine1 ONE_IS_LOADED.
6655  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6656  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6657  *        for just the one belonging to its engine).
6658  */
6659 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6660 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6661 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6662 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6663 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6664 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6665 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6666 #define BXE_GLOBAL_RESET_BIT      0x00040000
6667
6668 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6669 static void
6670 bxe_set_reset_global(struct bxe_softc *sc)
6671 {
6672     uint32_t val;
6673     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6674     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6675     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6676     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6677 }
6678
6679 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6680 static void
6681 bxe_clear_reset_global(struct bxe_softc *sc)
6682 {
6683     uint32_t val;
6684     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6685     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6686     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6687     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6688 }
6689
6690 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6691 static uint8_t
6692 bxe_reset_is_global(struct bxe_softc *sc)
6693 {
6694     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6695     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6696     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6697 }
6698
6699 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6700 static void
6701 bxe_set_reset_done(struct bxe_softc *sc)
6702 {
6703     uint32_t val;
6704     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6705                                  BXE_PATH0_RST_IN_PROG_BIT;
6706
6707     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6708
6709     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6710     /* Clear the bit */
6711     val &= ~bit;
6712     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6713
6714     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6715 }
6716
6717 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6718 static void
6719 bxe_set_reset_in_progress(struct bxe_softc *sc)
6720 {
6721     uint32_t val;
6722     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6723                                  BXE_PATH0_RST_IN_PROG_BIT;
6724
6725     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6726
6727     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6728     /* Set the bit */
6729     val |= bit;
6730     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6731
6732     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6733 }
6734
6735 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6736 static uint8_t
6737 bxe_reset_is_done(struct bxe_softc *sc,
6738                   int              engine)
6739 {
6740     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6741     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6742                             BXE_PATH0_RST_IN_PROG_BIT;
6743
6744     /* return false if bit is set */
6745     return (val & bit) ? FALSE : TRUE;
6746 }
6747
6748 /* get the load status for an engine, should be run under rtnl lock */
6749 static uint8_t
6750 bxe_get_load_status(struct bxe_softc *sc,
6751                     int              engine)
6752 {
6753     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6754                              BXE_PATH0_LOAD_CNT_MASK;
6755     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6756                               BXE_PATH0_LOAD_CNT_SHIFT;
6757     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6758
6759     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6760
6761     val = ((val & mask) >> shift);
6762
6763     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6764
6765     return (val != 0);
6766 }
6767
6768 /* set pf load mark */
6769 /* XXX needs to be under rtnl lock */
6770 static void
6771 bxe_set_pf_load(struct bxe_softc *sc)
6772 {
6773     uint32_t val;
6774     uint32_t val1;
6775     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6776                                   BXE_PATH0_LOAD_CNT_MASK;
6777     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6778                                    BXE_PATH0_LOAD_CNT_SHIFT;
6779
6780     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6781
6782     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6783     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6784
6785     /* get the current counter value */
6786     val1 = ((val & mask) >> shift);
6787
6788     /* set bit of this PF */
6789     val1 |= (1 << SC_ABS_FUNC(sc));
6790
6791     /* clear the old value */
6792     val &= ~mask;
6793
6794     /* set the new one */
6795     val |= ((val1 << shift) & mask);
6796
6797     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6798
6799     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6800 }
6801
6802 /* clear pf load mark */
6803 /* XXX needs to be under rtnl lock */
6804 static uint8_t
6805 bxe_clear_pf_load(struct bxe_softc *sc)
6806 {
6807     uint32_t val1, val;
6808     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6809                                   BXE_PATH0_LOAD_CNT_MASK;
6810     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6811                                    BXE_PATH0_LOAD_CNT_SHIFT;
6812
6813     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6814     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6815     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6816
6817     /* get the current counter value */
6818     val1 = (val & mask) >> shift;
6819
6820     /* clear bit of that PF */
6821     val1 &= ~(1 << SC_ABS_FUNC(sc));
6822
6823     /* clear the old value */
6824     val &= ~mask;
6825
6826     /* set the new one */
6827     val |= ((val1 << shift) & mask);
6828
6829     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6830     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6831     return (val1 != 0);
6832 }
6833
6834 /* send load requrest to mcp and analyze response */
6835 static int
6836 bxe_nic_load_request(struct bxe_softc *sc,
6837                      uint32_t         *load_code)
6838 {
6839     /* init fw_seq */
6840     sc->fw_seq =
6841         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6842          DRV_MSG_SEQ_NUMBER_MASK);
6843
6844     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6845
6846     /* get the current FW pulse sequence */
6847     sc->fw_drv_pulse_wr_seq =
6848         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6849          DRV_PULSE_SEQ_MASK);
6850
6851     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6852           sc->fw_drv_pulse_wr_seq);
6853
6854     /* load request */
6855     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6856                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6857
6858     /* if the MCP fails to respond we must abort */
6859     if (!(*load_code)) {
6860         BLOGE(sc, "MCP response failure!\n");
6861         return (-1);
6862     }
6863
6864     /* if MCP refused then must abort */
6865     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6866         BLOGE(sc, "MCP refused load request\n");
6867         return (-1);
6868     }
6869
6870     return (0);
6871 }
6872
6873 /*
6874  * Check whether another PF has already loaded FW to chip. In virtualized
6875  * environments a pf from anoth VM may have already initialized the device
6876  * including loading FW.
6877  */
6878 static int
6879 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6880                          uint32_t         load_code)
6881 {
6882     uint32_t my_fw, loaded_fw;
6883
6884     /* is another pf loaded on this engine? */
6885     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6886         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6887         /* build my FW version dword */
6888         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6889                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6890                  (BCM_5710_FW_REVISION_VERSION << 16) +
6891                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6892
6893         /* read loaded FW from chip */
6894         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6895         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6896               loaded_fw, my_fw);
6897
6898         /* abort nic load if version mismatch */
6899         if (my_fw != loaded_fw) {
6900             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6901                   loaded_fw, my_fw);
6902             return (-1);
6903         }
6904     }
6905
6906     return (0);
6907 }
6908
6909 /* mark PMF if applicable */
6910 static void
6911 bxe_nic_load_pmf(struct bxe_softc *sc,
6912                  uint32_t         load_code)
6913 {
6914     uint32_t ncsi_oem_data_addr;
6915
6916     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6917         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6918         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6919         /*
6920          * Barrier here for ordering between the writing to sc->port.pmf here
6921          * and reading it from the periodic task.
6922          */
6923         sc->port.pmf = 1;
6924         mb();
6925     } else {
6926         sc->port.pmf = 0;
6927     }
6928
6929     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6930
6931     /* XXX needed? */
6932     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6933         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6934             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6935             if (ncsi_oem_data_addr) {
6936                 REG_WR(sc,
6937                        (ncsi_oem_data_addr +
6938                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6939                        0);
6940             }
6941         }
6942     }
6943 }
6944
6945 static void
6946 bxe_read_mf_cfg(struct bxe_softc *sc)
6947 {
6948     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6949     int abs_func;
6950     int vn;
6951
6952     if (BXE_NOMCP(sc)) {
6953         return; /* what should be the default bvalue in this case */
6954     }
6955
6956     /*
6957      * The formula for computing the absolute function number is...
6958      * For 2 port configuration (4 functions per port):
6959      *   abs_func = 2 * vn + SC_PORT + SC_PATH
6960      * For 4 port configuration (2 functions per port):
6961      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6962      */
6963     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6964         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6965         if (abs_func >= E1H_FUNC_MAX) {
6966             break;
6967         }
6968         sc->devinfo.mf_info.mf_config[vn] =
6969             MFCFG_RD(sc, func_mf_config[abs_func].config);
6970     }
6971
6972     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6973         FUNC_MF_CFG_FUNC_DISABLED) {
6974         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6975         sc->flags |= BXE_MF_FUNC_DIS;
6976     } else {
6977         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6978         sc->flags &= ~BXE_MF_FUNC_DIS;
6979     }
6980 }
6981
6982 /* acquire split MCP access lock register */
6983 static int bxe_acquire_alr(struct bxe_softc *sc)
6984 {
6985     uint32_t j, val;
6986
6987     for (j = 0; j < 1000; j++) {
6988         val = (1UL << 31);
6989         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6990         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6991         if (val & (1L << 31))
6992             break;
6993
6994         DELAY(5000);
6995     }
6996
6997     if (!(val & (1L << 31))) {
6998         BLOGE(sc, "Cannot acquire MCP access lock register\n");
6999         return (-1);
7000     }
7001
7002     return (0);
7003 }
7004
7005 /* release split MCP access lock register */
7006 static void bxe_release_alr(struct bxe_softc *sc)
7007 {
7008     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
7009 }
7010
7011 static void
7012 bxe_fan_failure(struct bxe_softc *sc)
7013 {
7014     int port = SC_PORT(sc);
7015     uint32_t ext_phy_config;
7016
7017     /* mark the failure */
7018     ext_phy_config =
7019         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7020
7021     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7022     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7023     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7024              ext_phy_config);
7025
7026     /* log the failure */
7027     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7028               "the card to prevent permanent damage. "
7029               "Please contact OEM Support for assistance\n");
7030
7031     /* XXX */
7032 #if 1
7033     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7034 #else
7035     /*
7036      * Schedule device reset (unload)
7037      * This is due to some boards consuming sufficient power when driver is
7038      * up to overheat if fan fails.
7039      */
7040     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7041     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7042 #endif
7043 }
7044
7045 /* this function is called upon a link interrupt */
7046 static void
7047 bxe_link_attn(struct bxe_softc *sc)
7048 {
7049     uint32_t pause_enabled = 0;
7050     struct host_port_stats *pstats;
7051     int cmng_fns;
7052     struct bxe_fastpath *fp;
7053     int i;
7054
7055     /* Make sure that we are synced with the current statistics */
7056     bxe_stats_handle(sc, STATS_EVENT_STOP);
7057     BLOGD(sc, DBG_LOAD, "link_vars phy_flags : %x\n", sc->link_vars.phy_flags);
7058     elink_link_update(&sc->link_params, &sc->link_vars);
7059
7060     if (sc->link_vars.link_up) {
7061
7062         /* dropless flow control */
7063         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7064             pause_enabled = 0;
7065
7066             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7067                 pause_enabled = 1;
7068             }
7069
7070             REG_WR(sc,
7071                    (BAR_USTRORM_INTMEM +
7072                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7073                    pause_enabled);
7074         }
7075
7076         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7077             pstats = BXE_SP(sc, port_stats);
7078             /* reset old mac stats */
7079             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7080         }
7081
7082         if (sc->state == BXE_STATE_OPEN) {
7083             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7084             /* Restart tx when the link comes back. */
7085             FOR_EACH_ETH_QUEUE(sc, i) {
7086                 fp = &sc->fp[i];
7087                 taskqueue_enqueue(fp->tq, &fp->tx_task);
7088             }
7089         }
7090
7091     }
7092
7093     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7094         cmng_fns = bxe_get_cmng_fns_mode(sc);
7095
7096         if (cmng_fns != CMNG_FNS_NONE) {
7097             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7098             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7099         } else {
7100             /* rate shaping and fairness are disabled */
7101             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7102         }
7103     }
7104
7105     bxe_link_report_locked(sc);
7106
7107     if (IS_MF(sc)) {
7108         ; // XXX bxe_link_sync_notify(sc);
7109     }
7110 }
7111
7112 static void
7113 bxe_attn_int_asserted(struct bxe_softc *sc,
7114                       uint32_t         asserted)
7115 {
7116     int port = SC_PORT(sc);
7117     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7118                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7119     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7120                                         NIG_REG_MASK_INTERRUPT_PORT0;
7121     uint32_t aeu_mask;
7122     uint32_t nig_mask = 0;
7123     uint32_t reg_addr;
7124     uint32_t igu_acked;
7125     uint32_t cnt;
7126
7127     if (sc->attn_state & asserted) {
7128         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7129     }
7130
7131     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7132
7133     aeu_mask = REG_RD(sc, aeu_addr);
7134
7135     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7136           aeu_mask, asserted);
7137
7138     aeu_mask &= ~(asserted & 0x3ff);
7139
7140     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7141
7142     REG_WR(sc, aeu_addr, aeu_mask);
7143
7144     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7145
7146     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7147     sc->attn_state |= asserted;
7148     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7149
7150     if (asserted & ATTN_HARD_WIRED_MASK) {
7151         if (asserted & ATTN_NIG_FOR_FUNC) {
7152
7153             bxe_acquire_phy_lock(sc);
7154             /* save nig interrupt mask */
7155             nig_mask = REG_RD(sc, nig_int_mask_addr);
7156
7157             /* If nig_mask is not set, no need to call the update function */
7158             if (nig_mask) {
7159                 REG_WR(sc, nig_int_mask_addr, 0);
7160
7161                 bxe_link_attn(sc);
7162             }
7163
7164             /* handle unicore attn? */
7165         }
7166
7167         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7168             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7169         }
7170
7171         if (asserted & GPIO_2_FUNC) {
7172             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7173         }
7174
7175         if (asserted & GPIO_3_FUNC) {
7176             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7177         }
7178
7179         if (asserted & GPIO_4_FUNC) {
7180             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7181         }
7182
7183         if (port == 0) {
7184             if (asserted & ATTN_GENERAL_ATTN_1) {
7185                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7186                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7187             }
7188             if (asserted & ATTN_GENERAL_ATTN_2) {
7189                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7190                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7191             }
7192             if (asserted & ATTN_GENERAL_ATTN_3) {
7193                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7194                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7195             }
7196         } else {
7197             if (asserted & ATTN_GENERAL_ATTN_4) {
7198                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7199                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7200             }
7201             if (asserted & ATTN_GENERAL_ATTN_5) {
7202                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7203                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7204             }
7205             if (asserted & ATTN_GENERAL_ATTN_6) {
7206                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7207                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7208             }
7209         }
7210     } /* hardwired */
7211
7212     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7213         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7214     } else {
7215         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7216     }
7217
7218     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7219           asserted,
7220           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7221     REG_WR(sc, reg_addr, asserted);
7222
7223     /* now set back the mask */
7224     if (asserted & ATTN_NIG_FOR_FUNC) {
7225         /*
7226          * Verify that IGU ack through BAR was written before restoring
7227          * NIG mask. This loop should exit after 2-3 iterations max.
7228          */
7229         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7230             cnt = 0;
7231
7232             do {
7233                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7234             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7235                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7236
7237             if (!igu_acked) {
7238                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7239             }
7240
7241             mb();
7242         }
7243
7244         REG_WR(sc, nig_int_mask_addr, nig_mask);
7245
7246         bxe_release_phy_lock(sc);
7247     }
7248 }
7249
7250 static void
7251 bxe_print_next_block(struct bxe_softc *sc,
7252                      int              idx,
7253                      const char       *blk)
7254 {
7255     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7256 }
7257
7258 static int
7259 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7260                               uint32_t         sig,
7261                               int              par_num,
7262                               uint8_t          print)
7263 {
7264     uint32_t cur_bit = 0;
7265     int i = 0;
7266
7267     for (i = 0; sig; i++) {
7268         cur_bit = ((uint32_t)0x1 << i);
7269         if (sig & cur_bit) {
7270             switch (cur_bit) {
7271             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7272                 if (print)
7273                     bxe_print_next_block(sc, par_num++, "BRB");
7274                 break;
7275             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7276                 if (print)
7277                     bxe_print_next_block(sc, par_num++, "PARSER");
7278                 break;
7279             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7280                 if (print)
7281                     bxe_print_next_block(sc, par_num++, "TSDM");
7282                 break;
7283             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7284                 if (print)
7285                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7286                 break;
7287             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7288                 if (print)
7289                     bxe_print_next_block(sc, par_num++, "TCM");
7290                 break;
7291             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7292                 if (print)
7293                     bxe_print_next_block(sc, par_num++, "TSEMI");
7294                 break;
7295             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7296                 if (print)
7297                     bxe_print_next_block(sc, par_num++, "XPB");
7298                 break;
7299             }
7300
7301             /* Clear the bit */
7302             sig &= ~cur_bit;
7303         }
7304     }
7305
7306     return (par_num);
7307 }
7308
7309 static int
7310 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7311                               uint32_t         sig,
7312                               int              par_num,
7313                               uint8_t          *global,
7314                               uint8_t          print)
7315 {
7316     int i = 0;
7317     uint32_t cur_bit = 0;
7318     for (i = 0; sig; i++) {
7319         cur_bit = ((uint32_t)0x1 << i);
7320         if (sig & cur_bit) {
7321             switch (cur_bit) {
7322             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7323                 if (print)
7324                     bxe_print_next_block(sc, par_num++, "PBF");
7325                 break;
7326             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7327                 if (print)
7328                     bxe_print_next_block(sc, par_num++, "QM");
7329                 break;
7330             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7331                 if (print)
7332                     bxe_print_next_block(sc, par_num++, "TM");
7333                 break;
7334             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7335                 if (print)
7336                     bxe_print_next_block(sc, par_num++, "XSDM");
7337                 break;
7338             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7339                 if (print)
7340                     bxe_print_next_block(sc, par_num++, "XCM");
7341                 break;
7342             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7343                 if (print)
7344                     bxe_print_next_block(sc, par_num++, "XSEMI");
7345                 break;
7346             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7347                 if (print)
7348                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7349                 break;
7350             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7351                 if (print)
7352                     bxe_print_next_block(sc, par_num++, "NIG");
7353                 break;
7354             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7355                 if (print)
7356                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7357                 *global = TRUE;
7358                 break;
7359             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7360                 if (print)
7361                     bxe_print_next_block(sc, par_num++, "DEBUG");
7362                 break;
7363             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7364                 if (print)
7365                     bxe_print_next_block(sc, par_num++, "USDM");
7366                 break;
7367             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7368                 if (print)
7369                     bxe_print_next_block(sc, par_num++, "UCM");
7370                 break;
7371             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7372                 if (print)
7373                     bxe_print_next_block(sc, par_num++, "USEMI");
7374                 break;
7375             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7376                 if (print)
7377                     bxe_print_next_block(sc, par_num++, "UPB");
7378                 break;
7379             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7380                 if (print)
7381                     bxe_print_next_block(sc, par_num++, "CSDM");
7382                 break;
7383             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7384                 if (print)
7385                     bxe_print_next_block(sc, par_num++, "CCM");
7386                 break;
7387             }
7388
7389             /* Clear the bit */
7390             sig &= ~cur_bit;
7391         }
7392     }
7393
7394     return (par_num);
7395 }
7396
7397 static int
7398 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7399                               uint32_t         sig,
7400                               int              par_num,
7401                               uint8_t          print)
7402 {
7403     uint32_t cur_bit = 0;
7404     int i = 0;
7405
7406     for (i = 0; sig; i++) {
7407         cur_bit = ((uint32_t)0x1 << i);
7408         if (sig & cur_bit) {
7409             switch (cur_bit) {
7410             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7411                 if (print)
7412                     bxe_print_next_block(sc, par_num++, "CSEMI");
7413                 break;
7414             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7415                 if (print)
7416                     bxe_print_next_block(sc, par_num++, "PXP");
7417                 break;
7418             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7419                 if (print)
7420                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7421                 break;
7422             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7423                 if (print)
7424                     bxe_print_next_block(sc, par_num++, "CFC");
7425                 break;
7426             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7427                 if (print)
7428                     bxe_print_next_block(sc, par_num++, "CDU");
7429                 break;
7430             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7431                 if (print)
7432                     bxe_print_next_block(sc, par_num++, "DMAE");
7433                 break;
7434             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7435                 if (print)
7436                     bxe_print_next_block(sc, par_num++, "IGU");
7437                 break;
7438             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7439                 if (print)
7440                     bxe_print_next_block(sc, par_num++, "MISC");
7441                 break;
7442             }
7443
7444             /* Clear the bit */
7445             sig &= ~cur_bit;
7446         }
7447     }
7448
7449     return (par_num);
7450 }
7451
7452 static int
7453 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7454                               uint32_t         sig,
7455                               int              par_num,
7456                               uint8_t          *global,
7457                               uint8_t          print)
7458 {
7459     uint32_t cur_bit = 0;
7460     int i = 0;
7461
7462     for (i = 0; sig; i++) {
7463         cur_bit = ((uint32_t)0x1 << i);
7464         if (sig & cur_bit) {
7465             switch (cur_bit) {
7466             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7467                 if (print)
7468                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7469                 *global = TRUE;
7470                 break;
7471             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7472                 if (print)
7473                     bxe_print_next_block(sc, par_num++,
7474                               "MCP UMP RX");
7475                 *global = TRUE;
7476                 break;
7477             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7478                 if (print)
7479                     bxe_print_next_block(sc, par_num++,
7480                               "MCP UMP TX");
7481                 *global = TRUE;
7482                 break;
7483             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7484                 if (print)
7485                     bxe_print_next_block(sc, par_num++,
7486                               "MCP SCPAD");
7487                 *global = TRUE;
7488                 break;
7489             }
7490
7491             /* Clear the bit */
7492             sig &= ~cur_bit;
7493         }
7494     }
7495
7496     return (par_num);
7497 }
7498
7499 static int
7500 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7501                               uint32_t         sig,
7502                               int              par_num,
7503                               uint8_t          print)
7504 {
7505     uint32_t cur_bit = 0;
7506     int i = 0;
7507
7508     for (i = 0; sig; i++) {
7509         cur_bit = ((uint32_t)0x1 << i);
7510         if (sig & cur_bit) {
7511             switch (cur_bit) {
7512             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7513                 if (print)
7514                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7515                 break;
7516             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7517                 if (print)
7518                     bxe_print_next_block(sc, par_num++, "ATC");
7519                 break;
7520             }
7521
7522             /* Clear the bit */
7523             sig &= ~cur_bit;
7524         }
7525     }
7526
7527     return (par_num);
7528 }
7529
7530 static uint8_t
7531 bxe_parity_attn(struct bxe_softc *sc,
7532                 uint8_t          *global,
7533                 uint8_t          print,
7534                 uint32_t         *sig)
7535 {
7536     int par_num = 0;
7537
7538     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7539         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7540         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7541         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7542         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7543         BLOGE(sc, "Parity error: HW block parity attention:\n"
7544                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7545               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7546               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7547               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7548               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7549               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7550
7551         if (print)
7552             BLOGI(sc, "Parity errors detected in blocks: ");
7553
7554         par_num =
7555             bxe_check_blocks_with_parity0(sc, sig[0] &
7556                                           HW_PRTY_ASSERT_SET_0,
7557                                           par_num, print);
7558         par_num =
7559             bxe_check_blocks_with_parity1(sc, sig[1] &
7560                                           HW_PRTY_ASSERT_SET_1,
7561                                           par_num, global, print);
7562         par_num =
7563             bxe_check_blocks_with_parity2(sc, sig[2] &
7564                                           HW_PRTY_ASSERT_SET_2,
7565                                           par_num, print);
7566         par_num =
7567             bxe_check_blocks_with_parity3(sc, sig[3] &
7568                                           HW_PRTY_ASSERT_SET_3,
7569                                           par_num, global, print);
7570         par_num =
7571             bxe_check_blocks_with_parity4(sc, sig[4] &
7572                                           HW_PRTY_ASSERT_SET_4,
7573                                           par_num, print);
7574
7575         if (print)
7576             BLOGI(sc, "\n");
7577
7578         return (TRUE);
7579     }
7580
7581     return (FALSE);
7582 }
7583
7584 static uint8_t
7585 bxe_chk_parity_attn(struct bxe_softc *sc,
7586                     uint8_t          *global,
7587                     uint8_t          print)
7588 {
7589     struct attn_route attn = { {0} };
7590     int port = SC_PORT(sc);
7591
7592     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7593     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7594     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7595     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7596
7597     /*
7598      * Since MCP attentions can't be disabled inside the block, we need to
7599      * read AEU registers to see whether they're currently disabled
7600      */
7601     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7602                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7603                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7604                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7605
7606
7607     if (!CHIP_IS_E1x(sc))
7608         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7609
7610     return (bxe_parity_attn(sc, global, print, attn.sig));
7611 }
7612
7613 static void
7614 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7615                          uint32_t         attn)
7616 {
7617     uint32_t val;
7618
7619     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7620         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7621         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7622         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7623             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7624         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7625             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7626         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7627             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7628         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7629             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7630         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7631             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7632         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7633             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7634         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7635             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7636         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7637             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7638         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7639             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7640     }
7641
7642     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7643         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7644         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7645         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7646             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7647         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7648             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7649         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7650             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7651         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7652             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7653         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7654             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7655         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7656             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7657     }
7658
7659     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7660                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7661         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7662               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7663                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7664     }
7665 }
7666
7667 static void
7668 bxe_e1h_disable(struct bxe_softc *sc)
7669 {
7670     int port = SC_PORT(sc);
7671
7672     bxe_tx_disable(sc);
7673
7674     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7675 }
7676
7677 static void
7678 bxe_e1h_enable(struct bxe_softc *sc)
7679 {
7680     int port = SC_PORT(sc);
7681
7682     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7683
7684     // XXX bxe_tx_enable(sc);
7685 }
7686
7687 /*
7688  * called due to MCP event (on pmf):
7689  *   reread new bandwidth configuration
7690  *   configure FW
7691  *   notify others function about the change
7692  */
7693 static void
7694 bxe_config_mf_bw(struct bxe_softc *sc)
7695 {
7696     if (sc->link_vars.link_up) {
7697         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7698         // XXX bxe_link_sync_notify(sc);
7699     }
7700
7701     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7702 }
7703
7704 static void
7705 bxe_set_mf_bw(struct bxe_softc *sc)
7706 {
7707     bxe_config_mf_bw(sc);
7708     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7709 }
7710
7711 static void
7712 bxe_handle_eee_event(struct bxe_softc *sc)
7713 {
7714     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7715     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7716 }
7717
7718 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7719
7720 static void
7721 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7722 {
7723     struct eth_stats_info *ether_stat =
7724         &sc->sp->drv_info_to_mcp.ether_stat;
7725
7726     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7727             ETH_STAT_INFO_VERSION_LEN);
7728
7729     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7730     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7731                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7732                                           ether_stat->mac_local + MAC_PAD,
7733                                           MAC_PAD, ETH_ALEN);
7734
7735     ether_stat->mtu_size = sc->mtu;
7736
7737     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7738     if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
7739         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7740     }
7741
7742     // XXX ether_stat->feature_flags |= ???;
7743
7744     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7745
7746     ether_stat->txq_size = sc->tx_ring_size;
7747     ether_stat->rxq_size = sc->rx_ring_size;
7748 }
7749
7750 static void
7751 bxe_handle_drv_info_req(struct bxe_softc *sc)
7752 {
7753     enum drv_info_opcode op_code;
7754     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7755
7756     /* if drv_info version supported by MFW doesn't match - send NACK */
7757     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7758         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7759         return;
7760     }
7761
7762     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7763                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7764
7765     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7766
7767     switch (op_code) {
7768     case ETH_STATS_OPCODE:
7769         bxe_drv_info_ether_stat(sc);
7770         break;
7771     case FCOE_STATS_OPCODE:
7772     case ISCSI_STATS_OPCODE:
7773     default:
7774         /* if op code isn't supported - send NACK */
7775         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7776         return;
7777     }
7778
7779     /*
7780      * If we got drv_info attn from MFW then these fields are defined in
7781      * shmem2 for sure
7782      */
7783     SHMEM2_WR(sc, drv_info_host_addr_lo,
7784               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7785     SHMEM2_WR(sc, drv_info_host_addr_hi,
7786               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7787
7788     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7789 }
7790
7791 static void
7792 bxe_dcc_event(struct bxe_softc *sc,
7793               uint32_t         dcc_event)
7794 {
7795     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7796
7797     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7798         /*
7799          * This is the only place besides the function initialization
7800          * where the sc->flags can change so it is done without any
7801          * locks
7802          */
7803         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7804             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7805             sc->flags |= BXE_MF_FUNC_DIS;
7806             bxe_e1h_disable(sc);
7807         } else {
7808             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7809             sc->flags &= ~BXE_MF_FUNC_DIS;
7810             bxe_e1h_enable(sc);
7811         }
7812         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7813     }
7814
7815     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7816         bxe_config_mf_bw(sc);
7817         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7818     }
7819
7820     /* Report results to MCP */
7821     if (dcc_event)
7822         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7823     else
7824         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7825 }
7826
7827 static void
7828 bxe_pmf_update(struct bxe_softc *sc)
7829 {
7830     int port = SC_PORT(sc);
7831     uint32_t val;
7832
7833     sc->port.pmf = 1;
7834     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7835
7836     /*
7837      * We need the mb() to ensure the ordering between the writing to
7838      * sc->port.pmf here and reading it from the bxe_periodic_task().
7839      */
7840     mb();
7841
7842     /* queue a periodic task */
7843     // XXX schedule task...
7844
7845     // XXX bxe_dcbx_pmf_update(sc);
7846
7847     /* enable nig attention */
7848     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7849     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7850         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7851         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7852     } else if (!CHIP_IS_E1x(sc)) {
7853         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7854         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7855     }
7856
7857     bxe_stats_handle(sc, STATS_EVENT_PMF);
7858 }
7859
7860 static int
7861 bxe_mc_assert(struct bxe_softc *sc)
7862 {
7863     char last_idx;
7864     int i, rc = 0;
7865     uint32_t row0, row1, row2, row3;
7866
7867     /* XSTORM */
7868     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7869     if (last_idx)
7870         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7871
7872     /* print the asserts */
7873     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7874
7875         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7876         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7877         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7878         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7879
7880         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7881             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7882                   i, row3, row2, row1, row0);
7883             rc++;
7884         } else {
7885             break;
7886         }
7887     }
7888
7889     /* TSTORM */
7890     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7891     if (last_idx) {
7892         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7893     }
7894
7895     /* print the asserts */
7896     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7897
7898         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7899         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7900         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7901         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7902
7903         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7904             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7905                   i, row3, row2, row1, row0);
7906             rc++;
7907         } else {
7908             break;
7909         }
7910     }
7911
7912     /* CSTORM */
7913     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7914     if (last_idx) {
7915         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7916     }
7917
7918     /* print the asserts */
7919     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7920
7921         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7922         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7923         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7924         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7925
7926         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7927             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7928                   i, row3, row2, row1, row0);
7929             rc++;
7930         } else {
7931             break;
7932         }
7933     }
7934
7935     /* USTORM */
7936     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7937     if (last_idx) {
7938         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7939     }
7940
7941     /* print the asserts */
7942     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7943
7944         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7945         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7946         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7947         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7948
7949         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7950             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7951                   i, row3, row2, row1, row0);
7952             rc++;
7953         } else {
7954             break;
7955         }
7956     }
7957
7958     return (rc);
7959 }
7960
7961 static void
7962 bxe_attn_int_deasserted3(struct bxe_softc *sc,
7963                          uint32_t         attn)
7964 {
7965     int func = SC_FUNC(sc);
7966     uint32_t val;
7967
7968     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7969
7970         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7971
7972             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7973             bxe_read_mf_cfg(sc);
7974             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7975                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7976             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7977
7978             if (val & DRV_STATUS_DCC_EVENT_MASK)
7979                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7980
7981             if (val & DRV_STATUS_SET_MF_BW)
7982                 bxe_set_mf_bw(sc);
7983
7984             if (val & DRV_STATUS_DRV_INFO_REQ)
7985                 bxe_handle_drv_info_req(sc);
7986
7987             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
7988                 bxe_pmf_update(sc);
7989
7990             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
7991                 bxe_handle_eee_event(sc);
7992
7993             if (sc->link_vars.periodic_flags &
7994                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
7995                 /* sync with link */
7996                 bxe_acquire_phy_lock(sc);
7997                 sc->link_vars.periodic_flags &=
7998                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
7999                 bxe_release_phy_lock(sc);
8000                 if (IS_MF(sc))
8001                     ; // XXX bxe_link_sync_notify(sc);
8002                 bxe_link_report(sc);
8003             }
8004
8005             /*
8006              * Always call it here: bxe_link_report() will
8007              * prevent the link indication duplication.
8008              */
8009             bxe_link_status_update(sc);
8010
8011         } else if (attn & BXE_MC_ASSERT_BITS) {
8012
8013             BLOGE(sc, "MC assert!\n");
8014             bxe_mc_assert(sc);
8015             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8016             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8017             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8018             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8019             bxe_panic(sc, ("MC assert!\n"));
8020
8021         } else if (attn & BXE_MCP_ASSERT) {
8022
8023             BLOGE(sc, "MCP assert!\n");
8024             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8025             // XXX bxe_fw_dump(sc);
8026
8027         } else {
8028             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8029         }
8030     }
8031
8032     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8033         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8034         if (attn & BXE_GRC_TIMEOUT) {
8035             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8036             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8037         }
8038         if (attn & BXE_GRC_RSV) {
8039             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8040             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8041         }
8042         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8043     }
8044 }
8045
8046 static void
8047 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8048                          uint32_t         attn)
8049 {
8050     int port = SC_PORT(sc);
8051     int reg_offset;
8052     uint32_t val0, mask0, val1, mask1;
8053     uint32_t val;
8054
8055     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8056         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8057         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8058         /* CFC error attention */
8059         if (val & 0x2) {
8060             BLOGE(sc, "FATAL error from CFC\n");
8061         }
8062     }
8063
8064     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8065         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8066         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8067         /* RQ_USDMDP_FIFO_OVERFLOW */
8068         if (val & 0x18000) {
8069             BLOGE(sc, "FATAL error from PXP\n");
8070         }
8071
8072         if (!CHIP_IS_E1x(sc)) {
8073             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8074             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8075         }
8076     }
8077
8078 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8079 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8080
8081     if (attn & AEU_PXP2_HW_INT_BIT) {
8082         /*  CQ47854 workaround do not panic on
8083          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8084          */
8085         if (!CHIP_IS_E1x(sc)) {
8086             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8087             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8088             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8089             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8090             /*
8091              * If the olny PXP2_EOP_ERROR_BIT is set in
8092              * STS0 and STS1 - clear it
8093              *
8094              * probably we lose additional attentions between
8095              * STS0 and STS_CLR0, in this case user will not
8096              * be notified about them
8097              */
8098             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8099                 !(val1 & mask1))
8100                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8101
8102             /* print the register, since no one can restore it */
8103             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8104
8105             /*
8106              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8107              * then notify
8108              */
8109             if (val0 & PXP2_EOP_ERROR_BIT) {
8110                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8111
8112                 /*
8113                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8114                  * set then clear attention from PXP2 block without panic
8115                  */
8116                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8117                     ((val1 & mask1) == 0))
8118                     attn &= ~AEU_PXP2_HW_INT_BIT;
8119             }
8120         }
8121     }
8122
8123     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8124         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8125                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8126
8127         val = REG_RD(sc, reg_offset);
8128         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8129         REG_WR(sc, reg_offset, val);
8130
8131         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8132               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8133         bxe_panic(sc, ("HW block attention set2\n"));
8134     }
8135 }
8136
8137 static void
8138 bxe_attn_int_deasserted1(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     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8146         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8147         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8148         /* DORQ discard attention */
8149         if (val & 0x2) {
8150             BLOGE(sc, "FATAL error from DORQ\n");
8151         }
8152     }
8153
8154     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8155         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8156                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8157
8158         val = REG_RD(sc, reg_offset);
8159         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8160         REG_WR(sc, reg_offset, val);
8161
8162         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8163               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8164         bxe_panic(sc, ("HW block attention set1\n"));
8165     }
8166 }
8167
8168 static void
8169 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8170                          uint32_t         attn)
8171 {
8172     int port = SC_PORT(sc);
8173     int reg_offset;
8174     uint32_t val;
8175
8176     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8177                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8178
8179     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8180         val = REG_RD(sc, reg_offset);
8181         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8182         REG_WR(sc, reg_offset, val);
8183
8184         BLOGW(sc, "SPIO5 hw attention\n");
8185
8186         /* Fan failure attention */
8187         elink_hw_reset_phy(&sc->link_params);
8188         bxe_fan_failure(sc);
8189     }
8190
8191     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8192         bxe_acquire_phy_lock(sc);
8193         elink_handle_module_detect_int(&sc->link_params);
8194         bxe_release_phy_lock(sc);
8195     }
8196
8197     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8198         val = REG_RD(sc, reg_offset);
8199         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8200         REG_WR(sc, reg_offset, val);
8201
8202         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8203                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8204     }
8205 }
8206
8207 static void
8208 bxe_attn_int_deasserted(struct bxe_softc *sc,
8209                         uint32_t         deasserted)
8210 {
8211     struct attn_route attn;
8212     struct attn_route *group_mask;
8213     int port = SC_PORT(sc);
8214     int index;
8215     uint32_t reg_addr;
8216     uint32_t val;
8217     uint32_t aeu_mask;
8218     uint8_t global = FALSE;
8219
8220     /*
8221      * Need to take HW lock because MCP or other port might also
8222      * try to handle this event.
8223      */
8224     bxe_acquire_alr(sc);
8225
8226     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8227         /* XXX
8228          * In case of parity errors don't handle attentions so that
8229          * other function would "see" parity errors.
8230          */
8231         sc->recovery_state = BXE_RECOVERY_INIT;
8232         // XXX schedule a recovery task...
8233         /* disable HW interrupts */
8234         bxe_int_disable(sc);
8235         bxe_release_alr(sc);
8236         return;
8237     }
8238
8239     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8240     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8241     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8242     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8243     if (!CHIP_IS_E1x(sc)) {
8244         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8245     } else {
8246         attn.sig[4] = 0;
8247     }
8248
8249     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8250           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8251
8252     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8253         if (deasserted & (1 << index)) {
8254             group_mask = &sc->attn_group[index];
8255
8256             BLOGD(sc, DBG_INTR,
8257                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8258                   group_mask->sig[0], group_mask->sig[1],
8259                   group_mask->sig[2], group_mask->sig[3],
8260                   group_mask->sig[4]);
8261
8262             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8263             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8264             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8265             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8266             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8267         }
8268     }
8269
8270     bxe_release_alr(sc);
8271
8272     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8273         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8274                     COMMAND_REG_ATTN_BITS_CLR);
8275     } else {
8276         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8277     }
8278
8279     val = ~deasserted;
8280     BLOGD(sc, DBG_INTR,
8281           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8282           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8283     REG_WR(sc, reg_addr, val);
8284
8285     if (~sc->attn_state & deasserted) {
8286         BLOGE(sc, "IGU error\n");
8287     }
8288
8289     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8290                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8291
8292     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8293
8294     aeu_mask = REG_RD(sc, reg_addr);
8295
8296     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8297           aeu_mask, deasserted);
8298     aeu_mask |= (deasserted & 0x3ff);
8299     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8300
8301     REG_WR(sc, reg_addr, aeu_mask);
8302     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8303
8304     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8305     sc->attn_state &= ~deasserted;
8306     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8307 }
8308
8309 static void
8310 bxe_attn_int(struct bxe_softc *sc)
8311 {
8312     /* read local copy of bits */
8313     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8314     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8315     uint32_t attn_state = sc->attn_state;
8316
8317     /* look for changed bits */
8318     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8319     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8320
8321     BLOGD(sc, DBG_INTR,
8322           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8323           attn_bits, attn_ack, asserted, deasserted);
8324
8325     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8326         BLOGE(sc, "BAD attention state\n");
8327     }
8328
8329     /* handle bits that were raised */
8330     if (asserted) {
8331         bxe_attn_int_asserted(sc, asserted);
8332     }
8333
8334     if (deasserted) {
8335         bxe_attn_int_deasserted(sc, deasserted);
8336     }
8337 }
8338
8339 static uint16_t
8340 bxe_update_dsb_idx(struct bxe_softc *sc)
8341 {
8342     struct host_sp_status_block *def_sb = sc->def_sb;
8343     uint16_t rc = 0;
8344
8345     mb(); /* status block is written to by the chip */
8346
8347     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8348         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8349         rc |= BXE_DEF_SB_ATT_IDX;
8350     }
8351
8352     if (sc->def_idx != def_sb->sp_sb.running_index) {
8353         sc->def_idx = def_sb->sp_sb.running_index;
8354         rc |= BXE_DEF_SB_IDX;
8355     }
8356
8357     mb();
8358
8359     return (rc);
8360 }
8361
8362 static inline struct ecore_queue_sp_obj *
8363 bxe_cid_to_q_obj(struct bxe_softc *sc,
8364                  uint32_t         cid)
8365 {
8366     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8367     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8368 }
8369
8370 static void
8371 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8372 {
8373     struct ecore_mcast_ramrod_params rparam;
8374     int rc;
8375
8376     memset(&rparam, 0, sizeof(rparam));
8377
8378     rparam.mcast_obj = &sc->mcast_obj;
8379
8380     BXE_MCAST_LOCK(sc);
8381
8382     /* clear pending state for the last command */
8383     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8384
8385     /* if there are pending mcast commands - send them */
8386     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8387         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8388         if (rc < 0) {
8389             BLOGD(sc, DBG_SP,
8390                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8391         }
8392     }
8393
8394     BXE_MCAST_UNLOCK(sc);
8395 }
8396
8397 static void
8398 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8399                               union event_ring_elem *elem)
8400 {
8401     unsigned long ramrod_flags = 0;
8402     int rc = 0;
8403     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8404     struct ecore_vlan_mac_obj *vlan_mac_obj;
8405
8406     /* always push next commands out, don't wait here */
8407     bit_set(&ramrod_flags, RAMROD_CONT);
8408
8409     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8410     case ECORE_FILTER_MAC_PENDING:
8411         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8412         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8413         break;
8414
8415     case ECORE_FILTER_MCAST_PENDING:
8416         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8417         /*
8418          * This is only relevant for 57710 where multicast MACs are
8419          * configured as unicast MACs using the same ramrod.
8420          */
8421         bxe_handle_mcast_eqe(sc);
8422         return;
8423
8424     default:
8425         BLOGE(sc, "Unsupported classification command: %d\n",
8426               elem->message.data.eth_event.echo);
8427         return;
8428     }
8429
8430     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8431
8432     if (rc < 0) {
8433         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8434     } else if (rc > 0) {
8435         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8436     }
8437 }
8438
8439 static void
8440 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8441                        union event_ring_elem *elem)
8442 {
8443     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8444
8445     /* send rx_mode command again if was requested */
8446     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8447                                &sc->sp_state)) {
8448         bxe_set_storm_rx_mode(sc);
8449     }
8450 }
8451
8452 static void
8453 bxe_update_eq_prod(struct bxe_softc *sc,
8454                    uint16_t         prod)
8455 {
8456     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8457     wmb(); /* keep prod updates ordered */
8458 }
8459
8460 static void
8461 bxe_eq_int(struct bxe_softc *sc)
8462 {
8463     uint16_t hw_cons, sw_cons, sw_prod;
8464     union event_ring_elem *elem;
8465     uint8_t echo;
8466     uint32_t cid;
8467     uint8_t opcode;
8468     int spqe_cnt = 0;
8469     struct ecore_queue_sp_obj *q_obj;
8470     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8471     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8472
8473     hw_cons = le16toh(*sc->eq_cons_sb);
8474
8475     /*
8476      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8477      * when we get to the next-page we need to adjust so the loop
8478      * condition below will be met. The next element is the size of a
8479      * regular element and hence incrementing by 1
8480      */
8481     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8482         hw_cons++;
8483     }
8484
8485     /*
8486      * This function may never run in parallel with itself for a
8487      * specific sc and no need for a read memory barrier here.
8488      */
8489     sw_cons = sc->eq_cons;
8490     sw_prod = sc->eq_prod;
8491
8492     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8493           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8494
8495     for (;
8496          sw_cons != hw_cons;
8497          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8498
8499         elem = &sc->eq[EQ_DESC(sw_cons)];
8500
8501         /* elem CID originates from FW, actually LE */
8502         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8503         opcode = elem->message.opcode;
8504
8505         /* handle eq element */
8506         switch (opcode) {
8507
8508         case EVENT_RING_OPCODE_STAT_QUERY:
8509             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8510                   sc->stats_comp++);
8511             /* nothing to do with stats comp */
8512             goto next_spqe;
8513
8514         case EVENT_RING_OPCODE_CFC_DEL:
8515             /* handle according to cid range */
8516             /* we may want to verify here that the sc state is HALTING */
8517             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8518             q_obj = bxe_cid_to_q_obj(sc, cid);
8519             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8520                 break;
8521             }
8522             goto next_spqe;
8523
8524         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8525             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8526             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8527                 break;
8528             }
8529             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8530             goto next_spqe;
8531
8532         case EVENT_RING_OPCODE_START_TRAFFIC:
8533             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8534             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8535                 break;
8536             }
8537             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8538             goto next_spqe;
8539
8540         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8541             echo = elem->message.data.function_update_event.echo;
8542             if (echo == SWITCH_UPDATE) {
8543                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8544                 if (f_obj->complete_cmd(sc, f_obj,
8545                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8546                     break;
8547                 }
8548             }
8549             else {
8550                 BLOGD(sc, DBG_SP,
8551                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8552             }
8553             goto next_spqe;
8554
8555         case EVENT_RING_OPCODE_FORWARD_SETUP:
8556             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8557             if (q_obj->complete_cmd(sc, q_obj,
8558                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8559                 break;
8560             }
8561             goto next_spqe;
8562
8563         case EVENT_RING_OPCODE_FUNCTION_START:
8564             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8565             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8566                 break;
8567             }
8568             goto next_spqe;
8569
8570         case EVENT_RING_OPCODE_FUNCTION_STOP:
8571             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8572             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8573                 break;
8574             }
8575             goto next_spqe;
8576         }
8577
8578         switch (opcode | sc->state) {
8579         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8580         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8581             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8582             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8583             rss_raw->clear_pending(rss_raw);
8584             break;
8585
8586         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8587         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8588         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8589         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8590         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8591         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8592             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8593             bxe_handle_classification_eqe(sc, elem);
8594             break;
8595
8596         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8597         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8598         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8599             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8600             bxe_handle_mcast_eqe(sc);
8601             break;
8602
8603         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8604         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8605         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8606             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8607             bxe_handle_rx_mode_eqe(sc, elem);
8608             break;
8609
8610         default:
8611             /* unknown event log error and continue */
8612             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8613                   elem->message.opcode, sc->state);
8614         }
8615
8616 next_spqe:
8617         spqe_cnt++;
8618     } /* for */
8619
8620     mb();
8621     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8622
8623     sc->eq_cons = sw_cons;
8624     sc->eq_prod = sw_prod;
8625
8626     /* make sure that above mem writes were issued towards the memory */
8627     wmb();
8628
8629     /* update producer */
8630     bxe_update_eq_prod(sc, sc->eq_prod);
8631 }
8632
8633 static void
8634 bxe_handle_sp_tq(void *context,
8635                  int  pending)
8636 {
8637     struct bxe_softc *sc = (struct bxe_softc *)context;
8638     uint16_t status;
8639
8640     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8641
8642     /* what work needs to be performed? */
8643     status = bxe_update_dsb_idx(sc);
8644
8645     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8646
8647     /* HW attentions */
8648     if (status & BXE_DEF_SB_ATT_IDX) {
8649         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8650         bxe_attn_int(sc);
8651         status &= ~BXE_DEF_SB_ATT_IDX;
8652     }
8653
8654     /* SP events: STAT_QUERY and others */
8655     if (status & BXE_DEF_SB_IDX) {
8656         /* handle EQ completions */
8657         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8658         bxe_eq_int(sc);
8659         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8660                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8661         status &= ~BXE_DEF_SB_IDX;
8662     }
8663
8664     /* if status is non zero then something went wrong */
8665     if (__predict_false(status)) {
8666         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8667     }
8668
8669     /* ack status block only if something was actually handled */
8670     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8671                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8672
8673     /*
8674      * Must be called after the EQ processing (since eq leads to sriov
8675      * ramrod completion flows).
8676      * This flow may have been scheduled by the arrival of a ramrod
8677      * completion, or by the sriov code rescheduling itself.
8678      */
8679     // XXX bxe_iov_sp_task(sc);
8680
8681 }
8682
8683 static void
8684 bxe_handle_fp_tq(void *context,
8685                  int  pending)
8686 {
8687     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8688     struct bxe_softc *sc = fp->sc;
8689     uint8_t more_tx = FALSE;
8690     uint8_t more_rx = FALSE;
8691
8692     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8693
8694     /* XXX
8695      * IFF_DRV_RUNNING state can't be checked here since we process
8696      * slowpath events on a client queue during setup. Instead
8697      * we need to add a "process/continue" flag here that the driver
8698      * can use to tell the task here not to do anything.
8699      */
8700 #if 0
8701     if (!(sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
8702         return;
8703     }
8704 #endif
8705
8706     /* update the fastpath index */
8707     bxe_update_fp_sb_idx(fp);
8708
8709     /* XXX add loop here if ever support multiple tx CoS */
8710     /* fp->txdata[cos] */
8711     if (bxe_has_tx_work(fp)) {
8712         BXE_FP_TX_LOCK(fp);
8713         more_tx = bxe_txeof(sc, fp);
8714         BXE_FP_TX_UNLOCK(fp);
8715     }
8716
8717     if (bxe_has_rx_work(fp)) {
8718         more_rx = bxe_rxeof(sc, fp);
8719     }
8720
8721     if (more_rx /*|| more_tx*/) {
8722         /* still more work to do */
8723         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8724         return;
8725     }
8726
8727     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8728                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8729 }
8730
8731 static void
8732 bxe_task_fp(struct bxe_fastpath *fp)
8733 {
8734     struct bxe_softc *sc = fp->sc;
8735     uint8_t more_tx = FALSE;
8736     uint8_t more_rx = FALSE;
8737
8738     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8739
8740     /* update the fastpath index */
8741     bxe_update_fp_sb_idx(fp);
8742
8743     /* XXX add loop here if ever support multiple tx CoS */
8744     /* fp->txdata[cos] */
8745     if (bxe_has_tx_work(fp)) {
8746         BXE_FP_TX_LOCK(fp);
8747         more_tx = bxe_txeof(sc, fp);
8748         BXE_FP_TX_UNLOCK(fp);
8749     }
8750
8751     if (bxe_has_rx_work(fp)) {
8752         more_rx = bxe_rxeof(sc, fp);
8753     }
8754
8755     if (more_rx /*|| more_tx*/) {
8756         /* still more work to do, bail out if this ISR and process later */
8757         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8758         return;
8759     }
8760
8761     /*
8762      * Here we write the fastpath index taken before doing any tx or rx work.
8763      * It is very well possible other hw events occurred up to this point and
8764      * they were actually processed accordingly above. Since we're going to
8765      * write an older fastpath index, an interrupt is coming which we might
8766      * not do any work in.
8767      */
8768     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8769                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8770 }
8771
8772 /*
8773  * Legacy interrupt entry point.
8774  *
8775  * Verifies that the controller generated the interrupt and
8776  * then calls a separate routine to handle the various
8777  * interrupt causes: link, RX, and TX.
8778  */
8779 static void
8780 bxe_intr_legacy(void *xsc)
8781 {
8782     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8783     struct bxe_fastpath *fp;
8784     uint16_t status, mask;
8785     int i;
8786
8787     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8788
8789     /*
8790      * 0 for ustorm, 1 for cstorm
8791      * the bits returned from ack_int() are 0-15
8792      * bit 0 = attention status block
8793      * bit 1 = fast path status block
8794      * a mask of 0x2 or more = tx/rx event
8795      * a mask of 1 = slow path event
8796      */
8797
8798     status = bxe_ack_int(sc);
8799
8800     /* the interrupt is not for us */
8801     if (__predict_false(status == 0)) {
8802         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8803         return;
8804     }
8805
8806     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8807
8808     FOR_EACH_ETH_QUEUE(sc, i) {
8809         fp = &sc->fp[i];
8810         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8811         if (status & mask) {
8812             /* acknowledge and disable further fastpath interrupts */
8813             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8814             bxe_task_fp(fp);
8815             status &= ~mask;
8816         }
8817     }
8818
8819     if (__predict_false(status & 0x1)) {
8820         /* acknowledge and disable further slowpath interrupts */
8821         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8822
8823         /* schedule slowpath handler */
8824         taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8825
8826         status &= ~0x1;
8827     }
8828
8829     if (__predict_false(status)) {
8830         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8831     }
8832 }
8833
8834 /* slowpath interrupt entry point */
8835 static void
8836 bxe_intr_sp(void *xsc)
8837 {
8838     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8839
8840     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8841
8842     /* acknowledge and disable further slowpath interrupts */
8843     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8844
8845     /* schedule slowpath handler */
8846     taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8847 }
8848
8849 /* fastpath interrupt entry point */
8850 static void
8851 bxe_intr_fp(void *xfp)
8852 {
8853     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8854     struct bxe_softc *sc = fp->sc;
8855
8856     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8857
8858     BLOGD(sc, DBG_INTR,
8859           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8860           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8861
8862     /* acknowledge and disable further fastpath interrupts */
8863     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8864
8865     bxe_task_fp(fp);
8866 }
8867
8868 /* Release all interrupts allocated by the driver. */
8869 static void
8870 bxe_interrupt_free(struct bxe_softc *sc)
8871 {
8872     int i;
8873
8874     switch (sc->interrupt_mode) {
8875     case INTR_MODE_INTX:
8876         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8877         if (sc->intr[0].resource != NULL) {
8878             bus_release_resource(sc->dev,
8879                                  SYS_RES_IRQ,
8880                                  sc->intr[0].rid,
8881                                  sc->intr[0].resource);
8882         }
8883         break;
8884     case INTR_MODE_MSI:
8885         for (i = 0; i < sc->intr_count; i++) {
8886             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8887             if (sc->intr[i].resource && sc->intr[i].rid) {
8888                 bus_release_resource(sc->dev,
8889                                      SYS_RES_IRQ,
8890                                      sc->intr[i].rid,
8891                                      sc->intr[i].resource);
8892             }
8893         }
8894         pci_release_msi(sc->dev);
8895         break;
8896     case INTR_MODE_MSIX:
8897         for (i = 0; i < sc->intr_count; i++) {
8898             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8899             if (sc->intr[i].resource && sc->intr[i].rid) {
8900                 bus_release_resource(sc->dev,
8901                                      SYS_RES_IRQ,
8902                                      sc->intr[i].rid,
8903                                      sc->intr[i].resource);
8904             }
8905         }
8906         pci_release_msi(sc->dev);
8907         break;
8908     default:
8909         /* nothing to do as initial allocation failed */
8910         break;
8911     }
8912 }
8913
8914 /*
8915  * This function determines and allocates the appropriate
8916  * interrupt based on system capabilites and user request.
8917  *
8918  * The user may force a particular interrupt mode, specify
8919  * the number of receive queues, specify the method for
8920  * distribuitng received frames to receive queues, or use
8921  * the default settings which will automatically select the
8922  * best supported combination.  In addition, the OS may or
8923  * may not support certain combinations of these settings.
8924  * This routine attempts to reconcile the settings requested
8925  * by the user with the capabilites available from the system
8926  * to select the optimal combination of features.
8927  *
8928  * Returns:
8929  *   0 = Success, !0 = Failure.
8930  */
8931 static int
8932 bxe_interrupt_alloc(struct bxe_softc *sc)
8933 {
8934     int msix_count = 0;
8935     int msi_count = 0;
8936     int num_requested = 0;
8937     int num_allocated = 0;
8938     int rid, i, j;
8939     int rc;
8940
8941     /* get the number of available MSI/MSI-X interrupts from the OS */
8942     if (sc->interrupt_mode > 0) {
8943         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8944             msix_count = pci_msix_count(sc->dev);
8945         }
8946
8947         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8948             msi_count = pci_msi_count(sc->dev);
8949         }
8950
8951         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8952               msi_count, msix_count);
8953     }
8954
8955     do { /* try allocating MSI-X interrupt resources (at least 2) */
8956         if (sc->interrupt_mode != INTR_MODE_MSIX) {
8957             break;
8958         }
8959
8960         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
8961             (msix_count < 2)) {
8962             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8963             break;
8964         }
8965
8966         /* ask for the necessary number of MSI-X vectors */
8967         num_requested = min((sc->num_queues + 1), msix_count);
8968
8969         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
8970
8971         num_allocated = num_requested;
8972         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
8973             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
8974             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8975             break;
8976         }
8977
8978         if (num_allocated < 2) { /* possible? */
8979             BLOGE(sc, "MSI-X allocation less than 2!\n");
8980             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8981             pci_release_msi(sc->dev);
8982             break;
8983         }
8984
8985         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
8986               num_requested, num_allocated);
8987
8988         /* best effort so use the number of vectors allocated to us */
8989         sc->intr_count = num_allocated;
8990         sc->num_queues = num_allocated - 1;
8991
8992         rid = 1; /* initial resource identifier */
8993
8994         /* allocate the MSI-X vectors */
8995         for (i = 0; i < num_allocated; i++) {
8996             sc->intr[i].rid = (rid + i);
8997
8998             if ((sc->intr[i].resource =
8999                  bus_alloc_resource_any(sc->dev,
9000                                         SYS_RES_IRQ,
9001                                         &sc->intr[i].rid,
9002                                         RF_ACTIVE)) == NULL) {
9003                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
9004                       i, (rid + i));
9005
9006                 for (j = (i - 1); j >= 0; j--) {
9007                     bus_release_resource(sc->dev,
9008                                          SYS_RES_IRQ,
9009                                          sc->intr[j].rid,
9010                                          sc->intr[j].resource);
9011                 }
9012
9013                 sc->intr_count = 0;
9014                 sc->num_queues = 0;
9015                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9016                 pci_release_msi(sc->dev);
9017                 break;
9018             }
9019
9020             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9021         }
9022     } while (0);
9023
9024     do { /* try allocating MSI vector resources (at least 2) */
9025         if (sc->interrupt_mode != INTR_MODE_MSI) {
9026             break;
9027         }
9028
9029         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9030             (msi_count < 1)) {
9031             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9032             break;
9033         }
9034
9035         /* ask for a single MSI vector */
9036         num_requested = 1;
9037
9038         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9039
9040         num_allocated = num_requested;
9041         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9042             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9043             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9044             break;
9045         }
9046
9047         if (num_allocated != 1) { /* possible? */
9048             BLOGE(sc, "MSI allocation is not 1!\n");
9049             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9050             pci_release_msi(sc->dev);
9051             break;
9052         }
9053
9054         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9055               num_requested, num_allocated);
9056
9057         /* best effort so use the number of vectors allocated to us */
9058         sc->intr_count = num_allocated;
9059         sc->num_queues = num_allocated;
9060
9061         rid = 1; /* 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)) == NULL) {
9070             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9071             sc->intr_count = 0;
9072             sc->num_queues = 0;
9073             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9074             pci_release_msi(sc->dev);
9075             break;
9076         }
9077
9078         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9079     } while (0);
9080
9081     do { /* try allocating INTx vector resources */
9082         if (sc->interrupt_mode != INTR_MODE_INTX) {
9083             break;
9084         }
9085
9086         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9087
9088         /* only one vector for INTx */
9089         sc->intr_count = 1;
9090         sc->num_queues = 1;
9091
9092         rid = 0; /* initial resource identifier */
9093
9094         sc->intr[0].rid = rid;
9095
9096         if ((sc->intr[0].resource =
9097              bus_alloc_resource_any(sc->dev,
9098                                     SYS_RES_IRQ,
9099                                     &sc->intr[0].rid,
9100                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9101             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9102             sc->intr_count = 0;
9103             sc->num_queues = 0;
9104             sc->interrupt_mode = -1; /* Failed! */
9105             break;
9106         }
9107
9108         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9109     } while (0);
9110
9111     if (sc->interrupt_mode == -1) {
9112         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9113         rc = 1;
9114     } else {
9115         BLOGD(sc, DBG_LOAD,
9116               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9117               sc->interrupt_mode, sc->num_queues);
9118         rc = 0;
9119     }
9120
9121     return (rc);
9122 }
9123
9124 static void
9125 bxe_interrupt_detach(struct bxe_softc *sc)
9126 {
9127     struct bxe_fastpath *fp;
9128     int i;
9129
9130     /* release interrupt resources */
9131     for (i = 0; i < sc->intr_count; i++) {
9132         if (sc->intr[i].resource && sc->intr[i].tag) {
9133             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9134             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9135         }
9136     }
9137
9138     for (i = 0; i < sc->num_queues; i++) {
9139         fp = &sc->fp[i];
9140         if (fp->tq) {
9141             taskqueue_drain(fp->tq, &fp->tq_task);
9142             taskqueue_drain(fp->tq, &fp->tx_task);
9143             while (taskqueue_cancel_timeout(fp->tq, &fp->tx_timeout_task,
9144                 NULL))
9145                 taskqueue_drain_timeout(fp->tq, &fp->tx_timeout_task);
9146         }
9147
9148         for (i = 0; i < sc->num_queues; i++) {
9149             fp = &sc->fp[i];
9150             if (fp->tq != NULL) {
9151                 taskqueue_free(fp->tq);
9152                 fp->tq = NULL;
9153             }
9154         }
9155     }
9156
9157     if (sc->sp_tq) {
9158         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9159         taskqueue_free(sc->sp_tq);
9160         sc->sp_tq = NULL;
9161     }
9162 }
9163
9164 /*
9165  * Enables interrupts and attach to the ISR.
9166  *
9167  * When using multiple MSI/MSI-X vectors the first vector
9168  * is used for slowpath operations while all remaining
9169  * vectors are used for fastpath operations.  If only a
9170  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9171  * ISR must look for both slowpath and fastpath completions.
9172  */
9173 static int
9174 bxe_interrupt_attach(struct bxe_softc *sc)
9175 {
9176     struct bxe_fastpath *fp;
9177     int rc = 0;
9178     int i;
9179
9180     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9181              "bxe%d_sp_tq", sc->unit);
9182     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9183     sc->sp_tq = taskqueue_create(sc->sp_tq_name, M_NOWAIT,
9184                                  taskqueue_thread_enqueue,
9185                                  &sc->sp_tq);
9186     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9187                             "%s", sc->sp_tq_name);
9188
9189
9190     for (i = 0; i < sc->num_queues; i++) {
9191         fp = &sc->fp[i];
9192         snprintf(fp->tq_name, sizeof(fp->tq_name),
9193                  "bxe%d_fp%d_tq", sc->unit, i);
9194         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9195         TASK_INIT(&fp->tx_task, 0, bxe_tx_mq_start_deferred, fp);
9196         fp->tq = taskqueue_create(fp->tq_name, M_NOWAIT,
9197                                   taskqueue_thread_enqueue,
9198                                   &fp->tq);
9199         TIMEOUT_TASK_INIT(fp->tq, &fp->tx_timeout_task, 0,
9200                           bxe_tx_mq_start_deferred, fp);
9201         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9202                                 "%s", fp->tq_name);
9203     }
9204
9205     /* setup interrupt handlers */
9206     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9207         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9208
9209         /*
9210          * Setup the interrupt handler. Note that we pass the driver instance
9211          * to the interrupt handler for the slowpath.
9212          */
9213         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9214                                  (INTR_TYPE_NET | INTR_MPSAFE),
9215                                  NULL, bxe_intr_sp, sc,
9216                                  &sc->intr[0].tag)) != 0) {
9217             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9218             goto bxe_interrupt_attach_exit;
9219         }
9220
9221         bus_describe_intr(sc->dev, sc->intr[0].resource,
9222                           sc->intr[0].tag, "sp");
9223
9224         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9225
9226         /* initialize the fastpath vectors (note the first was used for sp) */
9227         for (i = 0; i < sc->num_queues; i++) {
9228             fp = &sc->fp[i];
9229             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9230
9231             /*
9232              * Setup the interrupt handler. Note that we pass the
9233              * fastpath context to the interrupt handler in this
9234              * case.
9235              */
9236             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9237                                      (INTR_TYPE_NET | INTR_MPSAFE),
9238                                      NULL, bxe_intr_fp, fp,
9239                                      &sc->intr[i + 1].tag)) != 0) {
9240                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9241                       (i + 1), rc);
9242                 goto bxe_interrupt_attach_exit;
9243             }
9244
9245             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9246                               sc->intr[i + 1].tag, "fp%02d", i);
9247
9248             /* bind the fastpath instance to a cpu */
9249             if (sc->num_queues > 1) {
9250                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9251             }
9252
9253             fp->state = BXE_FP_STATE_IRQ;
9254         }
9255     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9256         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9257
9258         /*
9259          * Setup the interrupt handler. Note that we pass the
9260          * driver instance to the interrupt handler which
9261          * will handle both the slowpath and fastpath.
9262          */
9263         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9264                                  (INTR_TYPE_NET | INTR_MPSAFE),
9265                                  NULL, bxe_intr_legacy, sc,
9266                                  &sc->intr[0].tag)) != 0) {
9267             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9268             goto bxe_interrupt_attach_exit;
9269         }
9270
9271     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9272         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9273
9274         /*
9275          * Setup the interrupt handler. Note that we pass the
9276          * driver instance to the interrupt handler which
9277          * will handle both the slowpath and fastpath.
9278          */
9279         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9280                                  (INTR_TYPE_NET | INTR_MPSAFE),
9281                                  NULL, bxe_intr_legacy, sc,
9282                                  &sc->intr[0].tag)) != 0) {
9283             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9284             goto bxe_interrupt_attach_exit;
9285         }
9286     }
9287
9288 bxe_interrupt_attach_exit:
9289
9290     return (rc);
9291 }
9292
9293 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9294 static int  bxe_init_hw_common(struct bxe_softc *sc);
9295 static int  bxe_init_hw_port(struct bxe_softc *sc);
9296 static int  bxe_init_hw_func(struct bxe_softc *sc);
9297 static void bxe_reset_common(struct bxe_softc *sc);
9298 static void bxe_reset_port(struct bxe_softc *sc);
9299 static void bxe_reset_func(struct bxe_softc *sc);
9300 static int  bxe_gunzip_init(struct bxe_softc *sc);
9301 static void bxe_gunzip_end(struct bxe_softc *sc);
9302 static int  bxe_init_firmware(struct bxe_softc *sc);
9303 static void bxe_release_firmware(struct bxe_softc *sc);
9304
9305 static struct
9306 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9307     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9308     .init_hw_cmn      = bxe_init_hw_common,
9309     .init_hw_port     = bxe_init_hw_port,
9310     .init_hw_func     = bxe_init_hw_func,
9311
9312     .reset_hw_cmn     = bxe_reset_common,
9313     .reset_hw_port    = bxe_reset_port,
9314     .reset_hw_func    = bxe_reset_func,
9315
9316     .gunzip_init      = bxe_gunzip_init,
9317     .gunzip_end       = bxe_gunzip_end,
9318
9319     .init_fw          = bxe_init_firmware,
9320     .release_fw       = bxe_release_firmware,
9321 };
9322
9323 static void
9324 bxe_init_func_obj(struct bxe_softc *sc)
9325 {
9326     sc->dmae_ready = 0;
9327
9328     ecore_init_func_obj(sc,
9329                         &sc->func_obj,
9330                         BXE_SP(sc, func_rdata),
9331                         BXE_SP_MAPPING(sc, func_rdata),
9332                         BXE_SP(sc, func_afex_rdata),
9333                         BXE_SP_MAPPING(sc, func_afex_rdata),
9334                         &bxe_func_sp_drv);
9335 }
9336
9337 static int
9338 bxe_init_hw(struct bxe_softc *sc,
9339             uint32_t         load_code)
9340 {
9341     struct ecore_func_state_params func_params = { NULL };
9342     int rc;
9343
9344     /* prepare the parameters for function state transitions */
9345     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9346
9347     func_params.f_obj = &sc->func_obj;
9348     func_params.cmd = ECORE_F_CMD_HW_INIT;
9349
9350     func_params.params.hw_init.load_phase = load_code;
9351
9352     /*
9353      * Via a plethora of function pointers, we will eventually reach
9354      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9355      */
9356     rc = ecore_func_state_change(sc, &func_params);
9357
9358     return (rc);
9359 }
9360
9361 static void
9362 bxe_fill(struct bxe_softc *sc,
9363          uint32_t         addr,
9364          int              fill,
9365          uint32_t         len)
9366 {
9367     uint32_t i;
9368
9369     if (!(len % 4) && !(addr % 4)) {
9370         for (i = 0; i < len; i += 4) {
9371             REG_WR(sc, (addr + i), fill);
9372         }
9373     } else {
9374         for (i = 0; i < len; i++) {
9375             REG_WR8(sc, (addr + i), fill);
9376         }
9377     }
9378 }
9379
9380 /* writes FP SP data to FW - data_size in dwords */
9381 static void
9382 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9383                   int              fw_sb_id,
9384                   uint32_t         *sb_data_p,
9385                   uint32_t         data_size)
9386 {
9387     int index;
9388
9389     for (index = 0; index < data_size; index++) {
9390         REG_WR(sc,
9391                (BAR_CSTRORM_INTMEM +
9392                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9393                 (sizeof(uint32_t) * index)),
9394                *(sb_data_p + index));
9395     }
9396 }
9397
9398 static void
9399 bxe_zero_fp_sb(struct bxe_softc *sc,
9400                int              fw_sb_id)
9401 {
9402     struct hc_status_block_data_e2 sb_data_e2;
9403     struct hc_status_block_data_e1x sb_data_e1x;
9404     uint32_t *sb_data_p;
9405     uint32_t data_size = 0;
9406
9407     if (!CHIP_IS_E1x(sc)) {
9408         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9409         sb_data_e2.common.state = SB_DISABLED;
9410         sb_data_e2.common.p_func.vf_valid = FALSE;
9411         sb_data_p = (uint32_t *)&sb_data_e2;
9412         data_size = (sizeof(struct hc_status_block_data_e2) /
9413                      sizeof(uint32_t));
9414     } else {
9415         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9416         sb_data_e1x.common.state = SB_DISABLED;
9417         sb_data_e1x.common.p_func.vf_valid = FALSE;
9418         sb_data_p = (uint32_t *)&sb_data_e1x;
9419         data_size = (sizeof(struct hc_status_block_data_e1x) /
9420                      sizeof(uint32_t));
9421     }
9422
9423     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9424
9425     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9426              0, CSTORM_STATUS_BLOCK_SIZE);
9427     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9428              0, CSTORM_SYNC_BLOCK_SIZE);
9429 }
9430
9431 static void
9432 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9433                   struct hc_sp_status_block_data *sp_sb_data)
9434 {
9435     int i;
9436
9437     for (i = 0;
9438          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9439          i++) {
9440         REG_WR(sc,
9441                (BAR_CSTRORM_INTMEM +
9442                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9443                 (i * sizeof(uint32_t))),
9444                *((uint32_t *)sp_sb_data + i));
9445     }
9446 }
9447
9448 static void
9449 bxe_zero_sp_sb(struct bxe_softc *sc)
9450 {
9451     struct hc_sp_status_block_data sp_sb_data;
9452
9453     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9454
9455     sp_sb_data.state           = SB_DISABLED;
9456     sp_sb_data.p_func.vf_valid = FALSE;
9457
9458     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9459
9460     bxe_fill(sc,
9461              (BAR_CSTRORM_INTMEM +
9462               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9463               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9464     bxe_fill(sc,
9465              (BAR_CSTRORM_INTMEM +
9466               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9467               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9468 }
9469
9470 static void
9471 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9472                              int                       igu_sb_id,
9473                              int                       igu_seg_id)
9474 {
9475     hc_sm->igu_sb_id      = igu_sb_id;
9476     hc_sm->igu_seg_id     = igu_seg_id;
9477     hc_sm->timer_value    = 0xFF;
9478     hc_sm->time_to_expire = 0xFFFFFFFF;
9479 }
9480
9481 static void
9482 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9483 {
9484     /* zero out state machine indices */
9485
9486     /* rx indices */
9487     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9488
9489     /* tx indices */
9490     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9491     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9492     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9493     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9494
9495     /* map indices */
9496
9497     /* rx indices */
9498     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9499         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9500
9501     /* tx indices */
9502     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9503         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9504     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9505         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9506     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9507         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9508     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9509         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9510 }
9511
9512 static void
9513 bxe_init_sb(struct bxe_softc *sc,
9514             bus_addr_t       busaddr,
9515             int              vfid,
9516             uint8_t          vf_valid,
9517             int              fw_sb_id,
9518             int              igu_sb_id)
9519 {
9520     struct hc_status_block_data_e2  sb_data_e2;
9521     struct hc_status_block_data_e1x sb_data_e1x;
9522     struct hc_status_block_sm       *hc_sm_p;
9523     uint32_t *sb_data_p;
9524     int igu_seg_id;
9525     int data_size;
9526
9527     if (CHIP_INT_MODE_IS_BC(sc)) {
9528         igu_seg_id = HC_SEG_ACCESS_NORM;
9529     } else {
9530         igu_seg_id = IGU_SEG_ACCESS_NORM;
9531     }
9532
9533     bxe_zero_fp_sb(sc, fw_sb_id);
9534
9535     if (!CHIP_IS_E1x(sc)) {
9536         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9537         sb_data_e2.common.state = SB_ENABLED;
9538         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9539         sb_data_e2.common.p_func.vf_id = vfid;
9540         sb_data_e2.common.p_func.vf_valid = vf_valid;
9541         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9542         sb_data_e2.common.same_igu_sb_1b = TRUE;
9543         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9544         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9545         hc_sm_p = sb_data_e2.common.state_machine;
9546         sb_data_p = (uint32_t *)&sb_data_e2;
9547         data_size = (sizeof(struct hc_status_block_data_e2) /
9548                      sizeof(uint32_t));
9549         bxe_map_sb_state_machines(sb_data_e2.index_data);
9550     } else {
9551         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9552         sb_data_e1x.common.state = SB_ENABLED;
9553         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9554         sb_data_e1x.common.p_func.vf_id = 0xff;
9555         sb_data_e1x.common.p_func.vf_valid = FALSE;
9556         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9557         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9558         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9559         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9560         hc_sm_p = sb_data_e1x.common.state_machine;
9561         sb_data_p = (uint32_t *)&sb_data_e1x;
9562         data_size = (sizeof(struct hc_status_block_data_e1x) /
9563                      sizeof(uint32_t));
9564         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9565     }
9566
9567     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9568     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9569
9570     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9571
9572     /* write indices to HW - PCI guarantees endianity of regpairs */
9573     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9574 }
9575
9576 static inline uint8_t
9577 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9578 {
9579     if (CHIP_IS_E1x(fp->sc)) {
9580         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9581     } else {
9582         return (fp->cl_id);
9583     }
9584 }
9585
9586 static inline uint32_t
9587 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9588                            struct bxe_fastpath *fp)
9589 {
9590     uint32_t offset = BAR_USTRORM_INTMEM;
9591
9592     if (!CHIP_IS_E1x(sc)) {
9593         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9594     } else {
9595         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9596     }
9597
9598     return (offset);
9599 }
9600
9601 static void
9602 bxe_init_eth_fp(struct bxe_softc *sc,
9603                 int              idx)
9604 {
9605     struct bxe_fastpath *fp = &sc->fp[idx];
9606     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9607     unsigned long q_type = 0;
9608     int cos;
9609
9610     fp->sc    = sc;
9611     fp->index = idx;
9612
9613     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9614     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9615
9616     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9617                     (SC_L_ID(sc) + idx) :
9618                     /* want client ID same as IGU SB ID for non-E1 */
9619                     fp->igu_sb_id;
9620     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9621
9622     /* setup sb indices */
9623     if (!CHIP_IS_E1x(sc)) {
9624         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9625         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9626     } else {
9627         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9628         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9629     }
9630
9631     /* init shortcut */
9632     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9633
9634     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9635
9636     /*
9637      * XXX If multiple CoS is ever supported then each fastpath structure
9638      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9639      */
9640     for (cos = 0; cos < sc->max_cos; cos++) {
9641         cids[cos] = idx;
9642     }
9643     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9644
9645     /* nothing more for a VF to do */
9646     if (IS_VF(sc)) {
9647         return;
9648     }
9649
9650     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9651                 fp->fw_sb_id, fp->igu_sb_id);
9652
9653     bxe_update_fp_sb_idx(fp);
9654
9655     /* Configure Queue State object */
9656     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9657     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9658
9659     ecore_init_queue_obj(sc,
9660                          &sc->sp_objs[idx].q_obj,
9661                          fp->cl_id,
9662                          cids,
9663                          sc->max_cos,
9664                          SC_FUNC(sc),
9665                          BXE_SP(sc, q_rdata),
9666                          BXE_SP_MAPPING(sc, q_rdata),
9667                          q_type);
9668
9669     /* configure classification DBs */
9670     ecore_init_mac_obj(sc,
9671                        &sc->sp_objs[idx].mac_obj,
9672                        fp->cl_id,
9673                        idx,
9674                        SC_FUNC(sc),
9675                        BXE_SP(sc, mac_rdata),
9676                        BXE_SP_MAPPING(sc, mac_rdata),
9677                        ECORE_FILTER_MAC_PENDING,
9678                        &sc->sp_state,
9679                        ECORE_OBJ_TYPE_RX_TX,
9680                        &sc->macs_pool);
9681
9682     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9683           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9684 }
9685
9686 static inline void
9687 bxe_update_rx_prod(struct bxe_softc    *sc,
9688                    struct bxe_fastpath *fp,
9689                    uint16_t            rx_bd_prod,
9690                    uint16_t            rx_cq_prod,
9691                    uint16_t            rx_sge_prod)
9692 {
9693     struct ustorm_eth_rx_producers rx_prods = { 0 };
9694     uint32_t i;
9695
9696     /* update producers */
9697     rx_prods.bd_prod  = rx_bd_prod;
9698     rx_prods.cqe_prod = rx_cq_prod;
9699     rx_prods.sge_prod = rx_sge_prod;
9700
9701     /*
9702      * Make sure that the BD and SGE data is updated before updating the
9703      * producers since FW might read the BD/SGE right after the producer
9704      * is updated.
9705      * This is only applicable for weak-ordered memory model archs such
9706      * as IA-64. The following barrier is also mandatory since FW will
9707      * assumes BDs must have buffers.
9708      */
9709     wmb();
9710
9711     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9712         REG_WR(sc,
9713                (fp->ustorm_rx_prods_offset + (i * 4)),
9714                ((uint32_t *)&rx_prods)[i]);
9715     }
9716
9717     wmb(); /* keep prod updates ordered */
9718
9719     BLOGD(sc, DBG_RX,
9720           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9721           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9722 }
9723
9724 static void
9725 bxe_init_rx_rings(struct bxe_softc *sc)
9726 {
9727     struct bxe_fastpath *fp;
9728     int i;
9729
9730     for (i = 0; i < sc->num_queues; i++) {
9731         fp = &sc->fp[i];
9732
9733         fp->rx_bd_cons = 0;
9734
9735         /*
9736          * Activate the BD ring...
9737          * Warning, this will generate an interrupt (to the TSTORM)
9738          * so this can only be done after the chip is initialized
9739          */
9740         bxe_update_rx_prod(sc, fp,
9741                            fp->rx_bd_prod,
9742                            fp->rx_cq_prod,
9743                            fp->rx_sge_prod);
9744
9745         if (i != 0) {
9746             continue;
9747         }
9748
9749         if (CHIP_IS_E1(sc)) {
9750             REG_WR(sc,
9751                    (BAR_USTRORM_INTMEM +
9752                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9753                    U64_LO(fp->rcq_dma.paddr));
9754             REG_WR(sc,
9755                    (BAR_USTRORM_INTMEM +
9756                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9757                    U64_HI(fp->rcq_dma.paddr));
9758         }
9759     }
9760 }
9761
9762 static void
9763 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9764 {
9765     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9766     fp->tx_db.data.zero_fill1 = 0;
9767     fp->tx_db.data.prod = 0;
9768
9769     fp->tx_pkt_prod = 0;
9770     fp->tx_pkt_cons = 0;
9771     fp->tx_bd_prod = 0;
9772     fp->tx_bd_cons = 0;
9773     fp->eth_q_stats.tx_pkts = 0;
9774 }
9775
9776 static inline void
9777 bxe_init_tx_rings(struct bxe_softc *sc)
9778 {
9779     int i;
9780
9781     for (i = 0; i < sc->num_queues; i++) {
9782         bxe_init_tx_ring_one(&sc->fp[i]);
9783     }
9784 }
9785
9786 static void
9787 bxe_init_def_sb(struct bxe_softc *sc)
9788 {
9789     struct host_sp_status_block *def_sb = sc->def_sb;
9790     bus_addr_t mapping = sc->def_sb_dma.paddr;
9791     int igu_sp_sb_index;
9792     int igu_seg_id;
9793     int port = SC_PORT(sc);
9794     int func = SC_FUNC(sc);
9795     int reg_offset, reg_offset_en5;
9796     uint64_t section;
9797     int index, sindex;
9798     struct hc_sp_status_block_data sp_sb_data;
9799
9800     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9801
9802     if (CHIP_INT_MODE_IS_BC(sc)) {
9803         igu_sp_sb_index = DEF_SB_IGU_ID;
9804         igu_seg_id = HC_SEG_ACCESS_DEF;
9805     } else {
9806         igu_sp_sb_index = sc->igu_dsb_id;
9807         igu_seg_id = IGU_SEG_ACCESS_DEF;
9808     }
9809
9810     /* attentions */
9811     section = ((uint64_t)mapping +
9812                offsetof(struct host_sp_status_block, atten_status_block));
9813     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9814     sc->attn_state = 0;
9815
9816     reg_offset = (port) ?
9817                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9818                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9819     reg_offset_en5 = (port) ?
9820                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9821                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9822
9823     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9824         /* take care of sig[0]..sig[4] */
9825         for (sindex = 0; sindex < 4; sindex++) {
9826             sc->attn_group[index].sig[sindex] =
9827                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9828         }
9829
9830         if (!CHIP_IS_E1x(sc)) {
9831             /*
9832              * enable5 is separate from the rest of the registers,
9833              * and the address skip is 4 and not 16 between the
9834              * different groups
9835              */
9836             sc->attn_group[index].sig[4] =
9837                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9838         } else {
9839             sc->attn_group[index].sig[4] = 0;
9840         }
9841     }
9842
9843     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9844         reg_offset = (port) ?
9845                          HC_REG_ATTN_MSG1_ADDR_L :
9846                          HC_REG_ATTN_MSG0_ADDR_L;
9847         REG_WR(sc, reg_offset, U64_LO(section));
9848         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9849     } else if (!CHIP_IS_E1x(sc)) {
9850         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9851         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9852     }
9853
9854     section = ((uint64_t)mapping +
9855                offsetof(struct host_sp_status_block, sp_sb));
9856
9857     bxe_zero_sp_sb(sc);
9858
9859     /* PCI guarantees endianity of regpair */
9860     sp_sb_data.state           = SB_ENABLED;
9861     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9862     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9863     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9864     sp_sb_data.igu_seg_id      = igu_seg_id;
9865     sp_sb_data.p_func.pf_id    = func;
9866     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9867     sp_sb_data.p_func.vf_id    = 0xff;
9868
9869     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9870
9871     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9872 }
9873
9874 static void
9875 bxe_init_sp_ring(struct bxe_softc *sc)
9876 {
9877     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9878     sc->spq_prod_idx = 0;
9879     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9880     sc->spq_prod_bd = sc->spq;
9881     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9882 }
9883
9884 static void
9885 bxe_init_eq_ring(struct bxe_softc *sc)
9886 {
9887     union event_ring_elem *elem;
9888     int i;
9889
9890     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9891         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9892
9893         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9894                                                  BCM_PAGE_SIZE *
9895                                                  (i % NUM_EQ_PAGES)));
9896         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9897                                                  BCM_PAGE_SIZE *
9898                                                  (i % NUM_EQ_PAGES)));
9899     }
9900
9901     sc->eq_cons    = 0;
9902     sc->eq_prod    = NUM_EQ_DESC;
9903     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9904
9905     atomic_store_rel_long(&sc->eq_spq_left,
9906                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9907                                NUM_EQ_DESC) - 1));
9908 }
9909
9910 static void
9911 bxe_init_internal_common(struct bxe_softc *sc)
9912 {
9913     int i;
9914
9915     /*
9916      * Zero this manually as its initialization is currently missing
9917      * in the initTool.
9918      */
9919     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9920         REG_WR(sc,
9921                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9922                0);
9923     }
9924
9925     if (!CHIP_IS_E1x(sc)) {
9926         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9927                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9928     }
9929 }
9930
9931 static void
9932 bxe_init_internal(struct bxe_softc *sc,
9933                   uint32_t         load_code)
9934 {
9935     switch (load_code) {
9936     case FW_MSG_CODE_DRV_LOAD_COMMON:
9937     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9938         bxe_init_internal_common(sc);
9939         /* no break */
9940
9941     case FW_MSG_CODE_DRV_LOAD_PORT:
9942         /* nothing to do */
9943         /* no break */
9944
9945     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9946         /* internal memory per function is initialized inside bxe_pf_init */
9947         break;
9948
9949     default:
9950         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9951         break;
9952     }
9953 }
9954
9955 static void
9956 storm_memset_func_cfg(struct bxe_softc                         *sc,
9957                       struct tstorm_eth_function_common_config *tcfg,
9958                       uint16_t                                  abs_fid)
9959 {
9960     uint32_t addr;
9961     size_t size;
9962
9963     addr = (BAR_TSTRORM_INTMEM +
9964             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
9965     size = sizeof(struct tstorm_eth_function_common_config);
9966     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
9967 }
9968
9969 static void
9970 bxe_func_init(struct bxe_softc            *sc,
9971               struct bxe_func_init_params *p)
9972 {
9973     struct tstorm_eth_function_common_config tcfg = { 0 };
9974
9975     if (CHIP_IS_E1x(sc)) {
9976         storm_memset_func_cfg(sc, &tcfg, p->func_id);
9977     }
9978
9979     /* Enable the function in the FW */
9980     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
9981     storm_memset_func_en(sc, p->func_id, 1);
9982
9983     /* spq */
9984     if (p->func_flgs & FUNC_FLG_SPQ) {
9985         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
9986         REG_WR(sc,
9987                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
9988                p->spq_prod);
9989     }
9990 }
9991
9992 /*
9993  * Calculates the sum of vn_min_rates.
9994  * It's needed for further normalizing of the min_rates.
9995  * Returns:
9996  *   sum of vn_min_rates.
9997  *     or
9998  *   0 - if all the min_rates are 0.
9999  * In the later case fainess algorithm should be deactivated.
10000  * If all min rates are not zero then those that are zeroes will be set to 1.
10001  */
10002 static void
10003 bxe_calc_vn_min(struct bxe_softc       *sc,
10004                 struct cmng_init_input *input)
10005 {
10006     uint32_t vn_cfg;
10007     uint32_t vn_min_rate;
10008     int all_zero = 1;
10009     int vn;
10010
10011     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10012         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10013         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
10014                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
10015
10016         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10017             /* skip hidden VNs */
10018             vn_min_rate = 0;
10019         } else if (!vn_min_rate) {
10020             /* If min rate is zero - set it to 100 */
10021             vn_min_rate = DEF_MIN_RATE;
10022         } else {
10023             all_zero = 0;
10024         }
10025
10026         input->vnic_min_rate[vn] = vn_min_rate;
10027     }
10028
10029     /* if ETS or all min rates are zeros - disable fairness */
10030     if (BXE_IS_ETS_ENABLED(sc)) {
10031         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10032         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10033     } else if (all_zero) {
10034         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10035         BLOGD(sc, DBG_LOAD,
10036               "Fariness disabled (all MIN values are zeroes)\n");
10037     } else {
10038         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10039     }
10040 }
10041
10042 static inline uint16_t
10043 bxe_extract_max_cfg(struct bxe_softc *sc,
10044                     uint32_t         mf_cfg)
10045 {
10046     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10047                         FUNC_MF_CFG_MAX_BW_SHIFT);
10048
10049     if (!max_cfg) {
10050         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10051         max_cfg = 100;
10052     }
10053
10054     return (max_cfg);
10055 }
10056
10057 static void
10058 bxe_calc_vn_max(struct bxe_softc       *sc,
10059                 int                    vn,
10060                 struct cmng_init_input *input)
10061 {
10062     uint16_t vn_max_rate;
10063     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10064     uint32_t max_cfg;
10065
10066     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10067         vn_max_rate = 0;
10068     } else {
10069         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10070
10071         if (IS_MF_SI(sc)) {
10072             /* max_cfg in percents of linkspeed */
10073             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10074         } else { /* SD modes */
10075             /* max_cfg is absolute in 100Mb units */
10076             vn_max_rate = (max_cfg * 100);
10077         }
10078     }
10079
10080     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10081
10082     input->vnic_max_rate[vn] = vn_max_rate;
10083 }
10084
10085 static void
10086 bxe_cmng_fns_init(struct bxe_softc *sc,
10087                   uint8_t          read_cfg,
10088                   uint8_t          cmng_type)
10089 {
10090     struct cmng_init_input input;
10091     int vn;
10092
10093     memset(&input, 0, sizeof(struct cmng_init_input));
10094
10095     input.port_rate = sc->link_vars.line_speed;
10096
10097     if (cmng_type == CMNG_FNS_MINMAX) {
10098         /* read mf conf from shmem */
10099         if (read_cfg) {
10100             bxe_read_mf_cfg(sc);
10101         }
10102
10103         /* get VN min rate and enable fairness if not 0 */
10104         bxe_calc_vn_min(sc, &input);
10105
10106         /* get VN max rate */
10107         if (sc->port.pmf) {
10108             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10109                 bxe_calc_vn_max(sc, vn, &input);
10110             }
10111         }
10112
10113         /* always enable rate shaping and fairness */
10114         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10115
10116         ecore_init_cmng(&input, &sc->cmng);
10117         return;
10118     }
10119
10120     /* rate shaping and fairness are disabled */
10121     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10122 }
10123
10124 static int
10125 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10126 {
10127     if (CHIP_REV_IS_SLOW(sc)) {
10128         return (CMNG_FNS_NONE);
10129     }
10130
10131     if (IS_MF(sc)) {
10132         return (CMNG_FNS_MINMAX);
10133     }
10134
10135     return (CMNG_FNS_NONE);
10136 }
10137
10138 static void
10139 storm_memset_cmng(struct bxe_softc *sc,
10140                   struct cmng_init *cmng,
10141                   uint8_t          port)
10142 {
10143     int vn;
10144     int func;
10145     uint32_t addr;
10146     size_t size;
10147
10148     addr = (BAR_XSTRORM_INTMEM +
10149             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10150     size = sizeof(struct cmng_struct_per_port);
10151     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10152
10153     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10154         func = func_by_vn(sc, vn);
10155
10156         addr = (BAR_XSTRORM_INTMEM +
10157                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10158         size = sizeof(struct rate_shaping_vars_per_vn);
10159         ecore_storm_memset_struct(sc, addr, size,
10160                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10161
10162         addr = (BAR_XSTRORM_INTMEM +
10163                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10164         size = sizeof(struct fairness_vars_per_vn);
10165         ecore_storm_memset_struct(sc, addr, size,
10166                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10167     }
10168 }
10169
10170 static void
10171 bxe_pf_init(struct bxe_softc *sc)
10172 {
10173     struct bxe_func_init_params func_init = { 0 };
10174     struct event_ring_data eq_data = { { 0 } };
10175     uint16_t flags;
10176
10177     if (!CHIP_IS_E1x(sc)) {
10178         /* reset IGU PF statistics: MSIX + ATTN */
10179         /* PF */
10180         REG_WR(sc,
10181                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10182                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10183                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10184                0);
10185         /* ATTN */
10186         REG_WR(sc,
10187                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10188                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10189                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10190                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10191                0);
10192     }
10193
10194     /* function setup flags */
10195     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10196
10197     /*
10198      * This flag is relevant for E1x only.
10199      * E2 doesn't have a TPA configuration in a function level.
10200      */
10201     flags |= (sc->ifnet->if_capenable & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10202
10203     func_init.func_flgs = flags;
10204     func_init.pf_id     = SC_FUNC(sc);
10205     func_init.func_id   = SC_FUNC(sc);
10206     func_init.spq_map   = sc->spq_dma.paddr;
10207     func_init.spq_prod  = sc->spq_prod_idx;
10208
10209     bxe_func_init(sc, &func_init);
10210
10211     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10212
10213     /*
10214      * Congestion management values depend on the link rate.
10215      * There is no active link so initial link rate is set to 10Gbps.
10216      * When the link comes up the congestion management values are
10217      * re-calculated according to the actual link rate.
10218      */
10219     sc->link_vars.line_speed = SPEED_10000;
10220     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10221
10222     /* Only the PMF sets the HW */
10223     if (sc->port.pmf) {
10224         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10225     }
10226
10227     /* init Event Queue - PCI bus guarantees correct endainity */
10228     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10229     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10230     eq_data.producer     = sc->eq_prod;
10231     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10232     eq_data.sb_id        = DEF_SB_ID;
10233     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10234 }
10235
10236 static void
10237 bxe_hc_int_enable(struct bxe_softc *sc)
10238 {
10239     int port = SC_PORT(sc);
10240     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10241     uint32_t val = REG_RD(sc, addr);
10242     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10243     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10244                            (sc->intr_count == 1)) ? TRUE : FALSE;
10245     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10246
10247     if (msix) {
10248         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10249                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10250         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10251                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10252         if (single_msix) {
10253             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10254         }
10255     } else if (msi) {
10256         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10257         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10258                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10259                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10260     } else {
10261         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10262                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10263                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10264                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10265
10266         if (!CHIP_IS_E1(sc)) {
10267             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10268                   val, port, addr);
10269
10270             REG_WR(sc, addr, val);
10271
10272             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10273         }
10274     }
10275
10276     if (CHIP_IS_E1(sc)) {
10277         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10278     }
10279
10280     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10281           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10282
10283     REG_WR(sc, addr, val);
10284
10285     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10286     mb();
10287
10288     if (!CHIP_IS_E1(sc)) {
10289         /* init leading/trailing edge */
10290         if (IS_MF(sc)) {
10291             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10292             if (sc->port.pmf) {
10293                 /* enable nig and gpio3 attention */
10294                 val |= 0x1100;
10295             }
10296         } else {
10297             val = 0xffff;
10298         }
10299
10300         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10301         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10302     }
10303
10304     /* make sure that interrupts are indeed enabled from here on */
10305     mb();
10306 }
10307
10308 static void
10309 bxe_igu_int_enable(struct bxe_softc *sc)
10310 {
10311     uint32_t val;
10312     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10313     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10314                            (sc->intr_count == 1)) ? TRUE : FALSE;
10315     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10316
10317     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10318
10319     if (msix) {
10320         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10321                  IGU_PF_CONF_SINGLE_ISR_EN);
10322         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10323                 IGU_PF_CONF_ATTN_BIT_EN);
10324         if (single_msix) {
10325             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10326         }
10327     } else if (msi) {
10328         val &= ~IGU_PF_CONF_INT_LINE_EN;
10329         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10330                 IGU_PF_CONF_ATTN_BIT_EN |
10331                 IGU_PF_CONF_SINGLE_ISR_EN);
10332     } else {
10333         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10334         val |= (IGU_PF_CONF_INT_LINE_EN |
10335                 IGU_PF_CONF_ATTN_BIT_EN |
10336                 IGU_PF_CONF_SINGLE_ISR_EN);
10337     }
10338
10339     /* clean previous status - need to configure igu prior to ack*/
10340     if ((!msix) || single_msix) {
10341         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10342         bxe_ack_int(sc);
10343     }
10344
10345     val |= IGU_PF_CONF_FUNC_EN;
10346
10347     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10348           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10349
10350     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10351
10352     mb();
10353
10354     /* init leading/trailing edge */
10355     if (IS_MF(sc)) {
10356         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10357         if (sc->port.pmf) {
10358             /* enable nig and gpio3 attention */
10359             val |= 0x1100;
10360         }
10361     } else {
10362         val = 0xffff;
10363     }
10364
10365     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10366     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10367
10368     /* make sure that interrupts are indeed enabled from here on */
10369     mb();
10370 }
10371
10372 static void
10373 bxe_int_enable(struct bxe_softc *sc)
10374 {
10375     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10376         bxe_hc_int_enable(sc);
10377     } else {
10378         bxe_igu_int_enable(sc);
10379     }
10380 }
10381
10382 static void
10383 bxe_hc_int_disable(struct bxe_softc *sc)
10384 {
10385     int port = SC_PORT(sc);
10386     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10387     uint32_t val = REG_RD(sc, addr);
10388
10389     /*
10390      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10391      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10392      * block
10393      */
10394     if (CHIP_IS_E1(sc)) {
10395         /*
10396          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10397          * to prevent from HC sending interrupts after we exit the function
10398          */
10399         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10400
10401         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10402                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10403                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10404     } else {
10405         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10406                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10407                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10408                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10409     }
10410
10411     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10412
10413     /* flush all outstanding writes */
10414     mb();
10415
10416     REG_WR(sc, addr, val);
10417     if (REG_RD(sc, addr) != val) {
10418         BLOGE(sc, "proper val not read from HC IGU!\n");
10419     }
10420 }
10421
10422 static void
10423 bxe_igu_int_disable(struct bxe_softc *sc)
10424 {
10425     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10426
10427     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10428              IGU_PF_CONF_INT_LINE_EN |
10429              IGU_PF_CONF_ATTN_BIT_EN);
10430
10431     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10432
10433     /* flush all outstanding writes */
10434     mb();
10435
10436     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10437     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10438         BLOGE(sc, "proper val not read from IGU!\n");
10439     }
10440 }
10441
10442 static void
10443 bxe_int_disable(struct bxe_softc *sc)
10444 {
10445     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10446         bxe_hc_int_disable(sc);
10447     } else {
10448         bxe_igu_int_disable(sc);
10449     }
10450 }
10451
10452 static void
10453 bxe_nic_init(struct bxe_softc *sc,
10454              int              load_code)
10455 {
10456     int i;
10457
10458     for (i = 0; i < sc->num_queues; i++) {
10459         bxe_init_eth_fp(sc, i);
10460     }
10461
10462     rmb(); /* ensure status block indices were read */
10463
10464     bxe_init_rx_rings(sc);
10465     bxe_init_tx_rings(sc);
10466
10467     if (IS_VF(sc)) {
10468         return;
10469     }
10470
10471     /* initialize MOD_ABS interrupts */
10472     elink_init_mod_abs_int(sc, &sc->link_vars,
10473                            sc->devinfo.chip_id,
10474                            sc->devinfo.shmem_base,
10475                            sc->devinfo.shmem2_base,
10476                            SC_PORT(sc));
10477
10478     bxe_init_def_sb(sc);
10479     bxe_update_dsb_idx(sc);
10480     bxe_init_sp_ring(sc);
10481     bxe_init_eq_ring(sc);
10482     bxe_init_internal(sc, load_code);
10483     bxe_pf_init(sc);
10484     bxe_stats_init(sc);
10485
10486     /* flush all before enabling interrupts */
10487     mb();
10488
10489     bxe_int_enable(sc);
10490
10491     /* check for SPIO5 */
10492     bxe_attn_int_deasserted0(sc,
10493                              REG_RD(sc,
10494                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10495                                      SC_PORT(sc)*4)) &
10496                              AEU_INPUTS_ATTN_BITS_SPIO5);
10497 }
10498
10499 static inline void
10500 bxe_init_objs(struct bxe_softc *sc)
10501 {
10502     /* mcast rules must be added to tx if tx switching is enabled */
10503     ecore_obj_type o_type =
10504         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10505                                          ECORE_OBJ_TYPE_RX;
10506
10507     /* RX_MODE controlling object */
10508     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10509
10510     /* multicast configuration controlling object */
10511     ecore_init_mcast_obj(sc,
10512                          &sc->mcast_obj,
10513                          sc->fp[0].cl_id,
10514                          sc->fp[0].index,
10515                          SC_FUNC(sc),
10516                          SC_FUNC(sc),
10517                          BXE_SP(sc, mcast_rdata),
10518                          BXE_SP_MAPPING(sc, mcast_rdata),
10519                          ECORE_FILTER_MCAST_PENDING,
10520                          &sc->sp_state,
10521                          o_type);
10522
10523     /* Setup CAM credit pools */
10524     ecore_init_mac_credit_pool(sc,
10525                                &sc->macs_pool,
10526                                SC_FUNC(sc),
10527                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10528                                                  VNICS_PER_PATH(sc));
10529
10530     ecore_init_vlan_credit_pool(sc,
10531                                 &sc->vlans_pool,
10532                                 SC_ABS_FUNC(sc) >> 1,
10533                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10534                                                   VNICS_PER_PATH(sc));
10535
10536     /* RSS configuration object */
10537     ecore_init_rss_config_obj(sc,
10538                               &sc->rss_conf_obj,
10539                               sc->fp[0].cl_id,
10540                               sc->fp[0].index,
10541                               SC_FUNC(sc),
10542                               SC_FUNC(sc),
10543                               BXE_SP(sc, rss_rdata),
10544                               BXE_SP_MAPPING(sc, rss_rdata),
10545                               ECORE_FILTER_RSS_CONF_PENDING,
10546                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10547 }
10548
10549 /*
10550  * Initialize the function. This must be called before sending CLIENT_SETUP
10551  * for the first client.
10552  */
10553 static inline int
10554 bxe_func_start(struct bxe_softc *sc)
10555 {
10556     struct ecore_func_state_params func_params = { NULL };
10557     struct ecore_func_start_params *start_params = &func_params.params.start;
10558
10559     /* Prepare parameters for function state transitions */
10560     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10561
10562     func_params.f_obj = &sc->func_obj;
10563     func_params.cmd = ECORE_F_CMD_START;
10564
10565     /* Function parameters */
10566     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10567     start_params->sd_vlan_tag = OVLAN(sc);
10568
10569     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10570         start_params->network_cos_mode = STATIC_COS;
10571     } else { /* CHIP_IS_E1X */
10572         start_params->network_cos_mode = FW_WRR;
10573     }
10574
10575     //start_params->gre_tunnel_mode = 0;
10576     //start_params->gre_tunnel_rss  = 0;
10577
10578     return (ecore_func_state_change(sc, &func_params));
10579 }
10580
10581 static int
10582 bxe_set_power_state(struct bxe_softc *sc,
10583                     uint8_t          state)
10584 {
10585     uint16_t pmcsr;
10586
10587     /* If there is no power capability, silently succeed */
10588     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10589         BLOGW(sc, "No power capability\n");
10590         return (0);
10591     }
10592
10593     pmcsr = pci_read_config(sc->dev,
10594                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10595                             2);
10596
10597     switch (state) {
10598     case PCI_PM_D0:
10599         pci_write_config(sc->dev,
10600                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10601                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10602
10603         if (pmcsr & PCIM_PSTAT_DMASK) {
10604             /* delay required during transition out of D3hot */
10605             DELAY(20000);
10606         }
10607
10608         break;
10609
10610     case PCI_PM_D3hot:
10611         /* XXX if there are other clients above don't shut down the power */
10612
10613         /* don't shut down the power for emulation and FPGA */
10614         if (CHIP_REV_IS_SLOW(sc)) {
10615             return (0);
10616         }
10617
10618         pmcsr &= ~PCIM_PSTAT_DMASK;
10619         pmcsr |= PCIM_PSTAT_D3;
10620
10621         if (sc->wol) {
10622             pmcsr |= PCIM_PSTAT_PMEENABLE;
10623         }
10624
10625         pci_write_config(sc->dev,
10626                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10627                          pmcsr, 4);
10628
10629         /*
10630          * No more memory access after this point until device is brought back
10631          * to D0 state.
10632          */
10633         break;
10634
10635     default:
10636         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10637             state, pmcsr);
10638         return (-1);
10639     }
10640
10641     return (0);
10642 }
10643
10644
10645 /* return true if succeeded to acquire the lock */
10646 static uint8_t
10647 bxe_trylock_hw_lock(struct bxe_softc *sc,
10648                     uint32_t         resource)
10649 {
10650     uint32_t lock_status;
10651     uint32_t resource_bit = (1 << resource);
10652     int func = SC_FUNC(sc);
10653     uint32_t hw_lock_control_reg;
10654
10655     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10656
10657     /* Validating that the resource is within range */
10658     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10659         BLOGD(sc, DBG_LOAD,
10660               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10661               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10662         return (FALSE);
10663     }
10664
10665     if (func <= 5) {
10666         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10667     } else {
10668         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10669     }
10670
10671     /* try to acquire the lock */
10672     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10673     lock_status = REG_RD(sc, hw_lock_control_reg);
10674     if (lock_status & resource_bit) {
10675         return (TRUE);
10676     }
10677
10678     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10679         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10680         lock_status, resource_bit);
10681
10682     return (FALSE);
10683 }
10684
10685 /*
10686  * Get the recovery leader resource id according to the engine this function
10687  * belongs to. Currently only only 2 engines is supported.
10688  */
10689 static int
10690 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10691 {
10692     if (SC_PATH(sc)) {
10693         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10694     } else {
10695         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10696     }
10697 }
10698
10699 /* try to acquire a leader lock for current engine */
10700 static uint8_t
10701 bxe_trylock_leader_lock(struct bxe_softc *sc)
10702 {
10703     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10704 }
10705
10706 static int
10707 bxe_release_leader_lock(struct bxe_softc *sc)
10708 {
10709     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10710 }
10711
10712 /* close gates #2, #3 and #4 */
10713 static void
10714 bxe_set_234_gates(struct bxe_softc *sc,
10715                   uint8_t          close)
10716 {
10717     uint32_t val;
10718
10719     /* gates #2 and #4a are closed/opened for "not E1" only */
10720     if (!CHIP_IS_E1(sc)) {
10721         /* #4 */
10722         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10723         /* #2 */
10724         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10725     }
10726
10727     /* #3 */
10728     if (CHIP_IS_E1x(sc)) {
10729         /* prevent interrupts from HC on both ports */
10730         val = REG_RD(sc, HC_REG_CONFIG_1);
10731         REG_WR(sc, HC_REG_CONFIG_1,
10732                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10733                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10734
10735         val = REG_RD(sc, HC_REG_CONFIG_0);
10736         REG_WR(sc, HC_REG_CONFIG_0,
10737                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10738                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10739     } else {
10740         /* Prevent incomming interrupts in IGU */
10741         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10742
10743         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10744                (!close) ?
10745                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10746                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10747     }
10748
10749     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10750           close ? "closing" : "opening");
10751
10752     wmb();
10753 }
10754
10755 /* poll for pending writes bit, it should get cleared in no more than 1s */
10756 static int
10757 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10758 {
10759     uint32_t cnt = 1000;
10760     uint32_t pend_bits = 0;
10761
10762     do {
10763         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10764
10765         if (pend_bits == 0) {
10766             break;
10767         }
10768
10769         DELAY(1000);
10770     } while (--cnt > 0);
10771
10772     if (cnt == 0) {
10773         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10774         return (-1);
10775     }
10776
10777     return (0);
10778 }
10779
10780 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10781
10782 static void
10783 bxe_clp_reset_prep(struct bxe_softc *sc,
10784                    uint32_t         *magic_val)
10785 {
10786     /* Do some magic... */
10787     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10788     *magic_val = val & SHARED_MF_CLP_MAGIC;
10789     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10790 }
10791
10792 /* restore the value of the 'magic' bit */
10793 static void
10794 bxe_clp_reset_done(struct bxe_softc *sc,
10795                    uint32_t         magic_val)
10796 {
10797     /* Restore the 'magic' bit value... */
10798     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10799     MFCFG_WR(sc, shared_mf_config.clp_mb,
10800               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10801 }
10802
10803 /* prepare for MCP reset, takes care of CLP configurations */
10804 static void
10805 bxe_reset_mcp_prep(struct bxe_softc *sc,
10806                    uint32_t         *magic_val)
10807 {
10808     uint32_t shmem;
10809     uint32_t validity_offset;
10810
10811     /* set `magic' bit in order to save MF config */
10812     if (!CHIP_IS_E1(sc)) {
10813         bxe_clp_reset_prep(sc, magic_val);
10814     }
10815
10816     /* get shmem offset */
10817     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10818     validity_offset =
10819         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10820
10821     /* Clear validity map flags */
10822     if (shmem > 0) {
10823         REG_WR(sc, shmem + validity_offset, 0);
10824     }
10825 }
10826
10827 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10828 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10829
10830 static void
10831 bxe_mcp_wait_one(struct bxe_softc *sc)
10832 {
10833     /* special handling for emulation and FPGA (10 times longer) */
10834     if (CHIP_REV_IS_SLOW(sc)) {
10835         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10836     } else {
10837         DELAY((MCP_ONE_TIMEOUT) * 1000);
10838     }
10839 }
10840
10841 /* initialize shmem_base and waits for validity signature to appear */
10842 static int
10843 bxe_init_shmem(struct bxe_softc *sc)
10844 {
10845     int cnt = 0;
10846     uint32_t val = 0;
10847
10848     do {
10849         sc->devinfo.shmem_base     =
10850         sc->link_params.shmem_base =
10851             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10852
10853         if (sc->devinfo.shmem_base) {
10854             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10855             if (val & SHR_MEM_VALIDITY_MB)
10856                 return (0);
10857         }
10858
10859         bxe_mcp_wait_one(sc);
10860
10861     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10862
10863     BLOGE(sc, "BAD MCP validity signature\n");
10864
10865     return (-1);
10866 }
10867
10868 static int
10869 bxe_reset_mcp_comp(struct bxe_softc *sc,
10870                    uint32_t         magic_val)
10871 {
10872     int rc = bxe_init_shmem(sc);
10873
10874     /* Restore the `magic' bit value */
10875     if (!CHIP_IS_E1(sc)) {
10876         bxe_clp_reset_done(sc, magic_val);
10877     }
10878
10879     return (rc);
10880 }
10881
10882 static void
10883 bxe_pxp_prep(struct bxe_softc *sc)
10884 {
10885     if (!CHIP_IS_E1(sc)) {
10886         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10887         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10888         wmb();
10889     }
10890 }
10891
10892 /*
10893  * Reset the whole chip except for:
10894  *      - PCIE core
10895  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10896  *      - IGU
10897  *      - MISC (including AEU)
10898  *      - GRC
10899  *      - RBCN, RBCP
10900  */
10901 static void
10902 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10903                             uint8_t          global)
10904 {
10905     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10906     uint32_t global_bits2, stay_reset2;
10907
10908     /*
10909      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10910      * (per chip) blocks.
10911      */
10912     global_bits2 =
10913         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10914         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10915
10916     /*
10917      * Don't reset the following blocks.
10918      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10919      *            reset, as in 4 port device they might still be owned
10920      *            by the MCP (there is only one leader per path).
10921      */
10922     not_reset_mask1 =
10923         MISC_REGISTERS_RESET_REG_1_RST_HC |
10924         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10925         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10926
10927     not_reset_mask2 =
10928         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10929         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10930         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10931         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10932         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10933         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10934         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10935         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10936         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10937         MISC_REGISTERS_RESET_REG_2_PGLC |
10938         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10939         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10940         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10941         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10942         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10943         MISC_REGISTERS_RESET_REG_2_UMAC1;
10944
10945     /*
10946      * Keep the following blocks in reset:
10947      *  - all xxMACs are handled by the elink code.
10948      */
10949     stay_reset2 =
10950         MISC_REGISTERS_RESET_REG_2_XMAC |
10951         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10952
10953     /* Full reset masks according to the chip */
10954     reset_mask1 = 0xffffffff;
10955
10956     if (CHIP_IS_E1(sc))
10957         reset_mask2 = 0xffff;
10958     else if (CHIP_IS_E1H(sc))
10959         reset_mask2 = 0x1ffff;
10960     else if (CHIP_IS_E2(sc))
10961         reset_mask2 = 0xfffff;
10962     else /* CHIP_IS_E3 */
10963         reset_mask2 = 0x3ffffff;
10964
10965     /* Don't reset global blocks unless we need to */
10966     if (!global)
10967         reset_mask2 &= ~global_bits2;
10968
10969     /*
10970      * In case of attention in the QM, we need to reset PXP
10971      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
10972      * because otherwise QM reset would release 'close the gates' shortly
10973      * before resetting the PXP, then the PSWRQ would send a write
10974      * request to PGLUE. Then when PXP is reset, PGLUE would try to
10975      * read the payload data from PSWWR, but PSWWR would not
10976      * respond. The write queue in PGLUE would stuck, dmae commands
10977      * would not return. Therefore it's important to reset the second
10978      * reset register (containing the
10979      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
10980      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
10981      * bit).
10982      */
10983     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
10984            reset_mask2 & (~not_reset_mask2));
10985
10986     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
10987            reset_mask1 & (~not_reset_mask1));
10988
10989     mb();
10990     wmb();
10991
10992     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
10993            reset_mask2 & (~stay_reset2));
10994
10995     mb();
10996     wmb();
10997
10998     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
10999     wmb();
11000 }
11001
11002 static int
11003 bxe_process_kill(struct bxe_softc *sc,
11004                  uint8_t          global)
11005 {
11006     int cnt = 1000;
11007     uint32_t val = 0;
11008     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
11009     uint32_t tags_63_32 = 0;
11010
11011     /* Empty the Tetris buffer, wait for 1s */
11012     do {
11013         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
11014         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
11015         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
11016         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
11017         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
11018         if (CHIP_IS_E3(sc)) {
11019             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
11020         }
11021
11022         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11023             ((port_is_idle_0 & 0x1) == 0x1) &&
11024             ((port_is_idle_1 & 0x1) == 0x1) &&
11025             (pgl_exp_rom2 == 0xffffffff) &&
11026             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11027             break;
11028         DELAY(1000);
11029     } while (cnt-- > 0);
11030
11031     if (cnt <= 0) {
11032         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11033                   "are still outstanding read requests after 1s! "
11034                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11035                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11036               sr_cnt, blk_cnt, port_is_idle_0,
11037               port_is_idle_1, pgl_exp_rom2);
11038         return (-1);
11039     }
11040
11041     mb();
11042
11043     /* Close gates #2, #3 and #4 */
11044     bxe_set_234_gates(sc, TRUE);
11045
11046     /* Poll for IGU VQs for 57712 and newer chips */
11047     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11048         return (-1);
11049     }
11050
11051     /* XXX indicate that "process kill" is in progress to MCP */
11052
11053     /* clear "unprepared" bit */
11054     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11055     mb();
11056
11057     /* Make sure all is written to the chip before the reset */
11058     wmb();
11059
11060     /*
11061      * Wait for 1ms to empty GLUE and PCI-E core queues,
11062      * PSWHST, GRC and PSWRD Tetris buffer.
11063      */
11064     DELAY(1000);
11065
11066     /* Prepare to chip reset: */
11067     /* MCP */
11068     if (global) {
11069         bxe_reset_mcp_prep(sc, &val);
11070     }
11071
11072     /* PXP */
11073     bxe_pxp_prep(sc);
11074     mb();
11075
11076     /* reset the chip */
11077     bxe_process_kill_chip_reset(sc, global);
11078     mb();
11079
11080     /* clear errors in PGB */
11081     if (!CHIP_IS_E1(sc))
11082         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11083
11084     /* Recover after reset: */
11085     /* MCP */
11086     if (global && bxe_reset_mcp_comp(sc, val)) {
11087         return (-1);
11088     }
11089
11090     /* XXX add resetting the NO_MCP mode DB here */
11091
11092     /* Open the gates #2, #3 and #4 */
11093     bxe_set_234_gates(sc, FALSE);
11094
11095     /* XXX
11096      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11097      * re-enable attentions
11098      */
11099
11100     return (0);
11101 }
11102
11103 static int
11104 bxe_leader_reset(struct bxe_softc *sc)
11105 {
11106     int rc = 0;
11107     uint8_t global = bxe_reset_is_global(sc);
11108     uint32_t load_code;
11109
11110     /*
11111      * If not going to reset MCP, load "fake" driver to reset HW while
11112      * driver is owner of the HW.
11113      */
11114     if (!global && !BXE_NOMCP(sc)) {
11115         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11116                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11117         if (!load_code) {
11118             BLOGE(sc, "MCP response failure, aborting\n");
11119             rc = -1;
11120             goto exit_leader_reset;
11121         }
11122
11123         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11124             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11125             BLOGE(sc, "MCP unexpected response, aborting\n");
11126             rc = -1;
11127             goto exit_leader_reset2;
11128         }
11129
11130         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11131         if (!load_code) {
11132             BLOGE(sc, "MCP response failure, aborting\n");
11133             rc = -1;
11134             goto exit_leader_reset2;
11135         }
11136     }
11137
11138     /* try to recover after the failure */
11139     if (bxe_process_kill(sc, global)) {
11140         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11141         rc = -1;
11142         goto exit_leader_reset2;
11143     }
11144
11145     /*
11146      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11147      * state.
11148      */
11149     bxe_set_reset_done(sc);
11150     if (global) {
11151         bxe_clear_reset_global(sc);
11152     }
11153
11154 exit_leader_reset2:
11155
11156     /* unload "fake driver" if it was loaded */
11157     if (!global && !BXE_NOMCP(sc)) {
11158         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11159         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11160     }
11161
11162 exit_leader_reset:
11163
11164     sc->is_leader = 0;
11165     bxe_release_leader_lock(sc);
11166
11167     mb();
11168     return (rc);
11169 }
11170
11171 /*
11172  * prepare INIT transition, parameters configured:
11173  *   - HC configuration
11174  *   - Queue's CDU context
11175  */
11176 static void
11177 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11178                    struct bxe_fastpath            *fp,
11179                    struct ecore_queue_init_params *init_params)
11180 {
11181     uint8_t cos;
11182     int cxt_index, cxt_offset;
11183
11184     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11185     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11186
11187     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11188     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11189
11190     /* HC rate */
11191     init_params->rx.hc_rate =
11192         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11193     init_params->tx.hc_rate =
11194         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11195
11196     /* FW SB ID */
11197     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11198
11199     /* CQ index among the SB indices */
11200     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11201     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11202
11203     /* set maximum number of COSs supported by this queue */
11204     init_params->max_cos = sc->max_cos;
11205
11206     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11207           fp->index, init_params->max_cos);
11208
11209     /* set the context pointers queue object */
11210     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11211         /* XXX change index/cid here if ever support multiple tx CoS */
11212         /* fp->txdata[cos]->cid */
11213         cxt_index = fp->index / ILT_PAGE_CIDS;
11214         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11215         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11216     }
11217 }
11218
11219 /* set flags that are common for the Tx-only and not normal connections */
11220 static unsigned long
11221 bxe_get_common_flags(struct bxe_softc    *sc,
11222                      struct bxe_fastpath *fp,
11223                      uint8_t             zero_stats)
11224 {
11225     unsigned long flags = 0;
11226
11227     /* PF driver will always initialize the Queue to an ACTIVE state */
11228     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11229
11230     /*
11231      * tx only connections collect statistics (on the same index as the
11232      * parent connection). The statistics are zeroed when the parent
11233      * connection is initialized.
11234      */
11235
11236     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11237     if (zero_stats) {
11238         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11239     }
11240
11241     /*
11242      * tx only connections can support tx-switching, though their
11243      * CoS-ness doesn't survive the loopback
11244      */
11245     if (sc->flags & BXE_TX_SWITCHING) {
11246         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11247     }
11248
11249     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11250
11251     return (flags);
11252 }
11253
11254 static unsigned long
11255 bxe_get_q_flags(struct bxe_softc    *sc,
11256                 struct bxe_fastpath *fp,
11257                 uint8_t             leading)
11258 {
11259     unsigned long flags = 0;
11260
11261     if (IS_MF_SD(sc)) {
11262         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11263     }
11264
11265     if (sc->ifnet->if_capenable & IFCAP_LRO) {
11266         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11267 #if __FreeBSD_version >= 800000
11268         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11269 #endif
11270     }
11271
11272     if (leading) {
11273         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11274         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11275     }
11276
11277     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11278
11279     /* merge with common flags */
11280     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11281 }
11282
11283 static void
11284 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11285                       struct bxe_fastpath               *fp,
11286                       struct ecore_general_setup_params *gen_init,
11287                       uint8_t                           cos)
11288 {
11289     gen_init->stat_id = bxe_stats_id(fp);
11290     gen_init->spcl_id = fp->cl_id;
11291     gen_init->mtu = sc->mtu;
11292     gen_init->cos = cos;
11293 }
11294
11295 static void
11296 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11297                  struct bxe_fastpath           *fp,
11298                  struct rxq_pause_params       *pause,
11299                  struct ecore_rxq_setup_params *rxq_init)
11300 {
11301     uint8_t max_sge = 0;
11302     uint16_t sge_sz = 0;
11303     uint16_t tpa_agg_size = 0;
11304
11305     pause->sge_th_lo = SGE_TH_LO(sc);
11306     pause->sge_th_hi = SGE_TH_HI(sc);
11307
11308     /* validate SGE ring has enough to cross high threshold */
11309     if (sc->dropless_fc &&
11310             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11311             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11312         BLOGW(sc, "sge ring threshold limit\n");
11313     }
11314
11315     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11316     tpa_agg_size = (2 * sc->mtu);
11317     if (tpa_agg_size < sc->max_aggregation_size) {
11318         tpa_agg_size = sc->max_aggregation_size;
11319     }
11320
11321     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11322     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11323                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11324     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11325
11326     /* pause - not for e1 */
11327     if (!CHIP_IS_E1(sc)) {
11328         pause->bd_th_lo = BD_TH_LO(sc);
11329         pause->bd_th_hi = BD_TH_HI(sc);
11330
11331         pause->rcq_th_lo = RCQ_TH_LO(sc);
11332         pause->rcq_th_hi = RCQ_TH_HI(sc);
11333
11334         /* validate rings have enough entries to cross high thresholds */
11335         if (sc->dropless_fc &&
11336             pause->bd_th_hi + FW_PREFETCH_CNT >
11337             sc->rx_ring_size) {
11338             BLOGW(sc, "rx bd ring threshold limit\n");
11339         }
11340
11341         if (sc->dropless_fc &&
11342             pause->rcq_th_hi + FW_PREFETCH_CNT >
11343             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11344             BLOGW(sc, "rcq ring threshold limit\n");
11345         }
11346
11347         pause->pri_map = 1;
11348     }
11349
11350     /* rxq setup */
11351     rxq_init->dscr_map   = fp->rx_dma.paddr;
11352     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11353     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11354     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11355
11356     /*
11357      * This should be a maximum number of data bytes that may be
11358      * placed on the BD (not including paddings).
11359      */
11360     rxq_init->buf_sz = (fp->rx_buf_size -
11361                         IP_HEADER_ALIGNMENT_PADDING);
11362
11363     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11364     rxq_init->tpa_agg_sz      = tpa_agg_size;
11365     rxq_init->sge_buf_sz      = sge_sz;
11366     rxq_init->max_sges_pkt    = max_sge;
11367     rxq_init->rss_engine_id   = SC_FUNC(sc);
11368     rxq_init->mcast_engine_id = SC_FUNC(sc);
11369
11370     /*
11371      * Maximum number or simultaneous TPA aggregation for this Queue.
11372      * For PF Clients it should be the maximum available number.
11373      * VF driver(s) may want to define it to a smaller value.
11374      */
11375     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11376
11377     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11378     rxq_init->fw_sb_id = fp->fw_sb_id;
11379
11380     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11381
11382     /*
11383      * configure silent vlan removal
11384      * if multi function mode is afex, then mask default vlan
11385      */
11386     if (IS_MF_AFEX(sc)) {
11387         rxq_init->silent_removal_value =
11388             sc->devinfo.mf_info.afex_def_vlan_tag;
11389         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11390     }
11391 }
11392
11393 static void
11394 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11395                  struct bxe_fastpath           *fp,
11396                  struct ecore_txq_setup_params *txq_init,
11397                  uint8_t                       cos)
11398 {
11399     /*
11400      * XXX If multiple CoS is ever supported then each fastpath structure
11401      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11402      * fp->txdata[cos]->tx_dma.paddr;
11403      */
11404     txq_init->dscr_map     = fp->tx_dma.paddr;
11405     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11406     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11407     txq_init->fw_sb_id     = fp->fw_sb_id;
11408
11409     /*
11410      * set the TSS leading client id for TX classfication to the
11411      * leading RSS client id
11412      */
11413     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11414 }
11415
11416 /*
11417  * This function performs 2 steps in a queue state machine:
11418  *   1) RESET->INIT
11419  *   2) INIT->SETUP
11420  */
11421 static int
11422 bxe_setup_queue(struct bxe_softc    *sc,
11423                 struct bxe_fastpath *fp,
11424                 uint8_t             leading)
11425 {
11426     struct ecore_queue_state_params q_params = { NULL };
11427     struct ecore_queue_setup_params *setup_params =
11428                         &q_params.params.setup;
11429     int rc;
11430
11431     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11432
11433     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11434
11435     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11436
11437     /* we want to wait for completion in this context */
11438     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11439
11440     /* prepare the INIT parameters */
11441     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11442
11443     /* Set the command */
11444     q_params.cmd = ECORE_Q_CMD_INIT;
11445
11446     /* Change the state to INIT */
11447     rc = ecore_queue_state_change(sc, &q_params);
11448     if (rc) {
11449         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11450         return (rc);
11451     }
11452
11453     BLOGD(sc, DBG_LOAD, "init complete\n");
11454
11455     /* now move the Queue to the SETUP state */
11456     memset(setup_params, 0, sizeof(*setup_params));
11457
11458     /* set Queue flags */
11459     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11460
11461     /* set general SETUP parameters */
11462     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11463                           FIRST_TX_COS_INDEX);
11464
11465     bxe_pf_rx_q_prep(sc, fp,
11466                      &setup_params->pause_params,
11467                      &setup_params->rxq_params);
11468
11469     bxe_pf_tx_q_prep(sc, fp,
11470                      &setup_params->txq_params,
11471                      FIRST_TX_COS_INDEX);
11472
11473     /* Set the command */
11474     q_params.cmd = ECORE_Q_CMD_SETUP;
11475
11476     /* change the state to SETUP */
11477     rc = ecore_queue_state_change(sc, &q_params);
11478     if (rc) {
11479         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11480         return (rc);
11481     }
11482
11483     return (rc);
11484 }
11485
11486 static int
11487 bxe_setup_leading(struct bxe_softc *sc)
11488 {
11489     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11490 }
11491
11492 static int
11493 bxe_config_rss_pf(struct bxe_softc            *sc,
11494                   struct ecore_rss_config_obj *rss_obj,
11495                   uint8_t                     config_hash)
11496 {
11497     struct ecore_config_rss_params params = { NULL };
11498     int i;
11499
11500     /*
11501      * Although RSS is meaningless when there is a single HW queue we
11502      * still need it enabled in order to have HW Rx hash generated.
11503      */
11504
11505     params.rss_obj = rss_obj;
11506
11507     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11508
11509     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11510
11511     /* RSS configuration */
11512     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11513     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11514     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11515     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11516     if (rss_obj->udp_rss_v4) {
11517         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11518     }
11519     if (rss_obj->udp_rss_v6) {
11520         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11521     }
11522
11523     /* Hash bits */
11524     params.rss_result_mask = MULTI_MASK;
11525
11526     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11527
11528     if (config_hash) {
11529         /* RSS keys */
11530         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11531             params.rss_key[i] = arc4random();
11532         }
11533
11534         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11535     }
11536
11537     return (ecore_config_rss(sc, &params));
11538 }
11539
11540 static int
11541 bxe_config_rss_eth(struct bxe_softc *sc,
11542                    uint8_t          config_hash)
11543 {
11544     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11545 }
11546
11547 static int
11548 bxe_init_rss_pf(struct bxe_softc *sc)
11549 {
11550     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11551     int i;
11552
11553     /*
11554      * Prepare the initial contents of the indirection table if
11555      * RSS is enabled
11556      */
11557     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11558         sc->rss_conf_obj.ind_table[i] =
11559             (sc->fp->cl_id + (i % num_eth_queues));
11560     }
11561
11562     if (sc->udp_rss) {
11563         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11564     }
11565
11566     /*
11567      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11568      * per-port, so if explicit configuration is needed, do it only
11569      * for a PMF.
11570      *
11571      * For 57712 and newer it's a per-function configuration.
11572      */
11573     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11574 }
11575
11576 static int
11577 bxe_set_mac_one(struct bxe_softc          *sc,
11578                 uint8_t                   *mac,
11579                 struct ecore_vlan_mac_obj *obj,
11580                 uint8_t                   set,
11581                 int                       mac_type,
11582                 unsigned long             *ramrod_flags)
11583 {
11584     struct ecore_vlan_mac_ramrod_params ramrod_param;
11585     int rc;
11586
11587     memset(&ramrod_param, 0, sizeof(ramrod_param));
11588
11589     /* fill in general parameters */
11590     ramrod_param.vlan_mac_obj = obj;
11591     ramrod_param.ramrod_flags = *ramrod_flags;
11592
11593     /* fill a user request section if needed */
11594     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11595         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11596
11597         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11598
11599         /* Set the command: ADD or DEL */
11600         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11601                                             ECORE_VLAN_MAC_DEL;
11602     }
11603
11604     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11605
11606     if (rc == ECORE_EXISTS) {
11607         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11608         /* do not treat adding same MAC as error */
11609         rc = 0;
11610     } else if (rc < 0) {
11611         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11612     }
11613
11614     return (rc);
11615 }
11616
11617 static int
11618 bxe_set_eth_mac(struct bxe_softc *sc,
11619                 uint8_t          set)
11620 {
11621     unsigned long ramrod_flags = 0;
11622
11623     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11624
11625     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11626
11627     /* Eth MAC is set on RSS leading client (fp[0]) */
11628     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11629                             &sc->sp_objs->mac_obj,
11630                             set, ECORE_ETH_MAC, &ramrod_flags));
11631 }
11632
11633 static int
11634 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11635 {
11636     uint32_t sel_phy_idx = 0;
11637
11638     if (sc->link_params.num_phys <= 1) {
11639         return (ELINK_INT_PHY);
11640     }
11641
11642     if (sc->link_vars.link_up) {
11643         sel_phy_idx = ELINK_EXT_PHY1;
11644         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11645         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11646             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11647              ELINK_SUPPORTED_FIBRE))
11648             sel_phy_idx = ELINK_EXT_PHY2;
11649     } else {
11650         switch (elink_phy_selection(&sc->link_params)) {
11651         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11652         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11653         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11654                sel_phy_idx = ELINK_EXT_PHY1;
11655                break;
11656         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11657         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11658                sel_phy_idx = ELINK_EXT_PHY2;
11659                break;
11660         }
11661     }
11662
11663     return (sel_phy_idx);
11664 }
11665
11666 static int
11667 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11668 {
11669     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11670
11671     /*
11672      * The selected activated PHY is always after swapping (in case PHY
11673      * swapping is enabled). So when swapping is enabled, we need to reverse
11674      * the configuration
11675      */
11676
11677     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11678         if (sel_phy_idx == ELINK_EXT_PHY1)
11679             sel_phy_idx = ELINK_EXT_PHY2;
11680         else if (sel_phy_idx == ELINK_EXT_PHY2)
11681             sel_phy_idx = ELINK_EXT_PHY1;
11682     }
11683
11684     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11685 }
11686
11687 static void
11688 bxe_set_requested_fc(struct bxe_softc *sc)
11689 {
11690     /*
11691      * Initialize link parameters structure variables
11692      * It is recommended to turn off RX FC for jumbo frames
11693      * for better performance
11694      */
11695     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11696         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11697     } else {
11698         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11699     }
11700 }
11701
11702 static void
11703 bxe_calc_fc_adv(struct bxe_softc *sc)
11704 {
11705     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11706
11707
11708     sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11709                                            ADVERTISED_Pause);
11710
11711     switch (sc->link_vars.ieee_fc &
11712             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11713
11714     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11715         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11716                                           ADVERTISED_Pause);
11717         break;
11718
11719     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11720         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11721         break;
11722
11723     default:
11724         break;
11725
11726     }
11727 }
11728
11729 static uint16_t
11730 bxe_get_mf_speed(struct bxe_softc *sc)
11731 {
11732     uint16_t line_speed = sc->link_vars.line_speed;
11733     if (IS_MF(sc)) {
11734         uint16_t maxCfg =
11735             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11736
11737         /* calculate the current MAX line speed limit for the MF devices */
11738         if (IS_MF_SI(sc)) {
11739             line_speed = (line_speed * maxCfg) / 100;
11740         } else { /* SD mode */
11741             uint16_t vn_max_rate = maxCfg * 100;
11742
11743             if (vn_max_rate < line_speed) {
11744                 line_speed = vn_max_rate;
11745             }
11746         }
11747     }
11748
11749     return (line_speed);
11750 }
11751
11752 static void
11753 bxe_fill_report_data(struct bxe_softc            *sc,
11754                      struct bxe_link_report_data *data)
11755 {
11756     uint16_t line_speed = bxe_get_mf_speed(sc);
11757
11758     memset(data, 0, sizeof(*data));
11759
11760     /* fill the report data with the effective line speed */
11761     data->line_speed = line_speed;
11762
11763     /* Link is down */
11764     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11765         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11766     }
11767
11768     /* Full DUPLEX */
11769     if (sc->link_vars.duplex == DUPLEX_FULL) {
11770         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11771     }
11772
11773     /* Rx Flow Control is ON */
11774     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11775         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11776     }
11777
11778     /* Tx Flow Control is ON */
11779     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11780         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11781     }
11782 }
11783
11784 /* report link status to OS, should be called under phy_lock */
11785 static void
11786 bxe_link_report_locked(struct bxe_softc *sc)
11787 {
11788     struct bxe_link_report_data cur_data;
11789
11790     /* reread mf_cfg */
11791     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11792         bxe_read_mf_cfg(sc);
11793     }
11794
11795     /* Read the current link report info */
11796     bxe_fill_report_data(sc, &cur_data);
11797
11798     /* Don't report link down or exactly the same link status twice */
11799     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11800         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11801                       &sc->last_reported_link.link_report_flags) &&
11802          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11803                       &cur_data.link_report_flags))) {
11804         return;
11805     }
11806
11807         ELINK_DEBUG_P2(sc, "Change in link status : cur_data = %x, last_reported_link = %x\n",
11808                                         cur_data.link_report_flags, sc->last_reported_link.link_report_flags);
11809     sc->link_cnt++;
11810
11811         ELINK_DEBUG_P1(sc, "link status change count = %x\n", sc->link_cnt);
11812     /* report new link params and remember the state for the next time */
11813     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11814
11815     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11816                      &cur_data.link_report_flags)) {
11817         if_link_state_change(sc->ifnet, LINK_STATE_DOWN);
11818     } else {
11819         const char *duplex;
11820         const char *flow;
11821
11822         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11823                                    &cur_data.link_report_flags)) {
11824             duplex = "full";
11825                         ELINK_DEBUG_P0(sc, "link set to full duplex\n");
11826         } else {
11827             duplex = "half";
11828                         ELINK_DEBUG_P0(sc, "link set to half duplex\n");
11829         }
11830
11831         /*
11832          * Handle the FC at the end so that only these flags would be
11833          * possibly set. This way we may easily check if there is no FC
11834          * enabled.
11835          */
11836         if (cur_data.link_report_flags) {
11837             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11838                              &cur_data.link_report_flags) &&
11839                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11840                              &cur_data.link_report_flags)) {
11841                 flow = "ON - receive & transmit";
11842             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11843                                     &cur_data.link_report_flags) &&
11844                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11845                                      &cur_data.link_report_flags)) {
11846                 flow = "ON - receive";
11847             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11848                                      &cur_data.link_report_flags) &&
11849                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11850                                     &cur_data.link_report_flags)) {
11851                 flow = "ON - transmit";
11852             } else {
11853                 flow = "none"; /* possible? */
11854             }
11855         } else {
11856             flow = "none";
11857         }
11858
11859         if_link_state_change(sc->ifnet, LINK_STATE_UP);
11860         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11861               cur_data.line_speed, duplex, flow);
11862     }
11863 }
11864
11865 static void
11866 bxe_link_report(struct bxe_softc *sc)
11867 {
11868     bxe_acquire_phy_lock(sc);
11869     bxe_link_report_locked(sc);
11870     bxe_release_phy_lock(sc);
11871 }
11872
11873 static void
11874 bxe_link_status_update(struct bxe_softc *sc)
11875 {
11876     if (sc->state != BXE_STATE_OPEN) {
11877         return;
11878     }
11879
11880     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11881         elink_link_status_update(&sc->link_params, &sc->link_vars);
11882     } else {
11883         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11884                                   ELINK_SUPPORTED_10baseT_Full |
11885                                   ELINK_SUPPORTED_100baseT_Half |
11886                                   ELINK_SUPPORTED_100baseT_Full |
11887                                   ELINK_SUPPORTED_1000baseT_Full |
11888                                   ELINK_SUPPORTED_2500baseX_Full |
11889                                   ELINK_SUPPORTED_10000baseT_Full |
11890                                   ELINK_SUPPORTED_TP |
11891                                   ELINK_SUPPORTED_FIBRE |
11892                                   ELINK_SUPPORTED_Autoneg |
11893                                   ELINK_SUPPORTED_Pause |
11894                                   ELINK_SUPPORTED_Asym_Pause);
11895         sc->port.advertising[0] = sc->port.supported[0];
11896
11897         sc->link_params.sc                = sc;
11898         sc->link_params.port              = SC_PORT(sc);
11899         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11900         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11901         sc->link_params.req_line_speed[0] = SPEED_10000;
11902         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11903         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11904
11905         if (CHIP_REV_IS_FPGA(sc)) {
11906             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11907             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11908             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11909                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11910         } else {
11911             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11912             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11913             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11914                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11915         }
11916
11917         sc->link_vars.link_up = 1;
11918
11919         sc->link_vars.duplex    = DUPLEX_FULL;
11920         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11921
11922         if (IS_PF(sc)) {
11923             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11924             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11925             bxe_link_report(sc);
11926         }
11927     }
11928
11929     if (IS_PF(sc)) {
11930         if (sc->link_vars.link_up) {
11931             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11932         } else {
11933             bxe_stats_handle(sc, STATS_EVENT_STOP);
11934         }
11935         bxe_link_report(sc);
11936     } else {
11937         bxe_link_report(sc);
11938         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11939     }
11940 }
11941
11942 static int
11943 bxe_initial_phy_init(struct bxe_softc *sc,
11944                      int              load_mode)
11945 {
11946     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11947     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11948     struct elink_params *lp = &sc->link_params;
11949
11950     bxe_set_requested_fc(sc);
11951
11952     if (CHIP_REV_IS_SLOW(sc)) {
11953         uint32_t bond = CHIP_BOND_ID(sc);
11954         uint32_t feat = 0;
11955
11956         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11957             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11958         } else if (bond & 0x4) {
11959             if (CHIP_IS_E3(sc)) {
11960                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11961             } else {
11962                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11963             }
11964         } else if (bond & 0x8) {
11965             if (CHIP_IS_E3(sc)) {
11966                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11967             } else {
11968                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11969             }
11970         }
11971
11972         /* disable EMAC for E3 and above */
11973         if (bond & 0x2) {
11974             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11975         }
11976
11977         sc->link_params.feature_config_flags |= feat;
11978     }
11979
11980     bxe_acquire_phy_lock(sc);
11981
11982     if (load_mode == LOAD_DIAG) {
11983         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
11984         /* Prefer doing PHY loopback at 10G speed, if possible */
11985         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
11986             if (lp->speed_cap_mask[cfg_idx] &
11987                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
11988                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
11989             } else {
11990                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
11991             }
11992         }
11993     }
11994
11995     if (load_mode == LOAD_LOOPBACK_EXT) {
11996         lp->loopback_mode = ELINK_LOOPBACK_EXT;
11997     }
11998
11999     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
12000
12001     bxe_release_phy_lock(sc);
12002
12003     bxe_calc_fc_adv(sc);
12004
12005     if (sc->link_vars.link_up) {
12006         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12007         bxe_link_report(sc);
12008     }
12009
12010     if (!CHIP_REV_IS_SLOW(sc)) {
12011         bxe_periodic_start(sc);
12012     }
12013
12014     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
12015     return (rc);
12016 }
12017
12018 /* must be called under IF_ADDR_LOCK */
12019 static int
12020 bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
12021                          struct ecore_mcast_ramrod_params *p)
12022 {
12023     struct ifnet *ifp = sc->ifnet;
12024     int mc_count = 0;
12025     struct ifmultiaddr *ifma;
12026     struct ecore_mcast_list_elem *mc_mac;
12027
12028     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12029         if (ifma->ifma_addr->sa_family != AF_LINK) {
12030             continue;
12031         }
12032
12033         mc_count++;
12034     }
12035
12036     ECORE_LIST_INIT(&p->mcast_list);
12037     p->mcast_list_len = 0;
12038
12039     if (!mc_count) {
12040         return (0);
12041     }
12042
12043     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12044                     (M_NOWAIT | M_ZERO));
12045     if (!mc_mac) {
12046         BLOGE(sc, "Failed to allocate temp mcast list\n");
12047         return (-1);
12048     }
12049     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12050
12051     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12052         if (ifma->ifma_addr->sa_family != AF_LINK) {
12053             continue;
12054         }
12055
12056         mc_mac->mac = (uint8_t *)LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
12057         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &p->mcast_list);
12058
12059         BLOGD(sc, DBG_LOAD,
12060               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X and mc_count %d\n",
12061               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12062               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5], mc_count);
12063        mc_mac++;
12064     }
12065
12066     p->mcast_list_len = mc_count;
12067
12068     return (0);
12069 }
12070
12071
12072 static void
12073 bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12074 {
12075     struct ecore_mcast_list_elem *mc_mac =
12076         ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12077                                struct ecore_mcast_list_elem,
12078                                link);
12079
12080     if (mc_mac) {
12081         /* only a single free as all mc_macs are in the same heap array */
12082         free(mc_mac, M_DEVBUF);
12083     }
12084 }
12085
12086 static int
12087 bxe_set_mc_list(struct bxe_softc *sc)
12088 {
12089     struct ecore_mcast_ramrod_params rparam = { NULL };
12090     int rc = 0;
12091
12092     rparam.mcast_obj = &sc->mcast_obj;
12093
12094     BXE_MCAST_LOCK(sc);
12095
12096     /* first, clear all configured multicast MACs */
12097     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12098     if (rc < 0) {
12099         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12100         /* Manual backport parts of FreeBSD upstream r284470. */
12101         BXE_MCAST_UNLOCK(sc);
12102         return (rc);
12103     }
12104
12105     /* configure a new MACs list */
12106     rc = bxe_init_mcast_macs_list(sc, &rparam);
12107     if (rc) {
12108         BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12109         BXE_MCAST_UNLOCK(sc);
12110         return (rc);
12111     }
12112
12113     /* Now add the new MACs */
12114     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12115     if (rc < 0) {
12116         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12117     }
12118
12119     bxe_free_mcast_macs_list(&rparam);
12120
12121     BXE_MCAST_UNLOCK(sc);
12122
12123     return (rc);
12124 }
12125
12126 static int
12127 bxe_set_uc_list(struct bxe_softc *sc)
12128 {
12129     struct ifnet *ifp = sc->ifnet;
12130     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12131     struct ifaddr *ifa;
12132     unsigned long ramrod_flags = 0;
12133     int rc;
12134
12135 #if __FreeBSD_version < 800000
12136     IF_ADDR_LOCK(ifp);
12137 #else
12138     if_addr_rlock(ifp);
12139 #endif
12140
12141     /* first schedule a cleanup up of old configuration */
12142     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12143     if (rc < 0) {
12144         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12145 #if __FreeBSD_version < 800000
12146         IF_ADDR_UNLOCK(ifp);
12147 #else
12148         if_addr_runlock(ifp);
12149 #endif
12150         return (rc);
12151     }
12152
12153     ifa = ifp->if_addr;
12154     while (ifa) {
12155         if (ifa->ifa_addr->sa_family != AF_LINK) {
12156             ifa = TAILQ_NEXT(ifa, ifa_link);
12157             continue;
12158         }
12159
12160         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12161                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12162         if (rc == -EEXIST) {
12163             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12164             /* do not treat adding same MAC as an error */
12165             rc = 0;
12166         } else if (rc < 0) {
12167             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12168 #if __FreeBSD_version < 800000
12169             IF_ADDR_UNLOCK(ifp);
12170 #else
12171             if_addr_runlock(ifp);
12172 #endif
12173             return (rc);
12174         }
12175
12176         ifa = TAILQ_NEXT(ifa, ifa_link);
12177     }
12178
12179 #if __FreeBSD_version < 800000
12180     IF_ADDR_UNLOCK(ifp);
12181 #else
12182     if_addr_runlock(ifp);
12183 #endif
12184
12185     /* Execute the pending commands */
12186     bit_set(&ramrod_flags, RAMROD_CONT);
12187     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12188                             ECORE_UC_LIST_MAC, &ramrod_flags));
12189 }
12190
12191 static void
12192 bxe_set_rx_mode(struct bxe_softc *sc)
12193 {
12194     struct ifnet *ifp = sc->ifnet;
12195     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12196
12197     if (sc->state != BXE_STATE_OPEN) {
12198         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12199         return;
12200     }
12201
12202     BLOGD(sc, DBG_SP, "ifp->if_flags=0x%x\n", ifp->if_flags);
12203
12204     if (ifp->if_flags & IFF_PROMISC) {
12205         rx_mode = BXE_RX_MODE_PROMISC;
12206     } else if ((ifp->if_flags & IFF_ALLMULTI) ||
12207                ((ifp->if_amcount > BXE_MAX_MULTICAST) &&
12208                 CHIP_IS_E1(sc))) {
12209         rx_mode = BXE_RX_MODE_ALLMULTI;
12210     } else {
12211         if (IS_PF(sc)) {
12212             /* some multicasts */
12213             if (bxe_set_mc_list(sc) < 0) {
12214                 rx_mode = BXE_RX_MODE_ALLMULTI;
12215             }
12216             if (bxe_set_uc_list(sc) < 0) {
12217                 rx_mode = BXE_RX_MODE_PROMISC;
12218             }
12219         }
12220     }
12221
12222     sc->rx_mode = rx_mode;
12223
12224     /* schedule the rx_mode command */
12225     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12226         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12227         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12228         return;
12229     }
12230
12231     if (IS_PF(sc)) {
12232         bxe_set_storm_rx_mode(sc);
12233     }
12234 }
12235
12236
12237 /* update flags in shmem */
12238 static void
12239 bxe_update_drv_flags(struct bxe_softc *sc,
12240                      uint32_t         flags,
12241                      uint32_t         set)
12242 {
12243     uint32_t drv_flags;
12244
12245     if (SHMEM2_HAS(sc, drv_flags)) {
12246         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12247         drv_flags = SHMEM2_RD(sc, drv_flags);
12248
12249         if (set) {
12250             SET_FLAGS(drv_flags, flags);
12251         } else {
12252             RESET_FLAGS(drv_flags, flags);
12253         }
12254
12255         SHMEM2_WR(sc, drv_flags, drv_flags);
12256         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12257
12258         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12259     }
12260 }
12261
12262 /* periodic timer callout routine, only runs when the interface is up */
12263
12264 static void
12265 bxe_periodic_callout_func(void *xsc)
12266 {
12267     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12268     int i;
12269
12270     if (!BXE_CORE_TRYLOCK(sc)) {
12271         /* just bail and try again next time */
12272
12273         if ((sc->state == BXE_STATE_OPEN) &&
12274             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12275             /* schedule the next periodic callout */
12276             callout_reset(&sc->periodic_callout, hz,
12277                           bxe_periodic_callout_func, sc);
12278         }
12279
12280         return;
12281     }
12282
12283     if ((sc->state != BXE_STATE_OPEN) ||
12284         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12285         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12286         BXE_CORE_UNLOCK(sc);
12287         return;
12288     }
12289
12290
12291     /* Check for TX timeouts on any fastpath. */
12292     FOR_EACH_QUEUE(sc, i) {
12293         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12294             /* Ruh-Roh, chip was reset! */
12295             break;
12296         }
12297     }
12298
12299     if (!CHIP_REV_IS_SLOW(sc)) {
12300         /*
12301          * This barrier is needed to ensure the ordering between the writing
12302          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12303          * the reading here.
12304          */
12305         mb();
12306         if (sc->port.pmf) {
12307             bxe_acquire_phy_lock(sc);
12308             elink_period_func(&sc->link_params, &sc->link_vars);
12309             bxe_release_phy_lock(sc);
12310         }
12311     }
12312
12313     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12314         int mb_idx = SC_FW_MB_IDX(sc);
12315         uint32_t drv_pulse;
12316         uint32_t mcp_pulse;
12317
12318         ++sc->fw_drv_pulse_wr_seq;
12319         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12320
12321         drv_pulse = sc->fw_drv_pulse_wr_seq;
12322         bxe_drv_pulse(sc);
12323
12324         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12325                      MCP_PULSE_SEQ_MASK);
12326
12327         /*
12328          * The delta between driver pulse and mcp response should
12329          * be 1 (before mcp response) or 0 (after mcp response).
12330          */
12331         if ((drv_pulse != mcp_pulse) &&
12332             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12333             /* someone lost a heartbeat... */
12334             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12335                   drv_pulse, mcp_pulse);
12336         }
12337     }
12338
12339     /* state is BXE_STATE_OPEN */
12340     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12341
12342     BXE_CORE_UNLOCK(sc);
12343
12344     if ((sc->state == BXE_STATE_OPEN) &&
12345         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12346         /* schedule the next periodic callout */
12347         callout_reset(&sc->periodic_callout, hz,
12348                       bxe_periodic_callout_func, sc);
12349     }
12350 }
12351
12352 static void
12353 bxe_periodic_start(struct bxe_softc *sc)
12354 {
12355     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12356     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12357 }
12358
12359 static void
12360 bxe_periodic_stop(struct bxe_softc *sc)
12361 {
12362     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12363     callout_drain(&sc->periodic_callout);
12364 }
12365
12366 /* start the controller */
12367 static __noinline int
12368 bxe_nic_load(struct bxe_softc *sc,
12369              int              load_mode)
12370 {
12371     uint32_t val;
12372     int load_code = 0;
12373     int i, rc = 0;
12374
12375     BXE_CORE_LOCK_ASSERT(sc);
12376
12377     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12378
12379     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12380
12381     if (IS_PF(sc)) {
12382         /* must be called before memory allocation and HW init */
12383         bxe_ilt_set_info(sc);
12384     }
12385
12386     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12387
12388     bxe_set_fp_rx_buf_size(sc);
12389
12390     if (bxe_alloc_fp_buffers(sc) != 0) {
12391         BLOGE(sc, "Failed to allocate fastpath memory\n");
12392         sc->state = BXE_STATE_CLOSED;
12393         rc = ENOMEM;
12394         goto bxe_nic_load_error0;
12395     }
12396
12397     if (bxe_alloc_mem(sc) != 0) {
12398         sc->state = BXE_STATE_CLOSED;
12399         rc = ENOMEM;
12400         goto bxe_nic_load_error0;
12401     }
12402
12403     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12404         sc->state = BXE_STATE_CLOSED;
12405         rc = ENOMEM;
12406         goto bxe_nic_load_error0;
12407     }
12408
12409     if (IS_PF(sc)) {
12410         /* set pf load just before approaching the MCP */
12411         bxe_set_pf_load(sc);
12412
12413         /* if MCP exists send load request and analyze response */
12414         if (!BXE_NOMCP(sc)) {
12415             /* attempt to load pf */
12416             if (bxe_nic_load_request(sc, &load_code) != 0) {
12417                 sc->state = BXE_STATE_CLOSED;
12418                 rc = ENXIO;
12419                 goto bxe_nic_load_error1;
12420             }
12421
12422             /* what did the MCP say? */
12423             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12424                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12425                 sc->state = BXE_STATE_CLOSED;
12426                 rc = ENXIO;
12427                 goto bxe_nic_load_error2;
12428             }
12429         } else {
12430             BLOGI(sc, "Device has no MCP!\n");
12431             load_code = bxe_nic_load_no_mcp(sc);
12432         }
12433
12434         /* mark PMF if applicable */
12435         bxe_nic_load_pmf(sc, load_code);
12436
12437         /* Init Function state controlling object */
12438         bxe_init_func_obj(sc);
12439
12440         /* Initialize HW */
12441         if (bxe_init_hw(sc, load_code) != 0) {
12442             BLOGE(sc, "HW init failed\n");
12443             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12444             sc->state = BXE_STATE_CLOSED;
12445             rc = ENXIO;
12446             goto bxe_nic_load_error2;
12447         }
12448     }
12449
12450     /* set ALWAYS_ALIVE bit in shmem */
12451     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12452     bxe_drv_pulse(sc);
12453     sc->flags |= BXE_NO_PULSE;
12454
12455     /* attach interrupts */
12456     if (bxe_interrupt_attach(sc) != 0) {
12457         sc->state = BXE_STATE_CLOSED;
12458         rc = ENXIO;
12459         goto bxe_nic_load_error2;
12460     }
12461
12462     bxe_nic_init(sc, load_code);
12463
12464     /* Init per-function objects */
12465     if (IS_PF(sc)) {
12466         bxe_init_objs(sc);
12467         // XXX bxe_iov_nic_init(sc);
12468
12469         /* set AFEX default VLAN tag to an invalid value */
12470         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12471         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12472
12473         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12474         rc = bxe_func_start(sc);
12475         if (rc) {
12476             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12477             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12478             sc->state = BXE_STATE_ERROR;
12479             goto bxe_nic_load_error3;
12480         }
12481
12482         /* send LOAD_DONE command to MCP */
12483         if (!BXE_NOMCP(sc)) {
12484             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12485             if (!load_code) {
12486                 BLOGE(sc, "MCP response failure, aborting\n");
12487                 sc->state = BXE_STATE_ERROR;
12488                 rc = ENXIO;
12489                 goto bxe_nic_load_error3;
12490             }
12491         }
12492
12493         rc = bxe_setup_leading(sc);
12494         if (rc) {
12495             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12496             sc->state = BXE_STATE_ERROR;
12497             goto bxe_nic_load_error3;
12498         }
12499
12500         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12501             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12502             if (rc) {
12503                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12504                 sc->state = BXE_STATE_ERROR;
12505                 goto bxe_nic_load_error3;
12506             }
12507         }
12508
12509         rc = bxe_init_rss_pf(sc);
12510         if (rc) {
12511             BLOGE(sc, "PF RSS init failed\n");
12512             sc->state = BXE_STATE_ERROR;
12513             goto bxe_nic_load_error3;
12514         }
12515     }
12516     /* XXX VF */
12517
12518     /* now when Clients are configured we are ready to work */
12519     sc->state = BXE_STATE_OPEN;
12520
12521     /* Configure a ucast MAC */
12522     if (IS_PF(sc)) {
12523         rc = bxe_set_eth_mac(sc, TRUE);
12524     }
12525     if (rc) {
12526         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12527         sc->state = BXE_STATE_ERROR;
12528         goto bxe_nic_load_error3;
12529     }
12530
12531     if (sc->port.pmf) {
12532         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12533         if (rc) {
12534             sc->state = BXE_STATE_ERROR;
12535             goto bxe_nic_load_error3;
12536         }
12537     }
12538
12539     sc->link_params.feature_config_flags &=
12540         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12541
12542     /* start fast path */
12543
12544     /* Initialize Rx filter */
12545     bxe_set_rx_mode(sc);
12546
12547     /* start the Tx */
12548     switch (/* XXX load_mode */LOAD_OPEN) {
12549     case LOAD_NORMAL:
12550     case LOAD_OPEN:
12551         break;
12552
12553     case LOAD_DIAG:
12554     case LOAD_LOOPBACK_EXT:
12555         sc->state = BXE_STATE_DIAG;
12556         break;
12557
12558     default:
12559         break;
12560     }
12561
12562     if (sc->port.pmf) {
12563         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12564     } else {
12565         bxe_link_status_update(sc);
12566     }
12567
12568     /* start the periodic timer callout */
12569     bxe_periodic_start(sc);
12570
12571     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12572         /* mark driver is loaded in shmem2 */
12573         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12574         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12575                   (val |
12576                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12577                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12578     }
12579
12580     /* wait for all pending SP commands to complete */
12581     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12582         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12583         bxe_periodic_stop(sc);
12584         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12585         return (ENXIO);
12586     }
12587
12588     /* Tell the stack the driver is running! */
12589     sc->ifnet->if_drv_flags = IFF_DRV_RUNNING;
12590
12591     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12592
12593     return (0);
12594
12595 bxe_nic_load_error3:
12596
12597     if (IS_PF(sc)) {
12598         bxe_int_disable_sync(sc, 1);
12599
12600         /* clean out queued objects */
12601         bxe_squeeze_objects(sc);
12602     }
12603
12604     bxe_interrupt_detach(sc);
12605
12606 bxe_nic_load_error2:
12607
12608     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12609         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12610         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12611     }
12612
12613     sc->port.pmf = 0;
12614
12615 bxe_nic_load_error1:
12616
12617     /* clear pf_load status, as it was already set */
12618     if (IS_PF(sc)) {
12619         bxe_clear_pf_load(sc);
12620     }
12621
12622 bxe_nic_load_error0:
12623
12624     bxe_free_fw_stats_mem(sc);
12625     bxe_free_fp_buffers(sc);
12626     bxe_free_mem(sc);
12627
12628     return (rc);
12629 }
12630
12631 static int
12632 bxe_init_locked(struct bxe_softc *sc)
12633 {
12634     int other_engine = SC_PATH(sc) ? 0 : 1;
12635     uint8_t other_load_status, load_status;
12636     uint8_t global = FALSE;
12637     int rc;
12638
12639     BXE_CORE_LOCK_ASSERT(sc);
12640
12641     /* check if the driver is already running */
12642     if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
12643         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12644         return (0);
12645     }
12646
12647     bxe_set_power_state(sc, PCI_PM_D0);
12648
12649     /*
12650      * If parity occurred during the unload, then attentions and/or
12651      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12652      * loaded on the current engine to complete the recovery. Parity recovery
12653      * is only relevant for PF driver.
12654      */
12655     if (IS_PF(sc)) {
12656         other_load_status = bxe_get_load_status(sc, other_engine);
12657         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12658
12659         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12660             bxe_chk_parity_attn(sc, &global, TRUE)) {
12661             do {
12662                 /*
12663                  * If there are attentions and they are in global blocks, set
12664                  * the GLOBAL_RESET bit regardless whether it will be this
12665                  * function that will complete the recovery or not.
12666                  */
12667                 if (global) {
12668                     bxe_set_reset_global(sc);
12669                 }
12670
12671                 /*
12672                  * Only the first function on the current engine should try
12673                  * to recover in open. In case of attentions in global blocks
12674                  * only the first in the chip should try to recover.
12675                  */
12676                 if ((!load_status && (!global || !other_load_status)) &&
12677                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12678                     BLOGI(sc, "Recovered during init\n");
12679                     break;
12680                 }
12681
12682                 /* recovery has failed... */
12683                 bxe_set_power_state(sc, PCI_PM_D3hot);
12684                 sc->recovery_state = BXE_RECOVERY_FAILED;
12685
12686                 BLOGE(sc, "Recovery flow hasn't properly "
12687                           "completed yet, try again later. "
12688                           "If you still see this message after a "
12689                           "few retries then power cycle is required.\n");
12690
12691                 rc = ENXIO;
12692                 goto bxe_init_locked_done;
12693             } while (0);
12694         }
12695     }
12696
12697     sc->recovery_state = BXE_RECOVERY_DONE;
12698
12699     rc = bxe_nic_load(sc, LOAD_OPEN);
12700
12701 bxe_init_locked_done:
12702
12703     if (rc) {
12704         /* Tell the stack the driver is NOT running! */
12705         BLOGE(sc, "Initialization failed, "
12706                   "stack notified driver is NOT running!\n");
12707         sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
12708     }
12709
12710     return (rc);
12711 }
12712
12713 static int
12714 bxe_stop_locked(struct bxe_softc *sc)
12715 {
12716     BXE_CORE_LOCK_ASSERT(sc);
12717     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12718 }
12719
12720 /*
12721  * Handles controller initialization when called from an unlocked routine.
12722  * ifconfig calls this function.
12723  *
12724  * Returns:
12725  *   void
12726  */
12727 static void
12728 bxe_init(void *xsc)
12729 {
12730     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12731
12732     BXE_CORE_LOCK(sc);
12733     bxe_init_locked(sc);
12734     BXE_CORE_UNLOCK(sc);
12735 }
12736
12737 static int
12738 bxe_init_ifnet(struct bxe_softc *sc)
12739 {
12740     struct ifnet *ifp;
12741
12742     /* ifconfig entrypoint for media type/status reporting */
12743     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12744                  bxe_ifmedia_update,
12745                  bxe_ifmedia_status);
12746
12747     /* set the default interface values */
12748     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12749     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12750     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12751
12752     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12753         BLOGI(sc, "IFMEDIA flags : %x\n", sc->ifmedia.ifm_media);
12754
12755     /* allocate the ifnet structure */
12756     if ((ifp = if_alloc(IFT_ETHER)) == NULL) {
12757         BLOGE(sc, "Interface allocation failed!\n");
12758         return (ENXIO);
12759     }
12760
12761     ifp->if_softc = sc;
12762     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12763     ifp->if_flags = (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
12764     ifp->if_ioctl = bxe_ioctl;
12765     ifp->if_start = bxe_tx_start;
12766 #if __FreeBSD_version >= 901504
12767     ifp->if_transmit = bxe_tx_mq_start;
12768     ifp->if_qflush = bxe_mq_flush;
12769 #endif
12770 #ifdef FreeBSD8_0
12771     ifp->if_timer = 0;
12772 #endif
12773     ifp->if_init = bxe_init;
12774     ifp->if_mtu = sc->mtu;
12775     ifp->if_hwassist = (CSUM_IP       |
12776                         CSUM_TCP      |
12777                         CSUM_UDP      |
12778                         CSUM_TSO      |
12779                         CSUM_TCP_IPV6 |
12780                         CSUM_UDP_IPV6);
12781     ifp->if_capabilities =
12782 #if __FreeBSD_version < 700000
12783         (IFCAP_VLAN_MTU       |
12784          IFCAP_VLAN_HWTAGGING |
12785          IFCAP_HWCSUM         |
12786          IFCAP_JUMBO_MTU      |
12787          IFCAP_LRO);
12788 #else
12789         (IFCAP_VLAN_MTU       |
12790          IFCAP_VLAN_HWTAGGING |
12791          IFCAP_VLAN_HWTSO     |
12792          IFCAP_VLAN_HWFILTER  |
12793          IFCAP_VLAN_HWCSUM    |
12794          IFCAP_HWCSUM         |
12795          IFCAP_JUMBO_MTU      |
12796          IFCAP_LRO            |
12797          IFCAP_TSO4           |
12798          IFCAP_TSO6           |
12799          IFCAP_WOL_MAGIC);
12800 #endif
12801     ifp->if_capenable = ifp->if_capabilities;
12802     ifp->if_capenable &= ~IFCAP_WOL_MAGIC; /* XXX not yet... */
12803 #if __FreeBSD_version < 1000025
12804     ifp->if_baudrate = 1000000000;
12805 #else
12806     if_initbaudrate(ifp, IF_Gbps(10));
12807 #endif
12808     ifp->if_snd.ifq_drv_maxlen = sc->tx_ring_size;
12809
12810     IFQ_SET_MAXLEN(&ifp->if_snd, ifp->if_snd.ifq_drv_maxlen);
12811     IFQ_SET_READY(&ifp->if_snd);
12812
12813     sc->ifnet = ifp;
12814
12815     /* attach to the Ethernet interface list */
12816     ether_ifattach(ifp, sc->link_params.mac_addr);
12817
12818     return (0);
12819 }
12820
12821 static void
12822 bxe_deallocate_bars(struct bxe_softc *sc)
12823 {
12824     int i;
12825
12826     for (i = 0; i < MAX_BARS; i++) {
12827         if (sc->bar[i].resource != NULL) {
12828             bus_release_resource(sc->dev,
12829                                  SYS_RES_MEMORY,
12830                                  sc->bar[i].rid,
12831                                  sc->bar[i].resource);
12832             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12833                   i, PCIR_BAR(i));
12834         }
12835     }
12836 }
12837
12838 static int
12839 bxe_allocate_bars(struct bxe_softc *sc)
12840 {
12841     u_int flags;
12842     int i;
12843
12844     memset(sc->bar, 0, sizeof(sc->bar));
12845
12846     for (i = 0; i < MAX_BARS; i++) {
12847
12848         /* memory resources reside at BARs 0, 2, 4 */
12849         /* Run `pciconf -lb` to see mappings */
12850         if ((i != 0) && (i != 2) && (i != 4)) {
12851             continue;
12852         }
12853
12854         sc->bar[i].rid = PCIR_BAR(i);
12855
12856         flags = RF_ACTIVE;
12857         if (i == 0) {
12858             flags |= RF_SHAREABLE;
12859         }
12860
12861         if ((sc->bar[i].resource =
12862              bus_alloc_resource_any(sc->dev,
12863                                     SYS_RES_MEMORY,
12864                                     &sc->bar[i].rid,
12865                                     flags)) == NULL) {
12866             return (0);
12867         }
12868
12869         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12870         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12871         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12872
12873         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%ld) -> %p\n",
12874               i, PCIR_BAR(i),
12875               (void *)rman_get_start(sc->bar[i].resource),
12876               (void *)rman_get_end(sc->bar[i].resource),
12877               rman_get_size(sc->bar[i].resource),
12878               (void *)sc->bar[i].kva);
12879     }
12880
12881     return (0);
12882 }
12883
12884 static void
12885 bxe_get_function_num(struct bxe_softc *sc)
12886 {
12887     uint32_t val = 0;
12888
12889     /*
12890      * Read the ME register to get the function number. The ME register
12891      * holds the relative-function number and absolute-function number. The
12892      * absolute-function number appears only in E2 and above. Before that
12893      * these bits always contained zero, therefore we cannot blindly use them.
12894      */
12895
12896     val = REG_RD(sc, BAR_ME_REGISTER);
12897
12898     sc->pfunc_rel =
12899         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12900     sc->path_id =
12901         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12902
12903     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12904         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12905     } else {
12906         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12907     }
12908
12909     BLOGD(sc, DBG_LOAD,
12910           "Relative function %d, Absolute function %d, Path %d\n",
12911           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12912 }
12913
12914 static uint32_t
12915 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12916 {
12917     uint32_t shmem2_size;
12918     uint32_t offset;
12919     uint32_t mf_cfg_offset_value;
12920
12921     /* Non 57712 */
12922     offset = (SHMEM_RD(sc, func_mb) +
12923               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12924
12925     /* 57712 plus */
12926     if (sc->devinfo.shmem2_base != 0) {
12927         shmem2_size = SHMEM2_RD(sc, size);
12928         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12929             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12930             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12931                 offset = mf_cfg_offset_value;
12932             }
12933         }
12934     }
12935
12936     return (offset);
12937 }
12938
12939 static uint32_t
12940 bxe_pcie_capability_read(struct bxe_softc *sc,
12941                          int    reg,
12942                          int    width)
12943 {
12944     int pcie_reg;
12945
12946     /* ensure PCIe capability is enabled */
12947     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12948         if (pcie_reg != 0) {
12949             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12950             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12951         }
12952     }
12953
12954     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12955
12956     return (0);
12957 }
12958
12959 static uint8_t
12960 bxe_is_pcie_pending(struct bxe_softc *sc)
12961 {
12962     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12963             PCIM_EXP_STA_TRANSACTION_PND);
12964 }
12965
12966 /*
12967  * Walk the PCI capabiites list for the device to find what features are
12968  * supported. These capabilites may be enabled/disabled by firmware so it's
12969  * best to walk the list rather than make assumptions.
12970  */
12971 static void
12972 bxe_probe_pci_caps(struct bxe_softc *sc)
12973 {
12974     uint16_t link_status;
12975     int reg;
12976
12977     /* check if PCI Power Management is enabled */
12978     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
12979         if (reg != 0) {
12980             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
12981
12982             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
12983             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
12984         }
12985     }
12986
12987     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
12988
12989     /* handle PCIe 2.0 workarounds for 57710 */
12990     if (CHIP_IS_E1(sc)) {
12991         /* workaround for 57710 errata E4_57710_27462 */
12992         sc->devinfo.pcie_link_speed =
12993             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
12994
12995         /* workaround for 57710 errata E4_57710_27488 */
12996         sc->devinfo.pcie_link_width =
12997             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12998         if (sc->devinfo.pcie_link_speed > 1) {
12999             sc->devinfo.pcie_link_width =
13000                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
13001         }
13002     } else {
13003         sc->devinfo.pcie_link_speed =
13004             (link_status & PCIM_LINK_STA_SPEED);
13005         sc->devinfo.pcie_link_width =
13006             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13007     }
13008
13009     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
13010           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
13011
13012     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
13013     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
13014
13015     /* check if MSI capability is enabled */
13016     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
13017         if (reg != 0) {
13018             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13019
13020             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13021             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13022         }
13023     }
13024
13025     /* check if MSI-X capability is enabled */
13026     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13027         if (reg != 0) {
13028             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13029
13030             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13031             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13032         }
13033     }
13034 }
13035
13036 static int
13037 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13038 {
13039     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13040     uint32_t val;
13041
13042     /* get the outer vlan if we're in switch-dependent mode */
13043
13044     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13045     mf_info->ext_id = (uint16_t)val;
13046
13047     mf_info->multi_vnics_mode = 1;
13048
13049     if (!VALID_OVLAN(mf_info->ext_id)) {
13050         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13051         return (1);
13052     }
13053
13054     /* get the capabilities */
13055     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13056         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13057         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13058     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13059                FUNC_MF_CFG_PROTOCOL_FCOE) {
13060         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13061     } else {
13062         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13063     }
13064
13065     mf_info->vnics_per_port =
13066         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13067
13068     return (0);
13069 }
13070
13071 static uint32_t
13072 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13073 {
13074     uint32_t retval = 0;
13075     uint32_t val;
13076
13077     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13078
13079     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13080         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13081             retval |= MF_PROTO_SUPPORT_ETHERNET;
13082         }
13083         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13084             retval |= MF_PROTO_SUPPORT_ISCSI;
13085         }
13086         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13087             retval |= MF_PROTO_SUPPORT_FCOE;
13088         }
13089     }
13090
13091     return (retval);
13092 }
13093
13094 static int
13095 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13096 {
13097     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13098     uint32_t val;
13099
13100     /*
13101      * There is no outer vlan if we're in switch-independent mode.
13102      * If the mac is valid then assume multi-function.
13103      */
13104
13105     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13106
13107     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13108
13109     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13110
13111     mf_info->vnics_per_port =
13112         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13113
13114     return (0);
13115 }
13116
13117 static int
13118 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13119 {
13120     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13121     uint32_t e1hov_tag;
13122     uint32_t func_config;
13123     uint32_t niv_config;
13124
13125     mf_info->multi_vnics_mode = 1;
13126
13127     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13128     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13129     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13130
13131     mf_info->ext_id =
13132         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13133                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13134
13135     mf_info->default_vlan =
13136         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13137                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13138
13139     mf_info->niv_allowed_priorities =
13140         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13141                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13142
13143     mf_info->niv_default_cos =
13144         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13145                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13146
13147     mf_info->afex_vlan_mode =
13148         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13149          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13150
13151     mf_info->niv_mba_enabled =
13152         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13153          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13154
13155     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13156
13157     mf_info->vnics_per_port =
13158         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13159
13160     return (0);
13161 }
13162
13163 static int
13164 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13165 {
13166     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13167     uint32_t mf_cfg1;
13168     uint32_t mf_cfg2;
13169     uint32_t ovlan1;
13170     uint32_t ovlan2;
13171     uint8_t i, j;
13172
13173     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13174           SC_PORT(sc));
13175     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13176           mf_info->mf_config[SC_VN(sc)]);
13177     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13178           mf_info->multi_vnics_mode);
13179     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13180           mf_info->vnics_per_port);
13181     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13182           mf_info->ext_id);
13183     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13184           mf_info->min_bw[0], mf_info->min_bw[1],
13185           mf_info->min_bw[2], mf_info->min_bw[3]);
13186     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13187           mf_info->max_bw[0], mf_info->max_bw[1],
13188           mf_info->max_bw[2], mf_info->max_bw[3]);
13189     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13190           sc->mac_addr_str);
13191
13192     /* various MF mode sanity checks... */
13193
13194     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13195         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13196               SC_PORT(sc));
13197         return (1);
13198     }
13199
13200     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13201         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13202               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13203         return (1);
13204     }
13205
13206     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13207         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13208         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13209             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13210                   SC_VN(sc), OVLAN(sc));
13211             return (1);
13212         }
13213
13214         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13215             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13216                   mf_info->multi_vnics_mode, OVLAN(sc));
13217             return (1);
13218         }
13219
13220         /*
13221          * Verify all functions are either MF or SF mode. If MF, make sure
13222          * sure that all non-hidden functions have a valid ovlan. If SF,
13223          * make sure that all non-hidden functions have an invalid ovlan.
13224          */
13225         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13226             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13227             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13228             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13229                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13230                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13231                 BLOGE(sc, "mf_mode=SD function %d MF config "
13232                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13233                       i, mf_info->multi_vnics_mode, ovlan1);
13234                 return (1);
13235             }
13236         }
13237
13238         /* Verify all funcs on the same port each have a different ovlan. */
13239         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13240             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13241             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13242             /* iterate from the next function on the port to the max func */
13243             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13244                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13245                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13246                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13247                     VALID_OVLAN(ovlan1) &&
13248                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13249                     VALID_OVLAN(ovlan2) &&
13250                     (ovlan1 == ovlan2)) {
13251                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13252                               "have the same ovlan (%d)\n",
13253                           i, j, ovlan1);
13254                     return (1);
13255                 }
13256             }
13257         }
13258     } /* MULTI_FUNCTION_SD */
13259
13260     return (0);
13261 }
13262
13263 static int
13264 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13265 {
13266     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13267     uint32_t val, mac_upper;
13268     uint8_t i, vnic;
13269
13270     /* initialize mf_info defaults */
13271     mf_info->vnics_per_port   = 1;
13272     mf_info->multi_vnics_mode = FALSE;
13273     mf_info->path_has_ovlan   = FALSE;
13274     mf_info->mf_mode          = SINGLE_FUNCTION;
13275
13276     if (!CHIP_IS_MF_CAP(sc)) {
13277         return (0);
13278     }
13279
13280     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13281         BLOGE(sc, "Invalid mf_cfg_base!\n");
13282         return (1);
13283     }
13284
13285     /* get the MF mode (switch dependent / independent / single-function) */
13286
13287     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13288
13289     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13290     {
13291     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13292
13293         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13294
13295         /* check for legal upper mac bytes */
13296         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13297             mf_info->mf_mode = MULTI_FUNCTION_SI;
13298         } else {
13299             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13300         }
13301
13302         break;
13303
13304     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13305     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13306
13307         /* get outer vlan configuration */
13308         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13309
13310         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13311             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13312             mf_info->mf_mode = MULTI_FUNCTION_SD;
13313         } else {
13314             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13315         }
13316
13317         break;
13318
13319     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13320
13321         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13322         return (0);
13323
13324     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13325
13326         /*
13327          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13328          * and the MAC address is valid.
13329          */
13330         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13331
13332         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13333             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13334             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13335         } else {
13336             BLOGE(sc, "Invalid config for AFEX mode\n");
13337         }
13338
13339         break;
13340
13341     default:
13342
13343         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13344               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13345
13346         return (1);
13347     }
13348
13349     /* set path mf_mode (which could be different than function mf_mode) */
13350     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13351         mf_info->path_has_ovlan = TRUE;
13352     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13353         /*
13354          * Decide on path multi vnics mode. If we're not in MF mode and in
13355          * 4-port mode, this is good enough to check vnic-0 of the other port
13356          * on the same path
13357          */
13358         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13359             uint8_t other_port = !(PORT_ID(sc) & 1);
13360             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13361
13362             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13363
13364             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13365         }
13366     }
13367
13368     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13369         /* invalid MF config */
13370         if (SC_VN(sc) >= 1) {
13371             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13372             return (1);
13373         }
13374
13375         return (0);
13376     }
13377
13378     /* get the MF configuration */
13379     mf_info->mf_config[SC_VN(sc)] =
13380         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13381
13382     switch(mf_info->mf_mode)
13383     {
13384     case MULTI_FUNCTION_SD:
13385
13386         bxe_get_shmem_mf_cfg_info_sd(sc);
13387         break;
13388
13389     case MULTI_FUNCTION_SI:
13390
13391         bxe_get_shmem_mf_cfg_info_si(sc);
13392         break;
13393
13394     case MULTI_FUNCTION_AFEX:
13395
13396         bxe_get_shmem_mf_cfg_info_niv(sc);
13397         break;
13398
13399     default:
13400
13401         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13402               mf_info->mf_mode);
13403         return (1);
13404     }
13405
13406     /* get the congestion management parameters */
13407
13408     vnic = 0;
13409     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13410         /* get min/max bw */
13411         val = MFCFG_RD(sc, func_mf_config[i].config);
13412         mf_info->min_bw[vnic] =
13413             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13414         mf_info->max_bw[vnic] =
13415             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13416         vnic++;
13417     }
13418
13419     return (bxe_check_valid_mf_cfg(sc));
13420 }
13421
13422 static int
13423 bxe_get_shmem_info(struct bxe_softc *sc)
13424 {
13425     int port;
13426     uint32_t mac_hi, mac_lo, val;
13427
13428     port = SC_PORT(sc);
13429     mac_hi = mac_lo = 0;
13430
13431     sc->link_params.sc   = sc;
13432     sc->link_params.port = port;
13433
13434     /* get the hardware config info */
13435     sc->devinfo.hw_config =
13436         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13437     sc->devinfo.hw_config2 =
13438         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13439
13440     sc->link_params.hw_led_mode =
13441         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13442          SHARED_HW_CFG_LED_MODE_SHIFT);
13443
13444     /* get the port feature config */
13445     sc->port.config =
13446         SHMEM_RD(sc, dev_info.port_feature_config[port].config),
13447
13448     /* get the link params */
13449     sc->link_params.speed_cap_mask[0] =
13450         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13451     sc->link_params.speed_cap_mask[1] =
13452         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13453
13454     /* get the lane config */
13455     sc->link_params.lane_config =
13456         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13457
13458     /* get the link config */
13459     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13460     sc->port.link_config[ELINK_INT_PHY] = val;
13461     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13462     sc->port.link_config[ELINK_EXT_PHY1] =
13463         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13464
13465     /* get the override preemphasis flag and enable it or turn it off */
13466     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13467     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13468         sc->link_params.feature_config_flags |=
13469             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13470     } else {
13471         sc->link_params.feature_config_flags &=
13472             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13473     }
13474
13475     /* get the initial value of the link params */
13476     sc->link_params.multi_phy_config =
13477         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13478
13479     /* get external phy info */
13480     sc->port.ext_phy_config =
13481         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13482
13483     /* get the multifunction configuration */
13484     bxe_get_mf_cfg_info(sc);
13485
13486     /* get the mac address */
13487     if (IS_MF(sc)) {
13488         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13489         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13490     } else {
13491         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13492         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13493     }
13494
13495     if ((mac_lo == 0) && (mac_hi == 0)) {
13496         *sc->mac_addr_str = 0;
13497         BLOGE(sc, "No Ethernet address programmed!\n");
13498     } else {
13499         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13500         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13501         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13502         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13503         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13504         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13505         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13506                  "%02x:%02x:%02x:%02x:%02x:%02x",
13507                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13508                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13509                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13510         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13511     }
13512
13513     return (0);
13514 }
13515
13516 static void
13517 bxe_get_tunable_params(struct bxe_softc *sc)
13518 {
13519     /* sanity checks */
13520
13521     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13522         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13523         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13524         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13525         bxe_interrupt_mode = INTR_MODE_MSIX;
13526     }
13527
13528     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13529         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13530         bxe_queue_count = 0;
13531     }
13532
13533     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13534         if (bxe_max_rx_bufs == 0) {
13535             bxe_max_rx_bufs = RX_BD_USABLE;
13536         } else {
13537             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13538             bxe_max_rx_bufs = 2048;
13539         }
13540     }
13541
13542     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13543         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13544         bxe_hc_rx_ticks = 25;
13545     }
13546
13547     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13548         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13549         bxe_hc_tx_ticks = 50;
13550     }
13551
13552     if (bxe_max_aggregation_size == 0) {
13553         bxe_max_aggregation_size = TPA_AGG_SIZE;
13554     }
13555
13556     if (bxe_max_aggregation_size > 0xffff) {
13557         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13558               bxe_max_aggregation_size);
13559         bxe_max_aggregation_size = TPA_AGG_SIZE;
13560     }
13561
13562     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13563         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13564         bxe_mrrs = -1;
13565     }
13566
13567     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13568         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13569         bxe_autogreeen = 0;
13570     }
13571
13572     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13573         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13574         bxe_udp_rss = 0;
13575     }
13576
13577     /* pull in user settings */
13578
13579     sc->interrupt_mode       = bxe_interrupt_mode;
13580     sc->max_rx_bufs          = bxe_max_rx_bufs;
13581     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13582     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13583     sc->max_aggregation_size = bxe_max_aggregation_size;
13584     sc->mrrs                 = bxe_mrrs;
13585     sc->autogreeen           = bxe_autogreeen;
13586     sc->udp_rss              = bxe_udp_rss;
13587
13588     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13589         sc->num_queues = 1;
13590     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13591         sc->num_queues =
13592             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13593                 MAX_RSS_CHAINS);
13594         if (sc->num_queues > mp_ncpus) {
13595             sc->num_queues = mp_ncpus;
13596         }
13597     }
13598
13599     BLOGD(sc, DBG_LOAD,
13600           "User Config: "
13601           "debug=0x%lx "
13602           "interrupt_mode=%d "
13603           "queue_count=%d "
13604           "hc_rx_ticks=%d "
13605           "hc_tx_ticks=%d "
13606           "rx_budget=%d "
13607           "max_aggregation_size=%d "
13608           "mrrs=%d "
13609           "autogreeen=%d "
13610           "udp_rss=%d\n",
13611           bxe_debug,
13612           sc->interrupt_mode,
13613           sc->num_queues,
13614           sc->hc_rx_ticks,
13615           sc->hc_tx_ticks,
13616           bxe_rx_budget,
13617           sc->max_aggregation_size,
13618           sc->mrrs,
13619           sc->autogreeen,
13620           sc->udp_rss);
13621 }
13622
13623 static int
13624 bxe_media_detect(struct bxe_softc *sc)
13625 {
13626     int port_type;
13627     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13628
13629     switch (sc->link_params.phy[phy_idx].media_type) {
13630     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13631     case ELINK_ETH_PHY_XFP_FIBER:
13632         BLOGI(sc, "Found 10Gb Fiber media.\n");
13633         sc->media = IFM_10G_SR;
13634         port_type = PORT_FIBRE;
13635         break;
13636     case ELINK_ETH_PHY_SFP_1G_FIBER:
13637         BLOGI(sc, "Found 1Gb Fiber media.\n");
13638         sc->media = IFM_1000_SX;
13639         port_type = PORT_FIBRE;
13640         break;
13641     case ELINK_ETH_PHY_KR:
13642     case ELINK_ETH_PHY_CX4:
13643         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13644         sc->media = IFM_10G_CX4;
13645         port_type = PORT_FIBRE;
13646         break;
13647     case ELINK_ETH_PHY_DA_TWINAX:
13648         BLOGI(sc, "Found 10Gb Twinax media.\n");
13649         sc->media = IFM_10G_TWINAX;
13650         port_type = PORT_DA;
13651         break;
13652     case ELINK_ETH_PHY_BASE_T:
13653         if (sc->link_params.speed_cap_mask[0] &
13654             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13655             BLOGI(sc, "Found 10GBase-T media.\n");
13656             sc->media = IFM_10G_T;
13657             port_type = PORT_TP;
13658         } else {
13659             BLOGI(sc, "Found 1000Base-T media.\n");
13660             sc->media = IFM_1000_T;
13661             port_type = PORT_TP;
13662         }
13663         break;
13664     case ELINK_ETH_PHY_NOT_PRESENT:
13665         BLOGI(sc, "Media not present.\n");
13666         sc->media = 0;
13667         port_type = PORT_OTHER;
13668         break;
13669     case ELINK_ETH_PHY_UNSPECIFIED:
13670     default:
13671         BLOGI(sc, "Unknown media!\n");
13672         sc->media = 0;
13673         port_type = PORT_OTHER;
13674         break;
13675     }
13676     return port_type;
13677 }
13678
13679 #define GET_FIELD(value, fname)                     \
13680     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13681 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13682 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13683
13684 static int
13685 bxe_get_igu_cam_info(struct bxe_softc *sc)
13686 {
13687     int pfid = SC_FUNC(sc);
13688     int igu_sb_id;
13689     uint32_t val;
13690     uint8_t fid, igu_sb_cnt = 0;
13691
13692     sc->igu_base_sb = 0xff;
13693
13694     if (CHIP_INT_MODE_IS_BC(sc)) {
13695         int vn = SC_VN(sc);
13696         igu_sb_cnt = sc->igu_sb_cnt;
13697         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13698                            FP_SB_MAX_E1x);
13699         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13700                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13701         return (0);
13702     }
13703
13704     /* IGU in normal mode - read CAM */
13705     for (igu_sb_id = 0;
13706          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13707          igu_sb_id++) {
13708         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13709         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13710             continue;
13711         }
13712         fid = IGU_FID(val);
13713         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13714             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13715                 continue;
13716             }
13717             if (IGU_VEC(val) == 0) {
13718                 /* default status block */
13719                 sc->igu_dsb_id = igu_sb_id;
13720             } else {
13721                 if (sc->igu_base_sb == 0xff) {
13722                     sc->igu_base_sb = igu_sb_id;
13723                 }
13724                 igu_sb_cnt++;
13725             }
13726         }
13727     }
13728
13729     /*
13730      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13731      * that number of CAM entries will not be equal to the value advertised in
13732      * PCI. Driver should use the minimal value of both as the actual status
13733      * block count
13734      */
13735     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13736
13737     if (igu_sb_cnt == 0) {
13738         BLOGE(sc, "CAM configuration error\n");
13739         return (-1);
13740     }
13741
13742     return (0);
13743 }
13744
13745 /*
13746  * Gather various information from the device config space, the device itself,
13747  * shmem, and the user input.
13748  */
13749 static int
13750 bxe_get_device_info(struct bxe_softc *sc)
13751 {
13752     uint32_t val;
13753     int rc;
13754
13755     /* Get the data for the device */
13756     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13757     sc->devinfo.device_id    = pci_get_device(sc->dev);
13758     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13759     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13760
13761     /* get the chip revision (chip metal comes from pci config space) */
13762     sc->devinfo.chip_id     =
13763     sc->link_params.chip_id =
13764         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13765          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13766          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13767          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13768
13769     /* force 57811 according to MISC register */
13770     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13771         if (CHIP_IS_57810(sc)) {
13772             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13773                                    (sc->devinfo.chip_id & 0x0000ffff));
13774         } else if (CHIP_IS_57810_MF(sc)) {
13775             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13776                                    (sc->devinfo.chip_id & 0x0000ffff));
13777         }
13778         sc->devinfo.chip_id |= 0x1;
13779     }
13780
13781     BLOGD(sc, DBG_LOAD,
13782           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13783           sc->devinfo.chip_id,
13784           ((sc->devinfo.chip_id >> 16) & 0xffff),
13785           ((sc->devinfo.chip_id >> 12) & 0xf),
13786           ((sc->devinfo.chip_id >>  4) & 0xff),
13787           ((sc->devinfo.chip_id >>  0) & 0xf));
13788
13789     val = (REG_RD(sc, 0x2874) & 0x55);
13790     if ((sc->devinfo.chip_id & 0x1) ||
13791         (CHIP_IS_E1(sc) && val) ||
13792         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13793         sc->flags |= BXE_ONE_PORT_FLAG;
13794         BLOGD(sc, DBG_LOAD, "single port device\n");
13795     }
13796
13797     /* set the doorbell size */
13798     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13799
13800     /* determine whether the device is in 2 port or 4 port mode */
13801     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13802     if (CHIP_IS_E2E3(sc)) {
13803         /*
13804          * Read port4mode_en_ovwr[0]:
13805          *   If 1, four port mode is in port4mode_en_ovwr[1].
13806          *   If 0, four port mode is in port4mode_en[0].
13807          */
13808         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13809         if (val & 1) {
13810             val = ((val >> 1) & 1);
13811         } else {
13812             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13813         }
13814
13815         sc->devinfo.chip_port_mode =
13816             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13817
13818         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13819     }
13820
13821     /* get the function and path info for the device */
13822     bxe_get_function_num(sc);
13823
13824     /* get the shared memory base address */
13825     sc->devinfo.shmem_base     =
13826     sc->link_params.shmem_base =
13827         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13828     sc->devinfo.shmem2_base =
13829         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13830                                   MISC_REG_GENERIC_CR_0));
13831
13832     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13833           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13834
13835     if (!sc->devinfo.shmem_base) {
13836         /* this should ONLY prevent upcoming shmem reads */
13837         BLOGI(sc, "MCP not active\n");
13838         sc->flags |= BXE_NO_MCP_FLAG;
13839         return (0);
13840     }
13841
13842     /* make sure the shared memory contents are valid */
13843     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13844     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13845         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13846         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13847         return (0);
13848     }
13849     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13850
13851     /* get the bootcode version */
13852     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13853     snprintf(sc->devinfo.bc_ver_str,
13854              sizeof(sc->devinfo.bc_ver_str),
13855              "%d.%d.%d",
13856              ((sc->devinfo.bc_ver >> 24) & 0xff),
13857              ((sc->devinfo.bc_ver >> 16) & 0xff),
13858              ((sc->devinfo.bc_ver >>  8) & 0xff));
13859     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13860
13861     /* get the bootcode shmem address */
13862     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13863     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13864
13865     /* clean indirect addresses as they're not used */
13866     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13867     if (IS_PF(sc)) {
13868         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13869         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13870         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13871         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13872         if (CHIP_IS_E1x(sc)) {
13873             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13874             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13875             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13876             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13877         }
13878
13879         /*
13880          * Enable internal target-read (in case we are probed after PF
13881          * FLR). Must be done prior to any BAR read access. Only for
13882          * 57712 and up
13883          */
13884         if (!CHIP_IS_E1x(sc)) {
13885             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13886         }
13887     }
13888
13889     /* get the nvram size */
13890     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13891     sc->devinfo.flash_size =
13892         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13893     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13894
13895     /* get PCI capabilites */
13896     bxe_probe_pci_caps(sc);
13897
13898     bxe_set_power_state(sc, PCI_PM_D0);
13899
13900     /* get various configuration parameters from shmem */
13901     bxe_get_shmem_info(sc);
13902
13903     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13904         val = pci_read_config(sc->dev,
13905                               (sc->devinfo.pcie_msix_cap_reg +
13906                                PCIR_MSIX_CTRL),
13907                               2);
13908         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13909     } else {
13910         sc->igu_sb_cnt = 1;
13911     }
13912
13913     sc->igu_base_addr = BAR_IGU_INTMEM;
13914
13915     /* initialize IGU parameters */
13916     if (CHIP_IS_E1x(sc)) {
13917         sc->devinfo.int_block = INT_BLOCK_HC;
13918         sc->igu_dsb_id = DEF_SB_IGU_ID;
13919         sc->igu_base_sb = 0;
13920     } else {
13921         sc->devinfo.int_block = INT_BLOCK_IGU;
13922
13923         /* do not allow device reset during IGU info preocessing */
13924         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13925
13926         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13927
13928         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13929             int tout = 5000;
13930
13931             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13932
13933             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13934             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13935             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13936
13937             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13938                 tout--;
13939                 DELAY(1000);
13940             }
13941
13942             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13943                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13944                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13945                 return (-1);
13946             }
13947         }
13948
13949         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13950             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13951             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13952         } else {
13953             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13954         }
13955
13956         rc = bxe_get_igu_cam_info(sc);
13957
13958         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13959
13960         if (rc) {
13961             return (rc);
13962         }
13963     }
13964
13965     /*
13966      * Get base FW non-default (fast path) status block ID. This value is
13967      * used to initialize the fw_sb_id saved on the fp/queue structure to
13968      * determine the id used by the FW.
13969      */
13970     if (CHIP_IS_E1x(sc)) {
13971         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
13972     } else {
13973         /*
13974          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
13975          * the same queue are indicated on the same IGU SB). So we prefer
13976          * FW and IGU SBs to be the same value.
13977          */
13978         sc->base_fw_ndsb = sc->igu_base_sb;
13979     }
13980
13981     BLOGD(sc, DBG_LOAD,
13982           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
13983           sc->igu_dsb_id, sc->igu_base_sb,
13984           sc->igu_sb_cnt, sc->base_fw_ndsb);
13985
13986     elink_phy_probe(&sc->link_params);
13987
13988     return (0);
13989 }
13990
13991 static void
13992 bxe_link_settings_supported(struct bxe_softc *sc,
13993                             uint32_t         switch_cfg)
13994 {
13995     uint32_t cfg_size = 0;
13996     uint32_t idx;
13997     uint8_t port = SC_PORT(sc);
13998
13999     /* aggregation of supported attributes of all external phys */
14000     sc->port.supported[0] = 0;
14001     sc->port.supported[1] = 0;
14002
14003     switch (sc->link_params.num_phys) {
14004     case 1:
14005         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
14006         cfg_size = 1;
14007         break;
14008     case 2:
14009         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
14010         cfg_size = 1;
14011         break;
14012     case 3:
14013         if (sc->link_params.multi_phy_config &
14014             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
14015             sc->port.supported[1] =
14016                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14017             sc->port.supported[0] =
14018                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14019         } else {
14020             sc->port.supported[0] =
14021                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14022             sc->port.supported[1] =
14023                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14024         }
14025         cfg_size = 2;
14026         break;
14027     }
14028
14029     if (!(sc->port.supported[0] || sc->port.supported[1])) {
14030         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14031               SHMEM_RD(sc,
14032                        dev_info.port_hw_config[port].external_phy_config),
14033               SHMEM_RD(sc,
14034                        dev_info.port_hw_config[port].external_phy_config2));
14035         return;
14036     }
14037
14038     if (CHIP_IS_E3(sc))
14039         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14040     else {
14041         switch (switch_cfg) {
14042         case ELINK_SWITCH_CFG_1G:
14043             sc->port.phy_addr =
14044                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14045             break;
14046         case ELINK_SWITCH_CFG_10G:
14047             sc->port.phy_addr =
14048                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14049             break;
14050         default:
14051             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14052                   sc->port.link_config[0]);
14053             return;
14054         }
14055     }
14056
14057     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14058
14059     /* mask what we support according to speed_cap_mask per configuration */
14060     for (idx = 0; idx < cfg_size; idx++) {
14061         if (!(sc->link_params.speed_cap_mask[idx] &
14062               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14063             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14064         }
14065
14066         if (!(sc->link_params.speed_cap_mask[idx] &
14067               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14068             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14069         }
14070
14071         if (!(sc->link_params.speed_cap_mask[idx] &
14072               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14073             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14074         }
14075
14076         if (!(sc->link_params.speed_cap_mask[idx] &
14077               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14078             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14079         }
14080
14081         if (!(sc->link_params.speed_cap_mask[idx] &
14082               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14083             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14084         }
14085
14086         if (!(sc->link_params.speed_cap_mask[idx] &
14087               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14088             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14089         }
14090
14091         if (!(sc->link_params.speed_cap_mask[idx] &
14092               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14093             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14094         }
14095
14096         if (!(sc->link_params.speed_cap_mask[idx] &
14097               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14098             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14099         }
14100     }
14101
14102     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14103           sc->port.supported[0], sc->port.supported[1]);
14104         ELINK_DEBUG_P2(sc, "PHY supported 0=0x%08x 1=0x%08x\n",
14105                                         sc->port.supported[0], sc->port.supported[1]);
14106 }
14107
14108 static void
14109 bxe_link_settings_requested(struct bxe_softc *sc)
14110 {
14111     uint32_t link_config;
14112     uint32_t idx;
14113     uint32_t cfg_size = 0;
14114
14115     sc->port.advertising[0] = 0;
14116     sc->port.advertising[1] = 0;
14117
14118     switch (sc->link_params.num_phys) {
14119     case 1:
14120     case 2:
14121         cfg_size = 1;
14122         break;
14123     case 3:
14124         cfg_size = 2;
14125         break;
14126     }
14127
14128     for (idx = 0; idx < cfg_size; idx++) {
14129         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14130         link_config = sc->port.link_config[idx];
14131
14132         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14133         case PORT_FEATURE_LINK_SPEED_AUTO:
14134             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14135                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14136                 sc->port.advertising[idx] |= sc->port.supported[idx];
14137                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14138                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14139                     sc->port.advertising[idx] |=
14140                         (ELINK_SUPPORTED_100baseT_Half |
14141                          ELINK_SUPPORTED_100baseT_Full);
14142             } else {
14143                 /* force 10G, no AN */
14144                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14145                 sc->port.advertising[idx] |=
14146                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14147                 continue;
14148             }
14149             break;
14150
14151         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14152             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14153                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14154                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14155                                               ADVERTISED_TP);
14156             } else {
14157                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14158                           "speed_cap_mask=0x%08x\n",
14159                       link_config, sc->link_params.speed_cap_mask[idx]);
14160                 return;
14161             }
14162             break;
14163
14164         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14165             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14166                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14167                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14168                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14169                                               ADVERTISED_TP);
14170                                 ELINK_DEBUG_P1(sc, "driver requesting DUPLEX_HALF req_duplex = %x!\n",
14171                                                                 sc->link_params.req_duplex[idx]);
14172             } else {
14173                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14174                           "speed_cap_mask=0x%08x\n",
14175                       link_config, sc->link_params.speed_cap_mask[idx]);
14176                 return;
14177             }
14178             break;
14179
14180         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14181             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14182                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14183                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14184                                               ADVERTISED_TP);
14185             } else {
14186                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14187                           "speed_cap_mask=0x%08x\n",
14188                       link_config, sc->link_params.speed_cap_mask[idx]);
14189                 return;
14190             }
14191             break;
14192
14193         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14194             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14195                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14196                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14197                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14198                                               ADVERTISED_TP);
14199             } else {
14200                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14201                           "speed_cap_mask=0x%08x\n",
14202                       link_config, sc->link_params.speed_cap_mask[idx]);
14203                 return;
14204             }
14205             break;
14206
14207         case PORT_FEATURE_LINK_SPEED_1G:
14208             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14209                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14210                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14211                                               ADVERTISED_TP);
14212             } else {
14213                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14214                           "speed_cap_mask=0x%08x\n",
14215                       link_config, sc->link_params.speed_cap_mask[idx]);
14216                 return;
14217             }
14218             break;
14219
14220         case PORT_FEATURE_LINK_SPEED_2_5G:
14221             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14222                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14223                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14224                                               ADVERTISED_TP);
14225             } else {
14226                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14227                           "speed_cap_mask=0x%08x\n",
14228                       link_config, sc->link_params.speed_cap_mask[idx]);
14229                 return;
14230             }
14231             break;
14232
14233         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14234             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14235                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14236                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14237                                               ADVERTISED_FIBRE);
14238             } else {
14239                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14240                           "speed_cap_mask=0x%08x\n",
14241                       link_config, sc->link_params.speed_cap_mask[idx]);
14242                 return;
14243             }
14244             break;
14245
14246         case PORT_FEATURE_LINK_SPEED_20G:
14247             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14248             break;
14249
14250         default:
14251             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14252                       "speed_cap_mask=0x%08x\n",
14253                   link_config, sc->link_params.speed_cap_mask[idx]);
14254             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14255             sc->port.advertising[idx] = sc->port.supported[idx];
14256             break;
14257         }
14258
14259         sc->link_params.req_flow_ctrl[idx] =
14260             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14261
14262         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14263             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14264                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14265             } else {
14266                 bxe_set_requested_fc(sc);
14267             }
14268         }
14269
14270         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14271                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14272               sc->link_params.req_line_speed[idx],
14273               sc->link_params.req_duplex[idx],
14274               sc->link_params.req_flow_ctrl[idx],
14275               sc->port.advertising[idx]);
14276                 ELINK_DEBUG_P3(sc, "req_line_speed=%d req_duplex=%d "
14277                                                 "advertising=0x%x\n",
14278                                                 sc->link_params.req_line_speed[idx],
14279                                                 sc->link_params.req_duplex[idx],
14280                                                 sc->port.advertising[idx]);
14281     }
14282 }
14283
14284 static void
14285 bxe_get_phy_info(struct bxe_softc *sc)
14286 {
14287     uint8_t port = SC_PORT(sc);
14288     uint32_t config = sc->port.config;
14289     uint32_t eee_mode;
14290
14291     /* shmem data already read in bxe_get_shmem_info() */
14292
14293     ELINK_DEBUG_P3(sc, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14294                         "link_config0=0x%08x\n",
14295                sc->link_params.lane_config,
14296                sc->link_params.speed_cap_mask[0],
14297                sc->port.link_config[0]);
14298      
14299
14300     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14301     bxe_link_settings_requested(sc);
14302
14303     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14304         sc->link_params.feature_config_flags |=
14305             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14306     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14307         sc->link_params.feature_config_flags &=
14308             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14309     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14310         sc->link_params.feature_config_flags |=
14311             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14312     }
14313
14314     /* configure link feature according to nvram value */
14315     eee_mode =
14316         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14317           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14318          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14319     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14320         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14321                                     ELINK_EEE_MODE_ENABLE_LPI |
14322                                     ELINK_EEE_MODE_OUTPUT_TIME);
14323     } else {
14324         sc->link_params.eee_mode = 0;
14325     }
14326
14327     /* get the media type */
14328     bxe_media_detect(sc);
14329         ELINK_DEBUG_P1(sc, "detected media type\n", sc->media);
14330 }
14331
14332 static void
14333 bxe_get_params(struct bxe_softc *sc)
14334 {
14335     /* get user tunable params */
14336     bxe_get_tunable_params(sc);
14337
14338     /* select the RX and TX ring sizes */
14339     sc->tx_ring_size = TX_BD_USABLE;
14340     sc->rx_ring_size = RX_BD_USABLE;
14341
14342     /* XXX disable WoL */
14343     sc->wol = 0;
14344 }
14345
14346 static void
14347 bxe_set_modes_bitmap(struct bxe_softc *sc)
14348 {
14349     uint32_t flags = 0;
14350
14351     if (CHIP_REV_IS_FPGA(sc)) {
14352         SET_FLAGS(flags, MODE_FPGA);
14353     } else if (CHIP_REV_IS_EMUL(sc)) {
14354         SET_FLAGS(flags, MODE_EMUL);
14355     } else {
14356         SET_FLAGS(flags, MODE_ASIC);
14357     }
14358
14359     if (CHIP_IS_MODE_4_PORT(sc)) {
14360         SET_FLAGS(flags, MODE_PORT4);
14361     } else {
14362         SET_FLAGS(flags, MODE_PORT2);
14363     }
14364
14365     if (CHIP_IS_E2(sc)) {
14366         SET_FLAGS(flags, MODE_E2);
14367     } else if (CHIP_IS_E3(sc)) {
14368         SET_FLAGS(flags, MODE_E3);
14369         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14370             SET_FLAGS(flags, MODE_E3_A0);
14371         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14372             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14373         }
14374     }
14375
14376     if (IS_MF(sc)) {
14377         SET_FLAGS(flags, MODE_MF);
14378         switch (sc->devinfo.mf_info.mf_mode) {
14379         case MULTI_FUNCTION_SD:
14380             SET_FLAGS(flags, MODE_MF_SD);
14381             break;
14382         case MULTI_FUNCTION_SI:
14383             SET_FLAGS(flags, MODE_MF_SI);
14384             break;
14385         case MULTI_FUNCTION_AFEX:
14386             SET_FLAGS(flags, MODE_MF_AFEX);
14387             break;
14388         }
14389     } else {
14390         SET_FLAGS(flags, MODE_SF);
14391     }
14392
14393 #if defined(__LITTLE_ENDIAN)
14394     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14395 #else /* __BIG_ENDIAN */
14396     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14397 #endif
14398
14399     INIT_MODE_FLAGS(sc) = flags;
14400 }
14401
14402 static int
14403 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14404 {
14405     struct bxe_fastpath *fp;
14406     bus_addr_t busaddr;
14407     int max_agg_queues;
14408     int max_segments;
14409     bus_size_t max_size;
14410     bus_size_t max_seg_size;
14411     char buf[32];
14412     int rc;
14413     int i, j;
14414
14415     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14416
14417     /* allocate the parent bus DMA tag */
14418     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14419                             1,                        /* alignment */
14420                             0,                        /* boundary limit */
14421                             BUS_SPACE_MAXADDR,        /* restricted low */
14422                             BUS_SPACE_MAXADDR,        /* restricted hi */
14423                             NULL,                     /* addr filter() */
14424                             NULL,                     /* addr filter() arg */
14425                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14426                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14427                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14428                             0,                        /* flags */
14429                             NULL,                     /* lock() */
14430                             NULL,                     /* lock() arg */
14431                             &sc->parent_dma_tag);     /* returned dma tag */
14432     if (rc != 0) {
14433         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14434         return (1);
14435     }
14436
14437     /************************/
14438     /* DEFAULT STATUS BLOCK */
14439     /************************/
14440
14441     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14442                       &sc->def_sb_dma, "default status block") != 0) {
14443         /* XXX */
14444         bus_dma_tag_destroy(sc->parent_dma_tag);
14445         return (1);
14446     }
14447
14448     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14449
14450     /***************/
14451     /* EVENT QUEUE */
14452     /***************/
14453
14454     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14455                       &sc->eq_dma, "event queue") != 0) {
14456         /* XXX */
14457         bxe_dma_free(sc, &sc->def_sb_dma);
14458         sc->def_sb = NULL;
14459         bus_dma_tag_destroy(sc->parent_dma_tag);
14460         return (1);
14461     }
14462
14463     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14464
14465     /*************/
14466     /* SLOW PATH */
14467     /*************/
14468
14469     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14470                       &sc->sp_dma, "slow path") != 0) {
14471         /* XXX */
14472         bxe_dma_free(sc, &sc->eq_dma);
14473         sc->eq = NULL;
14474         bxe_dma_free(sc, &sc->def_sb_dma);
14475         sc->def_sb = NULL;
14476         bus_dma_tag_destroy(sc->parent_dma_tag);
14477         return (1);
14478     }
14479
14480     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14481
14482     /*******************/
14483     /* SLOW PATH QUEUE */
14484     /*******************/
14485
14486     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14487                       &sc->spq_dma, "slow path queue") != 0) {
14488         /* XXX */
14489         bxe_dma_free(sc, &sc->sp_dma);
14490         sc->sp = NULL;
14491         bxe_dma_free(sc, &sc->eq_dma);
14492         sc->eq = NULL;
14493         bxe_dma_free(sc, &sc->def_sb_dma);
14494         sc->def_sb = NULL;
14495         bus_dma_tag_destroy(sc->parent_dma_tag);
14496         return (1);
14497     }
14498
14499     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14500
14501     /***************************/
14502     /* FW DECOMPRESSION BUFFER */
14503     /***************************/
14504
14505     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14506                       "fw decompression buffer") != 0) {
14507         /* XXX */
14508         bxe_dma_free(sc, &sc->spq_dma);
14509         sc->spq = NULL;
14510         bxe_dma_free(sc, &sc->sp_dma);
14511         sc->sp = NULL;
14512         bxe_dma_free(sc, &sc->eq_dma);
14513         sc->eq = NULL;
14514         bxe_dma_free(sc, &sc->def_sb_dma);
14515         sc->def_sb = NULL;
14516         bus_dma_tag_destroy(sc->parent_dma_tag);
14517         return (1);
14518     }
14519
14520     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14521
14522     if ((sc->gz_strm =
14523          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14524         /* XXX */
14525         bxe_dma_free(sc, &sc->gz_buf_dma);
14526         sc->gz_buf = NULL;
14527         bxe_dma_free(sc, &sc->spq_dma);
14528         sc->spq = NULL;
14529         bxe_dma_free(sc, &sc->sp_dma);
14530         sc->sp = NULL;
14531         bxe_dma_free(sc, &sc->eq_dma);
14532         sc->eq = NULL;
14533         bxe_dma_free(sc, &sc->def_sb_dma);
14534         sc->def_sb = NULL;
14535         bus_dma_tag_destroy(sc->parent_dma_tag);
14536         return (1);
14537     }
14538
14539     /*************/
14540     /* FASTPATHS */
14541     /*************/
14542
14543     /* allocate DMA memory for each fastpath structure */
14544     for (i = 0; i < sc->num_queues; i++) {
14545         fp = &sc->fp[i];
14546         fp->sc    = sc;
14547         fp->index = i;
14548
14549         /*******************/
14550         /* FP STATUS BLOCK */
14551         /*******************/
14552
14553         snprintf(buf, sizeof(buf), "fp %d status block", i);
14554         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14555                           &fp->sb_dma, buf) != 0) {
14556             /* XXX unwind and free previous fastpath allocations */
14557             BLOGE(sc, "Failed to alloc %s\n", buf);
14558             return (1);
14559         } else {
14560             if (CHIP_IS_E2E3(sc)) {
14561                 fp->status_block.e2_sb =
14562                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14563             } else {
14564                 fp->status_block.e1x_sb =
14565                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14566             }
14567         }
14568
14569         /******************/
14570         /* FP TX BD CHAIN */
14571         /******************/
14572
14573         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14574         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14575                           &fp->tx_dma, buf) != 0) {
14576             /* XXX unwind and free previous fastpath allocations */
14577             BLOGE(sc, "Failed to alloc %s\n", buf);
14578             return (1);
14579         } else {
14580             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14581         }
14582
14583         /* link together the tx bd chain pages */
14584         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14585             /* index into the tx bd chain array to last entry per page */
14586             struct eth_tx_next_bd *tx_next_bd =
14587                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14588             /* point to the next page and wrap from last page */
14589             busaddr = (fp->tx_dma.paddr +
14590                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14591             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14592             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14593         }
14594
14595         /******************/
14596         /* FP RX BD CHAIN */
14597         /******************/
14598
14599         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14600         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14601                           &fp->rx_dma, buf) != 0) {
14602             /* XXX unwind and free previous fastpath allocations */
14603             BLOGE(sc, "Failed to alloc %s\n", buf);
14604             return (1);
14605         } else {
14606             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14607         }
14608
14609         /* link together the rx bd chain pages */
14610         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14611             /* index into the rx bd chain array to last entry per page */
14612             struct eth_rx_bd *rx_bd =
14613                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14614             /* point to the next page and wrap from last page */
14615             busaddr = (fp->rx_dma.paddr +
14616                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14617             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14618             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14619         }
14620
14621         /*******************/
14622         /* FP RX RCQ CHAIN */
14623         /*******************/
14624
14625         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14626         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14627                           &fp->rcq_dma, buf) != 0) {
14628             /* XXX unwind and free previous fastpath allocations */
14629             BLOGE(sc, "Failed to alloc %s\n", buf);
14630             return (1);
14631         } else {
14632             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14633         }
14634
14635         /* link together the rcq chain pages */
14636         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14637             /* index into the rcq chain array to last entry per page */
14638             struct eth_rx_cqe_next_page *rx_cqe_next =
14639                 (struct eth_rx_cqe_next_page *)
14640                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14641             /* point to the next page and wrap from last page */
14642             busaddr = (fp->rcq_dma.paddr +
14643                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14644             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14645             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14646         }
14647
14648         /*******************/
14649         /* FP RX SGE CHAIN */
14650         /*******************/
14651
14652         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14653         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14654                           &fp->rx_sge_dma, buf) != 0) {
14655             /* XXX unwind and free previous fastpath allocations */
14656             BLOGE(sc, "Failed to alloc %s\n", buf);
14657             return (1);
14658         } else {
14659             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14660         }
14661
14662         /* link together the sge chain pages */
14663         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14664             /* index into the rcq chain array to last entry per page */
14665             struct eth_rx_sge *rx_sge =
14666                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14667             /* point to the next page and wrap from last page */
14668             busaddr = (fp->rx_sge_dma.paddr +
14669                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14670             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14671             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14672         }
14673
14674         /***********************/
14675         /* FP TX MBUF DMA MAPS */
14676         /***********************/
14677
14678         /* set required sizes before mapping to conserve resources */
14679         if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
14680             max_size     = BXE_TSO_MAX_SIZE;
14681             max_segments = BXE_TSO_MAX_SEGMENTS;
14682             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14683         } else {
14684             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14685             max_segments = BXE_MAX_SEGMENTS;
14686             max_seg_size = MCLBYTES;
14687         }
14688
14689         /* create a dma tag for the tx mbufs */
14690         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14691                                 1,                  /* alignment */
14692                                 0,                  /* boundary limit */
14693                                 BUS_SPACE_MAXADDR,  /* restricted low */
14694                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14695                                 NULL,               /* addr filter() */
14696                                 NULL,               /* addr filter() arg */
14697                                 max_size,           /* max map size */
14698                                 max_segments,       /* num discontinuous */
14699                                 max_seg_size,       /* max seg size */
14700                                 0,                  /* flags */
14701                                 NULL,               /* lock() */
14702                                 NULL,               /* lock() arg */
14703                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14704         if (rc != 0) {
14705             /* XXX unwind and free previous fastpath allocations */
14706             BLOGE(sc, "Failed to create dma tag for "
14707                       "'fp %d tx mbufs' (%d)\n", i, rc);
14708             return (1);
14709         }
14710
14711         /* create dma maps for each of the tx mbuf clusters */
14712         for (j = 0; j < TX_BD_TOTAL; j++) {
14713             if (bus_dmamap_create(fp->tx_mbuf_tag,
14714                                   BUS_DMA_NOWAIT,
14715                                   &fp->tx_mbuf_chain[j].m_map)) {
14716                 /* XXX unwind and free previous fastpath allocations */
14717                 BLOGE(sc, "Failed to create dma map for "
14718                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14719                 return (1);
14720             }
14721         }
14722
14723         /***********************/
14724         /* FP RX MBUF DMA MAPS */
14725         /***********************/
14726
14727         /* create a dma tag for the rx mbufs */
14728         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14729                                 1,                  /* alignment */
14730                                 0,                  /* boundary limit */
14731                                 BUS_SPACE_MAXADDR,  /* restricted low */
14732                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14733                                 NULL,               /* addr filter() */
14734                                 NULL,               /* addr filter() arg */
14735                                 MJUM9BYTES,         /* max map size */
14736                                 1,                  /* num discontinuous */
14737                                 MJUM9BYTES,         /* max seg size */
14738                                 0,                  /* flags */
14739                                 NULL,               /* lock() */
14740                                 NULL,               /* lock() arg */
14741                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14742         if (rc != 0) {
14743             /* XXX unwind and free previous fastpath allocations */
14744             BLOGE(sc, "Failed to create dma tag for "
14745                       "'fp %d rx mbufs' (%d)\n", i, rc);
14746             return (1);
14747         }
14748
14749         /* create dma maps for each of the rx mbuf clusters */
14750         for (j = 0; j < RX_BD_TOTAL; j++) {
14751             if (bus_dmamap_create(fp->rx_mbuf_tag,
14752                                   BUS_DMA_NOWAIT,
14753                                   &fp->rx_mbuf_chain[j].m_map)) {
14754                 /* XXX unwind and free previous fastpath allocations */
14755                 BLOGE(sc, "Failed to create dma map for "
14756                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14757                 return (1);
14758             }
14759         }
14760
14761         /* create dma map for the spare rx mbuf cluster */
14762         if (bus_dmamap_create(fp->rx_mbuf_tag,
14763                               BUS_DMA_NOWAIT,
14764                               &fp->rx_mbuf_spare_map)) {
14765             /* XXX unwind and free previous fastpath allocations */
14766             BLOGE(sc, "Failed to create dma map for "
14767                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14768             return (1);
14769         }
14770
14771         /***************************/
14772         /* FP RX SGE MBUF DMA MAPS */
14773         /***************************/
14774
14775         /* create a dma tag for the rx sge mbufs */
14776         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14777                                 1,                  /* alignment */
14778                                 0,                  /* boundary limit */
14779                                 BUS_SPACE_MAXADDR,  /* restricted low */
14780                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14781                                 NULL,               /* addr filter() */
14782                                 NULL,               /* addr filter() arg */
14783                                 BCM_PAGE_SIZE,      /* max map size */
14784                                 1,                  /* num discontinuous */
14785                                 BCM_PAGE_SIZE,      /* max seg size */
14786                                 0,                  /* flags */
14787                                 NULL,               /* lock() */
14788                                 NULL,               /* lock() arg */
14789                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14790         if (rc != 0) {
14791             /* XXX unwind and free previous fastpath allocations */
14792             BLOGE(sc, "Failed to create dma tag for "
14793                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14794             return (1);
14795         }
14796
14797         /* create dma maps for the rx sge mbuf clusters */
14798         for (j = 0; j < RX_SGE_TOTAL; j++) {
14799             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14800                                   BUS_DMA_NOWAIT,
14801                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14802                 /* XXX unwind and free previous fastpath allocations */
14803                 BLOGE(sc, "Failed to create dma map for "
14804                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14805                 return (1);
14806             }
14807         }
14808
14809         /* create dma map for the spare rx sge mbuf cluster */
14810         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14811                               BUS_DMA_NOWAIT,
14812                               &fp->rx_sge_mbuf_spare_map)) {
14813             /* XXX unwind and free previous fastpath allocations */
14814             BLOGE(sc, "Failed to create dma map for "
14815                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14816             return (1);
14817         }
14818
14819         /***************************/
14820         /* FP RX TPA MBUF DMA MAPS */
14821         /***************************/
14822
14823         /* create dma maps for the rx tpa mbuf clusters */
14824         max_agg_queues = MAX_AGG_QS(sc);
14825
14826         for (j = 0; j < max_agg_queues; j++) {
14827             if (bus_dmamap_create(fp->rx_mbuf_tag,
14828                                   BUS_DMA_NOWAIT,
14829                                   &fp->rx_tpa_info[j].bd.m_map)) {
14830                 /* XXX unwind and free previous fastpath allocations */
14831                 BLOGE(sc, "Failed to create dma map for "
14832                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14833                 return (1);
14834             }
14835         }
14836
14837         /* create dma map for the spare rx tpa mbuf cluster */
14838         if (bus_dmamap_create(fp->rx_mbuf_tag,
14839                               BUS_DMA_NOWAIT,
14840                               &fp->rx_tpa_info_mbuf_spare_map)) {
14841             /* XXX unwind and free previous fastpath allocations */
14842             BLOGE(sc, "Failed to create dma map for "
14843                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14844             return (1);
14845         }
14846
14847         bxe_init_sge_ring_bit_mask(fp);
14848     }
14849
14850     return (0);
14851 }
14852
14853 static void
14854 bxe_free_hsi_mem(struct bxe_softc *sc)
14855 {
14856     struct bxe_fastpath *fp;
14857     int max_agg_queues;
14858     int i, j;
14859
14860     if (sc->parent_dma_tag == NULL) {
14861         return; /* assume nothing was allocated */
14862     }
14863
14864     for (i = 0; i < sc->num_queues; i++) {
14865         fp = &sc->fp[i];
14866
14867         /*******************/
14868         /* FP STATUS BLOCK */
14869         /*******************/
14870
14871         bxe_dma_free(sc, &fp->sb_dma);
14872         memset(&fp->status_block, 0, sizeof(fp->status_block));
14873
14874         /******************/
14875         /* FP TX BD CHAIN */
14876         /******************/
14877
14878         bxe_dma_free(sc, &fp->tx_dma);
14879         fp->tx_chain = NULL;
14880
14881         /******************/
14882         /* FP RX BD CHAIN */
14883         /******************/
14884
14885         bxe_dma_free(sc, &fp->rx_dma);
14886         fp->rx_chain = NULL;
14887
14888         /*******************/
14889         /* FP RX RCQ CHAIN */
14890         /*******************/
14891
14892         bxe_dma_free(sc, &fp->rcq_dma);
14893         fp->rcq_chain = NULL;
14894
14895         /*******************/
14896         /* FP RX SGE CHAIN */
14897         /*******************/
14898
14899         bxe_dma_free(sc, &fp->rx_sge_dma);
14900         fp->rx_sge_chain = NULL;
14901
14902         /***********************/
14903         /* FP TX MBUF DMA MAPS */
14904         /***********************/
14905
14906         if (fp->tx_mbuf_tag != NULL) {
14907             for (j = 0; j < TX_BD_TOTAL; j++) {
14908                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14909                     bus_dmamap_unload(fp->tx_mbuf_tag,
14910                                       fp->tx_mbuf_chain[j].m_map);
14911                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14912                                        fp->tx_mbuf_chain[j].m_map);
14913                 }
14914             }
14915
14916             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14917             fp->tx_mbuf_tag = NULL;
14918         }
14919
14920         /***********************/
14921         /* FP RX MBUF DMA MAPS */
14922         /***********************/
14923
14924         if (fp->rx_mbuf_tag != NULL) {
14925             for (j = 0; j < RX_BD_TOTAL; j++) {
14926                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14927                     bus_dmamap_unload(fp->rx_mbuf_tag,
14928                                       fp->rx_mbuf_chain[j].m_map);
14929                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14930                                        fp->rx_mbuf_chain[j].m_map);
14931                 }
14932             }
14933
14934             if (fp->rx_mbuf_spare_map != NULL) {
14935                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14936                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14937             }
14938
14939             /***************************/
14940             /* FP RX TPA MBUF DMA MAPS */
14941             /***************************/
14942
14943             max_agg_queues = MAX_AGG_QS(sc);
14944
14945             for (j = 0; j < max_agg_queues; j++) {
14946                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14947                     bus_dmamap_unload(fp->rx_mbuf_tag,
14948                                       fp->rx_tpa_info[j].bd.m_map);
14949                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14950                                        fp->rx_tpa_info[j].bd.m_map);
14951                 }
14952             }
14953
14954             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14955                 bus_dmamap_unload(fp->rx_mbuf_tag,
14956                                   fp->rx_tpa_info_mbuf_spare_map);
14957                 bus_dmamap_destroy(fp->rx_mbuf_tag,
14958                                    fp->rx_tpa_info_mbuf_spare_map);
14959             }
14960
14961             bus_dma_tag_destroy(fp->rx_mbuf_tag);
14962             fp->rx_mbuf_tag = NULL;
14963         }
14964
14965         /***************************/
14966         /* FP RX SGE MBUF DMA MAPS */
14967         /***************************/
14968
14969         if (fp->rx_sge_mbuf_tag != NULL) {
14970             for (j = 0; j < RX_SGE_TOTAL; j++) {
14971                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14972                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14973                                       fp->rx_sge_mbuf_chain[j].m_map);
14974                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14975                                        fp->rx_sge_mbuf_chain[j].m_map);
14976                 }
14977             }
14978
14979             if (fp->rx_sge_mbuf_spare_map != NULL) {
14980                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14981                                   fp->rx_sge_mbuf_spare_map);
14982                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14983                                    fp->rx_sge_mbuf_spare_map);
14984             }
14985
14986             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
14987             fp->rx_sge_mbuf_tag = NULL;
14988         }
14989     }
14990
14991     /***************************/
14992     /* FW DECOMPRESSION BUFFER */
14993     /***************************/
14994
14995     bxe_dma_free(sc, &sc->gz_buf_dma);
14996     sc->gz_buf = NULL;
14997     free(sc->gz_strm, M_DEVBUF);
14998     sc->gz_strm = NULL;
14999
15000     /*******************/
15001     /* SLOW PATH QUEUE */
15002     /*******************/
15003
15004     bxe_dma_free(sc, &sc->spq_dma);
15005     sc->spq = NULL;
15006
15007     /*************/
15008     /* SLOW PATH */
15009     /*************/
15010
15011     bxe_dma_free(sc, &sc->sp_dma);
15012     sc->sp = NULL;
15013
15014     /***************/
15015     /* EVENT QUEUE */
15016     /***************/
15017
15018     bxe_dma_free(sc, &sc->eq_dma);
15019     sc->eq = NULL;
15020
15021     /************************/
15022     /* DEFAULT STATUS BLOCK */
15023     /************************/
15024
15025     bxe_dma_free(sc, &sc->def_sb_dma);
15026     sc->def_sb = NULL;
15027
15028     bus_dma_tag_destroy(sc->parent_dma_tag);
15029     sc->parent_dma_tag = NULL;
15030 }
15031
15032 /*
15033  * Previous driver DMAE transaction may have occurred when pre-boot stage
15034  * ended and boot began. This would invalidate the addresses of the
15035  * transaction, resulting in was-error bit set in the PCI causing all
15036  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15037  * the interrupt which detected this from the pglueb and the was-done bit
15038  */
15039 static void
15040 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15041 {
15042     uint32_t val;
15043
15044     if (!CHIP_IS_E1x(sc)) {
15045         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15046         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15047             BLOGD(sc, DBG_LOAD,
15048                   "Clearing 'was-error' bit that was set in pglueb");
15049             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15050         }
15051     }
15052 }
15053
15054 static int
15055 bxe_prev_mcp_done(struct bxe_softc *sc)
15056 {
15057     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15058                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15059     if (!rc) {
15060         BLOGE(sc, "MCP response failure, aborting\n");
15061         return (-1);
15062     }
15063
15064     return (0);
15065 }
15066
15067 static struct bxe_prev_list_node *
15068 bxe_prev_path_get_entry(struct bxe_softc *sc)
15069 {
15070     struct bxe_prev_list_node *tmp;
15071
15072     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15073         if ((sc->pcie_bus == tmp->bus) &&
15074             (sc->pcie_device == tmp->slot) &&
15075             (SC_PATH(sc) == tmp->path)) {
15076             return (tmp);
15077         }
15078     }
15079
15080     return (NULL);
15081 }
15082
15083 static uint8_t
15084 bxe_prev_is_path_marked(struct bxe_softc *sc)
15085 {
15086     struct bxe_prev_list_node *tmp;
15087     int rc = FALSE;
15088
15089     mtx_lock(&bxe_prev_mtx);
15090
15091     tmp = bxe_prev_path_get_entry(sc);
15092     if (tmp) {
15093         if (tmp->aer) {
15094             BLOGD(sc, DBG_LOAD,
15095                   "Path %d/%d/%d was marked by AER\n",
15096                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15097         } else {
15098             rc = TRUE;
15099             BLOGD(sc, DBG_LOAD,
15100                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15101                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15102         }
15103     }
15104
15105     mtx_unlock(&bxe_prev_mtx);
15106
15107     return (rc);
15108 }
15109
15110 static int
15111 bxe_prev_mark_path(struct bxe_softc *sc,
15112                    uint8_t          after_undi)
15113 {
15114     struct bxe_prev_list_node *tmp;
15115
15116     mtx_lock(&bxe_prev_mtx);
15117
15118     /* Check whether the entry for this path already exists */
15119     tmp = bxe_prev_path_get_entry(sc);
15120     if (tmp) {
15121         if (!tmp->aer) {
15122             BLOGD(sc, DBG_LOAD,
15123                   "Re-marking AER in path %d/%d/%d\n",
15124                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15125         } else {
15126             BLOGD(sc, DBG_LOAD,
15127                   "Removing AER indication from path %d/%d/%d\n",
15128                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15129             tmp->aer = 0;
15130         }
15131
15132         mtx_unlock(&bxe_prev_mtx);
15133         return (0);
15134     }
15135
15136     mtx_unlock(&bxe_prev_mtx);
15137
15138     /* Create an entry for this path and add it */
15139     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15140                  (M_NOWAIT | M_ZERO));
15141     if (!tmp) {
15142         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15143         return (-1);
15144     }
15145
15146     tmp->bus  = sc->pcie_bus;
15147     tmp->slot = sc->pcie_device;
15148     tmp->path = SC_PATH(sc);
15149     tmp->aer  = 0;
15150     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15151
15152     mtx_lock(&bxe_prev_mtx);
15153
15154     BLOGD(sc, DBG_LOAD,
15155           "Marked path %d/%d/%d - finished previous unload\n",
15156           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15157     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15158
15159     mtx_unlock(&bxe_prev_mtx);
15160
15161     return (0);
15162 }
15163
15164 static int
15165 bxe_do_flr(struct bxe_softc *sc)
15166 {
15167     int i;
15168
15169     /* only E2 and onwards support FLR */
15170     if (CHIP_IS_E1x(sc)) {
15171         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15172         return (-1);
15173     }
15174
15175     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15176     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15177         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15178               sc->devinfo.bc_ver);
15179         return (-1);
15180     }
15181
15182     /* Wait for Transaction Pending bit clean */
15183     for (i = 0; i < 4; i++) {
15184         if (i) {
15185             DELAY(((1 << (i - 1)) * 100) * 1000);
15186         }
15187
15188         if (!bxe_is_pcie_pending(sc)) {
15189             goto clear;
15190         }
15191     }
15192
15193     BLOGE(sc, "PCIE transaction is not cleared, "
15194               "proceeding with reset anyway\n");
15195
15196 clear:
15197
15198     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15199     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15200
15201     return (0);
15202 }
15203
15204 struct bxe_mac_vals {
15205     uint32_t xmac_addr;
15206     uint32_t xmac_val;
15207     uint32_t emac_addr;
15208     uint32_t emac_val;
15209     uint32_t umac_addr;
15210     uint32_t umac_val;
15211     uint32_t bmac_addr;
15212     uint32_t bmac_val[2];
15213 };
15214
15215 static void
15216 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15217                           struct bxe_mac_vals *vals)
15218 {
15219     uint32_t val, base_addr, offset, mask, reset_reg;
15220     uint8_t mac_stopped = FALSE;
15221     uint8_t port = SC_PORT(sc);
15222     uint32_t wb_data[2];
15223
15224     /* reset addresses as they also mark which values were changed */
15225     vals->bmac_addr = 0;
15226     vals->umac_addr = 0;
15227     vals->xmac_addr = 0;
15228     vals->emac_addr = 0;
15229
15230     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15231
15232     if (!CHIP_IS_E3(sc)) {
15233         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15234         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15235         if ((mask & reset_reg) && val) {
15236             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15237             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15238                                     : NIG_REG_INGRESS_BMAC0_MEM;
15239             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15240                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15241
15242             /*
15243              * use rd/wr since we cannot use dmae. This is safe
15244              * since MCP won't access the bus due to the request
15245              * to unload, and no function on the path can be
15246              * loaded at this time.
15247              */
15248             wb_data[0] = REG_RD(sc, base_addr + offset);
15249             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15250             vals->bmac_addr = base_addr + offset;
15251             vals->bmac_val[0] = wb_data[0];
15252             vals->bmac_val[1] = wb_data[1];
15253             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15254             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15255             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15256         }
15257
15258         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15259         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15260         vals->emac_val = REG_RD(sc, vals->emac_addr);
15261         REG_WR(sc, vals->emac_addr, 0);
15262         mac_stopped = TRUE;
15263     } else {
15264         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15265             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15266             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15267             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15268             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15269             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15270             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15271             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15272             REG_WR(sc, vals->xmac_addr, 0);
15273             mac_stopped = TRUE;
15274         }
15275
15276         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15277         if (mask & reset_reg) {
15278             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15279             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15280             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15281             vals->umac_val = REG_RD(sc, vals->umac_addr);
15282             REG_WR(sc, vals->umac_addr, 0);
15283             mac_stopped = TRUE;
15284         }
15285     }
15286
15287     if (mac_stopped) {
15288         DELAY(20000);
15289     }
15290 }
15291
15292 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15293 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15294 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15295 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15296
15297 static void
15298 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15299                          uint8_t          port,
15300                          uint8_t          inc)
15301 {
15302     uint16_t rcq, bd;
15303     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15304
15305     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15306     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15307
15308     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15309     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15310
15311     BLOGD(sc, DBG_LOAD,
15312           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15313           port, bd, rcq);
15314 }
15315
15316 static int
15317 bxe_prev_unload_common(struct bxe_softc *sc)
15318 {
15319     uint32_t reset_reg, tmp_reg = 0, rc;
15320     uint8_t prev_undi = FALSE;
15321     struct bxe_mac_vals mac_vals;
15322     uint32_t timer_count = 1000;
15323     uint32_t prev_brb;
15324
15325     /*
15326      * It is possible a previous function received 'common' answer,
15327      * but hasn't loaded yet, therefore creating a scenario of
15328      * multiple functions receiving 'common' on the same path.
15329      */
15330     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15331
15332     memset(&mac_vals, 0, sizeof(mac_vals));
15333
15334     if (bxe_prev_is_path_marked(sc)) {
15335         return (bxe_prev_mcp_done(sc));
15336     }
15337
15338     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15339
15340     /* Reset should be performed after BRB is emptied */
15341     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15342         /* Close the MAC Rx to prevent BRB from filling up */
15343         bxe_prev_unload_close_mac(sc, &mac_vals);
15344
15345         /* close LLH filters towards the BRB */
15346         elink_set_rx_filter(&sc->link_params, 0);
15347
15348         /*
15349          * Check if the UNDI driver was previously loaded.
15350          * UNDI driver initializes CID offset for normal bell to 0x7
15351          */
15352         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15353             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15354             if (tmp_reg == 0x7) {
15355                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15356                 prev_undi = TRUE;
15357                 /* clear the UNDI indication */
15358                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15359                 /* clear possible idle check errors */
15360                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15361             }
15362         }
15363
15364         /* wait until BRB is empty */
15365         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15366         while (timer_count) {
15367             prev_brb = tmp_reg;
15368
15369             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15370             if (!tmp_reg) {
15371                 break;
15372             }
15373
15374             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15375
15376             /* reset timer as long as BRB actually gets emptied */
15377             if (prev_brb > tmp_reg) {
15378                 timer_count = 1000;
15379             } else {
15380                 timer_count--;
15381             }
15382
15383             /* If UNDI resides in memory, manually increment it */
15384             if (prev_undi) {
15385                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15386             }
15387
15388             DELAY(10);
15389         }
15390
15391         if (!timer_count) {
15392             BLOGE(sc, "Failed to empty BRB\n");
15393         }
15394     }
15395
15396     /* No packets are in the pipeline, path is ready for reset */
15397     bxe_reset_common(sc);
15398
15399     if (mac_vals.xmac_addr) {
15400         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15401     }
15402     if (mac_vals.umac_addr) {
15403         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15404     }
15405     if (mac_vals.emac_addr) {
15406         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15407     }
15408     if (mac_vals.bmac_addr) {
15409         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15410         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15411     }
15412
15413     rc = bxe_prev_mark_path(sc, prev_undi);
15414     if (rc) {
15415         bxe_prev_mcp_done(sc);
15416         return (rc);
15417     }
15418
15419     return (bxe_prev_mcp_done(sc));
15420 }
15421
15422 static int
15423 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15424 {
15425     int rc;
15426
15427     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15428
15429     /* Test if previous unload process was already finished for this path */
15430     if (bxe_prev_is_path_marked(sc)) {
15431         return (bxe_prev_mcp_done(sc));
15432     }
15433
15434     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15435
15436     /*
15437      * If function has FLR capabilities, and existing FW version matches
15438      * the one required, then FLR will be sufficient to clean any residue
15439      * left by previous driver
15440      */
15441     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15442     if (!rc) {
15443         /* fw version is good */
15444         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15445         rc = bxe_do_flr(sc);
15446     }
15447
15448     if (!rc) {
15449         /* FLR was performed */
15450         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15451         return (0);
15452     }
15453
15454     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15455
15456     /* Close the MCP request, return failure*/
15457     rc = bxe_prev_mcp_done(sc);
15458     if (!rc) {
15459         rc = BXE_PREV_WAIT_NEEDED;
15460     }
15461
15462     return (rc);
15463 }
15464
15465 static int
15466 bxe_prev_unload(struct bxe_softc *sc)
15467 {
15468     int time_counter = 10;
15469     uint32_t fw, hw_lock_reg, hw_lock_val;
15470     uint32_t rc = 0;
15471
15472     /*
15473      * Clear HW from errors which may have resulted from an interrupted
15474      * DMAE transaction.
15475      */
15476     bxe_prev_interrupted_dmae(sc);
15477
15478     /* Release previously held locks */
15479     hw_lock_reg =
15480         (SC_FUNC(sc) <= 5) ?
15481             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15482             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15483
15484     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15485     if (hw_lock_val) {
15486         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15487             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15488             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15489                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15490         }
15491         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15492         REG_WR(sc, hw_lock_reg, 0xffffffff);
15493     } else {
15494         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15495     }
15496
15497     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15498         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15499         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15500     }
15501
15502     do {
15503         /* Lock MCP using an unload request */
15504         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15505         if (!fw) {
15506             BLOGE(sc, "MCP response failure, aborting\n");
15507             rc = -1;
15508             break;
15509         }
15510
15511         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15512             rc = bxe_prev_unload_common(sc);
15513             break;
15514         }
15515
15516         /* non-common reply from MCP night require looping */
15517         rc = bxe_prev_unload_uncommon(sc);
15518         if (rc != BXE_PREV_WAIT_NEEDED) {
15519             break;
15520         }
15521
15522         DELAY(20000);
15523     } while (--time_counter);
15524
15525     if (!time_counter || rc) {
15526         BLOGE(sc, "Failed to unload previous driver!"
15527             " time_counter %d rc %d\n", time_counter, rc);
15528         rc = -1;
15529     }
15530
15531     return (rc);
15532 }
15533
15534 void
15535 bxe_dcbx_set_state(struct bxe_softc *sc,
15536                    uint8_t          dcb_on,
15537                    uint32_t         dcbx_enabled)
15538 {
15539     if (!CHIP_IS_E1x(sc)) {
15540         sc->dcb_state = dcb_on;
15541         sc->dcbx_enabled = dcbx_enabled;
15542     } else {
15543         sc->dcb_state = FALSE;
15544         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15545     }
15546     BLOGD(sc, DBG_LOAD,
15547           "DCB state [%s:%s]\n",
15548           dcb_on ? "ON" : "OFF",
15549           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15550           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15551           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15552           "on-chip with negotiation" : "invalid");
15553 }
15554
15555 /* must be called after sriov-enable */
15556 static int
15557 bxe_set_qm_cid_count(struct bxe_softc *sc)
15558 {
15559     int cid_count = BXE_L2_MAX_CID(sc);
15560
15561     if (IS_SRIOV(sc)) {
15562         cid_count += BXE_VF_CIDS;
15563     }
15564
15565     if (CNIC_SUPPORT(sc)) {
15566         cid_count += CNIC_CID_MAX;
15567     }
15568
15569     return (roundup(cid_count, QM_CID_ROUND));
15570 }
15571
15572 static void
15573 bxe_init_multi_cos(struct bxe_softc *sc)
15574 {
15575     int pri, cos;
15576
15577     uint32_t pri_map = 0; /* XXX change to user config */
15578
15579     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15580         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15581         if (cos < sc->max_cos) {
15582             sc->prio_to_cos[pri] = cos;
15583         } else {
15584             BLOGW(sc, "Invalid COS %d for priority %d "
15585                       "(max COS is %d), setting to 0\n",
15586                   cos, pri, (sc->max_cos - 1));
15587             sc->prio_to_cos[pri] = 0;
15588         }
15589     }
15590 }
15591
15592 static int
15593 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15594 {
15595     struct bxe_softc *sc;
15596     int error, result;
15597
15598     result = 0;
15599     error = sysctl_handle_int(oidp, &result, 0, req);
15600
15601     if (error || !req->newptr) {
15602         return (error);
15603     }
15604
15605     if (result == 1) {
15606         uint32_t  temp;
15607         sc = (struct bxe_softc *)arg1;
15608
15609         BLOGI(sc, "... dumping driver state ...\n");
15610         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15611         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15612     }
15613
15614     return (error);
15615 }
15616
15617 static int
15618 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15619 {
15620     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15621     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15622     uint32_t *offset;
15623     uint64_t value = 0;
15624     int index = (int)arg2;
15625
15626     if (index >= BXE_NUM_ETH_STATS) {
15627         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15628         return (-1);
15629     }
15630
15631     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15632
15633     switch (bxe_eth_stats_arr[index].size) {
15634     case 4:
15635         value = (uint64_t)*offset;
15636         break;
15637     case 8:
15638         value = HILO_U64(*offset, *(offset + 1));
15639         break;
15640     default:
15641         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15642               index, bxe_eth_stats_arr[index].size);
15643         return (-1);
15644     }
15645
15646     return (sysctl_handle_64(oidp, &value, 0, req));
15647 }
15648
15649 static int
15650 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15651 {
15652     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15653     uint32_t *eth_stats;
15654     uint32_t *offset;
15655     uint64_t value = 0;
15656     uint32_t q_stat = (uint32_t)arg2;
15657     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15658     uint32_t index = (q_stat & 0xffff);
15659
15660     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15661
15662     if (index >= BXE_NUM_ETH_Q_STATS) {
15663         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15664         return (-1);
15665     }
15666
15667     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15668
15669     switch (bxe_eth_q_stats_arr[index].size) {
15670     case 4:
15671         value = (uint64_t)*offset;
15672         break;
15673     case 8:
15674         value = HILO_U64(*offset, *(offset + 1));
15675         break;
15676     default:
15677         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15678               index, bxe_eth_q_stats_arr[index].size);
15679         return (-1);
15680     }
15681
15682     return (sysctl_handle_64(oidp, &value, 0, req));
15683 }
15684
15685 static void bxe_force_link_reset(struct bxe_softc *sc)
15686 {
15687
15688         bxe_acquire_phy_lock(sc);
15689         elink_link_reset(&sc->link_params, &sc->link_vars, 1);
15690         bxe_release_phy_lock(sc);
15691 }
15692
15693 static int
15694 bxe_sysctl_pauseparam(SYSCTL_HANDLER_ARGS)
15695 {
15696         struct bxe_softc *sc = (struct bxe_softc *)arg1;;
15697         uint32_t cfg_idx = bxe_get_link_cfg_idx(sc);
15698         int rc = 0;
15699         int error;
15700         int result;
15701
15702
15703         error = sysctl_handle_int(oidp, &sc->bxe_pause_param, 0, req);
15704
15705         if (error || !req->newptr) {
15706                 return (error);
15707         }
15708         if ((sc->bxe_pause_param < 0) ||  (sc->bxe_pause_param > 8)) {
15709                 BLOGW(sc, "invalid pause param (%d) - use intergers between 1 & 8\n",sc->bxe_pause_param);
15710                 sc->bxe_pause_param = 8;
15711         }
15712
15713         result = (sc->bxe_pause_param << PORT_FEATURE_FLOW_CONTROL_SHIFT);
15714
15715
15716         if((result & 0x400) && !(sc->port.supported[cfg_idx] & ELINK_SUPPORTED_Autoneg))  {
15717                         BLOGW(sc, "Does not support Autoneg pause_param %d\n", sc->bxe_pause_param);
15718                         return -EINVAL;
15719         }
15720
15721         if(IS_MF(sc))
15722                 return 0;
15723        sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_AUTO;
15724         if(result & ELINK_FLOW_CTRL_RX)
15725                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_RX;
15726
15727         if(result & ELINK_FLOW_CTRL_TX)
15728                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_TX;
15729         if(sc->link_params.req_flow_ctrl[cfg_idx] == ELINK_FLOW_CTRL_AUTO)
15730                 sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_NONE;
15731
15732         if(result & 0x400) {
15733                 if (sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG) {
15734                         sc->link_params.req_flow_ctrl[cfg_idx] =
15735                                 ELINK_FLOW_CTRL_AUTO;
15736                 }
15737                 sc->link_params.req_fc_auto_adv = 0;
15738                 if (result & ELINK_FLOW_CTRL_RX)
15739                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_RX;
15740
15741                 if (result & ELINK_FLOW_CTRL_TX)
15742                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_TX;
15743                 if (!sc->link_params.req_fc_auto_adv)
15744                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_NONE;
15745         }
15746          if (IS_PF(sc)) {
15747                         if (sc->link_vars.link_up) {
15748                                 bxe_stats_handle(sc, STATS_EVENT_STOP);
15749                         }
15750                         if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
15751                         bxe_force_link_reset(sc);
15752                         bxe_acquire_phy_lock(sc);
15753
15754                         rc = elink_phy_init(&sc->link_params, &sc->link_vars);
15755
15756                         bxe_release_phy_lock(sc);
15757
15758                         bxe_calc_fc_adv(sc);
15759                         }
15760         }
15761         return rc;
15762 }
15763
15764
15765 static void
15766 bxe_add_sysctls(struct bxe_softc *sc)
15767 {
15768     struct sysctl_ctx_list *ctx;
15769     struct sysctl_oid_list *children;
15770     struct sysctl_oid *queue_top, *queue;
15771     struct sysctl_oid_list *queue_top_children, *queue_children;
15772     char queue_num_buf[32];
15773     uint32_t q_stat;
15774     int i, j;
15775
15776     ctx = device_get_sysctl_ctx(sc->dev);
15777     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15778
15779     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15780                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15781                       "version");
15782
15783     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15784              BCM_5710_FW_MAJOR_VERSION,
15785              BCM_5710_FW_MINOR_VERSION,
15786              BCM_5710_FW_REVISION_VERSION,
15787              BCM_5710_FW_ENGINEERING_VERSION);
15788
15789     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15790         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15791          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15792          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15793          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15794                                                                 "Unknown"));
15795     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15796                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15797                     "multifunction vnics per port");
15798
15799     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15800         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15801          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15802          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15803                                               "???GT/s"),
15804         sc->devinfo.pcie_link_width);
15805
15806     sc->debug = bxe_debug;
15807
15808 #if __FreeBSD_version >= 900000
15809     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15810                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15811                       "bootcode version");
15812     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15813                       CTLFLAG_RD, sc->fw_ver_str, 0,
15814                       "firmware version");
15815     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15816                       CTLFLAG_RD, sc->mf_mode_str, 0,
15817                       "multifunction mode");
15818     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15819                       CTLFLAG_RD, sc->mac_addr_str, 0,
15820                       "mac address");
15821     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15822                       CTLFLAG_RD, sc->pci_link_str, 0,
15823                       "pci link status");
15824     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
15825                     CTLFLAG_RW, &sc->debug,
15826                     "debug logging mode");
15827 #else
15828     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15829                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15830                       "bootcode version");
15831     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15832                       CTLFLAG_RD, &sc->fw_ver_str, 0,
15833                       "firmware version");
15834     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15835                       CTLFLAG_RD, &sc->mf_mode_str, 0,
15836                       "multifunction mode");
15837     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15838                       CTLFLAG_RD, &sc->mac_addr_str, 0,
15839                       "mac address");
15840     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15841                       CTLFLAG_RD, &sc->pci_link_str, 0,
15842                       "pci link status");
15843     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15844                     CTLFLAG_RW, &sc->debug, 0,
15845                     "debug logging mode");
15846 #endif /* #if __FreeBSD_version >= 900000 */
15847
15848     sc->trigger_grcdump = 0;
15849     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
15850                    CTLFLAG_RW, &sc->trigger_grcdump, 0,
15851                    "trigger grcdump should be invoked"
15852                    "  before collecting grcdump");
15853
15854     sc->grcdump_started = 0;
15855     sc->grcdump_done = 0;
15856     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15857                    CTLFLAG_RD, &sc->grcdump_done, 0,
15858                    "set by driver when grcdump is done");
15859
15860     sc->rx_budget = bxe_rx_budget;
15861     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15862                     CTLFLAG_RW, &sc->rx_budget, 0,
15863                     "rx processing budget");
15864
15865    SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_param",
15866                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15867                     bxe_sysctl_pauseparam, "IU",
15868                     "need pause frames- DEF:0/TX:1/RX:2/BOTH:3/AUTO:4/AUTOTX:5/AUTORX:6/AUTORXTX:7/NONE:8");
15869
15870
15871     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15872                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15873                     bxe_sysctl_state, "IU", "dump driver state");
15874
15875     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15876         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15877                         bxe_eth_stats_arr[i].string,
15878                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15879                         bxe_sysctl_eth_stat, "LU",
15880                         bxe_eth_stats_arr[i].string);
15881     }
15882
15883     /* add a new parent node for all queues "dev.bxe.#.queue" */
15884     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15885                                 CTLFLAG_RD, NULL, "queue");
15886     queue_top_children = SYSCTL_CHILDREN(queue_top);
15887
15888     for (i = 0; i < sc->num_queues; i++) {
15889         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15890         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15891         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15892                                 queue_num_buf, CTLFLAG_RD, NULL,
15893                                 "single queue");
15894         queue_children = SYSCTL_CHILDREN(queue);
15895
15896         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15897             q_stat = ((i << 16) | j);
15898             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15899                             bxe_eth_q_stats_arr[j].string,
15900                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15901                             bxe_sysctl_eth_q_stat, "LU",
15902                             bxe_eth_q_stats_arr[j].string);
15903         }
15904     }
15905 }
15906
15907 static int
15908 bxe_alloc_buf_rings(struct bxe_softc *sc)
15909 {
15910 #if __FreeBSD_version >= 901504
15911
15912     int i;
15913     struct bxe_fastpath *fp;
15914
15915     for (i = 0; i < sc->num_queues; i++) {
15916
15917         fp = &sc->fp[i];
15918
15919         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15920                                    M_NOWAIT, &fp->tx_mtx);
15921         if (fp->tx_br == NULL)
15922             return (-1);
15923     }
15924 #endif
15925     return (0);
15926 }
15927
15928 static void
15929 bxe_free_buf_rings(struct bxe_softc *sc)
15930 {
15931 #if __FreeBSD_version >= 901504
15932
15933     int i;
15934     struct bxe_fastpath *fp;
15935
15936     for (i = 0; i < sc->num_queues; i++) {
15937
15938         fp = &sc->fp[i];
15939
15940         if (fp->tx_br) {
15941             buf_ring_free(fp->tx_br, M_DEVBUF);
15942             fp->tx_br = NULL;
15943         }
15944     }
15945
15946 #endif
15947 }
15948
15949 static void
15950 bxe_init_fp_mutexs(struct bxe_softc *sc)
15951 {
15952     int i;
15953     struct bxe_fastpath *fp;
15954
15955     for (i = 0; i < sc->num_queues; i++) {
15956
15957         fp = &sc->fp[i];
15958
15959         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15960             "bxe%d_fp%d_tx_lock", sc->unit, i);
15961         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15962
15963         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15964             "bxe%d_fp%d_rx_lock", sc->unit, i);
15965         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15966     }
15967 }
15968
15969 static void
15970 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15971 {
15972     int i;
15973     struct bxe_fastpath *fp;
15974
15975     for (i = 0; i < sc->num_queues; i++) {
15976
15977         fp = &sc->fp[i];
15978
15979         if (mtx_initialized(&fp->tx_mtx)) {
15980             mtx_destroy(&fp->tx_mtx);
15981         }
15982
15983         if (mtx_initialized(&fp->rx_mtx)) {
15984             mtx_destroy(&fp->rx_mtx);
15985         }
15986     }
15987 }
15988
15989
15990 /*
15991  * Device attach function.
15992  *
15993  * Allocates device resources, performs secondary chip identification, and
15994  * initializes driver instance variables. This function is called from driver
15995  * load after a successful probe.
15996  *
15997  * Returns:
15998  *   0 = Success, >0 = Failure
15999  */
16000 static int
16001 bxe_attach(device_t dev)
16002 {
16003     struct bxe_softc *sc;
16004
16005     sc = device_get_softc(dev);
16006
16007     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
16008
16009     sc->state = BXE_STATE_CLOSED;
16010
16011     sc->dev  = dev;
16012     sc->unit = device_get_unit(dev);
16013
16014     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
16015
16016     sc->pcie_bus    = pci_get_bus(dev);
16017     sc->pcie_device = pci_get_slot(dev);
16018     sc->pcie_func   = pci_get_function(dev);
16019
16020     /* enable bus master capability */
16021     pci_enable_busmaster(dev);
16022
16023     /* get the BARs */
16024     if (bxe_allocate_bars(sc) != 0) {
16025         return (ENXIO);
16026     }
16027
16028     /* initialize the mutexes */
16029     bxe_init_mutexes(sc);
16030
16031     /* prepare the periodic callout */
16032     callout_init(&sc->periodic_callout, 0);
16033
16034     /* prepare the chip taskqueue */
16035     sc->chip_tq_flags = CHIP_TQ_NONE;
16036     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
16037              "bxe%d_chip_tq", sc->unit);
16038     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
16039     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
16040                                    taskqueue_thread_enqueue,
16041                                    &sc->chip_tq);
16042     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
16043                             "%s", sc->chip_tq_name);
16044
16045     /* get device info and set params */
16046     if (bxe_get_device_info(sc) != 0) {
16047         BLOGE(sc, "getting device info\n");
16048         bxe_deallocate_bars(sc);
16049         pci_disable_busmaster(dev);
16050         return (ENXIO);
16051     }
16052
16053     /* get final misc params */
16054     bxe_get_params(sc);
16055
16056     /* set the default MTU (changed via ifconfig) */
16057     sc->mtu = ETHERMTU;
16058
16059     bxe_set_modes_bitmap(sc);
16060
16061     /* XXX
16062      * If in AFEX mode and the function is configured for FCoE
16063      * then bail... no L2 allowed.
16064      */
16065
16066     /* get phy settings from shmem and 'and' against admin settings */
16067     bxe_get_phy_info(sc);
16068
16069     /* initialize the FreeBSD ifnet interface */
16070     if (bxe_init_ifnet(sc) != 0) {
16071         bxe_release_mutexes(sc);
16072         bxe_deallocate_bars(sc);
16073         pci_disable_busmaster(dev);
16074         return (ENXIO);
16075     }
16076
16077     if (bxe_add_cdev(sc) != 0) {
16078         if (sc->ifnet != NULL) {
16079             ether_ifdetach(sc->ifnet);
16080         }
16081         ifmedia_removeall(&sc->ifmedia);
16082         bxe_release_mutexes(sc);
16083         bxe_deallocate_bars(sc);
16084         pci_disable_busmaster(dev);
16085         return (ENXIO);
16086     }
16087
16088     /* allocate device interrupts */
16089     if (bxe_interrupt_alloc(sc) != 0) {
16090         bxe_del_cdev(sc);
16091         if (sc->ifnet != NULL) {
16092             ether_ifdetach(sc->ifnet);
16093         }
16094         ifmedia_removeall(&sc->ifmedia);
16095         bxe_release_mutexes(sc);
16096         bxe_deallocate_bars(sc);
16097         pci_disable_busmaster(dev);
16098         return (ENXIO);
16099     }
16100
16101     bxe_init_fp_mutexs(sc);
16102
16103     if (bxe_alloc_buf_rings(sc) != 0) {
16104         bxe_free_buf_rings(sc);
16105         bxe_interrupt_free(sc);
16106         bxe_del_cdev(sc);
16107         if (sc->ifnet != NULL) {
16108             ether_ifdetach(sc->ifnet);
16109         }
16110         ifmedia_removeall(&sc->ifmedia);
16111         bxe_release_mutexes(sc);
16112         bxe_deallocate_bars(sc);
16113         pci_disable_busmaster(dev);
16114         return (ENXIO);
16115     }
16116
16117     /* allocate ilt */
16118     if (bxe_alloc_ilt_mem(sc) != 0) {
16119         bxe_free_buf_rings(sc);
16120         bxe_interrupt_free(sc);
16121         bxe_del_cdev(sc);
16122         if (sc->ifnet != NULL) {
16123             ether_ifdetach(sc->ifnet);
16124         }
16125         ifmedia_removeall(&sc->ifmedia);
16126         bxe_release_mutexes(sc);
16127         bxe_deallocate_bars(sc);
16128         pci_disable_busmaster(dev);
16129         return (ENXIO);
16130     }
16131
16132     /* allocate the host hardware/software hsi structures */
16133     if (bxe_alloc_hsi_mem(sc) != 0) {
16134         bxe_free_ilt_mem(sc);
16135         bxe_free_buf_rings(sc);
16136         bxe_interrupt_free(sc);
16137         bxe_del_cdev(sc);
16138         if (sc->ifnet != NULL) {
16139             ether_ifdetach(sc->ifnet);
16140         }
16141         ifmedia_removeall(&sc->ifmedia);
16142         bxe_release_mutexes(sc);
16143         bxe_deallocate_bars(sc);
16144         pci_disable_busmaster(dev);
16145         return (ENXIO);
16146     }
16147
16148     /* need to reset chip if UNDI was active */
16149     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16150         /* init fw_seq */
16151         sc->fw_seq =
16152             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16153              DRV_MSG_SEQ_NUMBER_MASK);
16154         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16155         bxe_prev_unload(sc);
16156     }
16157
16158 #if 1
16159     /* XXX */
16160     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16161 #else
16162     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16163         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16164         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16165         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16166         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16167         bxe_dcbx_init_params(sc);
16168     } else {
16169         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16170     }
16171 #endif
16172
16173     /* calculate qm_cid_count */
16174     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16175     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16176
16177     sc->max_cos = 1;
16178     bxe_init_multi_cos(sc);
16179
16180     bxe_add_sysctls(sc);
16181
16182     return (0);
16183 }
16184
16185 /*
16186  * Device detach function.
16187  *
16188  * Stops the controller, resets the controller, and releases resources.
16189  *
16190  * Returns:
16191  *   0 = Success, >0 = Failure
16192  */
16193 static int
16194 bxe_detach(device_t dev)
16195 {
16196     struct bxe_softc *sc;
16197     struct ifnet *ifp;
16198
16199     sc = device_get_softc(dev);
16200
16201     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16202
16203     ifp = sc->ifnet;
16204     if (ifp != NULL && ifp->if_vlantrunk != NULL) {
16205         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16206         return(EBUSY);
16207     }
16208
16209     bxe_del_cdev(sc);
16210
16211     /* stop the periodic callout */
16212     bxe_periodic_stop(sc);
16213
16214     /* stop the chip taskqueue */
16215     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16216     if (sc->chip_tq) {
16217         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16218         taskqueue_free(sc->chip_tq);
16219         sc->chip_tq = NULL;
16220     }
16221
16222     /* stop and reset the controller if it was open */
16223     if (sc->state != BXE_STATE_CLOSED) {
16224         BXE_CORE_LOCK(sc);
16225         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16226         sc->state = BXE_STATE_DISABLED;
16227         BXE_CORE_UNLOCK(sc);
16228     }
16229
16230     /* release the network interface */
16231     if (ifp != NULL) {
16232         ether_ifdetach(ifp);
16233     }
16234     ifmedia_removeall(&sc->ifmedia);
16235
16236     /* XXX do the following based on driver state... */
16237
16238     /* free the host hardware/software hsi structures */
16239     bxe_free_hsi_mem(sc);
16240
16241     /* free ilt */
16242     bxe_free_ilt_mem(sc);
16243
16244     bxe_free_buf_rings(sc);
16245
16246     /* release the interrupts */
16247     bxe_interrupt_free(sc);
16248
16249     /* Release the mutexes*/
16250     bxe_destroy_fp_mutexs(sc);
16251     bxe_release_mutexes(sc);
16252
16253
16254     /* Release the PCIe BAR mapped memory */
16255     bxe_deallocate_bars(sc);
16256
16257     /* Release the FreeBSD interface. */
16258     if (sc->ifnet != NULL) {
16259         if_free(sc->ifnet);
16260     }
16261
16262     pci_disable_busmaster(dev);
16263
16264     return (0);
16265 }
16266
16267 /*
16268  * Device shutdown function.
16269  *
16270  * Stops and resets the controller.
16271  *
16272  * Returns:
16273  *   Nothing
16274  */
16275 static int
16276 bxe_shutdown(device_t dev)
16277 {
16278     struct bxe_softc *sc;
16279
16280     sc = device_get_softc(dev);
16281
16282     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16283
16284     /* stop the periodic callout */
16285     bxe_periodic_stop(sc);
16286
16287     if (sc->state != BXE_STATE_CLOSED) {
16288         BXE_CORE_LOCK(sc);
16289         bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16290         BXE_CORE_UNLOCK(sc);
16291     }
16292
16293     return (0);
16294 }
16295
16296 void
16297 bxe_igu_ack_sb(struct bxe_softc *sc,
16298                uint8_t          igu_sb_id,
16299                uint8_t          segment,
16300                uint16_t         index,
16301                uint8_t          op,
16302                uint8_t          update)
16303 {
16304     uint32_t igu_addr = sc->igu_base_addr;
16305     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16306     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16307 }
16308
16309 static void
16310 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16311                      uint8_t          func,
16312                      uint8_t          idu_sb_id,
16313                      uint8_t          is_pf)
16314 {
16315     uint32_t data, ctl, cnt = 100;
16316     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16317     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16318     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16319     uint32_t sb_bit =  1 << (idu_sb_id%32);
16320     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16321     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16322
16323     /* Not supported in BC mode */
16324     if (CHIP_INT_MODE_IS_BC(sc)) {
16325         return;
16326     }
16327
16328     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16329              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16330             IGU_REGULAR_CLEANUP_SET |
16331             IGU_REGULAR_BCLEANUP);
16332
16333     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16334            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16335            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16336
16337     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16338             data, igu_addr_data);
16339     REG_WR(sc, igu_addr_data, data);
16340
16341     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16342                       BUS_SPACE_BARRIER_WRITE);
16343     mb();
16344
16345     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16346             ctl, igu_addr_ctl);
16347     REG_WR(sc, igu_addr_ctl, ctl);
16348
16349     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16350                       BUS_SPACE_BARRIER_WRITE);
16351     mb();
16352
16353     /* wait for clean up to finish */
16354     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16355         DELAY(20000);
16356     }
16357
16358     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16359         BLOGD(sc, DBG_LOAD,
16360               "Unable to finish IGU cleanup: "
16361               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16362               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16363     }
16364 }
16365
16366 static void
16367 bxe_igu_clear_sb(struct bxe_softc *sc,
16368                  uint8_t          idu_sb_id)
16369 {
16370     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16371 }
16372
16373
16374
16375
16376
16377
16378
16379 /*******************/
16380 /* ECORE CALLBACKS */
16381 /*******************/
16382
16383 static void
16384 bxe_reset_common(struct bxe_softc *sc)
16385 {
16386     uint32_t val = 0x1400;
16387
16388     /* reset_common */
16389     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16390
16391     if (CHIP_IS_E3(sc)) {
16392         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16393         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16394     }
16395
16396     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16397 }
16398
16399 static void
16400 bxe_common_init_phy(struct bxe_softc *sc)
16401 {
16402     uint32_t shmem_base[2];
16403     uint32_t shmem2_base[2];
16404
16405     /* Avoid common init in case MFW supports LFA */
16406     if (SHMEM2_RD(sc, size) >
16407         (uint32_t)offsetof(struct shmem2_region,
16408                            lfa_host_addr[SC_PORT(sc)])) {
16409         return;
16410     }
16411
16412     shmem_base[0]  = sc->devinfo.shmem_base;
16413     shmem2_base[0] = sc->devinfo.shmem2_base;
16414
16415     if (!CHIP_IS_E1x(sc)) {
16416         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16417         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16418     }
16419
16420     bxe_acquire_phy_lock(sc);
16421     elink_common_init_phy(sc, shmem_base, shmem2_base,
16422                           sc->devinfo.chip_id, 0);
16423     bxe_release_phy_lock(sc);
16424 }
16425
16426 static void
16427 bxe_pf_disable(struct bxe_softc *sc)
16428 {
16429     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16430
16431     val &= ~IGU_PF_CONF_FUNC_EN;
16432
16433     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16434     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16435     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16436 }
16437
16438 static void
16439 bxe_init_pxp(struct bxe_softc *sc)
16440 {
16441     uint16_t devctl;
16442     int r_order, w_order;
16443
16444     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16445
16446     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16447
16448     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16449
16450     if (sc->mrrs == -1) {
16451         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16452     } else {
16453         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16454         r_order = sc->mrrs;
16455     }
16456
16457     ecore_init_pxp_arb(sc, r_order, w_order);
16458 }
16459
16460 static uint32_t
16461 bxe_get_pretend_reg(struct bxe_softc *sc)
16462 {
16463     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16464     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16465     return (base + (SC_ABS_FUNC(sc)) * stride);
16466 }
16467
16468 /*
16469  * Called only on E1H or E2.
16470  * When pretending to be PF, the pretend value is the function number 0..7.
16471  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16472  * combination.
16473  */
16474 static int
16475 bxe_pretend_func(struct bxe_softc *sc,
16476                  uint16_t         pretend_func_val)
16477 {
16478     uint32_t pretend_reg;
16479
16480     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16481         return (-1);
16482     }
16483
16484     /* get my own pretend register */
16485     pretend_reg = bxe_get_pretend_reg(sc);
16486     REG_WR(sc, pretend_reg, pretend_func_val);
16487     REG_RD(sc, pretend_reg);
16488     return (0);
16489 }
16490
16491 static void
16492 bxe_iov_init_dmae(struct bxe_softc *sc)
16493 {
16494     return;
16495 }
16496
16497 static void
16498 bxe_iov_init_dq(struct bxe_softc *sc)
16499 {
16500     return;
16501 }
16502
16503 /* send a NIG loopback debug packet */
16504 static void
16505 bxe_lb_pckt(struct bxe_softc *sc)
16506 {
16507     uint32_t wb_write[3];
16508
16509     /* Ethernet source and destination addresses */
16510     wb_write[0] = 0x55555555;
16511     wb_write[1] = 0x55555555;
16512     wb_write[2] = 0x20;     /* SOP */
16513     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16514
16515     /* NON-IP protocol */
16516     wb_write[0] = 0x09000000;
16517     wb_write[1] = 0x55555555;
16518     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16519     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16520 }
16521
16522 /*
16523  * Some of the internal memories are not directly readable from the driver.
16524  * To test them we send debug packets.
16525  */
16526 static int
16527 bxe_int_mem_test(struct bxe_softc *sc)
16528 {
16529     int factor;
16530     int count, i;
16531     uint32_t val = 0;
16532
16533     if (CHIP_REV_IS_FPGA(sc)) {
16534         factor = 120;
16535     } else if (CHIP_REV_IS_EMUL(sc)) {
16536         factor = 200;
16537     } else {
16538         factor = 1;
16539     }
16540
16541     /* disable inputs of parser neighbor blocks */
16542     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16543     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16544     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16545     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16546
16547     /*  write 0 to parser credits for CFC search request */
16548     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16549
16550     /* send Ethernet packet */
16551     bxe_lb_pckt(sc);
16552
16553     /* TODO do i reset NIG statistic? */
16554     /* Wait until NIG register shows 1 packet of size 0x10 */
16555     count = 1000 * factor;
16556     while (count) {
16557         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16558         val = *BXE_SP(sc, wb_data[0]);
16559         if (val == 0x10) {
16560             break;
16561         }
16562
16563         DELAY(10000);
16564         count--;
16565     }
16566
16567     if (val != 0x10) {
16568         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16569         return (-1);
16570     }
16571
16572     /* wait until PRS register shows 1 packet */
16573     count = (1000 * factor);
16574     while (count) {
16575         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16576         if (val == 1) {
16577             break;
16578         }
16579
16580         DELAY(10000);
16581         count--;
16582     }
16583
16584     if (val != 0x1) {
16585         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16586         return (-2);
16587     }
16588
16589     /* Reset and init BRB, PRS */
16590     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16591     DELAY(50000);
16592     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16593     DELAY(50000);
16594     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16595     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16596
16597     /* Disable inputs of parser neighbor blocks */
16598     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16599     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16600     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16601     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16602
16603     /* Write 0 to parser credits for CFC search request */
16604     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16605
16606     /* send 10 Ethernet packets */
16607     for (i = 0; i < 10; i++) {
16608         bxe_lb_pckt(sc);
16609     }
16610
16611     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16612     count = (1000 * factor);
16613     while (count) {
16614         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16615         val = *BXE_SP(sc, wb_data[0]);
16616         if (val == 0xb0) {
16617             break;
16618         }
16619
16620         DELAY(10000);
16621         count--;
16622     }
16623
16624     if (val != 0xb0) {
16625         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16626         return (-3);
16627     }
16628
16629     /* Wait until PRS register shows 2 packets */
16630     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16631     if (val != 2) {
16632         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16633     }
16634
16635     /* Write 1 to parser credits for CFC search request */
16636     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16637
16638     /* Wait until PRS register shows 3 packets */
16639     DELAY(10000 * factor);
16640
16641     /* Wait until NIG register shows 1 packet of size 0x10 */
16642     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16643     if (val != 3) {
16644         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16645     }
16646
16647     /* clear NIG EOP FIFO */
16648     for (i = 0; i < 11; i++) {
16649         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16650     }
16651
16652     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16653     if (val != 1) {
16654         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16655         return (-4);
16656     }
16657
16658     /* Reset and init BRB, PRS, NIG */
16659     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16660     DELAY(50000);
16661     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16662     DELAY(50000);
16663     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16664     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16665     if (!CNIC_SUPPORT(sc)) {
16666         /* set NIC mode */
16667         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16668     }
16669
16670     /* Enable inputs of parser neighbor blocks */
16671     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16672     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16673     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16674     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16675
16676     return (0);
16677 }
16678
16679 static void
16680 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16681 {
16682     int is_required;
16683     uint32_t val;
16684     int port;
16685
16686     is_required = 0;
16687     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16688            SHARED_HW_CFG_FAN_FAILURE_MASK);
16689
16690     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16691         is_required = 1;
16692     }
16693     /*
16694      * The fan failure mechanism is usually related to the PHY type since
16695      * the power consumption of the board is affected by the PHY. Currently,
16696      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16697      */
16698     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16699         for (port = PORT_0; port < PORT_MAX; port++) {
16700             is_required |= elink_fan_failure_det_req(sc,
16701                                                      sc->devinfo.shmem_base,
16702                                                      sc->devinfo.shmem2_base,
16703                                                      port);
16704         }
16705     }
16706
16707     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16708
16709     if (is_required == 0) {
16710         return;
16711     }
16712
16713     /* Fan failure is indicated by SPIO 5 */
16714     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16715
16716     /* set to active low mode */
16717     val = REG_RD(sc, MISC_REG_SPIO_INT);
16718     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16719     REG_WR(sc, MISC_REG_SPIO_INT, val);
16720
16721     /* enable interrupt to signal the IGU */
16722     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16723     val |= MISC_SPIO_SPIO5;
16724     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16725 }
16726
16727 static void
16728 bxe_enable_blocks_attention(struct bxe_softc *sc)
16729 {
16730     uint32_t val;
16731
16732     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16733     if (!CHIP_IS_E1x(sc)) {
16734         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16735     } else {
16736         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16737     }
16738     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16739     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16740     /*
16741      * mask read length error interrupts in brb for parser
16742      * (parsing unit and 'checksum and crc' unit)
16743      * these errors are legal (PU reads fixed length and CAC can cause
16744      * read length error on truncated packets)
16745      */
16746     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16747     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16748     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16749     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16750     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16751     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16752 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16753 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16754     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16755     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16756     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16757 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16758 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16759     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16760     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16761     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16762     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16763 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16764 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16765
16766     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16767            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16768            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16769     if (!CHIP_IS_E1x(sc)) {
16770         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16771                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16772     }
16773     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16774
16775     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16776     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16777     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16778 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16779
16780     if (!CHIP_IS_E1x(sc)) {
16781         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16782         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16783     }
16784
16785     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16786     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16787 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16788     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16789 }
16790
16791 /**
16792  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16793  *
16794  * @sc:     driver handle
16795  */
16796 static int
16797 bxe_init_hw_common(struct bxe_softc *sc)
16798 {
16799     uint8_t abs_func_id;
16800     uint32_t val;
16801
16802     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16803           SC_ABS_FUNC(sc));
16804
16805     /*
16806      * take the RESET lock to protect undi_unload flow from accessing
16807      * registers while we are resetting the chip
16808      */
16809     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16810
16811     bxe_reset_common(sc);
16812
16813     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16814
16815     val = 0xfffc;
16816     if (CHIP_IS_E3(sc)) {
16817         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16818         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16819     }
16820
16821     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16822
16823     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16824
16825     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16826     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16827
16828     if (!CHIP_IS_E1x(sc)) {
16829         /*
16830          * 4-port mode or 2-port mode we need to turn off master-enable for
16831          * everyone. After that we turn it back on for self. So, we disregard
16832          * multi-function, and always disable all functions on the given path,
16833          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16834          */
16835         for (abs_func_id = SC_PATH(sc);
16836              abs_func_id < (E2_FUNC_MAX * 2);
16837              abs_func_id += 2) {
16838             if (abs_func_id == SC_ABS_FUNC(sc)) {
16839                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16840                 continue;
16841             }
16842
16843             bxe_pretend_func(sc, abs_func_id);
16844
16845             /* clear pf enable */
16846             bxe_pf_disable(sc);
16847
16848             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16849         }
16850     }
16851
16852     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16853
16854     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16855
16856     if (CHIP_IS_E1(sc)) {
16857         /*
16858          * enable HW interrupt from PXP on USDM overflow
16859          * bit 16 on INT_MASK_0
16860          */
16861         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16862     }
16863
16864     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16865     bxe_init_pxp(sc);
16866
16867 #ifdef __BIG_ENDIAN
16868     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16869     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16870     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16871     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16872     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16873     /* make sure this value is 0 */
16874     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16875
16876     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16877     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16878     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16879     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16880     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16881 #endif
16882
16883     ecore_ilt_init_page_size(sc, INITOP_SET);
16884
16885     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16886         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16887     }
16888
16889     /* let the HW do it's magic... */
16890     DELAY(100000);
16891
16892     /* finish PXP init */
16893     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16894     if (val != 1) {
16895         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16896             val);
16897         return (-1);
16898     }
16899     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16900     if (val != 1) {
16901         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16902         return (-1);
16903     }
16904
16905     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16906
16907     /*
16908      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16909      * entries with value "0" and valid bit on. This needs to be done by the
16910      * first PF that is loaded in a path (i.e. common phase)
16911      */
16912     if (!CHIP_IS_E1x(sc)) {
16913 /*
16914  * In E2 there is a bug in the timers block that can cause function 6 / 7
16915  * (i.e. vnic3) to start even if it is marked as "scan-off".
16916  * This occurs when a different function (func2,3) is being marked
16917  * as "scan-off". Real-life scenario for example: if a driver is being
16918  * load-unloaded while func6,7 are down. This will cause the timer to access
16919  * the ilt, translate to a logical address and send a request to read/write.
16920  * Since the ilt for the function that is down is not valid, this will cause
16921  * a translation error which is unrecoverable.
16922  * The Workaround is intended to make sure that when this happens nothing
16923  * fatal will occur. The workaround:
16924  *  1.  First PF driver which loads on a path will:
16925  *      a.  After taking the chip out of reset, by using pretend,
16926  *          it will write "0" to the following registers of
16927  *          the other vnics.
16928  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16929  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16930  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16931  *          And for itself it will write '1' to
16932  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16933  *          dmae-operations (writing to pram for example.)
16934  *          note: can be done for only function 6,7 but cleaner this
16935  *            way.
16936  *      b.  Write zero+valid to the entire ILT.
16937  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16938  *          VNIC3 (of that port). The range allocated will be the
16939  *          entire ILT. This is needed to prevent  ILT range error.
16940  *  2.  Any PF driver load flow:
16941  *      a.  ILT update with the physical addresses of the allocated
16942  *          logical pages.
16943  *      b.  Wait 20msec. - note that this timeout is needed to make
16944  *          sure there are no requests in one of the PXP internal
16945  *          queues with "old" ILT addresses.
16946  *      c.  PF enable in the PGLC.
16947  *      d.  Clear the was_error of the PF in the PGLC. (could have
16948  *          occurred while driver was down)
16949  *      e.  PF enable in the CFC (WEAK + STRONG)
16950  *      f.  Timers scan enable
16951  *  3.  PF driver unload flow:
16952  *      a.  Clear the Timers scan_en.
16953  *      b.  Polling for scan_on=0 for that PF.
16954  *      c.  Clear the PF enable bit in the PXP.
16955  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16956  *      e.  Write zero+valid to all ILT entries (The valid bit must
16957  *          stay set)
16958  *      f.  If this is VNIC 3 of a port then also init
16959  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16960  *          to the last enrty in the ILT.
16961  *
16962  *      Notes:
16963  *      Currently the PF error in the PGLC is non recoverable.
16964  *      In the future the there will be a recovery routine for this error.
16965  *      Currently attention is masked.
16966  *      Having an MCP lock on the load/unload process does not guarantee that
16967  *      there is no Timer disable during Func6/7 enable. This is because the
16968  *      Timers scan is currently being cleared by the MCP on FLR.
16969  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16970  *      there is error before clearing it. But the flow above is simpler and
16971  *      more general.
16972  *      All ILT entries are written by zero+valid and not just PF6/7
16973  *      ILT entries since in the future the ILT entries allocation for
16974  *      PF-s might be dynamic.
16975  */
16976         struct ilt_client_info ilt_cli;
16977         struct ecore_ilt ilt;
16978
16979         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16980         memset(&ilt, 0, sizeof(struct ecore_ilt));
16981
16982         /* initialize dummy TM client */
16983         ilt_cli.start      = 0;
16984         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16985         ilt_cli.client_num = ILT_CLIENT_TM;
16986
16987         /*
16988          * Step 1: set zeroes to all ilt page entries with valid bit on
16989          * Step 2: set the timers first/last ilt entry to point
16990          * to the entire range to prevent ILT range error for 3rd/4th
16991          * vnic (this code assumes existence of the vnic)
16992          *
16993          * both steps performed by call to ecore_ilt_client_init_op()
16994          * with dummy TM client
16995          *
16996          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16997          * and his brother are split registers
16998          */
16999
17000         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
17001         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
17002         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
17003
17004         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
17005         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
17006         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
17007     }
17008
17009     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
17010     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
17011
17012     if (!CHIP_IS_E1x(sc)) {
17013         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
17014                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
17015
17016         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
17017         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
17018
17019         /* let the HW do it's magic... */
17020         do {
17021             DELAY(200000);
17022             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
17023         } while (factor-- && (val != 1));
17024
17025         if (val != 1) {
17026             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
17027             return (-1);
17028         }
17029     }
17030
17031     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
17032
17033     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
17034
17035     bxe_iov_init_dmae(sc);
17036
17037     /* clean the DMAE memory */
17038     sc->dmae_ready = 1;
17039     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
17040
17041     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
17042
17043     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
17044
17045     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
17046
17047     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
17048
17049     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
17050     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17051     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17052     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17053
17054     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17055
17056     /* QM queues pointers table */
17057     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17058
17059     /* soft reset pulse */
17060     REG_WR(sc, QM_REG_SOFT_RESET, 1);
17061     REG_WR(sc, QM_REG_SOFT_RESET, 0);
17062
17063     if (CNIC_SUPPORT(sc))
17064         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17065
17066     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17067     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17068     if (!CHIP_REV_IS_SLOW(sc)) {
17069         /* enable hw interrupt from doorbell Q */
17070         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17071     }
17072
17073     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17074
17075     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17076     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17077
17078     if (!CHIP_IS_E1(sc)) {
17079         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17080     }
17081
17082     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17083         if (IS_MF_AFEX(sc)) {
17084             /*
17085              * configure that AFEX and VLAN headers must be
17086              * received in AFEX mode
17087              */
17088             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17089             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17090             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17091             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17092             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17093         } else {
17094             /*
17095              * Bit-map indicating which L2 hdrs may appear
17096              * after the basic Ethernet header
17097              */
17098             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17099                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17100         }
17101     }
17102
17103     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17104     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17105     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17106     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17107
17108     if (!CHIP_IS_E1x(sc)) {
17109         /* reset VFC memories */
17110         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17111                VFC_MEMORIES_RST_REG_CAM_RST |
17112                VFC_MEMORIES_RST_REG_RAM_RST);
17113         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17114                VFC_MEMORIES_RST_REG_CAM_RST |
17115                VFC_MEMORIES_RST_REG_RAM_RST);
17116
17117         DELAY(20000);
17118     }
17119
17120     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17121     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17122     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17123     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17124
17125     /* sync semi rtc */
17126     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17127            0x80000000);
17128     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17129            0x80000000);
17130
17131     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17132     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17133     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17134
17135     if (!CHIP_IS_E1x(sc)) {
17136         if (IS_MF_AFEX(sc)) {
17137             /*
17138              * configure that AFEX and VLAN headers must be
17139              * sent in AFEX mode
17140              */
17141             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17142             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17143             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17144             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17145             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17146         } else {
17147             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17148                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17149         }
17150     }
17151
17152     REG_WR(sc, SRC_REG_SOFT_RST, 1);
17153
17154     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17155
17156     if (CNIC_SUPPORT(sc)) {
17157         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17158         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17159         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17160         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17161         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17162         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17163         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17164         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17165         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17166         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17167     }
17168     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17169
17170     if (sizeof(union cdu_context) != 1024) {
17171         /* we currently assume that a context is 1024 bytes */
17172         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17173               (long)sizeof(union cdu_context));
17174     }
17175
17176     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17177     val = (4 << 24) + (0 << 12) + 1024;
17178     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17179
17180     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17181
17182     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17183     /* enable context validation interrupt from CFC */
17184     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17185
17186     /* set the thresholds to prevent CFC/CDU race */
17187     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17188     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17189
17190     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17191         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17192     }
17193
17194     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17195     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17196
17197     /* Reset PCIE errors for debug */
17198     REG_WR(sc, 0x2814, 0xffffffff);
17199     REG_WR(sc, 0x3820, 0xffffffff);
17200
17201     if (!CHIP_IS_E1x(sc)) {
17202         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17203                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17204                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17205         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17206                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17207                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17208                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17209         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17210                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17211                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17212                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17213     }
17214
17215     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17216
17217     if (!CHIP_IS_E1(sc)) {
17218         /* in E3 this done in per-port section */
17219         if (!CHIP_IS_E3(sc))
17220             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17221     }
17222
17223     if (CHIP_IS_E1H(sc)) {
17224         /* not applicable for E2 (and above ...) */
17225         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17226     }
17227
17228     if (CHIP_REV_IS_SLOW(sc)) {
17229         DELAY(200000);
17230     }
17231
17232     /* finish CFC init */
17233     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17234     if (val != 1) {
17235         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17236         return (-1);
17237     }
17238     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17239     if (val != 1) {
17240         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17241         return (-1);
17242     }
17243     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17244     if (val != 1) {
17245         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17246         return (-1);
17247     }
17248     REG_WR(sc, CFC_REG_DEBUG0, 0);
17249
17250     if (CHIP_IS_E1(sc)) {
17251         /* read NIG statistic to see if this is our first up since powerup */
17252         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17253         val = *BXE_SP(sc, wb_data[0]);
17254
17255         /* do internal memory self test */
17256         if ((val == 0) && bxe_int_mem_test(sc)) {
17257             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17258             return (-1);
17259         }
17260     }
17261
17262     bxe_setup_fan_failure_detection(sc);
17263
17264     /* clear PXP2 attentions */
17265     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17266
17267     bxe_enable_blocks_attention(sc);
17268
17269     if (!CHIP_REV_IS_SLOW(sc)) {
17270         ecore_enable_blocks_parity(sc);
17271     }
17272
17273     if (!BXE_NOMCP(sc)) {
17274         if (CHIP_IS_E1x(sc)) {
17275             bxe_common_init_phy(sc);
17276         }
17277     }
17278
17279     return (0);
17280 }
17281
17282 /**
17283  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17284  *
17285  * @sc:     driver handle
17286  */
17287 static int
17288 bxe_init_hw_common_chip(struct bxe_softc *sc)
17289 {
17290     int rc = bxe_init_hw_common(sc);
17291
17292     if (rc) {
17293         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17294         return (rc);
17295     }
17296
17297     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17298     if (!BXE_NOMCP(sc)) {
17299         bxe_common_init_phy(sc);
17300     }
17301
17302     return (0);
17303 }
17304
17305 static int
17306 bxe_init_hw_port(struct bxe_softc *sc)
17307 {
17308     int port = SC_PORT(sc);
17309     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17310     uint32_t low, high;
17311     uint32_t val;
17312
17313     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17314
17315     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17316
17317     ecore_init_block(sc, BLOCK_MISC, init_phase);
17318     ecore_init_block(sc, BLOCK_PXP, init_phase);
17319     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17320
17321     /*
17322      * Timers bug workaround: disables the pf_master bit in pglue at
17323      * common phase, we need to enable it here before any dmae access are
17324      * attempted. Therefore we manually added the enable-master to the
17325      * port phase (it also happens in the function phase)
17326      */
17327     if (!CHIP_IS_E1x(sc)) {
17328         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17329     }
17330
17331     ecore_init_block(sc, BLOCK_ATC, init_phase);
17332     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17333     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17334     ecore_init_block(sc, BLOCK_QM, init_phase);
17335
17336     ecore_init_block(sc, BLOCK_TCM, init_phase);
17337     ecore_init_block(sc, BLOCK_UCM, init_phase);
17338     ecore_init_block(sc, BLOCK_CCM, init_phase);
17339     ecore_init_block(sc, BLOCK_XCM, init_phase);
17340
17341     /* QM cid (connection) count */
17342     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17343
17344     if (CNIC_SUPPORT(sc)) {
17345         ecore_init_block(sc, BLOCK_TM, init_phase);
17346         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17347         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17348     }
17349
17350     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17351
17352     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17353
17354     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17355         if (IS_MF(sc)) {
17356             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17357         } else if (sc->mtu > 4096) {
17358             if (BXE_ONE_PORT(sc)) {
17359                 low = 160;
17360             } else {
17361                 val = sc->mtu;
17362                 /* (24*1024 + val*4)/256 */
17363                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17364             }
17365         } else {
17366             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17367         }
17368         high = (low + 56); /* 14*1024/256 */
17369         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17370         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17371     }
17372
17373     if (CHIP_IS_MODE_4_PORT(sc)) {
17374         REG_WR(sc, SC_PORT(sc) ?
17375                BRB1_REG_MAC_GUARANTIED_1 :
17376                BRB1_REG_MAC_GUARANTIED_0, 40);
17377     }
17378
17379     ecore_init_block(sc, BLOCK_PRS, init_phase);
17380     if (CHIP_IS_E3B0(sc)) {
17381         if (IS_MF_AFEX(sc)) {
17382             /* configure headers for AFEX mode */
17383             REG_WR(sc, SC_PORT(sc) ?
17384                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17385                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17386             REG_WR(sc, SC_PORT(sc) ?
17387                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17388                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17389             REG_WR(sc, SC_PORT(sc) ?
17390                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17391                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17392         } else {
17393             /* Ovlan exists only if we are in multi-function +
17394              * switch-dependent mode, in switch-independent there
17395              * is no ovlan headers
17396              */
17397             REG_WR(sc, SC_PORT(sc) ?
17398                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17399                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17400                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17401         }
17402     }
17403
17404     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17405     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17406     ecore_init_block(sc, BLOCK_USDM, init_phase);
17407     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17408
17409     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17410     ecore_init_block(sc, BLOCK_USEM, init_phase);
17411     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17412     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17413
17414     ecore_init_block(sc, BLOCK_UPB, init_phase);
17415     ecore_init_block(sc, BLOCK_XPB, init_phase);
17416
17417     ecore_init_block(sc, BLOCK_PBF, init_phase);
17418
17419     if (CHIP_IS_E1x(sc)) {
17420         /* configure PBF to work without PAUSE mtu 9000 */
17421         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17422
17423         /* update threshold */
17424         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17425         /* update init credit */
17426         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17427
17428         /* probe changes */
17429         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17430         DELAY(50);
17431         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17432     }
17433
17434     if (CNIC_SUPPORT(sc)) {
17435         ecore_init_block(sc, BLOCK_SRC, init_phase);
17436     }
17437
17438     ecore_init_block(sc, BLOCK_CDU, init_phase);
17439     ecore_init_block(sc, BLOCK_CFC, init_phase);
17440
17441     if (CHIP_IS_E1(sc)) {
17442         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17443         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17444     }
17445     ecore_init_block(sc, BLOCK_HC, init_phase);
17446
17447     ecore_init_block(sc, BLOCK_IGU, init_phase);
17448
17449     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17450     /* init aeu_mask_attn_func_0/1:
17451      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17452      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17453      *             bits 4-7 are used for "per vn group attention" */
17454     val = IS_MF(sc) ? 0xF7 : 0x7;
17455     /* Enable DCBX attention for all but E1 */
17456     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17457     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17458
17459     ecore_init_block(sc, BLOCK_NIG, init_phase);
17460
17461     if (!CHIP_IS_E1x(sc)) {
17462         /* Bit-map indicating which L2 hdrs may appear after the
17463          * basic Ethernet header
17464          */
17465         if (IS_MF_AFEX(sc)) {
17466             REG_WR(sc, SC_PORT(sc) ?
17467                    NIG_REG_P1_HDRS_AFTER_BASIC :
17468                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17469         } else {
17470             REG_WR(sc, SC_PORT(sc) ?
17471                    NIG_REG_P1_HDRS_AFTER_BASIC :
17472                    NIG_REG_P0_HDRS_AFTER_BASIC,
17473                    IS_MF_SD(sc) ? 7 : 6);
17474         }
17475
17476         if (CHIP_IS_E3(sc)) {
17477             REG_WR(sc, SC_PORT(sc) ?
17478                    NIG_REG_LLH1_MF_MODE :
17479                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17480         }
17481     }
17482     if (!CHIP_IS_E3(sc)) {
17483         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17484     }
17485
17486     if (!CHIP_IS_E1(sc)) {
17487         /* 0x2 disable mf_ov, 0x1 enable */
17488         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17489                (IS_MF_SD(sc) ? 0x1 : 0x2));
17490
17491         if (!CHIP_IS_E1x(sc)) {
17492             val = 0;
17493             switch (sc->devinfo.mf_info.mf_mode) {
17494             case MULTI_FUNCTION_SD:
17495                 val = 1;
17496                 break;
17497             case MULTI_FUNCTION_SI:
17498             case MULTI_FUNCTION_AFEX:
17499                 val = 2;
17500                 break;
17501             }
17502
17503             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17504                         NIG_REG_LLH0_CLS_TYPE), val);
17505         }
17506         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17507         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17508         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17509     }
17510
17511     /* If SPIO5 is set to generate interrupts, enable it for this port */
17512     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17513     if (val & MISC_SPIO_SPIO5) {
17514         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17515                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17516         val = REG_RD(sc, reg_addr);
17517         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17518         REG_WR(sc, reg_addr, val);
17519     }
17520
17521     return (0);
17522 }
17523
17524 static uint32_t
17525 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17526                        uint32_t         reg,
17527                        uint32_t         expected,
17528                        uint32_t         poll_count)
17529 {
17530     uint32_t cur_cnt = poll_count;
17531     uint32_t val;
17532
17533     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17534         DELAY(FLR_WAIT_INTERVAL);
17535     }
17536
17537     return (val);
17538 }
17539
17540 static int
17541 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17542                               uint32_t         reg,
17543                               char             *msg,
17544                               uint32_t         poll_cnt)
17545 {
17546     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17547
17548     if (val != 0) {
17549         BLOGE(sc, "%s usage count=%d\n", msg, val);
17550         return (1);
17551     }
17552
17553     return (0);
17554 }
17555
17556 /* Common routines with VF FLR cleanup */
17557 static uint32_t
17558 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17559 {
17560     /* adjust polling timeout */
17561     if (CHIP_REV_IS_EMUL(sc)) {
17562         return (FLR_POLL_CNT * 2000);
17563     }
17564
17565     if (CHIP_REV_IS_FPGA(sc)) {
17566         return (FLR_POLL_CNT * 120);
17567     }
17568
17569     return (FLR_POLL_CNT);
17570 }
17571
17572 static int
17573 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17574                            uint32_t         poll_cnt)
17575 {
17576     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17577     if (bxe_flr_clnup_poll_hw_counter(sc,
17578                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17579                                       "CFC PF usage counter timed out",
17580                                       poll_cnt)) {
17581         return (1);
17582     }
17583
17584     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17585     if (bxe_flr_clnup_poll_hw_counter(sc,
17586                                       DORQ_REG_PF_USAGE_CNT,
17587                                       "DQ PF usage counter timed out",
17588                                       poll_cnt)) {
17589         return (1);
17590     }
17591
17592     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17593     if (bxe_flr_clnup_poll_hw_counter(sc,
17594                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17595                                       "QM PF usage counter timed out",
17596                                       poll_cnt)) {
17597         return (1);
17598     }
17599
17600     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17601     if (bxe_flr_clnup_poll_hw_counter(sc,
17602                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17603                                       "Timers VNIC usage counter timed out",
17604                                       poll_cnt)) {
17605         return (1);
17606     }
17607
17608     if (bxe_flr_clnup_poll_hw_counter(sc,
17609                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17610                                       "Timers NUM_SCANS usage counter timed out",
17611                                       poll_cnt)) {
17612         return (1);
17613     }
17614
17615     /* Wait DMAE PF usage counter to zero */
17616     if (bxe_flr_clnup_poll_hw_counter(sc,
17617                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17618                                       "DMAE dommand register timed out",
17619                                       poll_cnt)) {
17620         return (1);
17621     }
17622
17623     return (0);
17624 }
17625
17626 #define OP_GEN_PARAM(param)                                            \
17627     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17628 #define OP_GEN_TYPE(type)                                           \
17629     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17630 #define OP_GEN_AGG_VECT(index)                                             \
17631     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17632
17633 static int
17634 bxe_send_final_clnup(struct bxe_softc *sc,
17635                      uint8_t          clnup_func,
17636                      uint32_t         poll_cnt)
17637 {
17638     uint32_t op_gen_command = 0;
17639     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17640                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17641     int ret = 0;
17642
17643     if (REG_RD(sc, comp_addr)) {
17644         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17645         return (1);
17646     }
17647
17648     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17649     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17650     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17651     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17652
17653     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17654     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17655
17656     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17657         BLOGE(sc, "FW final cleanup did not succeed\n");
17658         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17659               (REG_RD(sc, comp_addr)));
17660         bxe_panic(sc, ("FLR cleanup failed\n"));
17661         return (1);
17662     }
17663
17664     /* Zero completion for nxt FLR */
17665     REG_WR(sc, comp_addr, 0);
17666
17667     return (ret);
17668 }
17669
17670 static void
17671 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17672                        struct pbf_pN_buf_regs *regs,
17673                        uint32_t               poll_count)
17674 {
17675     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17676     uint32_t cur_cnt = poll_count;
17677
17678     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17679     crd = crd_start = REG_RD(sc, regs->crd);
17680     init_crd = REG_RD(sc, regs->init_crd);
17681
17682     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17683     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17684     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17685
17686     while ((crd != init_crd) &&
17687            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17688             (init_crd - crd_start))) {
17689         if (cur_cnt--) {
17690             DELAY(FLR_WAIT_INTERVAL);
17691             crd = REG_RD(sc, regs->crd);
17692             crd_freed = REG_RD(sc, regs->crd_freed);
17693         } else {
17694             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17695             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17696             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17697             break;
17698         }
17699     }
17700
17701     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17702           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17703 }
17704
17705 static void
17706 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17707                        struct pbf_pN_cmd_regs *regs,
17708                        uint32_t               poll_count)
17709 {
17710     uint32_t occup, to_free, freed, freed_start;
17711     uint32_t cur_cnt = poll_count;
17712
17713     occup = to_free = REG_RD(sc, regs->lines_occup);
17714     freed = freed_start = REG_RD(sc, regs->lines_freed);
17715
17716     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17717     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17718
17719     while (occup &&
17720            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17721         if (cur_cnt--) {
17722             DELAY(FLR_WAIT_INTERVAL);
17723             occup = REG_RD(sc, regs->lines_occup);
17724             freed = REG_RD(sc, regs->lines_freed);
17725         } else {
17726             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17727             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17728             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17729             break;
17730         }
17731     }
17732
17733     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17734           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17735 }
17736
17737 static void
17738 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17739 {
17740     struct pbf_pN_cmd_regs cmd_regs[] = {
17741         {0, (CHIP_IS_E3B0(sc)) ?
17742             PBF_REG_TQ_OCCUPANCY_Q0 :
17743             PBF_REG_P0_TQ_OCCUPANCY,
17744             (CHIP_IS_E3B0(sc)) ?
17745             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17746             PBF_REG_P0_TQ_LINES_FREED_CNT},
17747         {1, (CHIP_IS_E3B0(sc)) ?
17748             PBF_REG_TQ_OCCUPANCY_Q1 :
17749             PBF_REG_P1_TQ_OCCUPANCY,
17750             (CHIP_IS_E3B0(sc)) ?
17751             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17752             PBF_REG_P1_TQ_LINES_FREED_CNT},
17753         {4, (CHIP_IS_E3B0(sc)) ?
17754             PBF_REG_TQ_OCCUPANCY_LB_Q :
17755             PBF_REG_P4_TQ_OCCUPANCY,
17756             (CHIP_IS_E3B0(sc)) ?
17757             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17758             PBF_REG_P4_TQ_LINES_FREED_CNT}
17759     };
17760
17761     struct pbf_pN_buf_regs buf_regs[] = {
17762         {0, (CHIP_IS_E3B0(sc)) ?
17763             PBF_REG_INIT_CRD_Q0 :
17764             PBF_REG_P0_INIT_CRD ,
17765             (CHIP_IS_E3B0(sc)) ?
17766             PBF_REG_CREDIT_Q0 :
17767             PBF_REG_P0_CREDIT,
17768             (CHIP_IS_E3B0(sc)) ?
17769             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17770             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17771         {1, (CHIP_IS_E3B0(sc)) ?
17772             PBF_REG_INIT_CRD_Q1 :
17773             PBF_REG_P1_INIT_CRD,
17774             (CHIP_IS_E3B0(sc)) ?
17775             PBF_REG_CREDIT_Q1 :
17776             PBF_REG_P1_CREDIT,
17777             (CHIP_IS_E3B0(sc)) ?
17778             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17779             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17780         {4, (CHIP_IS_E3B0(sc)) ?
17781             PBF_REG_INIT_CRD_LB_Q :
17782             PBF_REG_P4_INIT_CRD,
17783             (CHIP_IS_E3B0(sc)) ?
17784             PBF_REG_CREDIT_LB_Q :
17785             PBF_REG_P4_CREDIT,
17786             (CHIP_IS_E3B0(sc)) ?
17787             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17788             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17789     };
17790
17791     int i;
17792
17793     /* Verify the command queues are flushed P0, P1, P4 */
17794     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17795         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17796     }
17797
17798     /* Verify the transmission buffers are flushed P0, P1, P4 */
17799     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17800         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17801     }
17802 }
17803
17804 static void
17805 bxe_hw_enable_status(struct bxe_softc *sc)
17806 {
17807     uint32_t val;
17808
17809     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17810     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17811
17812     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17813     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17814
17815     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17816     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17817
17818     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17819     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17820
17821     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17822     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17823
17824     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17825     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17826
17827     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17828     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17829
17830     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17831     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17832 }
17833
17834 static int
17835 bxe_pf_flr_clnup(struct bxe_softc *sc)
17836 {
17837     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17838
17839     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17840
17841     /* Re-enable PF target read access */
17842     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17843
17844     /* Poll HW usage counters */
17845     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17846     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17847         return (-1);
17848     }
17849
17850     /* Zero the igu 'trailing edge' and 'leading edge' */
17851
17852     /* Send the FW cleanup command */
17853     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17854         return (-1);
17855     }
17856
17857     /* ATC cleanup */
17858
17859     /* Verify TX hw is flushed */
17860     bxe_tx_hw_flushed(sc, poll_cnt);
17861
17862     /* Wait 100ms (not adjusted according to platform) */
17863     DELAY(100000);
17864
17865     /* Verify no pending pci transactions */
17866     if (bxe_is_pcie_pending(sc)) {
17867         BLOGE(sc, "PCIE Transactions still pending\n");
17868     }
17869
17870     /* Debug */
17871     bxe_hw_enable_status(sc);
17872
17873     /*
17874      * Master enable - Due to WB DMAE writes performed before this
17875      * register is re-initialized as part of the regular function init
17876      */
17877     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17878
17879     return (0);
17880 }
17881
17882 static int
17883 bxe_init_hw_func(struct bxe_softc *sc)
17884 {
17885     int port = SC_PORT(sc);
17886     int func = SC_FUNC(sc);
17887     int init_phase = PHASE_PF0 + func;
17888     struct ecore_ilt *ilt = sc->ilt;
17889     uint16_t cdu_ilt_start;
17890     uint32_t addr, val;
17891     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17892     int i, main_mem_width, rc;
17893
17894     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17895
17896     /* FLR cleanup */
17897     if (!CHIP_IS_E1x(sc)) {
17898         rc = bxe_pf_flr_clnup(sc);
17899         if (rc) {
17900             BLOGE(sc, "FLR cleanup failed!\n");
17901             // XXX bxe_fw_dump(sc);
17902             // XXX bxe_idle_chk(sc);
17903             return (rc);
17904         }
17905     }
17906
17907     /* set MSI reconfigure capability */
17908     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17909         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17910         val = REG_RD(sc, addr);
17911         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17912         REG_WR(sc, addr, val);
17913     }
17914
17915     ecore_init_block(sc, BLOCK_PXP, init_phase);
17916     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17917
17918     ilt = sc->ilt;
17919     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17920
17921     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17922         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17923         ilt->lines[cdu_ilt_start + i].page_mapping =
17924             sc->context[i].vcxt_dma.paddr;
17925         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17926     }
17927     ecore_ilt_init_op(sc, INITOP_SET);
17928
17929     /* Set NIC mode */
17930     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17931     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17932
17933     if (!CHIP_IS_E1x(sc)) {
17934         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17935
17936         /* Turn on a single ISR mode in IGU if driver is going to use
17937          * INT#x or MSI
17938          */
17939         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17940             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17941         }
17942
17943         /*
17944          * Timers workaround bug: function init part.
17945          * Need to wait 20msec after initializing ILT,
17946          * needed to make sure there are no requests in
17947          * one of the PXP internal queues with "old" ILT addresses
17948          */
17949         DELAY(20000);
17950
17951         /*
17952          * Master enable - Due to WB DMAE writes performed before this
17953          * register is re-initialized as part of the regular function
17954          * init
17955          */
17956         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17957         /* Enable the function in IGU */
17958         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17959     }
17960
17961     sc->dmae_ready = 1;
17962
17963     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17964
17965     if (!CHIP_IS_E1x(sc))
17966         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17967
17968     ecore_init_block(sc, BLOCK_ATC, init_phase);
17969     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17970     ecore_init_block(sc, BLOCK_NIG, init_phase);
17971     ecore_init_block(sc, BLOCK_SRC, init_phase);
17972     ecore_init_block(sc, BLOCK_MISC, init_phase);
17973     ecore_init_block(sc, BLOCK_TCM, init_phase);
17974     ecore_init_block(sc, BLOCK_UCM, init_phase);
17975     ecore_init_block(sc, BLOCK_CCM, init_phase);
17976     ecore_init_block(sc, BLOCK_XCM, init_phase);
17977     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17978     ecore_init_block(sc, BLOCK_USEM, init_phase);
17979     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17980     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17981
17982     if (!CHIP_IS_E1x(sc))
17983         REG_WR(sc, QM_REG_PF_EN, 1);
17984
17985     if (!CHIP_IS_E1x(sc)) {
17986         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17987         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17988         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17989         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17990     }
17991     ecore_init_block(sc, BLOCK_QM, init_phase);
17992
17993     ecore_init_block(sc, BLOCK_TM, init_phase);
17994     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17995
17996     bxe_iov_init_dq(sc);
17997
17998     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17999     ecore_init_block(sc, BLOCK_PRS, init_phase);
18000     ecore_init_block(sc, BLOCK_TSDM, init_phase);
18001     ecore_init_block(sc, BLOCK_CSDM, init_phase);
18002     ecore_init_block(sc, BLOCK_USDM, init_phase);
18003     ecore_init_block(sc, BLOCK_XSDM, init_phase);
18004     ecore_init_block(sc, BLOCK_UPB, init_phase);
18005     ecore_init_block(sc, BLOCK_XPB, init_phase);
18006     ecore_init_block(sc, BLOCK_PBF, init_phase);
18007     if (!CHIP_IS_E1x(sc))
18008         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
18009
18010     ecore_init_block(sc, BLOCK_CDU, init_phase);
18011
18012     ecore_init_block(sc, BLOCK_CFC, init_phase);
18013
18014     if (!CHIP_IS_E1x(sc))
18015         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
18016
18017     if (IS_MF(sc)) {
18018         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
18019         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
18020     }
18021
18022     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
18023
18024     /* HC init per function */
18025     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18026         if (CHIP_IS_E1H(sc)) {
18027             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18028
18029             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18030             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18031         }
18032         ecore_init_block(sc, BLOCK_HC, init_phase);
18033
18034     } else {
18035         int num_segs, sb_idx, prod_offset;
18036
18037         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18038
18039         if (!CHIP_IS_E1x(sc)) {
18040             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18041             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18042         }
18043
18044         ecore_init_block(sc, BLOCK_IGU, init_phase);
18045
18046         if (!CHIP_IS_E1x(sc)) {
18047             int dsb_idx = 0;
18048             /**
18049              * Producer memory:
18050              * E2 mode: address 0-135 match to the mapping memory;
18051              * 136 - PF0 default prod; 137 - PF1 default prod;
18052              * 138 - PF2 default prod; 139 - PF3 default prod;
18053              * 140 - PF0 attn prod;    141 - PF1 attn prod;
18054              * 142 - PF2 attn prod;    143 - PF3 attn prod;
18055              * 144-147 reserved.
18056              *
18057              * E1.5 mode - In backward compatible mode;
18058              * for non default SB; each even line in the memory
18059              * holds the U producer and each odd line hold
18060              * the C producer. The first 128 producers are for
18061              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18062              * producers are for the DSB for each PF.
18063              * Each PF has five segments: (the order inside each
18064              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18065              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18066              * 144-147 attn prods;
18067              */
18068             /* non-default-status-blocks */
18069             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18070                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18071             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18072                 prod_offset = (sc->igu_base_sb + sb_idx) *
18073                     num_segs;
18074
18075                 for (i = 0; i < num_segs; i++) {
18076                     addr = IGU_REG_PROD_CONS_MEMORY +
18077                             (prod_offset + i) * 4;
18078                     REG_WR(sc, addr, 0);
18079                 }
18080                 /* send consumer update with value 0 */
18081                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18082                            USTORM_ID, 0, IGU_INT_NOP, 1);
18083                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18084             }
18085
18086             /* default-status-blocks */
18087             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18088                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18089
18090             if (CHIP_IS_MODE_4_PORT(sc))
18091                 dsb_idx = SC_FUNC(sc);
18092             else
18093                 dsb_idx = SC_VN(sc);
18094
18095             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18096                        IGU_BC_BASE_DSB_PROD + dsb_idx :
18097                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
18098
18099             /*
18100              * igu prods come in chunks of E1HVN_MAX (4) -
18101              * does not matters what is the current chip mode
18102              */
18103             for (i = 0; i < (num_segs * E1HVN_MAX);
18104                  i += E1HVN_MAX) {
18105                 addr = IGU_REG_PROD_CONS_MEMORY +
18106                             (prod_offset + i)*4;
18107                 REG_WR(sc, addr, 0);
18108             }
18109             /* send consumer update with 0 */
18110             if (CHIP_INT_MODE_IS_BC(sc)) {
18111                 bxe_ack_sb(sc, sc->igu_dsb_id,
18112                            USTORM_ID, 0, IGU_INT_NOP, 1);
18113                 bxe_ack_sb(sc, sc->igu_dsb_id,
18114                            CSTORM_ID, 0, IGU_INT_NOP, 1);
18115                 bxe_ack_sb(sc, sc->igu_dsb_id,
18116                            XSTORM_ID, 0, IGU_INT_NOP, 1);
18117                 bxe_ack_sb(sc, sc->igu_dsb_id,
18118                            TSTORM_ID, 0, IGU_INT_NOP, 1);
18119                 bxe_ack_sb(sc, sc->igu_dsb_id,
18120                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18121             } else {
18122                 bxe_ack_sb(sc, sc->igu_dsb_id,
18123                            USTORM_ID, 0, IGU_INT_NOP, 1);
18124                 bxe_ack_sb(sc, sc->igu_dsb_id,
18125                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18126             }
18127             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18128
18129             /* !!! these should become driver const once
18130                rf-tool supports split-68 const */
18131             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18132             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18133             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18134             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18135             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18136             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18137         }
18138     }
18139
18140     /* Reset PCIE errors for debug */
18141     REG_WR(sc, 0x2114, 0xffffffff);
18142     REG_WR(sc, 0x2120, 0xffffffff);
18143
18144     if (CHIP_IS_E1x(sc)) {
18145         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18146         main_mem_base = HC_REG_MAIN_MEMORY +
18147                 SC_PORT(sc) * (main_mem_size * 4);
18148         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18149         main_mem_width = 8;
18150
18151         val = REG_RD(sc, main_mem_prty_clr);
18152         if (val) {
18153             BLOGD(sc, DBG_LOAD,
18154                   "Parity errors in HC block during function init (0x%x)!\n",
18155                   val);
18156         }
18157
18158         /* Clear "false" parity errors in MSI-X table */
18159         for (i = main_mem_base;
18160              i < main_mem_base + main_mem_size * 4;
18161              i += main_mem_width) {
18162             bxe_read_dmae(sc, i, main_mem_width / 4);
18163             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18164                            i, main_mem_width / 4);
18165         }
18166         /* Clear HC parity attention */
18167         REG_RD(sc, main_mem_prty_clr);
18168     }
18169
18170 #if 1
18171     /* Enable STORMs SP logging */
18172     REG_WR8(sc, BAR_USTRORM_INTMEM +
18173            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18174     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18175            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18176     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18177            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18178     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18179            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18180 #endif
18181
18182     elink_phy_probe(&sc->link_params);
18183
18184     return (0);
18185 }
18186
18187 static void
18188 bxe_link_reset(struct bxe_softc *sc)
18189 {
18190     if (!BXE_NOMCP(sc)) {
18191         bxe_acquire_phy_lock(sc);
18192         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18193         bxe_release_phy_lock(sc);
18194     } else {
18195         if (!CHIP_REV_IS_SLOW(sc)) {
18196             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18197         }
18198     }
18199 }
18200
18201 static void
18202 bxe_reset_port(struct bxe_softc *sc)
18203 {
18204     int port = SC_PORT(sc);
18205     uint32_t val;
18206
18207         ELINK_DEBUG_P0(sc, "bxe_reset_port called\n");
18208     /* reset physical Link */
18209     bxe_link_reset(sc);
18210
18211     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18212
18213     /* Do not rcv packets to BRB */
18214     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18215     /* Do not direct rcv packets that are not for MCP to the BRB */
18216     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18217                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18218
18219     /* Configure AEU */
18220     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18221
18222     DELAY(100000);
18223
18224     /* Check for BRB port occupancy */
18225     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18226     if (val) {
18227         BLOGD(sc, DBG_LOAD,
18228               "BRB1 is not empty, %d blocks are occupied\n", val);
18229     }
18230
18231     /* TODO: Close Doorbell port? */
18232 }
18233
18234 static void
18235 bxe_ilt_wr(struct bxe_softc *sc,
18236            uint32_t         index,
18237            bus_addr_t       addr)
18238 {
18239     int reg;
18240     uint32_t wb_write[2];
18241
18242     if (CHIP_IS_E1(sc)) {
18243         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18244     } else {
18245         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18246     }
18247
18248     wb_write[0] = ONCHIP_ADDR1(addr);
18249     wb_write[1] = ONCHIP_ADDR2(addr);
18250     REG_WR_DMAE(sc, reg, wb_write, 2);
18251 }
18252
18253 static void
18254 bxe_clear_func_ilt(struct bxe_softc *sc,
18255                    uint32_t         func)
18256 {
18257     uint32_t i, base = FUNC_ILT_BASE(func);
18258     for (i = base; i < base + ILT_PER_FUNC; i++) {
18259         bxe_ilt_wr(sc, i, 0);
18260     }
18261 }
18262
18263 static void
18264 bxe_reset_func(struct bxe_softc *sc)
18265 {
18266     struct bxe_fastpath *fp;
18267     int port = SC_PORT(sc);
18268     int func = SC_FUNC(sc);
18269     int i;
18270
18271     /* Disable the function in the FW */
18272     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18273     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18274     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18275     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18276
18277     /* FP SBs */
18278     FOR_EACH_ETH_QUEUE(sc, i) {
18279         fp = &sc->fp[i];
18280         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18281                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18282                 SB_DISABLED);
18283     }
18284
18285     /* SP SB */
18286     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18287             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18288             SB_DISABLED);
18289
18290     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18291         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18292     }
18293
18294     /* Configure IGU */
18295     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18296         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18297         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18298     } else {
18299         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18300         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18301     }
18302
18303     if (CNIC_LOADED(sc)) {
18304         /* Disable Timer scan */
18305         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18306         /*
18307          * Wait for at least 10ms and up to 2 second for the timers
18308          * scan to complete
18309          */
18310         for (i = 0; i < 200; i++) {
18311             DELAY(10000);
18312             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18313                 break;
18314         }
18315     }
18316
18317     /* Clear ILT */
18318     bxe_clear_func_ilt(sc, func);
18319
18320     /*
18321      * Timers workaround bug for E2: if this is vnic-3,
18322      * we need to set the entire ilt range for this timers.
18323      */
18324     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18325         struct ilt_client_info ilt_cli;
18326         /* use dummy TM client */
18327         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18328         ilt_cli.start = 0;
18329         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18330         ilt_cli.client_num = ILT_CLIENT_TM;
18331
18332         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18333     }
18334
18335     /* this assumes that reset_port() called before reset_func()*/
18336     if (!CHIP_IS_E1x(sc)) {
18337         bxe_pf_disable(sc);
18338     }
18339
18340     sc->dmae_ready = 0;
18341 }
18342
18343 static int
18344 bxe_gunzip_init(struct bxe_softc *sc)
18345 {
18346     return (0);
18347 }
18348
18349 static void
18350 bxe_gunzip_end(struct bxe_softc *sc)
18351 {
18352     return;
18353 }
18354
18355 static int
18356 bxe_init_firmware(struct bxe_softc *sc)
18357 {
18358     if (CHIP_IS_E1(sc)) {
18359         ecore_init_e1_firmware(sc);
18360         sc->iro_array = e1_iro_arr;
18361     } else if (CHIP_IS_E1H(sc)) {
18362         ecore_init_e1h_firmware(sc);
18363         sc->iro_array = e1h_iro_arr;
18364     } else if (!CHIP_IS_E1x(sc)) {
18365         ecore_init_e2_firmware(sc);
18366         sc->iro_array = e2_iro_arr;
18367     } else {
18368         BLOGE(sc, "Unsupported chip revision\n");
18369         return (-1);
18370     }
18371
18372     return (0);
18373 }
18374
18375 static void
18376 bxe_release_firmware(struct bxe_softc *sc)
18377 {
18378     /* Do nothing */
18379     return;
18380 }
18381
18382 static int
18383 ecore_gunzip(struct bxe_softc *sc,
18384              const uint8_t    *zbuf,
18385              int              len)
18386 {
18387     /* XXX : Implement... */
18388     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18389     return (FALSE);
18390 }
18391
18392 static void
18393 ecore_reg_wr_ind(struct bxe_softc *sc,
18394                  uint32_t         addr,
18395                  uint32_t         val)
18396 {
18397     bxe_reg_wr_ind(sc, addr, val);
18398 }
18399
18400 static void
18401 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18402                           bus_addr_t       phys_addr,
18403                           uint32_t         addr,
18404                           uint32_t         len)
18405 {
18406     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18407 }
18408
18409 void
18410 ecore_storm_memset_struct(struct bxe_softc *sc,
18411                           uint32_t         addr,
18412                           size_t           size,
18413                           uint32_t         *data)
18414 {
18415     uint8_t i;
18416     for (i = 0; i < size/4; i++) {
18417         REG_WR(sc, addr + (i * 4), data[i]);
18418     }
18419 }
18420
18421
18422 /*
18423  * character device - ioctl interface definitions
18424  */
18425
18426
18427 #include "bxe_dump.h"
18428 #include "bxe_ioctl.h"
18429 #include <sys/conf.h>
18430
18431 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18432                 struct thread *td);
18433
18434 static struct cdevsw bxe_cdevsw = {
18435     .d_version = D_VERSION,
18436     .d_ioctl = bxe_eioctl,
18437     .d_name = "bxecnic",
18438 };
18439
18440 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18441
18442
18443 #define DUMP_ALL_PRESETS        0x1FFF
18444 #define DUMP_MAX_PRESETS        13
18445 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18446 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18447 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18448 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18449 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18450
18451 #define IS_REG_IN_PRESET(presets, idx)  \
18452                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18453
18454
18455 static int
18456 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18457 {
18458     if (CHIP_IS_E1(sc))
18459         return dump_num_registers[0][preset-1];
18460     else if (CHIP_IS_E1H(sc))
18461         return dump_num_registers[1][preset-1];
18462     else if (CHIP_IS_E2(sc))
18463         return dump_num_registers[2][preset-1];
18464     else if (CHIP_IS_E3A0(sc))
18465         return dump_num_registers[3][preset-1];
18466     else if (CHIP_IS_E3B0(sc))
18467         return dump_num_registers[4][preset-1];
18468     else
18469         return 0;
18470 }
18471
18472 static int
18473 bxe_get_total_regs_len32(struct bxe_softc *sc)
18474 {
18475     uint32_t preset_idx;
18476     int regdump_len32 = 0;
18477
18478
18479     /* Calculate the total preset regs length */
18480     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18481         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18482     }
18483
18484     return regdump_len32;
18485 }
18486
18487 static const uint32_t *
18488 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18489 {
18490     if (CHIP_IS_E2(sc))
18491         return page_vals_e2;
18492     else if (CHIP_IS_E3(sc))
18493         return page_vals_e3;
18494     else
18495         return NULL;
18496 }
18497
18498 static uint32_t
18499 __bxe_get_page_reg_num(struct bxe_softc *sc)
18500 {
18501     if (CHIP_IS_E2(sc))
18502         return PAGE_MODE_VALUES_E2;
18503     else if (CHIP_IS_E3(sc))
18504         return PAGE_MODE_VALUES_E3;
18505     else
18506         return 0;
18507 }
18508
18509 static const uint32_t *
18510 __bxe_get_page_write_ar(struct bxe_softc *sc)
18511 {
18512     if (CHIP_IS_E2(sc))
18513         return page_write_regs_e2;
18514     else if (CHIP_IS_E3(sc))
18515         return page_write_regs_e3;
18516     else
18517         return NULL;
18518 }
18519
18520 static uint32_t
18521 __bxe_get_page_write_num(struct bxe_softc *sc)
18522 {
18523     if (CHIP_IS_E2(sc))
18524         return PAGE_WRITE_REGS_E2;
18525     else if (CHIP_IS_E3(sc))
18526         return PAGE_WRITE_REGS_E3;
18527     else
18528         return 0;
18529 }
18530
18531 static const struct reg_addr *
18532 __bxe_get_page_read_ar(struct bxe_softc *sc)
18533 {
18534     if (CHIP_IS_E2(sc))
18535         return page_read_regs_e2;
18536     else if (CHIP_IS_E3(sc))
18537         return page_read_regs_e3;
18538     else
18539         return NULL;
18540 }
18541
18542 static uint32_t
18543 __bxe_get_page_read_num(struct bxe_softc *sc)
18544 {
18545     if (CHIP_IS_E2(sc))
18546         return PAGE_READ_REGS_E2;
18547     else if (CHIP_IS_E3(sc))
18548         return PAGE_READ_REGS_E3;
18549     else
18550         return 0;
18551 }
18552
18553 static bool
18554 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18555 {
18556     if (CHIP_IS_E1(sc))
18557         return IS_E1_REG(reg_info->chips);
18558     else if (CHIP_IS_E1H(sc))
18559         return IS_E1H_REG(reg_info->chips);
18560     else if (CHIP_IS_E2(sc))
18561         return IS_E2_REG(reg_info->chips);
18562     else if (CHIP_IS_E3A0(sc))
18563         return IS_E3A0_REG(reg_info->chips);
18564     else if (CHIP_IS_E3B0(sc))
18565         return IS_E3B0_REG(reg_info->chips);
18566     else
18567         return 0;
18568 }
18569
18570 static bool
18571 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18572 {
18573     if (CHIP_IS_E1(sc))
18574         return IS_E1_REG(wreg_info->chips);
18575     else if (CHIP_IS_E1H(sc))
18576         return IS_E1H_REG(wreg_info->chips);
18577     else if (CHIP_IS_E2(sc))
18578         return IS_E2_REG(wreg_info->chips);
18579     else if (CHIP_IS_E3A0(sc))
18580         return IS_E3A0_REG(wreg_info->chips);
18581     else if (CHIP_IS_E3B0(sc))
18582         return IS_E3B0_REG(wreg_info->chips);
18583     else
18584         return 0;
18585 }
18586
18587 /**
18588  * bxe_read_pages_regs - read "paged" registers
18589  *
18590  * @bp          device handle
18591  * @p           output buffer
18592  *
18593  * Reads "paged" memories: memories that may only be read by first writing to a
18594  * specific address ("write address") and then reading from a specific address
18595  * ("read address"). There may be more than one write address per "page" and
18596  * more than one read address per write address.
18597  */
18598 static void
18599 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18600 {
18601     uint32_t i, j, k, n;
18602
18603     /* addresses of the paged registers */
18604     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18605     /* number of paged registers */
18606     int num_pages = __bxe_get_page_reg_num(sc);
18607     /* write addresses */
18608     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18609     /* number of write addresses */
18610     int write_num = __bxe_get_page_write_num(sc);
18611     /* read addresses info */
18612     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18613     /* number of read addresses */
18614     int read_num = __bxe_get_page_read_num(sc);
18615     uint32_t addr, size;
18616
18617     for (i = 0; i < num_pages; i++) {
18618         for (j = 0; j < write_num; j++) {
18619             REG_WR(sc, write_addr[j], page_addr[i]);
18620
18621             for (k = 0; k < read_num; k++) {
18622                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18623                     size = read_addr[k].size;
18624                     for (n = 0; n < size; n++) {
18625                         addr = read_addr[k].addr + n*4;
18626                         *p++ = REG_RD(sc, addr);
18627                     }
18628                 }
18629             }
18630         }
18631     }
18632     return;
18633 }
18634
18635
18636 static int
18637 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18638 {
18639     uint32_t i, j, addr;
18640     const struct wreg_addr *wreg_addr_p = NULL;
18641
18642     if (CHIP_IS_E1(sc))
18643         wreg_addr_p = &wreg_addr_e1;
18644     else if (CHIP_IS_E1H(sc))
18645         wreg_addr_p = &wreg_addr_e1h;
18646     else if (CHIP_IS_E2(sc))
18647         wreg_addr_p = &wreg_addr_e2;
18648     else if (CHIP_IS_E3A0(sc))
18649         wreg_addr_p = &wreg_addr_e3;
18650     else if (CHIP_IS_E3B0(sc))
18651         wreg_addr_p = &wreg_addr_e3b0;
18652     else
18653         return (-1);
18654
18655     /* Read the idle_chk registers */
18656     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18657         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18658             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18659             for (j = 0; j < idle_reg_addrs[i].size; j++)
18660                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18661         }
18662     }
18663
18664     /* Read the regular registers */
18665     for (i = 0; i < REGS_COUNT; i++) {
18666         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18667             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18668             for (j = 0; j < reg_addrs[i].size; j++)
18669                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18670         }
18671     }
18672
18673     /* Read the CAM registers */
18674     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18675         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18676         for (i = 0; i < wreg_addr_p->size; i++) {
18677             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18678
18679             /* In case of wreg_addr register, read additional
18680                registers from read_regs array
18681              */
18682             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18683                 addr = *(wreg_addr_p->read_regs);
18684                 *p++ = REG_RD(sc, addr + j*4);
18685             }
18686         }
18687     }
18688
18689     /* Paged registers are supported in E2 & E3 only */
18690     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18691         /* Read "paged" registers */
18692         bxe_read_pages_regs(sc, p, preset);
18693     }
18694
18695     return 0;
18696 }
18697
18698 int
18699 bxe_grc_dump(struct bxe_softc *sc)
18700 {
18701     int rval = 0;
18702     uint32_t preset_idx;
18703     uint8_t *buf;
18704     uint32_t size;
18705     struct  dump_header *d_hdr;
18706     uint32_t i;
18707     uint32_t reg_val;
18708     uint32_t reg_addr;
18709     uint32_t cmd_offset;
18710     struct ecore_ilt *ilt = SC_ILT(sc);
18711     struct bxe_fastpath *fp;
18712     struct ilt_client_info *ilt_cli;
18713     int grc_dump_size;
18714
18715
18716     if (sc->grcdump_done || sc->grcdump_started)
18717         return (rval);
18718     
18719     sc->grcdump_started = 1;
18720     BLOGI(sc, "Started collecting grcdump\n");
18721
18722     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18723                 sizeof(struct  dump_header);
18724
18725     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18726
18727     if (sc->grc_dump == NULL) {
18728         BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
18729         return(ENOMEM);
18730     }
18731
18732
18733
18734     /* Disable parity attentions as long as following dump may
18735      * cause false alarms by reading never written registers. We
18736      * will re-enable parity attentions right after the dump.
18737      */
18738
18739     /* Disable parity on path 0 */
18740     bxe_pretend_func(sc, 0);
18741
18742     ecore_disable_blocks_parity(sc);
18743
18744     /* Disable parity on path 1 */
18745     bxe_pretend_func(sc, 1);
18746     ecore_disable_blocks_parity(sc);
18747
18748     /* Return to current function */
18749     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18750
18751     buf = sc->grc_dump;
18752     d_hdr = sc->grc_dump;
18753
18754     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18755     d_hdr->version = BNX2X_DUMP_VERSION;
18756     d_hdr->preset = DUMP_ALL_PRESETS;
18757
18758     if (CHIP_IS_E1(sc)) {
18759         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18760     } else if (CHIP_IS_E1H(sc)) {
18761         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18762     } else if (CHIP_IS_E2(sc)) {
18763         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18764                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18765     } else if (CHIP_IS_E3A0(sc)) {
18766         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18767                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18768     } else if (CHIP_IS_E3B0(sc)) {
18769         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18770                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18771     }
18772
18773     buf += sizeof(struct  dump_header);
18774
18775     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18776
18777         /* Skip presets with IOR */
18778         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18779             (preset_idx == 11))
18780             continue;
18781
18782         rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
18783
18784         if (rval)
18785             break;
18786
18787         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18788
18789         buf += size;
18790     }
18791
18792     bxe_pretend_func(sc, 0);
18793     ecore_clear_blocks_parity(sc);
18794     ecore_enable_blocks_parity(sc);
18795
18796     bxe_pretend_func(sc, 1);
18797     ecore_clear_blocks_parity(sc);
18798     ecore_enable_blocks_parity(sc);
18799
18800     /* Return to current function */
18801     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18802
18803
18804
18805     if(sc->state == BXE_STATE_OPEN) {
18806         if(sc->fw_stats_req  != NULL) {
18807                 BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
18808                                 (uintmax_t)sc->fw_stats_req_mapping,
18809                                 (uintmax_t)sc->fw_stats_data_mapping,
18810                                 sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
18811                 }       
18812                 if(sc->def_sb != NULL) {
18813                         BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
18814                                 (void *)sc->def_sb_dma.paddr, sc->def_sb,
18815                                 sizeof(struct host_sp_status_block));
18816                 }
18817                 if(sc->eq_dma.vaddr != NULL) {
18818                 BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
18819                                 (uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
18820                 }
18821                 if(sc->sp_dma.vaddr != NULL) {
18822                 BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
18823                                 (uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
18824                                 sizeof(struct bxe_slowpath));
18825                 }
18826                 if(sc->spq_dma.vaddr != NULL) {
18827                 BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
18828                                 (uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
18829                 }
18830                 if(sc->gz_buf_dma.vaddr != NULL) {
18831                 BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
18832                                 (uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
18833                                 FW_BUF_SIZE);
18834                 }
18835         for (i = 0; i < sc->num_queues; i++) {
18836                 fp = &sc->fp[i];
18837                         if(fp->sb_dma.vaddr != NULL && fp->tx_dma.vaddr != NULL &&
18838                         fp->rx_dma.vaddr != NULL && fp->rcq_dma.vaddr != NULL &&
18839                         fp->rx_sge_dma.vaddr != NULL) {
18840
18841                                 BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18842                                 (uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
18843                                 sizeof(union bxe_host_hc_status_block));
18844                                 BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18845                                 (uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
18846                                 (BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
18847                         BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18848                                 (uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
18849                                 (BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
18850                         BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18851                                 (uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
18852                                 (BCM_PAGE_SIZE * RCQ_NUM_PAGES));
18853                         BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18854                                 (uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
18855                                 (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
18856                 }
18857                 }
18858                 if(ilt != NULL ) {
18859                 ilt_cli = &ilt->clients[1];
18860                         if(ilt->lines != NULL) {
18861                 for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
18862                         BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
18863                                 (uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
18864                                 ((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
18865                 }
18866                         }
18867                 }
18868
18869
18870         cmd_offset = DMAE_REG_CMD_MEM;
18871         for (i = 0; i < 224; i++) {
18872                 reg_addr = (cmd_offset +(i * 4));
18873                 reg_val = REG_RD(sc, reg_addr);
18874                 BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
18875                                 reg_addr, reg_val);
18876         }
18877         }
18878
18879     BLOGI(sc, "Collection of grcdump done\n");
18880     sc->grcdump_done = 1;
18881     return(rval);
18882 }
18883
18884 static int
18885 bxe_add_cdev(struct bxe_softc *sc)
18886 {
18887     sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
18888
18889     if (sc->eeprom == NULL) {
18890         BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
18891         return (-1);
18892     }
18893
18894     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18895                             sc->ifnet->if_dunit,
18896                             UID_ROOT,
18897                             GID_WHEEL,
18898                             0600,
18899                             "%s",
18900                             if_name(sc->ifnet));
18901
18902     if (sc->ioctl_dev == NULL) {
18903         free(sc->eeprom, M_DEVBUF);
18904         sc->eeprom = NULL;
18905         return (-1);
18906     }
18907
18908     sc->ioctl_dev->si_drv1 = sc;
18909
18910     return (0);
18911 }
18912
18913 static void
18914 bxe_del_cdev(struct bxe_softc *sc)
18915 {
18916     if (sc->ioctl_dev != NULL)
18917         destroy_dev(sc->ioctl_dev);
18918
18919     if (sc->eeprom != NULL) {
18920         free(sc->eeprom, M_DEVBUF);
18921         sc->eeprom = NULL;
18922     }
18923     sc->ioctl_dev = NULL;
18924
18925     return;
18926 }
18927
18928 static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
18929 {
18930
18931     if ((sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) == 0)
18932         return FALSE;
18933
18934     return TRUE;
18935 }
18936
18937
18938 static int
18939 bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18940 {
18941     int rval = 0;
18942
18943     if(!bxe_is_nvram_accessible(sc)) {
18944         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18945         return (-EAGAIN);
18946     }
18947     rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
18948
18949
18950    return (rval);
18951 }
18952
18953 static int
18954 bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18955 {
18956     int rval = 0;
18957
18958     if(!bxe_is_nvram_accessible(sc)) {
18959         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18960         return (-EAGAIN);
18961     }
18962     rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
18963
18964    return (rval);
18965 }
18966
18967 static int
18968 bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
18969 {
18970     int rval = 0;
18971
18972     switch (eeprom->eeprom_cmd) {
18973
18974     case BXE_EEPROM_CMD_SET_EEPROM:
18975
18976         rval = copyin(eeprom->eeprom_data, sc->eeprom,
18977                        eeprom->eeprom_data_len);
18978
18979         if (rval)
18980             break;
18981
18982         rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18983                        eeprom->eeprom_data_len);
18984         break;
18985
18986     case BXE_EEPROM_CMD_GET_EEPROM:
18987
18988         rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18989                        eeprom->eeprom_data_len);
18990
18991         if (rval) {
18992             break;
18993         }
18994
18995         rval = copyout(sc->eeprom, eeprom->eeprom_data,
18996                        eeprom->eeprom_data_len);
18997         break;
18998
18999     default:
19000             rval = EINVAL;
19001             break;
19002     }
19003
19004     if (rval) {
19005         BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
19006     }
19007
19008     return (rval);
19009 }
19010
19011 static int
19012 bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
19013 {
19014     uint32_t ext_phy_config;
19015     int port = SC_PORT(sc);
19016     int cfg_idx = bxe_get_link_cfg_idx(sc);
19017
19018     dev_p->supported = sc->port.supported[cfg_idx] |
19019             (sc->port.supported[cfg_idx ^ 1] &
19020             (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
19021     dev_p->advertising = sc->port.advertising[cfg_idx];
19022     if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
19023         ELINK_ETH_PHY_SFP_1G_FIBER) {
19024         dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
19025         dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
19026     }
19027     if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
19028         !(sc->flags & BXE_MF_FUNC_DIS)) {
19029         dev_p->duplex = sc->link_vars.duplex;
19030         if (IS_MF(sc) && !BXE_NOMCP(sc))
19031             dev_p->speed = bxe_get_mf_speed(sc);
19032         else
19033             dev_p->speed = sc->link_vars.line_speed;
19034     } else {
19035         dev_p->duplex = DUPLEX_UNKNOWN;
19036         dev_p->speed = SPEED_UNKNOWN;
19037     }
19038
19039     dev_p->port = bxe_media_detect(sc);
19040
19041     ext_phy_config = SHMEM_RD(sc,
19042                          dev_info.port_hw_config[port].external_phy_config);
19043     if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
19044         PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
19045         dev_p->phy_address =  sc->port.phy_addr;
19046     else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19047             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
19048         ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19049             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
19050         dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
19051     else
19052         dev_p->phy_address = 0;
19053
19054     if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
19055         dev_p->autoneg = AUTONEG_ENABLE;
19056     else
19057        dev_p->autoneg = AUTONEG_DISABLE;
19058
19059
19060     return 0;
19061 }
19062
19063 static int
19064 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
19065         struct thread *td)
19066 {
19067     struct bxe_softc    *sc;
19068     int                 rval = 0;
19069     device_t            pci_dev;
19070     bxe_grcdump_t       *dump = NULL;
19071     int grc_dump_size;
19072     bxe_drvinfo_t   *drv_infop = NULL;
19073     bxe_dev_setting_t  *dev_p;
19074     bxe_dev_setting_t  dev_set;
19075     bxe_get_regs_t  *reg_p;
19076     bxe_reg_rdw_t *reg_rdw_p;
19077     bxe_pcicfg_rdw_t *cfg_rdw_p;
19078     bxe_perm_mac_addr_t *mac_addr_p;
19079
19080
19081     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
19082         return ENXIO;
19083
19084     pci_dev= sc->dev;
19085
19086     dump = (bxe_grcdump_t *)data;
19087
19088     switch(cmd) {
19089
19090         case BXE_GRC_DUMP_SIZE:
19091             dump->pci_func = sc->pcie_func;
19092             dump->grcdump_size =
19093                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19094                      sizeof(struct  dump_header);
19095             break;
19096
19097         case BXE_GRC_DUMP:
19098             
19099             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19100                                 sizeof(struct  dump_header);
19101             if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
19102                 (dump->grcdump_size < grc_dump_size)) {
19103                 rval = EINVAL;
19104                 break;
19105             }
19106
19107             if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
19108                 (!sc->grcdump_started)) {
19109                 rval =  bxe_grc_dump(sc);
19110             }
19111
19112             if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
19113                 (sc->grc_dump != NULL))  {
19114                 dump->grcdump_dwords = grc_dump_size >> 2;
19115                 rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
19116                 free(sc->grc_dump, M_DEVBUF);
19117                 sc->grc_dump = NULL;
19118                 sc->grcdump_started = 0;
19119                 sc->grcdump_done = 0;
19120             }
19121
19122             break;
19123
19124         case BXE_DRV_INFO:
19125             drv_infop = (bxe_drvinfo_t *)data;
19126             snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
19127             snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
19128                 BXE_DRIVER_VERSION);
19129             snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
19130                 sc->devinfo.bc_ver_str);
19131             snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
19132                 "%s", sc->fw_ver_str);
19133             drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
19134             drv_infop->reg_dump_len =
19135                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
19136                     + sizeof(struct  dump_header);
19137             snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
19138                 sc->pcie_bus, sc->pcie_device, sc->pcie_func);
19139             break;
19140
19141         case BXE_DEV_SETTING:
19142             dev_p = (bxe_dev_setting_t *)data;
19143             bxe_get_settings(sc, &dev_set);
19144             dev_p->supported = dev_set.supported;
19145             dev_p->advertising = dev_set.advertising;
19146             dev_p->speed = dev_set.speed;
19147             dev_p->duplex = dev_set.duplex;
19148             dev_p->port = dev_set.port;
19149             dev_p->phy_address = dev_set.phy_address;
19150             dev_p->autoneg = dev_set.autoneg;
19151
19152             break;
19153
19154         case BXE_GET_REGS:
19155
19156             reg_p = (bxe_get_regs_t *)data;
19157             grc_dump_size = reg_p->reg_buf_len;
19158
19159             if((!sc->grcdump_done) && (!sc->grcdump_started)) {
19160                 bxe_grc_dump(sc);
19161             }
19162             if((sc->grcdump_done) && (sc->grcdump_started) &&
19163                 (sc->grc_dump != NULL))  {
19164                 rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
19165                 free(sc->grc_dump, M_DEVBUF);
19166                 sc->grc_dump = NULL;
19167                 sc->grcdump_started = 0;
19168                 sc->grcdump_done = 0;
19169             }
19170
19171             break;
19172
19173         case BXE_RDW_REG:
19174             reg_rdw_p = (bxe_reg_rdw_t *)data;
19175             if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
19176                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19177                 reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
19178
19179             if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
19180                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19181                 REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
19182
19183             break;
19184
19185         case BXE_RDW_PCICFG:
19186             cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
19187             if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
19188
19189                 cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
19190                                          cfg_rdw_p->cfg_width);
19191
19192             } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
19193                 pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
19194                             cfg_rdw_p->cfg_width);
19195             } else {
19196                 BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
19197             }
19198             break;
19199
19200         case BXE_MAC_ADDR:
19201             mac_addr_p = (bxe_perm_mac_addr_t *)data;
19202             snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
19203                 sc->mac_addr_str);
19204             break;
19205
19206         case BXE_EEPROM:
19207             rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
19208             break;
19209
19210
19211         default:
19212             break;
19213     }
19214
19215     return (rval);
19216 }