]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/dev/bxe/bxe.c
MFC r297873
[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.81"
31
32 #include "bxe.h"
33 #include "ecore_sp.h"
34 #include "ecore_init.h"
35 #include "ecore_init_ops.h"
36
37 #include "57710_int_offsets.h"
38 #include "57711_int_offsets.h"
39 #include "57712_int_offsets.h"
40
41 /*
42  * CTLTYPE_U64 and sysctl_handle_64 were added in r217616. Define these
43  * explicitly here for older kernels that don't include this changeset.
44  */
45 #ifndef CTLTYPE_U64
46 #define CTLTYPE_U64      CTLTYPE_QUAD
47 #define sysctl_handle_64 sysctl_handle_quad
48 #endif
49
50 /*
51  * CSUM_TCP_IPV6 and CSUM_UDP_IPV6 were added in r236170. Define these
52  * here as zero(0) for older kernels that don't include this changeset
53  * thereby masking the functionality.
54  */
55 #ifndef CSUM_TCP_IPV6
56 #define CSUM_TCP_IPV6 0
57 #define CSUM_UDP_IPV6 0
58 #endif
59
60 /*
61  * pci_find_cap was added in r219865. Re-define this at pci_find_extcap
62  * for older kernels that don't include this changeset.
63  */
64 #if __FreeBSD_version < 900035
65 #define pci_find_cap pci_find_extcap
66 #endif
67
68 #define BXE_DEF_SB_ATT_IDX 0x0001
69 #define BXE_DEF_SB_IDX     0x0002
70
71 /*
72  * FLR Support - bxe_pf_flr_clnup() is called during nic_load in the per
73  * function HW initialization.
74  */
75 #define FLR_WAIT_USEC     10000 /* 10 msecs */
76 #define FLR_WAIT_INTERVAL 50    /* usecs */
77 #define FLR_POLL_CNT      (FLR_WAIT_USEC / FLR_WAIT_INTERVAL) /* 200 */
78
79 struct pbf_pN_buf_regs {
80     int pN;
81     uint32_t init_crd;
82     uint32_t crd;
83     uint32_t crd_freed;
84 };
85
86 struct pbf_pN_cmd_regs {
87     int pN;
88     uint32_t lines_occup;
89     uint32_t lines_freed;
90 };
91
92 /*
93  * PCI Device ID Table used by bxe_probe().
94  */
95 #define BXE_DEVDESC_MAX 64
96 static struct bxe_device_type bxe_devs[] = {
97     {
98         BRCM_VENDORID,
99         CHIP_NUM_57710,
100         PCI_ANY_ID, PCI_ANY_ID,
101         "QLogic NetXtreme II BCM57710 10GbE"
102     },
103     {
104         BRCM_VENDORID,
105         CHIP_NUM_57711,
106         PCI_ANY_ID, PCI_ANY_ID,
107         "QLogic NetXtreme II BCM57711 10GbE"
108     },
109     {
110         BRCM_VENDORID,
111         CHIP_NUM_57711E,
112         PCI_ANY_ID, PCI_ANY_ID,
113         "QLogic NetXtreme II BCM57711E 10GbE"
114     },
115     {
116         BRCM_VENDORID,
117         CHIP_NUM_57712,
118         PCI_ANY_ID, PCI_ANY_ID,
119         "QLogic NetXtreme II BCM57712 10GbE"
120     },
121     {
122         BRCM_VENDORID,
123         CHIP_NUM_57712_MF,
124         PCI_ANY_ID, PCI_ANY_ID,
125         "QLogic NetXtreme II BCM57712 MF 10GbE"
126     },
127     {
128         BRCM_VENDORID,
129         CHIP_NUM_57800,
130         PCI_ANY_ID, PCI_ANY_ID,
131         "QLogic NetXtreme II BCM57800 10GbE"
132     },
133     {
134         BRCM_VENDORID,
135         CHIP_NUM_57800_MF,
136         PCI_ANY_ID, PCI_ANY_ID,
137         "QLogic NetXtreme II BCM57800 MF 10GbE"
138     },
139     {
140         BRCM_VENDORID,
141         CHIP_NUM_57810,
142         PCI_ANY_ID, PCI_ANY_ID,
143         "QLogic NetXtreme II BCM57810 10GbE"
144     },
145     {
146         BRCM_VENDORID,
147         CHIP_NUM_57810_MF,
148         PCI_ANY_ID, PCI_ANY_ID,
149         "QLogic NetXtreme II BCM57810 MF 10GbE"
150     },
151     {
152         BRCM_VENDORID,
153         CHIP_NUM_57811,
154         PCI_ANY_ID, PCI_ANY_ID,
155         "QLogic NetXtreme II BCM57811 10GbE"
156     },
157     {
158         BRCM_VENDORID,
159         CHIP_NUM_57811_MF,
160         PCI_ANY_ID, PCI_ANY_ID,
161         "QLogic NetXtreme II BCM57811 MF 10GbE"
162     },
163     {
164         BRCM_VENDORID,
165         CHIP_NUM_57840_4_10,
166         PCI_ANY_ID, PCI_ANY_ID,
167         "QLogic NetXtreme II BCM57840 4x10GbE"
168     },
169     {
170         BRCM_VENDORID,
171         CHIP_NUM_57840_MF,
172         PCI_ANY_ID, PCI_ANY_ID,
173         "QLogic NetXtreme II BCM57840 MF 10GbE"
174     },
175     {
176         0, 0, 0, 0, NULL
177     }
178 };
179
180 MALLOC_DECLARE(M_BXE_ILT);
181 MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
182
183 /*
184  * FreeBSD device entry points.
185  */
186 static int bxe_probe(device_t);
187 static int bxe_attach(device_t);
188 static int bxe_detach(device_t);
189 static int bxe_shutdown(device_t);
190
191 /*
192  * FreeBSD KLD module/device interface event handler method.
193  */
194 static device_method_t bxe_methods[] = {
195     /* Device interface (device_if.h) */
196     DEVMETHOD(device_probe,     bxe_probe),
197     DEVMETHOD(device_attach,    bxe_attach),
198     DEVMETHOD(device_detach,    bxe_detach),
199     DEVMETHOD(device_shutdown,  bxe_shutdown),
200     /* Bus interface (bus_if.h) */
201     DEVMETHOD(bus_print_child,  bus_generic_print_child),
202     DEVMETHOD(bus_driver_added, bus_generic_driver_added),
203     KOBJMETHOD_END
204 };
205
206 /*
207  * FreeBSD KLD Module data declaration
208  */
209 static driver_t bxe_driver = {
210     "bxe",                   /* module name */
211     bxe_methods,             /* event handler */
212     sizeof(struct bxe_softc) /* extra data */
213 };
214
215 /*
216  * FreeBSD dev class is needed to manage dev instances and
217  * to associate with a bus type
218  */
219 static devclass_t bxe_devclass;
220
221 MODULE_DEPEND(bxe, pci, 1, 1, 1);
222 MODULE_DEPEND(bxe, ether, 1, 1, 1);
223 DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
224
225 /* resources needed for unloading a previously loaded device */
226
227 #define BXE_PREV_WAIT_NEEDED 1
228 struct mtx bxe_prev_mtx;
229 MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
230 struct bxe_prev_list_node {
231     LIST_ENTRY(bxe_prev_list_node) node;
232     uint8_t bus;
233     uint8_t slot;
234     uint8_t path;
235     uint8_t aer; /* XXX automatic error recovery */
236     uint8_t undi;
237 };
238 static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
239
240 static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
241
242 /* Tunable device values... */
243
244 SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
245
246 /* Debug */
247 unsigned long bxe_debug = 0;
248 TUNABLE_ULONG("hw.bxe.debug", &bxe_debug);
249 SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, (CTLFLAG_RDTUN),
250              &bxe_debug, 0, "Debug logging mode");
251
252 /* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
253 static int bxe_interrupt_mode = INTR_MODE_MSIX;
254 TUNABLE_INT("hw.bxe.interrupt_mode", &bxe_interrupt_mode);
255 SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
256            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
257
258 /* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
259 static int bxe_queue_count = 4;
260 TUNABLE_INT("hw.bxe.queue_count", &bxe_queue_count);
261 SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
262            &bxe_queue_count, 0, "Multi-Queue queue count");
263
264 /* max number of buffers per queue (default RX_BD_USABLE) */
265 static int bxe_max_rx_bufs = 0;
266 TUNABLE_INT("hw.bxe.max_rx_bufs", &bxe_max_rx_bufs);
267 SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
268            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
269
270 /* Host interrupt coalescing RX tick timer (usecs) */
271 static int bxe_hc_rx_ticks = 25;
272 TUNABLE_INT("hw.bxe.hc_rx_ticks", &bxe_hc_rx_ticks);
273 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
274            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
275
276 /* Host interrupt coalescing TX tick timer (usecs) */
277 static int bxe_hc_tx_ticks = 50;
278 TUNABLE_INT("hw.bxe.hc_tx_ticks", &bxe_hc_tx_ticks);
279 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
280            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
281
282 /* Maximum number of Rx packets to process at a time */
283 static int bxe_rx_budget = 0xffffffff;
284 TUNABLE_INT("hw.bxe.rx_budget", &bxe_rx_budget);
285 SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
286            &bxe_rx_budget, 0, "Rx processing budget");
287
288 /* Maximum LRO aggregation size */
289 static int bxe_max_aggregation_size = 0;
290 TUNABLE_INT("hw.bxe.max_aggregation_size", &bxe_max_aggregation_size);
291 SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
292            &bxe_max_aggregation_size, 0, "max aggregation size");
293
294 /* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
295 static int bxe_mrrs = -1;
296 TUNABLE_INT("hw.bxe.mrrs", &bxe_mrrs);
297 SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
298            &bxe_mrrs, 0, "PCIe maximum read request size");
299
300 /* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
301 static int bxe_autogreeen = 0;
302 TUNABLE_INT("hw.bxe.autogreeen", &bxe_autogreeen);
303 SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
304            &bxe_autogreeen, 0, "AutoGrEEEn support");
305
306 /* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
307 static int bxe_udp_rss = 0;
308 TUNABLE_INT("hw.bxe.udp_rss", &bxe_udp_rss);
309 SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
310            &bxe_udp_rss, 0, "UDP RSS support");
311
312
313 #define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
314
315 #define STATS_OFFSET32(stat_name)                   \
316     (offsetof(struct bxe_eth_stats, stat_name) / 4)
317
318 #define Q_STATS_OFFSET32(stat_name)                   \
319     (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
320
321 static const struct {
322     uint32_t offset;
323     uint32_t size;
324     uint32_t flags;
325 #define STATS_FLAGS_PORT  1
326 #define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
327 #define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
328     char string[STAT_NAME_LEN];
329 } bxe_eth_stats_arr[] = {
330     { STATS_OFFSET32(total_bytes_received_hi),
331                 8, STATS_FLAGS_BOTH, "rx_bytes" },
332     { STATS_OFFSET32(error_bytes_received_hi),
333                 8, STATS_FLAGS_BOTH, "rx_error_bytes" },
334     { STATS_OFFSET32(total_unicast_packets_received_hi),
335                 8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
336     { STATS_OFFSET32(total_multicast_packets_received_hi),
337                 8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
338     { STATS_OFFSET32(total_broadcast_packets_received_hi),
339                 8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
340     { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
341                 8, STATS_FLAGS_PORT, "rx_crc_errors" },
342     { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
343                 8, STATS_FLAGS_PORT, "rx_align_errors" },
344     { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
345                 8, STATS_FLAGS_PORT, "rx_undersize_packets" },
346     { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
347                 8, STATS_FLAGS_PORT, "rx_oversize_packets" },
348     { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
349                 8, STATS_FLAGS_PORT, "rx_fragments" },
350     { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
351                 8, STATS_FLAGS_PORT, "rx_jabbers" },
352     { STATS_OFFSET32(no_buff_discard_hi),
353                 8, STATS_FLAGS_BOTH, "rx_discards" },
354     { STATS_OFFSET32(mac_filter_discard),
355                 4, STATS_FLAGS_PORT, "rx_filtered_packets" },
356     { STATS_OFFSET32(mf_tag_discard),
357                 4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
358     { STATS_OFFSET32(pfc_frames_received_hi),
359                 8, STATS_FLAGS_PORT, "pfc_frames_received" },
360     { STATS_OFFSET32(pfc_frames_sent_hi),
361                 8, STATS_FLAGS_PORT, "pfc_frames_sent" },
362     { STATS_OFFSET32(brb_drop_hi),
363                 8, STATS_FLAGS_PORT, "rx_brb_discard" },
364     { STATS_OFFSET32(brb_truncate_hi),
365                 8, STATS_FLAGS_PORT, "rx_brb_truncate" },
366     { STATS_OFFSET32(pause_frames_received_hi),
367                 8, STATS_FLAGS_PORT, "rx_pause_frames" },
368     { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
369                 8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
370     { STATS_OFFSET32(nig_timer_max),
371                 4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
372     { STATS_OFFSET32(total_bytes_transmitted_hi),
373                 8, STATS_FLAGS_BOTH, "tx_bytes" },
374     { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
375                 8, STATS_FLAGS_PORT, "tx_error_bytes" },
376     { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
377                 8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
378     { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
379                 8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
380     { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
381                 8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
382     { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
383                 8, STATS_FLAGS_PORT, "tx_mac_errors" },
384     { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
385                 8, STATS_FLAGS_PORT, "tx_carrier_errors" },
386     { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
387                 8, STATS_FLAGS_PORT, "tx_single_collisions" },
388     { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
389                 8, STATS_FLAGS_PORT, "tx_multi_collisions" },
390     { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
391                 8, STATS_FLAGS_PORT, "tx_deferred" },
392     { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
393                 8, STATS_FLAGS_PORT, "tx_excess_collisions" },
394     { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
395                 8, STATS_FLAGS_PORT, "tx_late_collisions" },
396     { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
397                 8, STATS_FLAGS_PORT, "tx_total_collisions" },
398     { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
399                 8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
400     { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
401                 8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
402     { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
403                 8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
404     { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
405                 8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
406     { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
407                 8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
408     { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
409                 8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
410     { STATS_OFFSET32(etherstatspktsover1522octets_hi),
411                 8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
412     { STATS_OFFSET32(pause_frames_sent_hi),
413                 8, STATS_FLAGS_PORT, "tx_pause_frames" },
414     { STATS_OFFSET32(total_tpa_aggregations_hi),
415                 8, STATS_FLAGS_FUNC, "tpa_aggregations" },
416     { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
417                 8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
418     { STATS_OFFSET32(total_tpa_bytes_hi),
419                 8, STATS_FLAGS_FUNC, "tpa_bytes"},
420     { STATS_OFFSET32(eee_tx_lpi),
421                 4, STATS_FLAGS_PORT, "eee_tx_lpi"},
422     { STATS_OFFSET32(rx_calls),
423                 4, STATS_FLAGS_FUNC, "rx_calls"},
424     { STATS_OFFSET32(rx_pkts),
425                 4, STATS_FLAGS_FUNC, "rx_pkts"},
426     { STATS_OFFSET32(rx_tpa_pkts),
427                 4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
428     { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
429                 4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
430     { STATS_OFFSET32(rx_bxe_service_rxsgl),
431                 4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
432     { STATS_OFFSET32(rx_jumbo_sge_pkts),
433                 4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
434     { STATS_OFFSET32(rx_soft_errors),
435                 4, STATS_FLAGS_FUNC, "rx_soft_errors"},
436     { STATS_OFFSET32(rx_hw_csum_errors),
437                 4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
438     { STATS_OFFSET32(rx_ofld_frames_csum_ip),
439                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
440     { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
441                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
442     { STATS_OFFSET32(rx_budget_reached),
443                 4, STATS_FLAGS_FUNC, "rx_budget_reached"},
444     { STATS_OFFSET32(tx_pkts),
445                 4, STATS_FLAGS_FUNC, "tx_pkts"},
446     { STATS_OFFSET32(tx_soft_errors),
447                 4, STATS_FLAGS_FUNC, "tx_soft_errors"},
448     { STATS_OFFSET32(tx_ofld_frames_csum_ip),
449                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
450     { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
451                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
452     { STATS_OFFSET32(tx_ofld_frames_csum_udp),
453                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
454     { STATS_OFFSET32(tx_ofld_frames_lso),
455                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
456     { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
457                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
458     { STATS_OFFSET32(tx_encap_failures),
459                 4, STATS_FLAGS_FUNC, "tx_encap_failures"},
460     { STATS_OFFSET32(tx_hw_queue_full),
461                 4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
462     { STATS_OFFSET32(tx_hw_max_queue_depth),
463                 4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
464     { STATS_OFFSET32(tx_dma_mapping_failure),
465                 4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
466     { STATS_OFFSET32(tx_max_drbr_queue_depth),
467                 4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
468     { STATS_OFFSET32(tx_window_violation_std),
469                 4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
470     { STATS_OFFSET32(tx_window_violation_tso),
471                 4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
472     { STATS_OFFSET32(tx_chain_lost_mbuf),
473                 4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
474     { STATS_OFFSET32(tx_frames_deferred),
475                 4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
476     { STATS_OFFSET32(tx_queue_xoff),
477                 4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
478     { STATS_OFFSET32(mbuf_defrag_attempts),
479                 4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
480     { STATS_OFFSET32(mbuf_defrag_failures),
481                 4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
482     { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
483                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
484     { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
485                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
486     { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
487                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
488     { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
489                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
490     { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
491                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
492     { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
493                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
494     { STATS_OFFSET32(mbuf_alloc_tx),
495                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
496     { STATS_OFFSET32(mbuf_alloc_rx),
497                 4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
498     { STATS_OFFSET32(mbuf_alloc_sge),
499                 4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
500     { STATS_OFFSET32(mbuf_alloc_tpa),
501                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"},
502     { STATS_OFFSET32(tx_queue_full_return),
503                 4, STATS_FLAGS_FUNC, "tx_queue_full_return"}
504 };
505
506 static const struct {
507     uint32_t offset;
508     uint32_t size;
509     char string[STAT_NAME_LEN];
510 } bxe_eth_q_stats_arr[] = {
511     { Q_STATS_OFFSET32(total_bytes_received_hi),
512                 8, "rx_bytes" },
513     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
514                 8, "rx_ucast_packets" },
515     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
516                 8, "rx_mcast_packets" },
517     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
518                 8, "rx_bcast_packets" },
519     { Q_STATS_OFFSET32(no_buff_discard_hi),
520                 8, "rx_discards" },
521     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
522                 8, "tx_bytes" },
523     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
524                 8, "tx_ucast_packets" },
525     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
526                 8, "tx_mcast_packets" },
527     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
528                 8, "tx_bcast_packets" },
529     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
530                 8, "tpa_aggregations" },
531     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
532                 8, "tpa_aggregated_frames"},
533     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
534                 8, "tpa_bytes"},
535     { Q_STATS_OFFSET32(rx_calls),
536                 4, "rx_calls"},
537     { Q_STATS_OFFSET32(rx_pkts),
538                 4, "rx_pkts"},
539     { Q_STATS_OFFSET32(rx_tpa_pkts),
540                 4, "rx_tpa_pkts"},
541     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
542                 4, "rx_erroneous_jumbo_sge_pkts"},
543     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
544                 4, "rx_bxe_service_rxsgl"},
545     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
546                 4, "rx_jumbo_sge_pkts"},
547     { Q_STATS_OFFSET32(rx_soft_errors),
548                 4, "rx_soft_errors"},
549     { Q_STATS_OFFSET32(rx_hw_csum_errors),
550                 4, "rx_hw_csum_errors"},
551     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
552                 4, "rx_ofld_frames_csum_ip"},
553     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
554                 4, "rx_ofld_frames_csum_tcp_udp"},
555     { Q_STATS_OFFSET32(rx_budget_reached),
556                 4, "rx_budget_reached"},
557     { Q_STATS_OFFSET32(tx_pkts),
558                 4, "tx_pkts"},
559     { Q_STATS_OFFSET32(tx_soft_errors),
560                 4, "tx_soft_errors"},
561     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
562                 4, "tx_ofld_frames_csum_ip"},
563     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
564                 4, "tx_ofld_frames_csum_tcp"},
565     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
566                 4, "tx_ofld_frames_csum_udp"},
567     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
568                 4, "tx_ofld_frames_lso"},
569     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
570                 4, "tx_ofld_frames_lso_hdr_splits"},
571     { Q_STATS_OFFSET32(tx_encap_failures),
572                 4, "tx_encap_failures"},
573     { Q_STATS_OFFSET32(tx_hw_queue_full),
574                 4, "tx_hw_queue_full"},
575     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
576                 4, "tx_hw_max_queue_depth"},
577     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
578                 4, "tx_dma_mapping_failure"},
579     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
580                 4, "tx_max_drbr_queue_depth"},
581     { Q_STATS_OFFSET32(tx_window_violation_std),
582                 4, "tx_window_violation_std"},
583     { Q_STATS_OFFSET32(tx_window_violation_tso),
584                 4, "tx_window_violation_tso"},
585     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
586                 4, "tx_chain_lost_mbuf"},
587     { Q_STATS_OFFSET32(tx_frames_deferred),
588                 4, "tx_frames_deferred"},
589     { Q_STATS_OFFSET32(tx_queue_xoff),
590                 4, "tx_queue_xoff"},
591     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
592                 4, "mbuf_defrag_attempts"},
593     { Q_STATS_OFFSET32(mbuf_defrag_failures),
594                 4, "mbuf_defrag_failures"},
595     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
596                 4, "mbuf_rx_bd_alloc_failed"},
597     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
598                 4, "mbuf_rx_bd_mapping_failed"},
599     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
600                 4, "mbuf_rx_tpa_alloc_failed"},
601     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
602                 4, "mbuf_rx_tpa_mapping_failed"},
603     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
604                 4, "mbuf_rx_sge_alloc_failed"},
605     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
606                 4, "mbuf_rx_sge_mapping_failed"},
607     { Q_STATS_OFFSET32(mbuf_alloc_tx),
608                 4, "mbuf_alloc_tx"},
609     { Q_STATS_OFFSET32(mbuf_alloc_rx),
610                 4, "mbuf_alloc_rx"},
611     { Q_STATS_OFFSET32(mbuf_alloc_sge),
612                 4, "mbuf_alloc_sge"},
613     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
614                 4, "mbuf_alloc_tpa"},
615     { Q_STATS_OFFSET32(tx_queue_full_return),
616                 4, "tx_queue_full_return"}
617 };
618
619 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
620 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
621
622
623 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
624                                  uint8_t          read_cfg,
625                                  uint8_t          cmng_type);
626 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
627 static void    storm_memset_cmng(struct bxe_softc *sc,
628                                  struct cmng_init *cmng,
629                                  uint8_t          port);
630 static void    bxe_set_reset_global(struct bxe_softc *sc);
631 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
632 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
633                                  int              engine);
634 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
635 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
636                                    uint8_t          *global,
637                                    uint8_t          print);
638 static void    bxe_int_disable(struct bxe_softc *sc);
639 static int     bxe_release_leader_lock(struct bxe_softc *sc);
640 static void    bxe_pf_disable(struct bxe_softc *sc);
641 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
642 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
643                                       struct bxe_fastpath *fp,
644                                       uint16_t            rx_bd_prod,
645                                       uint16_t            rx_cq_prod,
646                                       uint16_t            rx_sge_prod);
647 static void    bxe_link_report_locked(struct bxe_softc *sc);
648 static void    bxe_link_report(struct bxe_softc *sc);
649 static void    bxe_link_status_update(struct bxe_softc *sc);
650 static void    bxe_periodic_callout_func(void *xsc);
651 static void    bxe_periodic_start(struct bxe_softc *sc);
652 static void    bxe_periodic_stop(struct bxe_softc *sc);
653 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
654                                     uint16_t prev_index,
655                                     uint16_t index);
656 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
657                                      int                 queue);
658 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
659                                      uint16_t            index);
660 static uint8_t bxe_txeof(struct bxe_softc *sc,
661                          struct bxe_fastpath *fp);
662 static void    bxe_task_fp(struct bxe_fastpath *fp);
663 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
664                                      struct mbuf      *m,
665                                      uint8_t          contents);
666 static int     bxe_alloc_mem(struct bxe_softc *sc);
667 static void    bxe_free_mem(struct bxe_softc *sc);
668 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
669 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
670 static int     bxe_interrupt_attach(struct bxe_softc *sc);
671 static void    bxe_interrupt_detach(struct bxe_softc *sc);
672 static void    bxe_set_rx_mode(struct bxe_softc *sc);
673 static int     bxe_init_locked(struct bxe_softc *sc);
674 static int     bxe_stop_locked(struct bxe_softc *sc);
675 static __noinline int bxe_nic_load(struct bxe_softc *sc,
676                                    int              load_mode);
677 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
678                                      uint32_t         unload_mode,
679                                      uint8_t          keep_link);
680
681 static void bxe_handle_sp_tq(void *context, int pending);
682 static void bxe_handle_fp_tq(void *context, int pending);
683
684 static int bxe_add_cdev(struct bxe_softc *sc);
685 static void bxe_del_cdev(struct bxe_softc *sc);
686 static int bxe_grc_dump(struct bxe_softc *sc);
687 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
688 static void bxe_free_buf_rings(struct bxe_softc *sc);
689
690 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
691 uint32_t
692 calc_crc32(uint8_t  *crc32_packet,
693            uint32_t crc32_length,
694            uint32_t crc32_seed,
695            uint8_t  complement)
696 {
697    uint32_t byte         = 0;
698    uint32_t bit          = 0;
699    uint8_t  msb          = 0;
700    uint32_t temp         = 0;
701    uint32_t shft         = 0;
702    uint8_t  current_byte = 0;
703    uint32_t crc32_result = crc32_seed;
704    const uint32_t CRC32_POLY = 0x1edc6f41;
705
706    if ((crc32_packet == NULL) ||
707        (crc32_length == 0) ||
708        ((crc32_length % 8) != 0))
709     {
710         return (crc32_result);
711     }
712
713     for (byte = 0; byte < crc32_length; byte = byte + 1)
714     {
715         current_byte = crc32_packet[byte];
716         for (bit = 0; bit < 8; bit = bit + 1)
717         {
718             /* msb = crc32_result[31]; */
719             msb = (uint8_t)(crc32_result >> 31);
720
721             crc32_result = crc32_result << 1;
722
723             /* it (msb != current_byte[bit]) */
724             if (msb != (0x1 & (current_byte >> bit)))
725             {
726                 crc32_result = crc32_result ^ CRC32_POLY;
727                 /* crc32_result[0] = 1 */
728                 crc32_result |= 1;
729             }
730         }
731     }
732
733     /* Last step is to:
734      * 1. "mirror" every bit
735      * 2. swap the 4 bytes
736      * 3. complement each bit
737      */
738
739     /* Mirror */
740     temp = crc32_result;
741     shft = sizeof(crc32_result) * 8 - 1;
742
743     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
744     {
745         temp <<= 1;
746         temp |= crc32_result & 1;
747         shft-- ;
748     }
749
750     /* temp[31-bit] = crc32_result[bit] */
751     temp <<= shft;
752
753     /* Swap */
754     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
755     {
756         uint32_t t0, t1, t2, t3;
757         t0 = (0x000000ff & (temp >> 24));
758         t1 = (0x0000ff00 & (temp >> 8));
759         t2 = (0x00ff0000 & (temp << 8));
760         t3 = (0xff000000 & (temp << 24));
761         crc32_result = t0 | t1 | t2 | t3;
762     }
763
764     /* Complement */
765     if (complement)
766     {
767         crc32_result = ~crc32_result;
768     }
769
770     return (crc32_result);
771 }
772
773 int
774 bxe_test_bit(int                    nr,
775              volatile unsigned long *addr)
776 {
777     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
778 }
779
780 void
781 bxe_set_bit(unsigned int           nr,
782             volatile unsigned long *addr)
783 {
784     atomic_set_acq_long(addr, (1 << nr));
785 }
786
787 void
788 bxe_clear_bit(int                    nr,
789               volatile unsigned long *addr)
790 {
791     atomic_clear_acq_long(addr, (1 << nr));
792 }
793
794 int
795 bxe_test_and_set_bit(int                    nr,
796                        volatile unsigned long *addr)
797 {
798     unsigned long x;
799     nr = (1 << nr);
800     do {
801         x = *addr;
802     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
803     // if (x & nr) bit_was_set; else bit_was_not_set;
804     return (x & nr);
805 }
806
807 int
808 bxe_test_and_clear_bit(int                    nr,
809                        volatile unsigned long *addr)
810 {
811     unsigned long x;
812     nr = (1 << nr);
813     do {
814         x = *addr;
815     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
816     // if (x & nr) bit_was_set; else bit_was_not_set;
817     return (x & nr);
818 }
819
820 int
821 bxe_cmpxchg(volatile int *addr,
822             int          old,
823             int          new)
824 {
825     int x;
826     do {
827         x = *addr;
828     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
829     return (x);
830 }
831
832 /*
833  * Get DMA memory from the OS.
834  *
835  * Validates that the OS has provided DMA buffers in response to a
836  * bus_dmamap_load call and saves the physical address of those buffers.
837  * When the callback is used the OS will return 0 for the mapping function
838  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
839  * failures back to the caller.
840  *
841  * Returns:
842  *   Nothing.
843  */
844 static void
845 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
846 {
847     struct bxe_dma *dma = arg;
848
849     if (error) {
850         dma->paddr = 0;
851         dma->nseg  = 0;
852         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
853     } else {
854         dma->paddr = segs->ds_addr;
855         dma->nseg  = nseg;
856     }
857 }
858
859 /*
860  * Allocate a block of memory and map it for DMA. No partial completions
861  * allowed and release any resources acquired if we can't acquire all
862  * resources.
863  *
864  * Returns:
865  *   0 = Success, !0 = Failure
866  */
867 int
868 bxe_dma_alloc(struct bxe_softc *sc,
869               bus_size_t       size,
870               struct bxe_dma   *dma,
871               const char       *msg)
872 {
873     int rc;
874
875     if (dma->size > 0) {
876         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
877               (unsigned long)dma->size);
878         return (1);
879     }
880
881     memset(dma, 0, sizeof(*dma)); /* sanity */
882     dma->sc   = sc;
883     dma->size = size;
884     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
885
886     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
887                             BCM_PAGE_SIZE,      /* alignment */
888                             0,                  /* boundary limit */
889                             BUS_SPACE_MAXADDR,  /* restricted low */
890                             BUS_SPACE_MAXADDR,  /* restricted hi */
891                             NULL,               /* addr filter() */
892                             NULL,               /* addr filter() arg */
893                             size,               /* max map size */
894                             1,                  /* num discontinuous */
895                             size,               /* max seg size */
896                             BUS_DMA_ALLOCNOW,   /* flags */
897                             NULL,               /* lock() */
898                             NULL,               /* lock() arg */
899                             &dma->tag);         /* returned dma tag */
900     if (rc != 0) {
901         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
902         memset(dma, 0, sizeof(*dma));
903         return (1);
904     }
905
906     rc = bus_dmamem_alloc(dma->tag,
907                           (void **)&dma->vaddr,
908                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
909                           &dma->map);
910     if (rc != 0) {
911         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
912         bus_dma_tag_destroy(dma->tag);
913         memset(dma, 0, sizeof(*dma));
914         return (1);
915     }
916
917     rc = bus_dmamap_load(dma->tag,
918                          dma->map,
919                          dma->vaddr,
920                          size,
921                          bxe_dma_map_addr, /* BLOGD in here */
922                          dma,
923                          BUS_DMA_NOWAIT);
924     if (rc != 0) {
925         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
926         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
927         bus_dma_tag_destroy(dma->tag);
928         memset(dma, 0, sizeof(*dma));
929         return (1);
930     }
931
932     return (0);
933 }
934
935 void
936 bxe_dma_free(struct bxe_softc *sc,
937              struct bxe_dma   *dma)
938 {
939     if (dma->size > 0) {
940         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
941
942         bus_dmamap_sync(dma->tag, dma->map,
943                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
944         bus_dmamap_unload(dma->tag, dma->map);
945         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
946         bus_dma_tag_destroy(dma->tag);
947     }
948
949     memset(dma, 0, sizeof(*dma));
950 }
951
952 /*
953  * These indirect read and write routines are only during init.
954  * The locking is handled by the MCP.
955  */
956
957 void
958 bxe_reg_wr_ind(struct bxe_softc *sc,
959                uint32_t         addr,
960                uint32_t         val)
961 {
962     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
963     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
964     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
965 }
966
967 uint32_t
968 bxe_reg_rd_ind(struct bxe_softc *sc,
969                uint32_t         addr)
970 {
971     uint32_t val;
972
973     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
974     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
975     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
976
977     return (val);
978 }
979
980 static int
981 bxe_acquire_hw_lock(struct bxe_softc *sc,
982                     uint32_t         resource)
983 {
984     uint32_t lock_status;
985     uint32_t resource_bit = (1 << resource);
986     int func = SC_FUNC(sc);
987     uint32_t hw_lock_control_reg;
988     int cnt;
989
990     /* validate the resource is within range */
991     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
992         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
993             " resource_bit 0x%x\n", resource, resource_bit);
994         return (-1);
995     }
996
997     if (func <= 5) {
998         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
999     } else {
1000         hw_lock_control_reg =
1001                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1002     }
1003
1004     /* validate the resource is not already taken */
1005     lock_status = REG_RD(sc, hw_lock_control_reg);
1006     if (lock_status & resource_bit) {
1007         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1008               resource, lock_status, resource_bit);
1009         return (-1);
1010     }
1011
1012     /* try every 5ms for 5 seconds */
1013     for (cnt = 0; cnt < 1000; cnt++) {
1014         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1015         lock_status = REG_RD(sc, hw_lock_control_reg);
1016         if (lock_status & resource_bit) {
1017             return (0);
1018         }
1019         DELAY(5000);
1020     }
1021
1022     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1023         resource, resource_bit);
1024     return (-1);
1025 }
1026
1027 static int
1028 bxe_release_hw_lock(struct bxe_softc *sc,
1029                     uint32_t         resource)
1030 {
1031     uint32_t lock_status;
1032     uint32_t resource_bit = (1 << resource);
1033     int func = SC_FUNC(sc);
1034     uint32_t hw_lock_control_reg;
1035
1036     /* validate the resource is within range */
1037     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1038         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1039             " resource_bit 0x%x\n", resource, resource_bit);
1040         return (-1);
1041     }
1042
1043     if (func <= 5) {
1044         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1045     } else {
1046         hw_lock_control_reg =
1047                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1048     }
1049
1050     /* validate the resource is currently taken */
1051     lock_status = REG_RD(sc, hw_lock_control_reg);
1052     if (!(lock_status & resource_bit)) {
1053         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1054               resource, lock_status, resource_bit);
1055         return (-1);
1056     }
1057
1058     REG_WR(sc, hw_lock_control_reg, resource_bit);
1059     return (0);
1060 }
1061 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1062 {
1063         BXE_PHY_LOCK(sc);
1064         bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1065 }
1066
1067 static void bxe_release_phy_lock(struct bxe_softc *sc)
1068 {
1069         bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1070         BXE_PHY_UNLOCK(sc);
1071 }
1072 /*
1073  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1074  * had we done things the other way around, if two pfs from the same port
1075  * would attempt to access nvram at the same time, we could run into a
1076  * scenario such as:
1077  * pf A takes the port lock.
1078  * pf B succeeds in taking the same lock since they are from the same port.
1079  * pf A takes the per pf misc lock. Performs eeprom access.
1080  * pf A finishes. Unlocks the per pf misc lock.
1081  * Pf B takes the lock and proceeds to perform it's own access.
1082  * pf A unlocks the per port lock, while pf B is still working (!).
1083  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1084  * access corrupted by pf B).*
1085  */
1086 static int
1087 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1088 {
1089     int port = SC_PORT(sc);
1090     int count, i;
1091     uint32_t val = 0;
1092
1093     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1094     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1095
1096     /* adjust timeout for emulation/FPGA */
1097     count = NVRAM_TIMEOUT_COUNT;
1098     if (CHIP_REV_IS_SLOW(sc)) {
1099         count *= 100;
1100     }
1101
1102     /* request access to nvram interface */
1103     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1104            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1105
1106     for (i = 0; i < count*10; i++) {
1107         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1108         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1109             break;
1110         }
1111
1112         DELAY(5);
1113     }
1114
1115     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1116         BLOGE(sc, "Cannot get access to nvram interface "
1117             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1118             port, val);
1119         return (-1);
1120     }
1121
1122     return (0);
1123 }
1124
1125 static int
1126 bxe_release_nvram_lock(struct bxe_softc *sc)
1127 {
1128     int port = SC_PORT(sc);
1129     int count, i;
1130     uint32_t val = 0;
1131
1132     /* adjust timeout for emulation/FPGA */
1133     count = NVRAM_TIMEOUT_COUNT;
1134     if (CHIP_REV_IS_SLOW(sc)) {
1135         count *= 100;
1136     }
1137
1138     /* relinquish nvram interface */
1139     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1140            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1141
1142     for (i = 0; i < count*10; i++) {
1143         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1144         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1145             break;
1146         }
1147
1148         DELAY(5);
1149     }
1150
1151     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1152         BLOGE(sc, "Cannot free access to nvram interface "
1153             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1154             port, val);
1155         return (-1);
1156     }
1157
1158     /* release HW lock: protect against other PFs in PF Direct Assignment */
1159     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1160
1161     return (0);
1162 }
1163
1164 static void
1165 bxe_enable_nvram_access(struct bxe_softc *sc)
1166 {
1167     uint32_t val;
1168
1169     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1170
1171     /* enable both bits, even on read */
1172     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1173            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1174 }
1175
1176 static void
1177 bxe_disable_nvram_access(struct bxe_softc *sc)
1178 {
1179     uint32_t val;
1180
1181     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1182
1183     /* disable both bits, even after read */
1184     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1185            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1186                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1187 }
1188
1189 static int
1190 bxe_nvram_read_dword(struct bxe_softc *sc,
1191                      uint32_t         offset,
1192                      uint32_t         *ret_val,
1193                      uint32_t         cmd_flags)
1194 {
1195     int count, i, rc;
1196     uint32_t val;
1197
1198     /* build the command word */
1199     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1200
1201     /* need to clear DONE bit separately */
1202     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1203
1204     /* address of the NVRAM to read from */
1205     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1206            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1207
1208     /* issue a read command */
1209     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1210
1211     /* adjust timeout for emulation/FPGA */
1212     count = NVRAM_TIMEOUT_COUNT;
1213     if (CHIP_REV_IS_SLOW(sc)) {
1214         count *= 100;
1215     }
1216
1217     /* wait for completion */
1218     *ret_val = 0;
1219     rc = -1;
1220     for (i = 0; i < count; i++) {
1221         DELAY(5);
1222         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1223
1224         if (val & MCPR_NVM_COMMAND_DONE) {
1225             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1226             /* we read nvram data in cpu order
1227              * but ethtool sees it as an array of bytes
1228              * converting to big-endian will do the work
1229              */
1230             *ret_val = htobe32(val);
1231             rc = 0;
1232             break;
1233         }
1234     }
1235
1236     if (rc == -1) {
1237         BLOGE(sc, "nvram read timeout expired "
1238             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1239             offset, cmd_flags, val);
1240     }
1241
1242     return (rc);
1243 }
1244
1245 static int
1246 bxe_nvram_read(struct bxe_softc *sc,
1247                uint32_t         offset,
1248                uint8_t          *ret_buf,
1249                int              buf_size)
1250 {
1251     uint32_t cmd_flags;
1252     uint32_t val;
1253     int rc;
1254
1255     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1256         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1257               offset, buf_size);
1258         return (-1);
1259     }
1260
1261     if ((offset + buf_size) > sc->devinfo.flash_size) {
1262         BLOGE(sc, "Invalid parameter, "
1263                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1264               offset, buf_size, sc->devinfo.flash_size);
1265         return (-1);
1266     }
1267
1268     /* request access to nvram interface */
1269     rc = bxe_acquire_nvram_lock(sc);
1270     if (rc) {
1271         return (rc);
1272     }
1273
1274     /* enable access to nvram interface */
1275     bxe_enable_nvram_access(sc);
1276
1277     /* read the first word(s) */
1278     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1279     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1280         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1281         memcpy(ret_buf, &val, 4);
1282
1283         /* advance to the next dword */
1284         offset += sizeof(uint32_t);
1285         ret_buf += sizeof(uint32_t);
1286         buf_size -= sizeof(uint32_t);
1287         cmd_flags = 0;
1288     }
1289
1290     if (rc == 0) {
1291         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1292         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1293         memcpy(ret_buf, &val, 4);
1294     }
1295
1296     /* disable access to nvram interface */
1297     bxe_disable_nvram_access(sc);
1298     bxe_release_nvram_lock(sc);
1299
1300     return (rc);
1301 }
1302
1303 static int
1304 bxe_nvram_write_dword(struct bxe_softc *sc,
1305                       uint32_t         offset,
1306                       uint32_t         val,
1307                       uint32_t         cmd_flags)
1308 {
1309     int count, i, rc;
1310
1311     /* build the command word */
1312     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1313
1314     /* need to clear DONE bit separately */
1315     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1316
1317     /* write the data */
1318     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1319
1320     /* address of the NVRAM to write to */
1321     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1322            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1323
1324     /* issue the write command */
1325     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1326
1327     /* adjust timeout for emulation/FPGA */
1328     count = NVRAM_TIMEOUT_COUNT;
1329     if (CHIP_REV_IS_SLOW(sc)) {
1330         count *= 100;
1331     }
1332
1333     /* wait for completion */
1334     rc = -1;
1335     for (i = 0; i < count; i++) {
1336         DELAY(5);
1337         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1338         if (val & MCPR_NVM_COMMAND_DONE) {
1339             rc = 0;
1340             break;
1341         }
1342     }
1343
1344     if (rc == -1) {
1345         BLOGE(sc, "nvram write timeout expired "
1346             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1347             offset, cmd_flags, val);
1348     }
1349
1350     return (rc);
1351 }
1352
1353 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1354
1355 static int
1356 bxe_nvram_write1(struct bxe_softc *sc,
1357                  uint32_t         offset,
1358                  uint8_t          *data_buf,
1359                  int              buf_size)
1360 {
1361     uint32_t cmd_flags;
1362     uint32_t align_offset;
1363     uint32_t val;
1364     int rc;
1365
1366     if ((offset + buf_size) > sc->devinfo.flash_size) {
1367         BLOGE(sc, "Invalid parameter, "
1368                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1369               offset, buf_size, sc->devinfo.flash_size);
1370         return (-1);
1371     }
1372
1373     /* request access to nvram interface */
1374     rc = bxe_acquire_nvram_lock(sc);
1375     if (rc) {
1376         return (rc);
1377     }
1378
1379     /* enable access to nvram interface */
1380     bxe_enable_nvram_access(sc);
1381
1382     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1383     align_offset = (offset & ~0x03);
1384     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1385
1386     if (rc == 0) {
1387         val &= ~(0xff << BYTE_OFFSET(offset));
1388         val |= (*data_buf << BYTE_OFFSET(offset));
1389
1390         /* nvram data is returned as an array of bytes
1391          * convert it back to cpu order
1392          */
1393         val = be32toh(val);
1394
1395         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1396     }
1397
1398     /* disable access to nvram interface */
1399     bxe_disable_nvram_access(sc);
1400     bxe_release_nvram_lock(sc);
1401
1402     return (rc);
1403 }
1404
1405 static int
1406 bxe_nvram_write(struct bxe_softc *sc,
1407                 uint32_t         offset,
1408                 uint8_t          *data_buf,
1409                 int              buf_size)
1410 {
1411     uint32_t cmd_flags;
1412     uint32_t val;
1413     uint32_t written_so_far;
1414     int rc;
1415
1416     if (buf_size == 1) {
1417         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1418     }
1419
1420     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1421         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1422               offset, buf_size);
1423         return (-1);
1424     }
1425
1426     if (buf_size == 0) {
1427         return (0); /* nothing to do */
1428     }
1429
1430     if ((offset + buf_size) > sc->devinfo.flash_size) {
1431         BLOGE(sc, "Invalid parameter, "
1432                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1433               offset, buf_size, sc->devinfo.flash_size);
1434         return (-1);
1435     }
1436
1437     /* request access to nvram interface */
1438     rc = bxe_acquire_nvram_lock(sc);
1439     if (rc) {
1440         return (rc);
1441     }
1442
1443     /* enable access to nvram interface */
1444     bxe_enable_nvram_access(sc);
1445
1446     written_so_far = 0;
1447     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1448     while ((written_so_far < buf_size) && (rc == 0)) {
1449         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1450             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1451         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1452             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1453         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1454             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1455         }
1456
1457         memcpy(&val, data_buf, 4);
1458
1459         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1460
1461         /* advance to the next dword */
1462         offset += sizeof(uint32_t);
1463         data_buf += sizeof(uint32_t);
1464         written_so_far += sizeof(uint32_t);
1465         cmd_flags = 0;
1466     }
1467
1468     /* disable access to nvram interface */
1469     bxe_disable_nvram_access(sc);
1470     bxe_release_nvram_lock(sc);
1471
1472     return (rc);
1473 }
1474
1475 /* copy command into DMAE command memory and set DMAE command Go */
1476 void
1477 bxe_post_dmae(struct bxe_softc    *sc,
1478               struct dmae_cmd *dmae,
1479               int                 idx)
1480 {
1481     uint32_t cmd_offset;
1482     int i;
1483
1484     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1485     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1486         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1487     }
1488
1489     REG_WR(sc, dmae_reg_go_c[idx], 1);
1490 }
1491
1492 uint32_t
1493 bxe_dmae_opcode_add_comp(uint32_t opcode,
1494                          uint8_t  comp_type)
1495 {
1496     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1497                       DMAE_CMD_C_TYPE_ENABLE));
1498 }
1499
1500 uint32_t
1501 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1502 {
1503     return (opcode & ~DMAE_CMD_SRC_RESET);
1504 }
1505
1506 uint32_t
1507 bxe_dmae_opcode(struct bxe_softc *sc,
1508                 uint8_t          src_type,
1509                 uint8_t          dst_type,
1510                 uint8_t          with_comp,
1511                 uint8_t          comp_type)
1512 {
1513     uint32_t opcode = 0;
1514
1515     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1516                (dst_type << DMAE_CMD_DST_SHIFT));
1517
1518     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1519
1520     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1521
1522     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1523                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1524
1525     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1526
1527 #ifdef __BIG_ENDIAN
1528     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1529 #else
1530     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1531 #endif
1532
1533     if (with_comp) {
1534         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1535     }
1536
1537     return (opcode);
1538 }
1539
1540 static void
1541 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1542                         struct dmae_cmd *dmae,
1543                         uint8_t             src_type,
1544                         uint8_t             dst_type)
1545 {
1546     memset(dmae, 0, sizeof(struct dmae_cmd));
1547
1548     /* set the opcode */
1549     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1550                                    TRUE, DMAE_COMP_PCI);
1551
1552     /* fill in the completion parameters */
1553     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1554     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1555     dmae->comp_val     = DMAE_COMP_VAL;
1556 }
1557
1558 /* issue a DMAE command over the init channel and wait for completion */
1559 static int
1560 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1561                          struct dmae_cmd *dmae)
1562 {
1563     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1564     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1565
1566     BXE_DMAE_LOCK(sc);
1567
1568     /* reset completion */
1569     *wb_comp = 0;
1570
1571     /* post the command on the channel used for initializations */
1572     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1573
1574     /* wait for completion */
1575     DELAY(5);
1576
1577     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1578         if (!timeout ||
1579             (sc->recovery_state != BXE_RECOVERY_DONE &&
1580              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1581             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1582                 *wb_comp, sc->recovery_state);
1583             BXE_DMAE_UNLOCK(sc);
1584             return (DMAE_TIMEOUT);
1585         }
1586
1587         timeout--;
1588         DELAY(50);
1589     }
1590
1591     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1592         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1593                 *wb_comp, sc->recovery_state);
1594         BXE_DMAE_UNLOCK(sc);
1595         return (DMAE_PCI_ERROR);
1596     }
1597
1598     BXE_DMAE_UNLOCK(sc);
1599     return (0);
1600 }
1601
1602 void
1603 bxe_read_dmae(struct bxe_softc *sc,
1604               uint32_t         src_addr,
1605               uint32_t         len32)
1606 {
1607     struct dmae_cmd dmae;
1608     uint32_t *data;
1609     int i, rc;
1610
1611     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1612
1613     if (!sc->dmae_ready) {
1614         data = BXE_SP(sc, wb_data[0]);
1615
1616         for (i = 0; i < len32; i++) {
1617             data[i] = (CHIP_IS_E1(sc)) ?
1618                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1619                           REG_RD(sc, (src_addr + (i * 4)));
1620         }
1621
1622         return;
1623     }
1624
1625     /* set opcode and fixed command fields */
1626     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1627
1628     /* fill in addresses and len */
1629     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1630     dmae.src_addr_hi = 0;
1631     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1632     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1633     dmae.len         = len32;
1634
1635     /* issue the command and wait for completion */
1636     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1637         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1638     };
1639 }
1640
1641 void
1642 bxe_write_dmae(struct bxe_softc *sc,
1643                bus_addr_t       dma_addr,
1644                uint32_t         dst_addr,
1645                uint32_t         len32)
1646 {
1647     struct dmae_cmd dmae;
1648     int rc;
1649
1650     if (!sc->dmae_ready) {
1651         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1652
1653         if (CHIP_IS_E1(sc)) {
1654             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1655         } else {
1656             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1657         }
1658
1659         return;
1660     }
1661
1662     /* set opcode and fixed command fields */
1663     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1664
1665     /* fill in addresses and len */
1666     dmae.src_addr_lo = U64_LO(dma_addr);
1667     dmae.src_addr_hi = U64_HI(dma_addr);
1668     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1669     dmae.dst_addr_hi = 0;
1670     dmae.len         = len32;
1671
1672     /* issue the command and wait for completion */
1673     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1674         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1675     }
1676 }
1677
1678 void
1679 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1680                         bus_addr_t       phys_addr,
1681                         uint32_t         addr,
1682                         uint32_t         len)
1683 {
1684     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1685     int offset = 0;
1686
1687     while (len > dmae_wr_max) {
1688         bxe_write_dmae(sc,
1689                        (phys_addr + offset), /* src DMA address */
1690                        (addr + offset),      /* dst GRC address */
1691                        dmae_wr_max);
1692         offset += (dmae_wr_max * 4);
1693         len -= dmae_wr_max;
1694     }
1695
1696     bxe_write_dmae(sc,
1697                    (phys_addr + offset), /* src DMA address */
1698                    (addr + offset),      /* dst GRC address */
1699                    len);
1700 }
1701
1702 void
1703 bxe_set_ctx_validation(struct bxe_softc   *sc,
1704                        struct eth_context *cxt,
1705                        uint32_t           cid)
1706 {
1707     /* ustorm cxt validation */
1708     cxt->ustorm_ag_context.cdu_usage =
1709         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1710             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1711     /* xcontext validation */
1712     cxt->xstorm_ag_context.cdu_reserved =
1713         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1714             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1715 }
1716
1717 static void
1718 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1719                             uint8_t          port,
1720                             uint8_t          fw_sb_id,
1721                             uint8_t          sb_index,
1722                             uint8_t          ticks)
1723 {
1724     uint32_t addr =
1725         (BAR_CSTRORM_INTMEM +
1726          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1727
1728     REG_WR8(sc, addr, ticks);
1729
1730     BLOGD(sc, DBG_LOAD,
1731           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1732           port, fw_sb_id, sb_index, ticks);
1733 }
1734
1735 static void
1736 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1737                             uint8_t          port,
1738                             uint16_t         fw_sb_id,
1739                             uint8_t          sb_index,
1740                             uint8_t          disable)
1741 {
1742     uint32_t enable_flag =
1743         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1744     uint32_t addr =
1745         (BAR_CSTRORM_INTMEM +
1746          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1747     uint8_t flags;
1748
1749     /* clear and set */
1750     flags = REG_RD8(sc, addr);
1751     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1752     flags |= enable_flag;
1753     REG_WR8(sc, addr, flags);
1754
1755     BLOGD(sc, DBG_LOAD,
1756           "port %d fw_sb_id %d sb_index %d disable %d\n",
1757           port, fw_sb_id, sb_index, disable);
1758 }
1759
1760 void
1761 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1762                              uint8_t          fw_sb_id,
1763                              uint8_t          sb_index,
1764                              uint8_t          disable,
1765                              uint16_t         usec)
1766 {
1767     int port = SC_PORT(sc);
1768     uint8_t ticks = (usec / 4); /* XXX ??? */
1769
1770     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1771
1772     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1773     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1774 }
1775
1776 void
1777 elink_cb_udelay(struct bxe_softc *sc,
1778                 uint32_t         usecs)
1779 {
1780     DELAY(usecs);
1781 }
1782
1783 uint32_t
1784 elink_cb_reg_read(struct bxe_softc *sc,
1785                   uint32_t         reg_addr)
1786 {
1787     return (REG_RD(sc, reg_addr));
1788 }
1789
1790 void
1791 elink_cb_reg_write(struct bxe_softc *sc,
1792                    uint32_t         reg_addr,
1793                    uint32_t         val)
1794 {
1795     REG_WR(sc, reg_addr, val);
1796 }
1797
1798 void
1799 elink_cb_reg_wb_write(struct bxe_softc *sc,
1800                       uint32_t         offset,
1801                       uint32_t         *wb_write,
1802                       uint16_t         len)
1803 {
1804     REG_WR_DMAE(sc, offset, wb_write, len);
1805 }
1806
1807 void
1808 elink_cb_reg_wb_read(struct bxe_softc *sc,
1809                      uint32_t         offset,
1810                      uint32_t         *wb_write,
1811                      uint16_t         len)
1812 {
1813     REG_RD_DMAE(sc, offset, wb_write, len);
1814 }
1815
1816 uint8_t
1817 elink_cb_path_id(struct bxe_softc *sc)
1818 {
1819     return (SC_PATH(sc));
1820 }
1821
1822 void
1823 elink_cb_event_log(struct bxe_softc     *sc,
1824                    const elink_log_id_t elink_log_id,
1825                    ...)
1826 {
1827     /* XXX */
1828     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1829 }
1830
1831 static int
1832 bxe_set_spio(struct bxe_softc *sc,
1833              int              spio,
1834              uint32_t         mode)
1835 {
1836     uint32_t spio_reg;
1837
1838     /* Only 2 SPIOs are configurable */
1839     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1840         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1841         return (-1);
1842     }
1843
1844     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1845
1846     /* read SPIO and mask except the float bits */
1847     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1848
1849     switch (mode) {
1850     case MISC_SPIO_OUTPUT_LOW:
1851         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1852         /* clear FLOAT and set CLR */
1853         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1854         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1855         break;
1856
1857     case MISC_SPIO_OUTPUT_HIGH:
1858         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1859         /* clear FLOAT and set SET */
1860         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1861         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1862         break;
1863
1864     case MISC_SPIO_INPUT_HI_Z:
1865         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1866         /* set FLOAT */
1867         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1868         break;
1869
1870     default:
1871         break;
1872     }
1873
1874     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1875     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1876
1877     return (0);
1878 }
1879
1880 static int
1881 bxe_gpio_read(struct bxe_softc *sc,
1882               int              gpio_num,
1883               uint8_t          port)
1884 {
1885     /* The GPIO should be swapped if swap register is set and active */
1886     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1887                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1888     int gpio_shift = (gpio_num +
1889                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1890     uint32_t gpio_mask = (1 << gpio_shift);
1891     uint32_t gpio_reg;
1892
1893     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1894         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1895             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1896             gpio_mask);
1897         return (-1);
1898     }
1899
1900     /* read GPIO value */
1901     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1902
1903     /* get the requested pin value */
1904     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1905 }
1906
1907 static int
1908 bxe_gpio_write(struct bxe_softc *sc,
1909                int              gpio_num,
1910                uint32_t         mode,
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 mode 0x%x port 0x%x gpio_port %d"
1923             " gpio_shift %d gpio_mask 0x%x\n",
1924             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1925         return (-1);
1926     }
1927
1928     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1929
1930     /* read GPIO and mask except the float bits */
1931     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1932
1933     switch (mode) {
1934     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1935         BLOGD(sc, DBG_PHY,
1936               "Set GPIO %d (shift %d) -> output low\n",
1937               gpio_num, gpio_shift);
1938         /* clear FLOAT and set CLR */
1939         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1940         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1941         break;
1942
1943     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1944         BLOGD(sc, DBG_PHY,
1945               "Set GPIO %d (shift %d) -> output high\n",
1946               gpio_num, gpio_shift);
1947         /* clear FLOAT and set SET */
1948         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1949         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1950         break;
1951
1952     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1953         BLOGD(sc, DBG_PHY,
1954               "Set GPIO %d (shift %d) -> input\n",
1955               gpio_num, gpio_shift);
1956         /* set FLOAT */
1957         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1958         break;
1959
1960     default:
1961         break;
1962     }
1963
1964     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1965     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1966
1967     return (0);
1968 }
1969
1970 static int
1971 bxe_gpio_mult_write(struct bxe_softc *sc,
1972                     uint8_t          pins,
1973                     uint32_t         mode)
1974 {
1975     uint32_t gpio_reg;
1976
1977     /* any port swapping should be handled by caller */
1978
1979     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1980
1981     /* read GPIO and mask except the float bits */
1982     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1983     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1984     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
1985     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
1986
1987     switch (mode) {
1988     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1989         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
1990         /* set CLR */
1991         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
1992         break;
1993
1994     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1995         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
1996         /* set SET */
1997         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
1998         break;
1999
2000     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2001         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2002         /* set FLOAT */
2003         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2004         break;
2005
2006     default:
2007         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2008             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2009         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2010         return (-1);
2011     }
2012
2013     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2014     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2015
2016     return (0);
2017 }
2018
2019 static int
2020 bxe_gpio_int_write(struct bxe_softc *sc,
2021                    int              gpio_num,
2022                    uint32_t         mode,
2023                    uint8_t          port)
2024 {
2025     /* The GPIO should be swapped if swap register is set and active */
2026     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2027                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2028     int gpio_shift = (gpio_num +
2029                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2030     uint32_t gpio_mask = (1 << gpio_shift);
2031     uint32_t gpio_reg;
2032
2033     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2034         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2035             " gpio_shift %d gpio_mask 0x%x\n",
2036             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2037         return (-1);
2038     }
2039
2040     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2041
2042     /* read GPIO int */
2043     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2044
2045     switch (mode) {
2046     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2047         BLOGD(sc, DBG_PHY,
2048               "Clear GPIO INT %d (shift %d) -> output low\n",
2049               gpio_num, gpio_shift);
2050         /* clear SET and set CLR */
2051         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2052         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2053         break;
2054
2055     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2056         BLOGD(sc, DBG_PHY,
2057               "Set GPIO INT %d (shift %d) -> output high\n",
2058               gpio_num, gpio_shift);
2059         /* clear CLR and set SET */
2060         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2061         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2062         break;
2063
2064     default:
2065         break;
2066     }
2067
2068     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2069     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2070
2071     return (0);
2072 }
2073
2074 uint32_t
2075 elink_cb_gpio_read(struct bxe_softc *sc,
2076                    uint16_t         gpio_num,
2077                    uint8_t          port)
2078 {
2079     return (bxe_gpio_read(sc, gpio_num, port));
2080 }
2081
2082 uint8_t
2083 elink_cb_gpio_write(struct bxe_softc *sc,
2084                     uint16_t         gpio_num,
2085                     uint8_t          mode, /* 0=low 1=high */
2086                     uint8_t          port)
2087 {
2088     return (bxe_gpio_write(sc, gpio_num, mode, port));
2089 }
2090
2091 uint8_t
2092 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2093                          uint8_t          pins,
2094                          uint8_t          mode) /* 0=low 1=high */
2095 {
2096     return (bxe_gpio_mult_write(sc, pins, mode));
2097 }
2098
2099 uint8_t
2100 elink_cb_gpio_int_write(struct bxe_softc *sc,
2101                         uint16_t         gpio_num,
2102                         uint8_t          mode, /* 0=low 1=high */
2103                         uint8_t          port)
2104 {
2105     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2106 }
2107
2108 void
2109 elink_cb_notify_link_changed(struct bxe_softc *sc)
2110 {
2111     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2112                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2113 }
2114
2115 /* send the MCP a request, block until there is a reply */
2116 uint32_t
2117 elink_cb_fw_command(struct bxe_softc *sc,
2118                     uint32_t         command,
2119                     uint32_t         param)
2120 {
2121     int mb_idx = SC_FW_MB_IDX(sc);
2122     uint32_t seq;
2123     uint32_t rc = 0;
2124     uint32_t cnt = 1;
2125     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2126
2127     BXE_FWMB_LOCK(sc);
2128
2129     seq = ++sc->fw_seq;
2130     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2131     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2132
2133     BLOGD(sc, DBG_PHY,
2134           "wrote command 0x%08x to FW MB param 0x%08x\n",
2135           (command | seq), param);
2136
2137     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2138     do {
2139         DELAY(delay * 1000);
2140         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2141     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2142
2143     BLOGD(sc, DBG_PHY,
2144           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2145           cnt*delay, rc, seq);
2146
2147     /* is this a reply to our command? */
2148     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2149         rc &= FW_MSG_CODE_MASK;
2150     } else {
2151         /* Ruh-roh! */
2152         BLOGE(sc, "FW failed to respond!\n");
2153         // XXX bxe_fw_dump(sc);
2154         rc = 0;
2155     }
2156
2157     BXE_FWMB_UNLOCK(sc);
2158     return (rc);
2159 }
2160
2161 static uint32_t
2162 bxe_fw_command(struct bxe_softc *sc,
2163                uint32_t         command,
2164                uint32_t         param)
2165 {
2166     return (elink_cb_fw_command(sc, command, param));
2167 }
2168
2169 static void
2170 __storm_memset_dma_mapping(struct bxe_softc *sc,
2171                            uint32_t         addr,
2172                            bus_addr_t       mapping)
2173 {
2174     REG_WR(sc, addr, U64_LO(mapping));
2175     REG_WR(sc, (addr + 4), U64_HI(mapping));
2176 }
2177
2178 static void
2179 storm_memset_spq_addr(struct bxe_softc *sc,
2180                       bus_addr_t       mapping,
2181                       uint16_t         abs_fid)
2182 {
2183     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2184                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2185     __storm_memset_dma_mapping(sc, addr, mapping);
2186 }
2187
2188 static void
2189 storm_memset_vf_to_pf(struct bxe_softc *sc,
2190                       uint16_t         abs_fid,
2191                       uint16_t         pf_id)
2192 {
2193     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2194     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2195     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2196     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2197 }
2198
2199 static void
2200 storm_memset_func_en(struct bxe_softc *sc,
2201                      uint16_t         abs_fid,
2202                      uint8_t          enable)
2203 {
2204     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2205     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2206     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2207     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2208 }
2209
2210 static void
2211 storm_memset_eq_data(struct bxe_softc       *sc,
2212                      struct event_ring_data *eq_data,
2213                      uint16_t               pfid)
2214 {
2215     uint32_t addr;
2216     size_t size;
2217
2218     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2219     size = sizeof(struct event_ring_data);
2220     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2221 }
2222
2223 static void
2224 storm_memset_eq_prod(struct bxe_softc *sc,
2225                      uint16_t         eq_prod,
2226                      uint16_t         pfid)
2227 {
2228     uint32_t addr = (BAR_CSTRORM_INTMEM +
2229                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2230     REG_WR16(sc, addr, eq_prod);
2231 }
2232
2233 /*
2234  * Post a slowpath command.
2235  *
2236  * A slowpath command is used to propogate a configuration change through
2237  * the controller in a controlled manner, allowing each STORM processor and
2238  * other H/W blocks to phase in the change.  The commands sent on the
2239  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2240  * completion of the ramrod will occur in different ways.  Here's a
2241  * breakdown of ramrods and how they complete:
2242  *
2243  * RAMROD_CMD_ID_ETH_PORT_SETUP
2244  *   Used to setup the leading connection on a port.  Completes on the
2245  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2246  *
2247  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2248  *   Used to setup an additional connection on a port.  Completes on the
2249  *   RCQ of the multi-queue/RSS connection being initialized.
2250  *
2251  * RAMROD_CMD_ID_ETH_STAT_QUERY
2252  *   Used to force the storm processors to update the statistics database
2253  *   in host memory.  This ramrod is send on the leading connection CID and
2254  *   completes as an index increment of the CSTORM on the default status
2255  *   block.
2256  *
2257  * RAMROD_CMD_ID_ETH_UPDATE
2258  *   Used to update the state of the leading connection, usually to udpate
2259  *   the RSS indirection table.  Completes on the RCQ of the leading
2260  *   connection. (Not currently used under FreeBSD until OS support becomes
2261  *   available.)
2262  *
2263  * RAMROD_CMD_ID_ETH_HALT
2264  *   Used when tearing down a connection prior to driver unload.  Completes
2265  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2266  *   use this on the leading connection.
2267  *
2268  * RAMROD_CMD_ID_ETH_SET_MAC
2269  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2270  *   the RCQ of the leading connection.
2271  *
2272  * RAMROD_CMD_ID_ETH_CFC_DEL
2273  *   Used when tearing down a conneciton prior to driver unload.  Completes
2274  *   on the RCQ of the leading connection (since the current connection
2275  *   has been completely removed from controller memory).
2276  *
2277  * RAMROD_CMD_ID_ETH_PORT_DEL
2278  *   Used to tear down the leading connection prior to driver unload,
2279  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2280  *   default status block.
2281  *
2282  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2283  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2284  *   RSS connection that is being offloaded.  (Not currently used under
2285  *   FreeBSD.)
2286  *
2287  * There can only be one command pending per function.
2288  *
2289  * Returns:
2290  *   0 = Success, !0 = Failure.
2291  */
2292
2293 /* must be called under the spq lock */
2294 static inline
2295 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2296 {
2297     struct eth_spe *next_spe = sc->spq_prod_bd;
2298
2299     if (sc->spq_prod_bd == sc->spq_last_bd) {
2300         /* wrap back to the first eth_spq */
2301         sc->spq_prod_bd = sc->spq;
2302         sc->spq_prod_idx = 0;
2303     } else {
2304         sc->spq_prod_bd++;
2305         sc->spq_prod_idx++;
2306     }
2307
2308     return (next_spe);
2309 }
2310
2311 /* must be called under the spq lock */
2312 static inline
2313 void bxe_sp_prod_update(struct bxe_softc *sc)
2314 {
2315     int func = SC_FUNC(sc);
2316
2317     /*
2318      * Make sure that BD data is updated before writing the producer.
2319      * BD data is written to the memory, the producer is read from the
2320      * memory, thus we need a full memory barrier to ensure the ordering.
2321      */
2322     mb();
2323
2324     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2325              sc->spq_prod_idx);
2326
2327     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2328                       BUS_SPACE_BARRIER_WRITE);
2329 }
2330
2331 /**
2332  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2333  *
2334  * @cmd:      command to check
2335  * @cmd_type: command type
2336  */
2337 static inline
2338 int bxe_is_contextless_ramrod(int cmd,
2339                               int cmd_type)
2340 {
2341     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2342         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2343         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2344         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2345         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2346         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2347         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2348         return (TRUE);
2349     } else {
2350         return (FALSE);
2351     }
2352 }
2353
2354 /**
2355  * bxe_sp_post - place a single command on an SP ring
2356  *
2357  * @sc:         driver handle
2358  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2359  * @cid:        SW CID the command is related to
2360  * @data_hi:    command private data address (high 32 bits)
2361  * @data_lo:    command private data address (low 32 bits)
2362  * @cmd_type:   command type (e.g. NONE, ETH)
2363  *
2364  * SP data is handled as if it's always an address pair, thus data fields are
2365  * not swapped to little endian in upper functions. Instead this function swaps
2366  * data as if it's two uint32 fields.
2367  */
2368 int
2369 bxe_sp_post(struct bxe_softc *sc,
2370             int              command,
2371             int              cid,
2372             uint32_t         data_hi,
2373             uint32_t         data_lo,
2374             int              cmd_type)
2375 {
2376     struct eth_spe *spe;
2377     uint16_t type;
2378     int common;
2379
2380     common = bxe_is_contextless_ramrod(command, cmd_type);
2381
2382     BXE_SP_LOCK(sc);
2383
2384     if (common) {
2385         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2386             BLOGE(sc, "EQ ring is full!\n");
2387             BXE_SP_UNLOCK(sc);
2388             return (-1);
2389         }
2390     } else {
2391         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2392             BLOGE(sc, "SPQ ring is full!\n");
2393             BXE_SP_UNLOCK(sc);
2394             return (-1);
2395         }
2396     }
2397
2398     spe = bxe_sp_get_next(sc);
2399
2400     /* CID needs port number to be encoded int it */
2401     spe->hdr.conn_and_cmd_data =
2402         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2403
2404     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2405
2406     /* TBD: Check if it works for VFs */
2407     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2408              SPE_HDR_T_FUNCTION_ID);
2409
2410     spe->hdr.type = htole16(type);
2411
2412     spe->data.update_data_addr.hi = htole32(data_hi);
2413     spe->data.update_data_addr.lo = htole32(data_lo);
2414
2415     /*
2416      * It's ok if the actual decrement is issued towards the memory
2417      * somewhere between the lock and unlock. Thus no more explict
2418      * memory barrier is needed.
2419      */
2420     if (common) {
2421         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2422     } else {
2423         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2424     }
2425
2426     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2427     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2428           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2429     BLOGD(sc, DBG_SP,
2430           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2431           sc->spq_prod_idx,
2432           (uint32_t)U64_HI(sc->spq_dma.paddr),
2433           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2434           command,
2435           common,
2436           HW_CID(sc, cid),
2437           data_hi,
2438           data_lo,
2439           type,
2440           atomic_load_acq_long(&sc->cq_spq_left),
2441           atomic_load_acq_long(&sc->eq_spq_left));
2442
2443     bxe_sp_prod_update(sc);
2444
2445     BXE_SP_UNLOCK(sc);
2446     return (0);
2447 }
2448
2449 /**
2450  * bxe_debug_print_ind_table - prints the indirection table configuration.
2451  *
2452  * @sc: driver hanlde
2453  * @p:  pointer to rss configuration
2454  */
2455
2456 /*
2457  * FreeBSD Device probe function.
2458  *
2459  * Compares the device found to the driver's list of supported devices and
2460  * reports back to the bsd loader whether this is the right driver for the device.
2461  * This is the driver entry function called from the "kldload" command.
2462  *
2463  * Returns:
2464  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2465  */
2466 static int
2467 bxe_probe(device_t dev)
2468 {
2469     struct bxe_softc *sc;
2470     struct bxe_device_type *t;
2471     char *descbuf;
2472     uint16_t did, sdid, svid, vid;
2473
2474     /* Find our device structure */
2475     sc = device_get_softc(dev);
2476     sc->dev = dev;
2477     t = bxe_devs;
2478
2479     /* Get the data for the device to be probed. */
2480     vid  = pci_get_vendor(dev);
2481     did  = pci_get_device(dev);
2482     svid = pci_get_subvendor(dev);
2483     sdid = pci_get_subdevice(dev);
2484
2485     BLOGD(sc, DBG_LOAD,
2486           "%s(); VID = 0x%04X, DID = 0x%04X, SVID = 0x%04X, "
2487           "SDID = 0x%04X\n", __FUNCTION__, vid, did, svid, sdid);
2488
2489     /* Look through the list of known devices for a match. */
2490     while (t->bxe_name != NULL) {
2491         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2492             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2493             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2494             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2495             if (descbuf == NULL)
2496                 return (ENOMEM);
2497
2498             /* Print out the device identity. */
2499             snprintf(descbuf, BXE_DEVDESC_MAX,
2500                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2501                      (((pci_read_config(dev, PCIR_REVID, 4) &
2502                         0xf0) >> 4) + 'A'),
2503                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2504                      BXE_DRIVER_VERSION);
2505
2506             device_set_desc_copy(dev, descbuf);
2507             free(descbuf, M_TEMP);
2508             return (BUS_PROBE_DEFAULT);
2509         }
2510         t++;
2511     }
2512
2513     return (ENXIO);
2514 }
2515
2516 static void
2517 bxe_init_mutexes(struct bxe_softc *sc)
2518 {
2519 #ifdef BXE_CORE_LOCK_SX
2520     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2521              "bxe%d_core_lock", sc->unit);
2522     sx_init(&sc->core_sx, sc->core_sx_name);
2523 #else
2524     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2525              "bxe%d_core_lock", sc->unit);
2526     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2527 #endif
2528
2529     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2530              "bxe%d_sp_lock", sc->unit);
2531     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2532
2533     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2534              "bxe%d_dmae_lock", sc->unit);
2535     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2536
2537     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2538              "bxe%d_phy_lock", sc->unit);
2539     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2540
2541     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2542              "bxe%d_fwmb_lock", sc->unit);
2543     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2544
2545     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2546              "bxe%d_print_lock", sc->unit);
2547     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2548
2549     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2550              "bxe%d_stats_lock", sc->unit);
2551     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2552
2553     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2554              "bxe%d_mcast_lock", sc->unit);
2555     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2556 }
2557
2558 static void
2559 bxe_release_mutexes(struct bxe_softc *sc)
2560 {
2561 #ifdef BXE_CORE_LOCK_SX
2562     sx_destroy(&sc->core_sx);
2563 #else
2564     if (mtx_initialized(&sc->core_mtx)) {
2565         mtx_destroy(&sc->core_mtx);
2566     }
2567 #endif
2568
2569     if (mtx_initialized(&sc->sp_mtx)) {
2570         mtx_destroy(&sc->sp_mtx);
2571     }
2572
2573     if (mtx_initialized(&sc->dmae_mtx)) {
2574         mtx_destroy(&sc->dmae_mtx);
2575     }
2576
2577     if (mtx_initialized(&sc->port.phy_mtx)) {
2578         mtx_destroy(&sc->port.phy_mtx);
2579     }
2580
2581     if (mtx_initialized(&sc->fwmb_mtx)) {
2582         mtx_destroy(&sc->fwmb_mtx);
2583     }
2584
2585     if (mtx_initialized(&sc->print_mtx)) {
2586         mtx_destroy(&sc->print_mtx);
2587     }
2588
2589     if (mtx_initialized(&sc->stats_mtx)) {
2590         mtx_destroy(&sc->stats_mtx);
2591     }
2592
2593     if (mtx_initialized(&sc->mcast_mtx)) {
2594         mtx_destroy(&sc->mcast_mtx);
2595     }
2596 }
2597
2598 static void
2599 bxe_tx_disable(struct bxe_softc* sc)
2600 {
2601     struct ifnet *ifp = sc->ifnet;
2602
2603     /* tell the stack the driver is stopped and TX queue is full */
2604     if (ifp != NULL) {
2605         ifp->if_drv_flags = 0;
2606     }
2607 }
2608
2609 static void
2610 bxe_drv_pulse(struct bxe_softc *sc)
2611 {
2612     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2613              sc->fw_drv_pulse_wr_seq);
2614 }
2615
2616 static inline uint16_t
2617 bxe_tx_avail(struct bxe_softc *sc,
2618              struct bxe_fastpath *fp)
2619 {
2620     int16_t  used;
2621     uint16_t prod;
2622     uint16_t cons;
2623
2624     prod = fp->tx_bd_prod;
2625     cons = fp->tx_bd_cons;
2626
2627     used = SUB_S16(prod, cons);
2628
2629     return (int16_t)(sc->tx_ring_size) - used;
2630 }
2631
2632 static inline int
2633 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2634 {
2635     uint16_t hw_cons;
2636
2637     mb(); /* status block fields can change */
2638     hw_cons = le16toh(*fp->tx_cons_sb);
2639     return (hw_cons != fp->tx_pkt_cons);
2640 }
2641
2642 static inline uint8_t
2643 bxe_has_tx_work(struct bxe_fastpath *fp)
2644 {
2645     /* expand this for multi-cos if ever supported */
2646     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2647 }
2648
2649 static inline int
2650 bxe_has_rx_work(struct bxe_fastpath *fp)
2651 {
2652     uint16_t rx_cq_cons_sb;
2653
2654     mb(); /* status block fields can change */
2655     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2656     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2657         rx_cq_cons_sb++;
2658     return (fp->rx_cq_cons != rx_cq_cons_sb);
2659 }
2660
2661 static void
2662 bxe_sp_event(struct bxe_softc    *sc,
2663              struct bxe_fastpath *fp,
2664              union eth_rx_cqe    *rr_cqe)
2665 {
2666     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2667     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2668     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2669     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2670
2671     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2672           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2673
2674     switch (command) {
2675     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2676         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2677         drv_cmd = ECORE_Q_CMD_UPDATE;
2678         break;
2679
2680     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2681         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2682         drv_cmd = ECORE_Q_CMD_SETUP;
2683         break;
2684
2685     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2686         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2687         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2688         break;
2689
2690     case (RAMROD_CMD_ID_ETH_HALT):
2691         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2692         drv_cmd = ECORE_Q_CMD_HALT;
2693         break;
2694
2695     case (RAMROD_CMD_ID_ETH_TERMINATE):
2696         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2697         drv_cmd = ECORE_Q_CMD_TERMINATE;
2698         break;
2699
2700     case (RAMROD_CMD_ID_ETH_EMPTY):
2701         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2702         drv_cmd = ECORE_Q_CMD_EMPTY;
2703         break;
2704
2705     default:
2706         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2707               command, fp->index);
2708         return;
2709     }
2710
2711     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2712         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2713         /*
2714          * q_obj->complete_cmd() failure means that this was
2715          * an unexpected completion.
2716          *
2717          * In this case we don't want to increase the sc->spq_left
2718          * because apparently we haven't sent this command the first
2719          * place.
2720          */
2721         // bxe_panic(sc, ("Unexpected SP completion\n"));
2722         return;
2723     }
2724
2725     atomic_add_acq_long(&sc->cq_spq_left, 1);
2726
2727     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2728           atomic_load_acq_long(&sc->cq_spq_left));
2729 }
2730
2731 /*
2732  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2733  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2734  * the current aggregation queue as in-progress.
2735  */
2736 static void
2737 bxe_tpa_start(struct bxe_softc            *sc,
2738               struct bxe_fastpath         *fp,
2739               uint16_t                    queue,
2740               uint16_t                    cons,
2741               uint16_t                    prod,
2742               struct eth_fast_path_rx_cqe *cqe)
2743 {
2744     struct bxe_sw_rx_bd tmp_bd;
2745     struct bxe_sw_rx_bd *rx_buf;
2746     struct eth_rx_bd *rx_bd;
2747     int max_agg_queues;
2748     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2749     uint16_t index;
2750
2751     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2752                        "cons=%d prod=%d\n",
2753           fp->index, queue, cons, prod);
2754
2755     max_agg_queues = MAX_AGG_QS(sc);
2756
2757     KASSERT((queue < max_agg_queues),
2758             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2759              fp->index, queue, max_agg_queues));
2760
2761     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2762             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2763              fp->index, queue));
2764
2765     /* copy the existing mbuf and mapping from the TPA pool */
2766     tmp_bd = tpa_info->bd;
2767
2768     if (tmp_bd.m == NULL) {
2769         uint32_t *tmp;
2770
2771         tmp = (uint32_t *)cqe;
2772
2773         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2774               fp->index, queue, cons, prod);
2775         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2776             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2777             
2778         /* XXX Error handling? */
2779         return;
2780     }
2781
2782     /* change the TPA queue to the start state */
2783     tpa_info->state            = BXE_TPA_STATE_START;
2784     tpa_info->placement_offset = cqe->placement_offset;
2785     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2786     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2787     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2788
2789     fp->rx_tpa_queue_used |= (1 << queue);
2790
2791     /*
2792      * If all the buffer descriptors are filled with mbufs then fill in
2793      * the current consumer index with a new BD. Else if a maximum Rx
2794      * buffer limit is imposed then fill in the next producer index.
2795      */
2796     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2797                 prod : cons;
2798
2799     /* move the received mbuf and mapping to TPA pool */
2800     tpa_info->bd = fp->rx_mbuf_chain[cons];
2801
2802     /* release any existing RX BD mbuf mappings */
2803     if (cons != index) {
2804         rx_buf = &fp->rx_mbuf_chain[cons];
2805
2806         if (rx_buf->m_map != NULL) {
2807             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2808                             BUS_DMASYNC_POSTREAD);
2809             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2810         }
2811
2812         /*
2813          * We get here when the maximum number of rx buffers is less than
2814          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2815          * it out here without concern of a memory leak.
2816          */
2817         fp->rx_mbuf_chain[cons].m = NULL;
2818     }
2819
2820     /* update the Rx SW BD with the mbuf info from the TPA pool */
2821     fp->rx_mbuf_chain[index] = tmp_bd;
2822
2823     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2824     rx_bd = &fp->rx_chain[index];
2825     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2826     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2827 }
2828
2829 /*
2830  * When a TPA aggregation is completed, loop through the individual mbufs
2831  * of the aggregation, combining them into a single mbuf which will be sent
2832  * up the stack. Refill all freed SGEs with mbufs as we go along.
2833  */
2834 static int
2835 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2836                    struct bxe_fastpath       *fp,
2837                    struct bxe_sw_tpa_info    *tpa_info,
2838                    uint16_t                  queue,
2839                    uint16_t                  pages,
2840                    struct mbuf               *m,
2841                                struct eth_end_agg_rx_cqe *cqe,
2842                    uint16_t                  cqe_idx)
2843 {
2844     struct mbuf *m_frag;
2845     uint32_t frag_len, frag_size, i;
2846     uint16_t sge_idx;
2847     int rc = 0;
2848     int j;
2849
2850     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2851
2852     BLOGD(sc, DBG_LRO,
2853           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2854           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2855
2856     /* make sure the aggregated frame is not too big to handle */
2857     if (pages > 8 * PAGES_PER_SGE) {
2858
2859         uint32_t *tmp = (uint32_t *)cqe;
2860
2861         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2862                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2863               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2864               tpa_info->len_on_bd, frag_size);
2865
2866         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2867             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2868
2869         bxe_panic(sc, ("sge page count error\n"));
2870         return (EINVAL);
2871     }
2872
2873     /*
2874      * Scan through the scatter gather list pulling individual mbufs into a
2875      * single mbuf for the host stack.
2876      */
2877     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2878         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2879
2880         /*
2881          * Firmware gives the indices of the SGE as if the ring is an array
2882          * (meaning that the "next" element will consume 2 indices).
2883          */
2884         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2885
2886         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2887                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2888               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2889
2890         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2891
2892         /* allocate a new mbuf for the SGE */
2893         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2894         if (rc) {
2895             /* Leave all remaining SGEs in the ring! */
2896             return (rc);
2897         }
2898
2899         /* update the fragment length */
2900         m_frag->m_len = frag_len;
2901
2902         /* concatenate the fragment to the head mbuf */
2903         m_cat(m, m_frag);
2904         fp->eth_q_stats.mbuf_alloc_sge--;
2905
2906         /* update the TPA mbuf size and remaining fragment size */
2907         m->m_pkthdr.len += frag_len;
2908         frag_size -= frag_len;
2909     }
2910
2911     BLOGD(sc, DBG_LRO,
2912           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2913           fp->index, queue, frag_size);
2914
2915     return (rc);
2916 }
2917
2918 static inline void
2919 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2920 {
2921     int i, j;
2922
2923     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2924         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2925
2926         for (j = 0; j < 2; j++) {
2927             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2928             idx--;
2929         }
2930     }
2931 }
2932
2933 static inline void
2934 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2935 {
2936     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2937     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2938
2939     /*
2940      * Clear the two last indices in the page to 1. These are the indices that
2941      * correspond to the "next" element, hence will never be indicated and
2942      * should be removed from the calculations.
2943      */
2944     bxe_clear_sge_mask_next_elems(fp);
2945 }
2946
2947 static inline void
2948 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2949                         uint16_t            idx)
2950 {
2951     uint16_t last_max = fp->last_max_sge;
2952
2953     if (SUB_S16(idx, last_max) > 0) {
2954         fp->last_max_sge = idx;
2955     }
2956 }
2957
2958 static inline void
2959 bxe_update_sge_prod(struct bxe_softc          *sc,
2960                     struct bxe_fastpath       *fp,
2961                     uint16_t                  sge_len,
2962                     union eth_sgl_or_raw_data *cqe)
2963 {
2964     uint16_t last_max, last_elem, first_elem;
2965     uint16_t delta = 0;
2966     uint16_t i;
2967
2968     if (!sge_len) {
2969         return;
2970     }
2971
2972     /* first mark all used pages */
2973     for (i = 0; i < sge_len; i++) {
2974         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
2975                             RX_SGE(le16toh(cqe->sgl[i])));
2976     }
2977
2978     BLOGD(sc, DBG_LRO,
2979           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
2980           fp->index, sge_len - 1,
2981           le16toh(cqe->sgl[sge_len - 1]));
2982
2983     /* assume that the last SGE index is the biggest */
2984     bxe_update_last_max_sge(fp,
2985                             le16toh(cqe->sgl[sge_len - 1]));
2986
2987     last_max = RX_SGE(fp->last_max_sge);
2988     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
2989     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
2990
2991     /* if ring is not full */
2992     if (last_elem + 1 != first_elem) {
2993         last_elem++;
2994     }
2995
2996     /* now update the prod */
2997     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
2998         if (__predict_true(fp->sge_mask[i])) {
2999             break;
3000         }
3001
3002         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3003         delta += BIT_VEC64_ELEM_SZ;
3004     }
3005
3006     if (delta > 0) {
3007         fp->rx_sge_prod += delta;
3008         /* clear page-end entries */
3009         bxe_clear_sge_mask_next_elems(fp);
3010     }
3011
3012     BLOGD(sc, DBG_LRO,
3013           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3014           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3015 }
3016
3017 /*
3018  * The aggregation on the current TPA queue has completed. Pull the individual
3019  * mbuf fragments together into a single mbuf, perform all necessary checksum
3020  * calculations, and send the resuting mbuf to the stack.
3021  */
3022 static void
3023 bxe_tpa_stop(struct bxe_softc          *sc,
3024              struct bxe_fastpath       *fp,
3025              struct bxe_sw_tpa_info    *tpa_info,
3026              uint16_t                  queue,
3027              uint16_t                  pages,
3028                          struct eth_end_agg_rx_cqe *cqe,
3029              uint16_t                  cqe_idx)
3030 {
3031     struct ifnet *ifp = sc->ifnet;
3032     struct mbuf *m;
3033     int rc = 0;
3034
3035     BLOGD(sc, DBG_LRO,
3036           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3037           fp->index, queue, tpa_info->placement_offset,
3038           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3039
3040     m = tpa_info->bd.m;
3041
3042     /* allocate a replacement before modifying existing mbuf */
3043     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3044     if (rc) {
3045         /* drop the frame and log an error */
3046         fp->eth_q_stats.rx_soft_errors++;
3047         goto bxe_tpa_stop_exit;
3048     }
3049
3050     /* we have a replacement, fixup the current mbuf */
3051     m_adj(m, tpa_info->placement_offset);
3052     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3053
3054     /* mark the checksums valid (taken care of by the firmware) */
3055     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3056     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3057     m->m_pkthdr.csum_data = 0xffff;
3058     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3059                                CSUM_IP_VALID   |
3060                                CSUM_DATA_VALID |
3061                                CSUM_PSEUDO_HDR);
3062
3063     /* aggregate all of the SGEs into a single mbuf */
3064     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3065     if (rc) {
3066         /* drop the packet and log an error */
3067         fp->eth_q_stats.rx_soft_errors++;
3068         m_freem(m);
3069     } else {
3070         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3071             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3072             m->m_flags |= M_VLANTAG;
3073         }
3074
3075         /* assign packet to this interface interface */
3076         m->m_pkthdr.rcvif = ifp;
3077
3078 #if __FreeBSD_version >= 800000
3079         /* specify what RSS queue was used for this flow */
3080         m->m_pkthdr.flowid = fp->index;
3081         BXE_SET_FLOWID(m);
3082 #endif
3083
3084         ifp->if_ipackets++;
3085         fp->eth_q_stats.rx_tpa_pkts++;
3086
3087         /* pass the frame to the stack */
3088         (*ifp->if_input)(ifp, m);
3089     }
3090
3091     /* we passed an mbuf up the stack or dropped the frame */
3092     fp->eth_q_stats.mbuf_alloc_tpa--;
3093
3094 bxe_tpa_stop_exit:
3095
3096     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3097     fp->rx_tpa_queue_used &= ~(1 << queue);
3098 }
3099
3100 static uint8_t
3101 bxe_service_rxsgl(
3102                  struct bxe_fastpath *fp,
3103                  uint16_t len,
3104                  uint16_t lenonbd,
3105                  struct mbuf *m,
3106                  struct eth_fast_path_rx_cqe *cqe_fp)
3107 {
3108     struct mbuf *m_frag;
3109     uint16_t frags, frag_len;
3110     uint16_t sge_idx = 0;
3111     uint16_t j;
3112     uint8_t i, rc = 0;
3113     uint32_t frag_size;
3114
3115     /* adjust the mbuf */
3116     m->m_len = lenonbd;
3117
3118     frag_size =  len - lenonbd;
3119     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3120
3121     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3122         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3123
3124         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3125         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3126         m_frag->m_len = frag_len;
3127
3128        /* allocate a new mbuf for the SGE */
3129         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3130         if (rc) {
3131             /* Leave all remaining SGEs in the ring! */
3132             return (rc);
3133         }
3134         fp->eth_q_stats.mbuf_alloc_sge--;
3135
3136         /* concatenate the fragment to the head mbuf */
3137         m_cat(m, m_frag);
3138
3139         frag_size -= frag_len;
3140     }
3141
3142     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3143
3144     return rc;
3145 }
3146
3147 static uint8_t
3148 bxe_rxeof(struct bxe_softc    *sc,
3149           struct bxe_fastpath *fp)
3150 {
3151     struct ifnet *ifp = sc->ifnet;
3152     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3153     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3154     int rx_pkts = 0;
3155     int rc = 0;
3156
3157     BXE_FP_RX_LOCK(fp);
3158
3159     /* CQ "next element" is of the size of the regular element */
3160     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3161     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3162         hw_cq_cons++;
3163     }
3164
3165     bd_cons = fp->rx_bd_cons;
3166     bd_prod = fp->rx_bd_prod;
3167     bd_prod_fw = bd_prod;
3168     sw_cq_cons = fp->rx_cq_cons;
3169     sw_cq_prod = fp->rx_cq_prod;
3170
3171     /*
3172      * Memory barrier necessary as speculative reads of the rx
3173      * buffer can be ahead of the index in the status block
3174      */
3175     rmb();
3176
3177     BLOGD(sc, DBG_RX,
3178           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3179           fp->index, hw_cq_cons, sw_cq_cons);
3180
3181     while (sw_cq_cons != hw_cq_cons) {
3182         struct bxe_sw_rx_bd *rx_buf = NULL;
3183         union eth_rx_cqe *cqe;
3184         struct eth_fast_path_rx_cqe *cqe_fp;
3185         uint8_t cqe_fp_flags;
3186         enum eth_rx_cqe_type cqe_fp_type;
3187         uint16_t len, lenonbd,  pad;
3188         struct mbuf *m = NULL;
3189
3190         comp_ring_cons = RCQ(sw_cq_cons);
3191         bd_prod = RX_BD(bd_prod);
3192         bd_cons = RX_BD(bd_cons);
3193
3194         cqe          = &fp->rcq_chain[comp_ring_cons];
3195         cqe_fp       = &cqe->fast_path_cqe;
3196         cqe_fp_flags = cqe_fp->type_error_flags;
3197         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3198
3199         BLOGD(sc, DBG_RX,
3200               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3201               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3202               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3203               fp->index,
3204               hw_cq_cons,
3205               sw_cq_cons,
3206               bd_prod,
3207               bd_cons,
3208               CQE_TYPE(cqe_fp_flags),
3209               cqe_fp_flags,
3210               cqe_fp->status_flags,
3211               le32toh(cqe_fp->rss_hash_result),
3212               le16toh(cqe_fp->vlan_tag),
3213               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3214               le16toh(cqe_fp->len_on_bd));
3215
3216         /* is this a slowpath msg? */
3217         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3218             bxe_sp_event(sc, fp, cqe);
3219             goto next_cqe;
3220         }
3221
3222         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3223
3224         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3225             struct bxe_sw_tpa_info *tpa_info;
3226             uint16_t frag_size, pages;
3227             uint8_t queue;
3228
3229             if (CQE_TYPE_START(cqe_fp_type)) {
3230                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3231                               bd_cons, bd_prod, cqe_fp);
3232                 m = NULL; /* packet not ready yet */
3233                 goto next_rx;
3234             }
3235
3236             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3237                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3238
3239             queue = cqe->end_agg_cqe.queue_index;
3240             tpa_info = &fp->rx_tpa_info[queue];
3241
3242             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3243                   fp->index, queue);
3244
3245             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3246                          tpa_info->len_on_bd);
3247             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3248
3249             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3250                          &cqe->end_agg_cqe, comp_ring_cons);
3251
3252             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3253
3254             goto next_cqe;
3255         }
3256
3257         /* non TPA */
3258
3259         /* is this an error packet? */
3260         if (__predict_false(cqe_fp_flags &
3261                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3262             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3263             fp->eth_q_stats.rx_soft_errors++;
3264             goto next_rx;
3265         }
3266
3267         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3268         lenonbd = le16toh(cqe_fp->len_on_bd);
3269         pad = cqe_fp->placement_offset;
3270
3271         m = rx_buf->m;
3272
3273         if (__predict_false(m == NULL)) {
3274             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3275                   bd_cons, fp->index);
3276             goto next_rx;
3277         }
3278
3279         /* XXX double copy if packet length under a threshold */
3280
3281         /*
3282          * If all the buffer descriptors are filled with mbufs then fill in
3283          * the current consumer index with a new BD. Else if a maximum Rx
3284          * buffer limit is imposed then fill in the next producer index.
3285          */
3286         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3287                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3288                                       bd_prod : bd_cons);
3289         if (rc != 0) {
3290
3291             /* we simply reuse the received mbuf and don't post it to the stack */
3292             m = NULL;
3293
3294             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3295                   fp->index, rc);
3296             fp->eth_q_stats.rx_soft_errors++;
3297
3298             if (sc->max_rx_bufs != RX_BD_USABLE) {
3299                 /* copy this consumer index to the producer index */
3300                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3301                        sizeof(struct bxe_sw_rx_bd));
3302                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3303             }
3304
3305             goto next_rx;
3306         }
3307
3308         /* current mbuf was detached from the bd */
3309         fp->eth_q_stats.mbuf_alloc_rx--;
3310
3311         /* we allocated a replacement mbuf, fixup the current one */
3312         m_adj(m, pad);
3313         m->m_pkthdr.len = m->m_len = len;
3314
3315         if ((len > 60) && (len > lenonbd)) {
3316             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3317             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3318             if (rc)
3319                 break;
3320             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3321         } else if (lenonbd < len) {
3322             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3323         }
3324
3325         /* assign packet to this interface interface */
3326         m->m_pkthdr.rcvif = ifp;
3327
3328         /* assume no hardware checksum has complated */
3329         m->m_pkthdr.csum_flags = 0;
3330
3331         /* validate checksum if offload enabled */
3332         if (ifp->if_capenable & IFCAP_RXCSUM) {
3333             /* check for a valid IP frame */
3334             if (!(cqe->fast_path_cqe.status_flags &
3335                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3336                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3337                 if (__predict_false(cqe_fp_flags &
3338                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3339                     fp->eth_q_stats.rx_hw_csum_errors++;
3340                 } else {
3341                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3342                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3343                 }
3344             }
3345
3346             /* check for a valid TCP/UDP frame */
3347             if (!(cqe->fast_path_cqe.status_flags &
3348                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3349                 if (__predict_false(cqe_fp_flags &
3350                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3351                     fp->eth_q_stats.rx_hw_csum_errors++;
3352                 } else {
3353                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3354                     m->m_pkthdr.csum_data = 0xFFFF;
3355                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3356                                                CSUM_PSEUDO_HDR);
3357                 }
3358             }
3359         }
3360
3361         /* if there is a VLAN tag then flag that info */
3362         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3363             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3364             m->m_flags |= M_VLANTAG;
3365         }
3366
3367 #if __FreeBSD_version >= 800000
3368         /* specify what RSS queue was used for this flow */
3369         m->m_pkthdr.flowid = fp->index;
3370         BXE_SET_FLOWID(m);
3371 #endif
3372
3373 next_rx:
3374
3375         bd_cons    = RX_BD_NEXT(bd_cons);
3376         bd_prod    = RX_BD_NEXT(bd_prod);
3377         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3378
3379         /* pass the frame to the stack */
3380         if (__predict_true(m != NULL)) {
3381             ifp->if_ipackets++;
3382             rx_pkts++;
3383             (*ifp->if_input)(ifp, m);
3384         }
3385
3386 next_cqe:
3387
3388         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3389         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3390
3391         /* limit spinning on the queue */
3392         if (rc != 0)
3393             break;
3394
3395         if (rx_pkts == sc->rx_budget) {
3396             fp->eth_q_stats.rx_budget_reached++;
3397             break;
3398         }
3399     } /* while work to do */
3400
3401     fp->rx_bd_cons = bd_cons;
3402     fp->rx_bd_prod = bd_prod_fw;
3403     fp->rx_cq_cons = sw_cq_cons;
3404     fp->rx_cq_prod = sw_cq_prod;
3405
3406     /* Update producers */
3407     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3408
3409     fp->eth_q_stats.rx_pkts += rx_pkts;
3410     fp->eth_q_stats.rx_calls++;
3411
3412     BXE_FP_RX_UNLOCK(fp);
3413
3414     return (sw_cq_cons != hw_cq_cons);
3415 }
3416
3417 static uint16_t
3418 bxe_free_tx_pkt(struct bxe_softc    *sc,
3419                 struct bxe_fastpath *fp,
3420                 uint16_t            idx)
3421 {
3422     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3423     struct eth_tx_start_bd *tx_start_bd;
3424     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3425     uint16_t new_cons;
3426     int nbd;
3427
3428     /* unmap the mbuf from non-paged memory */
3429     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3430
3431     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3432     nbd = le16toh(tx_start_bd->nbd) - 1;
3433
3434     new_cons = (tx_buf->first_bd + nbd);
3435
3436     /* free the mbuf */
3437     if (__predict_true(tx_buf->m != NULL)) {
3438         m_freem(tx_buf->m);
3439         fp->eth_q_stats.mbuf_alloc_tx--;
3440     } else {
3441         fp->eth_q_stats.tx_chain_lost_mbuf++;
3442     }
3443
3444     tx_buf->m = NULL;
3445     tx_buf->first_bd = 0;
3446
3447     return (new_cons);
3448 }
3449
3450 /* transmit timeout watchdog */
3451 static int
3452 bxe_watchdog(struct bxe_softc    *sc,
3453              struct bxe_fastpath *fp)
3454 {
3455     BXE_FP_TX_LOCK(fp);
3456
3457     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3458         BXE_FP_TX_UNLOCK(fp);
3459         return (0);
3460     }
3461
3462     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3463
3464     BXE_FP_TX_UNLOCK(fp);
3465
3466     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3467     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3468
3469     return (-1);
3470 }
3471
3472 /* processes transmit completions */
3473 static uint8_t
3474 bxe_txeof(struct bxe_softc    *sc,
3475           struct bxe_fastpath *fp)
3476 {
3477     struct ifnet *ifp = sc->ifnet;
3478     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3479     uint16_t tx_bd_avail;
3480
3481     BXE_FP_TX_LOCK_ASSERT(fp);
3482
3483     bd_cons = fp->tx_bd_cons;
3484     hw_cons = le16toh(*fp->tx_cons_sb);
3485     sw_cons = fp->tx_pkt_cons;
3486
3487     while (sw_cons != hw_cons) {
3488         pkt_cons = TX_BD(sw_cons);
3489
3490         BLOGD(sc, DBG_TX,
3491               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3492               fp->index, hw_cons, sw_cons, pkt_cons);
3493
3494         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3495
3496         sw_cons++;
3497     }
3498
3499     fp->tx_pkt_cons = sw_cons;
3500     fp->tx_bd_cons  = bd_cons;
3501
3502     BLOGD(sc, DBG_TX,
3503           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3504           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3505
3506     mb();
3507
3508     tx_bd_avail = bxe_tx_avail(sc, fp);
3509
3510     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3511         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3512     } else {
3513         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3514     }
3515
3516     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3517         /* reset the watchdog timer if there are pending transmits */
3518         fp->watchdog_timer = BXE_TX_TIMEOUT;
3519         return (TRUE);
3520     } else {
3521         /* clear watchdog when there are no pending transmits */
3522         fp->watchdog_timer = 0;
3523         return (FALSE);
3524     }
3525 }
3526
3527 static void
3528 bxe_drain_tx_queues(struct bxe_softc *sc)
3529 {
3530     struct bxe_fastpath *fp;
3531     int i, count;
3532
3533     /* wait until all TX fastpath tasks have completed */
3534     for (i = 0; i < sc->num_queues; i++) {
3535         fp = &sc->fp[i];
3536
3537         count = 1000;
3538
3539         while (bxe_has_tx_work(fp)) {
3540
3541             BXE_FP_TX_LOCK(fp);
3542             bxe_txeof(sc, fp);
3543             BXE_FP_TX_UNLOCK(fp);
3544
3545             if (count == 0) {
3546                 BLOGE(sc, "Timeout waiting for fp[%d] "
3547                           "transmits to complete!\n", i);
3548                 bxe_panic(sc, ("tx drain failure\n"));
3549                 return;
3550             }
3551
3552             count--;
3553             DELAY(1000);
3554             rmb();
3555         }
3556     }
3557
3558     return;
3559 }
3560
3561 static int
3562 bxe_del_all_macs(struct bxe_softc          *sc,
3563                  struct ecore_vlan_mac_obj *mac_obj,
3564                  int                       mac_type,
3565                  uint8_t                   wait_for_comp)
3566 {
3567     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3568     int rc;
3569
3570     /* wait for completion of requested */
3571     if (wait_for_comp) {
3572         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3573     }
3574
3575     /* Set the mac type of addresses we want to clear */
3576     bxe_set_bit(mac_type, &vlan_mac_flags);
3577
3578     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3579     if (rc < 0) {
3580         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3581             rc, mac_type, wait_for_comp);
3582     }
3583
3584     return (rc);
3585 }
3586
3587 static int
3588 bxe_fill_accept_flags(struct bxe_softc *sc,
3589                       uint32_t         rx_mode,
3590                       unsigned long    *rx_accept_flags,
3591                       unsigned long    *tx_accept_flags)
3592 {
3593     /* Clear the flags first */
3594     *rx_accept_flags = 0;
3595     *tx_accept_flags = 0;
3596
3597     switch (rx_mode) {
3598     case BXE_RX_MODE_NONE:
3599         /*
3600          * 'drop all' supersedes any accept flags that may have been
3601          * passed to the function.
3602          */
3603         break;
3604
3605     case BXE_RX_MODE_NORMAL:
3606         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3607         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3608         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3609
3610         /* internal switching mode */
3611         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3612         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3613         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3614
3615         break;
3616
3617     case BXE_RX_MODE_ALLMULTI:
3618         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3619         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3620         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3621
3622         /* internal switching mode */
3623         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3624         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3625         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3626
3627         break;
3628
3629     case BXE_RX_MODE_PROMISC:
3630         /*
3631          * According to deffinition of SI mode, iface in promisc mode
3632          * should receive matched and unmatched (in resolution of port)
3633          * unicast packets.
3634          */
3635         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3636         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3637         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3638         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3639
3640         /* internal switching mode */
3641         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3642         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3643
3644         if (IS_MF_SI(sc)) {
3645             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3646         } else {
3647             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3648         }
3649
3650         break;
3651
3652     default:
3653         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3654         return (-1);
3655     }
3656
3657     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3658     if (rx_mode != BXE_RX_MODE_NONE) {
3659         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3660         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3661     }
3662
3663     return (0);
3664 }
3665
3666 static int
3667 bxe_set_q_rx_mode(struct bxe_softc *sc,
3668                   uint8_t          cl_id,
3669                   unsigned long    rx_mode_flags,
3670                   unsigned long    rx_accept_flags,
3671                   unsigned long    tx_accept_flags,
3672                   unsigned long    ramrod_flags)
3673 {
3674     struct ecore_rx_mode_ramrod_params ramrod_param;
3675     int rc;
3676
3677     memset(&ramrod_param, 0, sizeof(ramrod_param));
3678
3679     /* Prepare ramrod parameters */
3680     ramrod_param.cid = 0;
3681     ramrod_param.cl_id = cl_id;
3682     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3683     ramrod_param.func_id = SC_FUNC(sc);
3684
3685     ramrod_param.pstate = &sc->sp_state;
3686     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3687
3688     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3689     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3690
3691     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3692
3693     ramrod_param.ramrod_flags = ramrod_flags;
3694     ramrod_param.rx_mode_flags = rx_mode_flags;
3695
3696     ramrod_param.rx_accept_flags = rx_accept_flags;
3697     ramrod_param.tx_accept_flags = tx_accept_flags;
3698
3699     rc = ecore_config_rx_mode(sc, &ramrod_param);
3700     if (rc < 0) {
3701         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3702             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3703             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3704             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3705             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3706         return (rc);
3707     }
3708
3709     return (0);
3710 }
3711
3712 static int
3713 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3714 {
3715     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3716     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3717     int rc;
3718
3719     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3720                                &tx_accept_flags);
3721     if (rc) {
3722         return (rc);
3723     }
3724
3725     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3726     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3727
3728     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3729     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3730                               rx_accept_flags, tx_accept_flags,
3731                               ramrod_flags));
3732 }
3733
3734 /* returns the "mcp load_code" according to global load_count array */
3735 static int
3736 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3737 {
3738     int path = SC_PATH(sc);
3739     int port = SC_PORT(sc);
3740
3741     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3742           path, load_count[path][0], load_count[path][1],
3743           load_count[path][2]);
3744     load_count[path][0]++;
3745     load_count[path][1 + port]++;
3746     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3747           path, load_count[path][0], load_count[path][1],
3748           load_count[path][2]);
3749     if (load_count[path][0] == 1) {
3750         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3751     } else if (load_count[path][1 + port] == 1) {
3752         return (FW_MSG_CODE_DRV_LOAD_PORT);
3753     } else {
3754         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3755     }
3756 }
3757
3758 /* returns the "mcp load_code" according to global load_count array */
3759 static int
3760 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3761 {
3762     int port = SC_PORT(sc);
3763     int path = SC_PATH(sc);
3764
3765     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3766           path, load_count[path][0], load_count[path][1],
3767           load_count[path][2]);
3768     load_count[path][0]--;
3769     load_count[path][1 + port]--;
3770     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3771           path, load_count[path][0], load_count[path][1],
3772           load_count[path][2]);
3773     if (load_count[path][0] == 0) {
3774         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3775     } else if (load_count[path][1 + port] == 0) {
3776         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3777     } else {
3778         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3779     }
3780 }
3781
3782 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3783 static uint32_t
3784 bxe_send_unload_req(struct bxe_softc *sc,
3785                     int              unload_mode)
3786 {
3787     uint32_t reset_code = 0;
3788
3789     /* Select the UNLOAD request mode */
3790     if (unload_mode == UNLOAD_NORMAL) {
3791         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3792     } else {
3793         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3794     }
3795
3796     /* Send the request to the MCP */
3797     if (!BXE_NOMCP(sc)) {
3798         reset_code = bxe_fw_command(sc, reset_code, 0);
3799     } else {
3800         reset_code = bxe_nic_unload_no_mcp(sc);
3801     }
3802
3803     return (reset_code);
3804 }
3805
3806 /* send UNLOAD_DONE command to the MCP */
3807 static void
3808 bxe_send_unload_done(struct bxe_softc *sc,
3809                      uint8_t          keep_link)
3810 {
3811     uint32_t reset_param =
3812         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3813
3814     /* Report UNLOAD_DONE to MCP */
3815     if (!BXE_NOMCP(sc)) {
3816         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3817     }
3818 }
3819
3820 static int
3821 bxe_func_wait_started(struct bxe_softc *sc)
3822 {
3823     int tout = 50;
3824
3825     if (!sc->port.pmf) {
3826         return (0);
3827     }
3828
3829     /*
3830      * (assumption: No Attention from MCP at this stage)
3831      * PMF probably in the middle of TX disable/enable transaction
3832      * 1. Sync IRS for default SB
3833      * 2. Sync SP queue - this guarantees us that attention handling started
3834      * 3. Wait, that TX disable/enable transaction completes
3835      *
3836      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3837      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3838      * received completion for the transaction the state is TX_STOPPED.
3839      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3840      * transaction.
3841      */
3842
3843     /* XXX make sure default SB ISR is done */
3844     /* need a way to synchronize an irq (intr_mtx?) */
3845
3846     /* XXX flush any work queues */
3847
3848     while (ecore_func_get_state(sc, &sc->func_obj) !=
3849            ECORE_F_STATE_STARTED && tout--) {
3850         DELAY(20000);
3851     }
3852
3853     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3854         /*
3855          * Failed to complete the transaction in a "good way"
3856          * Force both transactions with CLR bit.
3857          */
3858         struct ecore_func_state_params func_params = { NULL };
3859
3860         BLOGE(sc, "Unexpected function state! "
3861                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3862
3863         func_params.f_obj = &sc->func_obj;
3864         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3865
3866         /* STARTED-->TX_STOPPED */
3867         func_params.cmd = ECORE_F_CMD_TX_STOP;
3868         ecore_func_state_change(sc, &func_params);
3869
3870         /* TX_STOPPED-->STARTED */
3871         func_params.cmd = ECORE_F_CMD_TX_START;
3872         return (ecore_func_state_change(sc, &func_params));
3873     }
3874
3875     return (0);
3876 }
3877
3878 static int
3879 bxe_stop_queue(struct bxe_softc *sc,
3880                int              index)
3881 {
3882     struct bxe_fastpath *fp = &sc->fp[index];
3883     struct ecore_queue_state_params q_params = { NULL };
3884     int rc;
3885
3886     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3887
3888     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3889     /* We want to wait for completion in this context */
3890     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3891
3892     /* Stop the primary connection: */
3893
3894     /* ...halt the connection */
3895     q_params.cmd = ECORE_Q_CMD_HALT;
3896     rc = ecore_queue_state_change(sc, &q_params);
3897     if (rc) {
3898         return (rc);
3899     }
3900
3901     /* ...terminate the connection */
3902     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3903     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3904     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3905     rc = ecore_queue_state_change(sc, &q_params);
3906     if (rc) {
3907         return (rc);
3908     }
3909
3910     /* ...delete cfc entry */
3911     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3912     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3913     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3914     return (ecore_queue_state_change(sc, &q_params));
3915 }
3916
3917 /* wait for the outstanding SP commands */
3918 static inline uint8_t
3919 bxe_wait_sp_comp(struct bxe_softc *sc,
3920                  unsigned long    mask)
3921 {
3922     unsigned long tmp;
3923     int tout = 5000; /* wait for 5 secs tops */
3924
3925     while (tout--) {
3926         mb();
3927         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3928             return (TRUE);
3929         }
3930
3931         DELAY(1000);
3932     }
3933
3934     mb();
3935
3936     tmp = atomic_load_acq_long(&sc->sp_state);
3937     if (tmp & mask) {
3938         BLOGE(sc, "Filtering completion timed out: "
3939                   "sp_state 0x%lx, mask 0x%lx\n",
3940               tmp, mask);
3941         return (FALSE);
3942     }
3943
3944     return (FALSE);
3945 }
3946
3947 static int
3948 bxe_func_stop(struct bxe_softc *sc)
3949 {
3950     struct ecore_func_state_params func_params = { NULL };
3951     int rc;
3952
3953     /* prepare parameters for function state transitions */
3954     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3955     func_params.f_obj = &sc->func_obj;
3956     func_params.cmd = ECORE_F_CMD_STOP;
3957
3958     /*
3959      * Try to stop the function the 'good way'. If it fails (in case
3960      * of a parity error during bxe_chip_cleanup()) and we are
3961      * not in a debug mode, perform a state transaction in order to
3962      * enable further HW_RESET transaction.
3963      */
3964     rc = ecore_func_state_change(sc, &func_params);
3965     if (rc) {
3966         BLOGE(sc, "FUNC_STOP ramrod failed. "
3967                   "Running a dry transaction (%d)\n", rc);
3968         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3969         return (ecore_func_state_change(sc, &func_params));
3970     }
3971
3972     return (0);
3973 }
3974
3975 static int
3976 bxe_reset_hw(struct bxe_softc *sc,
3977              uint32_t         load_code)
3978 {
3979     struct ecore_func_state_params func_params = { NULL };
3980
3981     /* Prepare parameters for function state transitions */
3982     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3983
3984     func_params.f_obj = &sc->func_obj;
3985     func_params.cmd = ECORE_F_CMD_HW_RESET;
3986
3987     func_params.params.hw_init.load_phase = load_code;
3988
3989     return (ecore_func_state_change(sc, &func_params));
3990 }
3991
3992 static void
3993 bxe_int_disable_sync(struct bxe_softc *sc,
3994                      int              disable_hw)
3995 {
3996     if (disable_hw) {
3997         /* prevent the HW from sending interrupts */
3998         bxe_int_disable(sc);
3999     }
4000
4001     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4002     /* make sure all ISRs are done */
4003
4004     /* XXX make sure sp_task is not running */
4005     /* cancel and flush work queues */
4006 }
4007
4008 static void
4009 bxe_chip_cleanup(struct bxe_softc *sc,
4010                  uint32_t         unload_mode,
4011                  uint8_t          keep_link)
4012 {
4013     int port = SC_PORT(sc);
4014     struct ecore_mcast_ramrod_params rparam = { NULL };
4015     uint32_t reset_code;
4016     int i, rc = 0;
4017
4018     bxe_drain_tx_queues(sc);
4019
4020     /* give HW time to discard old tx messages */
4021     DELAY(1000);
4022
4023     /* Clean all ETH MACs */
4024     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4025     if (rc < 0) {
4026         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4027     }
4028
4029     /* Clean up UC list  */
4030     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4031     if (rc < 0) {
4032         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4033     }
4034
4035     /* Disable LLH */
4036     if (!CHIP_IS_E1(sc)) {
4037         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4038     }
4039
4040     /* Set "drop all" to stop Rx */
4041
4042     /*
4043      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4044      * a race between the completion code and this code.
4045      */
4046     BXE_MCAST_LOCK(sc);
4047
4048     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4049         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4050     } else {
4051         bxe_set_storm_rx_mode(sc);
4052     }
4053
4054     /* Clean up multicast configuration */
4055     rparam.mcast_obj = &sc->mcast_obj;
4056     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4057     if (rc < 0) {
4058         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4059     }
4060
4061     BXE_MCAST_UNLOCK(sc);
4062
4063     // XXX bxe_iov_chip_cleanup(sc);
4064
4065     /*
4066      * Send the UNLOAD_REQUEST to the MCP. This will return if
4067      * this function should perform FUNCTION, PORT, or COMMON HW
4068      * reset.
4069      */
4070     reset_code = bxe_send_unload_req(sc, unload_mode);
4071
4072     /*
4073      * (assumption: No Attention from MCP at this stage)
4074      * PMF probably in the middle of TX disable/enable transaction
4075      */
4076     rc = bxe_func_wait_started(sc);
4077     if (rc) {
4078         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4079     }
4080
4081     /*
4082      * Close multi and leading connections
4083      * Completions for ramrods are collected in a synchronous way
4084      */
4085     for (i = 0; i < sc->num_queues; i++) {
4086         if (bxe_stop_queue(sc, i)) {
4087             goto unload_error;
4088         }
4089     }
4090
4091     /*
4092      * If SP settings didn't get completed so far - something
4093      * very wrong has happen.
4094      */
4095     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4096         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4097     }
4098
4099 unload_error:
4100
4101     rc = bxe_func_stop(sc);
4102     if (rc) {
4103         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4104     }
4105
4106     /* disable HW interrupts */
4107     bxe_int_disable_sync(sc, TRUE);
4108
4109     /* detach interrupts */
4110     bxe_interrupt_detach(sc);
4111
4112     /* Reset the chip */
4113     rc = bxe_reset_hw(sc, reset_code);
4114     if (rc) {
4115         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4116     }
4117
4118     /* Report UNLOAD_DONE to MCP */
4119     bxe_send_unload_done(sc, keep_link);
4120 }
4121
4122 static void
4123 bxe_disable_close_the_gate(struct bxe_softc *sc)
4124 {
4125     uint32_t val;
4126     int port = SC_PORT(sc);
4127
4128     BLOGD(sc, DBG_LOAD,
4129           "Disabling 'close the gates'\n");
4130
4131     if (CHIP_IS_E1(sc)) {
4132         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4133                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4134         val = REG_RD(sc, addr);
4135         val &= ~(0x300);
4136         REG_WR(sc, addr, val);
4137     } else {
4138         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4139         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4140                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4141         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4142     }
4143 }
4144
4145 /*
4146  * Cleans the object that have internal lists without sending
4147  * ramrods. Should be run when interrutps are disabled.
4148  */
4149 static void
4150 bxe_squeeze_objects(struct bxe_softc *sc)
4151 {
4152     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4153     struct ecore_mcast_ramrod_params rparam = { NULL };
4154     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4155     int rc;
4156
4157     /* Cleanup MACs' object first... */
4158
4159     /* Wait for completion of requested */
4160     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4161     /* Perform a dry cleanup */
4162     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4163
4164     /* Clean ETH primary MAC */
4165     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4166     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4167                              &ramrod_flags);
4168     if (rc != 0) {
4169         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4170     }
4171
4172     /* Cleanup UC list */
4173     vlan_mac_flags = 0;
4174     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4175     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4176                              &ramrod_flags);
4177     if (rc != 0) {
4178         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4179     }
4180
4181     /* Now clean mcast object... */
4182
4183     rparam.mcast_obj = &sc->mcast_obj;
4184     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4185
4186     /* Add a DEL command... */
4187     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4188     if (rc < 0) {
4189         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4190     }
4191
4192     /* now wait until all pending commands are cleared */
4193
4194     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4195     while (rc != 0) {
4196         if (rc < 0) {
4197             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4198             return;
4199         }
4200
4201         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4202     }
4203 }
4204
4205 /* stop the controller */
4206 static __noinline int
4207 bxe_nic_unload(struct bxe_softc *sc,
4208                uint32_t         unload_mode,
4209                uint8_t          keep_link)
4210 {
4211     uint8_t global = FALSE;
4212     uint32_t val;
4213     int i;
4214
4215     BXE_CORE_LOCK_ASSERT(sc);
4216
4217     sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
4218
4219     for (i = 0; i < sc->num_queues; i++) {
4220         struct bxe_fastpath *fp;
4221
4222         fp = &sc->fp[i];
4223         BXE_FP_TX_LOCK(fp);
4224         BXE_FP_TX_UNLOCK(fp);
4225     }
4226
4227     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4228
4229     /* mark driver as unloaded in shmem2 */
4230     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4231         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4232         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4233                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4234     }
4235
4236     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4237         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4238         /*
4239          * We can get here if the driver has been unloaded
4240          * during parity error recovery and is either waiting for a
4241          * leader to complete or for other functions to unload and
4242          * then ifconfig down has been issued. In this case we want to
4243          * unload and let other functions to complete a recovery
4244          * process.
4245          */
4246         sc->recovery_state = BXE_RECOVERY_DONE;
4247         sc->is_leader = 0;
4248         bxe_release_leader_lock(sc);
4249         mb();
4250
4251         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4252         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4253             " state = 0x%x\n", sc->recovery_state, sc->state);
4254         return (-1);
4255     }
4256
4257     /*
4258      * Nothing to do during unload if previous bxe_nic_load()
4259      * did not completed succesfully - all resourses are released.
4260      */
4261     if ((sc->state == BXE_STATE_CLOSED) ||
4262         (sc->state == BXE_STATE_ERROR)) {
4263         return (0);
4264     }
4265
4266     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4267     mb();
4268
4269     /* stop tx */
4270     bxe_tx_disable(sc);
4271
4272     sc->rx_mode = BXE_RX_MODE_NONE;
4273     /* XXX set rx mode ??? */
4274
4275     if (IS_PF(sc) && !sc->grcdump_done) {
4276         /* set ALWAYS_ALIVE bit in shmem */
4277         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4278
4279         bxe_drv_pulse(sc);
4280
4281         bxe_stats_handle(sc, STATS_EVENT_STOP);
4282         bxe_save_statistics(sc);
4283     }
4284
4285     /* wait till consumers catch up with producers in all queues */
4286     bxe_drain_tx_queues(sc);
4287
4288     /* if VF indicate to PF this function is going down (PF will delete sp
4289      * elements and clear initializations
4290      */
4291     if (IS_VF(sc)) {
4292         ; /* bxe_vfpf_close_vf(sc); */
4293     } else if (unload_mode != UNLOAD_RECOVERY) {
4294         /* if this is a normal/close unload need to clean up chip */
4295         if (!sc->grcdump_done)
4296             bxe_chip_cleanup(sc, unload_mode, keep_link);
4297     } else {
4298         /* Send the UNLOAD_REQUEST to the MCP */
4299         bxe_send_unload_req(sc, unload_mode);
4300
4301         /*
4302          * Prevent transactions to host from the functions on the
4303          * engine that doesn't reset global blocks in case of global
4304          * attention once gloabl blocks are reset and gates are opened
4305          * (the engine which leader will perform the recovery
4306          * last).
4307          */
4308         if (!CHIP_IS_E1x(sc)) {
4309             bxe_pf_disable(sc);
4310         }
4311
4312         /* disable HW interrupts */
4313         bxe_int_disable_sync(sc, TRUE);
4314
4315         /* detach interrupts */
4316         bxe_interrupt_detach(sc);
4317
4318         /* Report UNLOAD_DONE to MCP */
4319         bxe_send_unload_done(sc, FALSE);
4320     }
4321
4322     /*
4323      * At this stage no more interrupts will arrive so we may safely clean
4324      * the queue'able objects here in case they failed to get cleaned so far.
4325      */
4326     if (IS_PF(sc)) {
4327         bxe_squeeze_objects(sc);
4328     }
4329
4330     /* There should be no more pending SP commands at this stage */
4331     sc->sp_state = 0;
4332
4333     sc->port.pmf = 0;
4334
4335     bxe_free_fp_buffers(sc);
4336
4337     if (IS_PF(sc)) {
4338         bxe_free_mem(sc);
4339     }
4340
4341     bxe_free_fw_stats_mem(sc);
4342
4343     sc->state = BXE_STATE_CLOSED;
4344
4345     /*
4346      * Check if there are pending parity attentions. If there are - set
4347      * RECOVERY_IN_PROGRESS.
4348      */
4349     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4350         bxe_set_reset_in_progress(sc);
4351
4352         /* Set RESET_IS_GLOBAL if needed */
4353         if (global) {
4354             bxe_set_reset_global(sc);
4355         }
4356     }
4357
4358     /*
4359      * The last driver must disable a "close the gate" if there is no
4360      * parity attention or "process kill" pending.
4361      */
4362     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4363         bxe_reset_is_done(sc, SC_PATH(sc))) {
4364         bxe_disable_close_the_gate(sc);
4365     }
4366
4367     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4368
4369     return (0);
4370 }
4371
4372 /*
4373  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4374  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4375  */
4376 static int
4377 bxe_ifmedia_update(struct ifnet *ifp)
4378 {
4379     struct bxe_softc *sc = (struct bxe_softc *)ifp->if_softc;
4380     struct ifmedia *ifm;
4381
4382     ifm = &sc->ifmedia;
4383
4384     /* We only support Ethernet media type. */
4385     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4386         return (EINVAL);
4387     }
4388
4389     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4390     case IFM_AUTO:
4391          break;
4392     case IFM_10G_CX4:
4393     case IFM_10G_SR:
4394     case IFM_10G_T:
4395     case IFM_10G_TWINAX:
4396     default:
4397         /* We don't support changing the media type. */
4398         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4399               IFM_SUBTYPE(ifm->ifm_media));
4400         return (EINVAL);
4401     }
4402
4403     return (0);
4404 }
4405
4406 /*
4407  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4408  */
4409 static void
4410 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4411 {
4412     struct bxe_softc *sc = ifp->if_softc;
4413
4414     /* Report link down if the driver isn't running. */
4415     if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4416         ifmr->ifm_active |= IFM_NONE;
4417         return;
4418     }
4419
4420     /* Setup the default interface info. */
4421     ifmr->ifm_status = IFM_AVALID;
4422     ifmr->ifm_active = IFM_ETHER;
4423
4424     if (sc->link_vars.link_up) {
4425         ifmr->ifm_status |= IFM_ACTIVE;
4426     } else {
4427         ifmr->ifm_active |= IFM_NONE;
4428         return;
4429     }
4430
4431     ifmr->ifm_active |= sc->media;
4432
4433     if (sc->link_vars.duplex == DUPLEX_FULL) {
4434         ifmr->ifm_active |= IFM_FDX;
4435     } else {
4436         ifmr->ifm_active |= IFM_HDX;
4437     }
4438 }
4439
4440 static int
4441 bxe_ioctl_nvram(struct bxe_softc *sc,
4442                 uint32_t         priv_op,
4443                 struct ifreq     *ifr)
4444 {
4445     struct bxe_nvram_data nvdata_base;
4446     struct bxe_nvram_data *nvdata;
4447     int len;
4448     int error = 0;
4449
4450     copyin(ifr->ifr_data, &nvdata_base, sizeof(nvdata_base));
4451
4452     len = (sizeof(struct bxe_nvram_data) +
4453            nvdata_base.len -
4454            sizeof(uint32_t));
4455
4456     if (len > sizeof(struct bxe_nvram_data)) {
4457         if ((nvdata = (struct bxe_nvram_data *)
4458                  malloc(len, M_DEVBUF,
4459                         (M_NOWAIT | M_ZERO))) == NULL) {
4460             BLOGE(sc, "BXE_IOC_RD_NVRAM malloc failed priv_op 0x%x "
4461                 " len = 0x%x\n", priv_op, len);
4462             return (1);
4463         }
4464         memcpy(nvdata, &nvdata_base, sizeof(struct bxe_nvram_data));
4465     } else {
4466         nvdata = &nvdata_base;
4467     }
4468
4469     if (priv_op == BXE_IOC_RD_NVRAM) {
4470         BLOGD(sc, DBG_IOCTL, "IOC_RD_NVRAM 0x%x %d\n",
4471               nvdata->offset, nvdata->len);
4472         error = bxe_nvram_read(sc,
4473                                nvdata->offset,
4474                                (uint8_t *)nvdata->value,
4475                                nvdata->len);
4476         copyout(nvdata, ifr->ifr_data, len);
4477     } else { /* BXE_IOC_WR_NVRAM */
4478         BLOGD(sc, DBG_IOCTL, "IOC_WR_NVRAM 0x%x %d\n",
4479               nvdata->offset, nvdata->len);
4480         copyin(ifr->ifr_data, nvdata, len);
4481         error = bxe_nvram_write(sc,
4482                                 nvdata->offset,
4483                                 (uint8_t *)nvdata->value,
4484                                 nvdata->len);
4485     }
4486
4487     if (len > sizeof(struct bxe_nvram_data)) {
4488         free(nvdata, M_DEVBUF);
4489     }
4490
4491     return (error);
4492 }
4493
4494 static int
4495 bxe_ioctl_stats_show(struct bxe_softc *sc,
4496                      uint32_t         priv_op,
4497                      struct ifreq     *ifr)
4498 {
4499     const size_t str_size   = (BXE_NUM_ETH_STATS * STAT_NAME_LEN);
4500     const size_t stats_size = (BXE_NUM_ETH_STATS * sizeof(uint64_t));
4501     caddr_t p_tmp;
4502     uint32_t *offset;
4503     int i;
4504
4505     switch (priv_op)
4506     {
4507     case BXE_IOC_STATS_SHOW_NUM:
4508         memset(ifr->ifr_data, 0, sizeof(union bxe_stats_show_data));
4509         ((union bxe_stats_show_data *)ifr->ifr_data)->desc.num =
4510             BXE_NUM_ETH_STATS;
4511         ((union bxe_stats_show_data *)ifr->ifr_data)->desc.len =
4512             STAT_NAME_LEN;
4513         return (0);
4514
4515     case BXE_IOC_STATS_SHOW_STR:
4516         memset(ifr->ifr_data, 0, str_size);
4517         p_tmp = ifr->ifr_data;
4518         for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4519             strcpy(p_tmp, bxe_eth_stats_arr[i].string);
4520             p_tmp += STAT_NAME_LEN;
4521         }
4522         return (0);
4523
4524     case BXE_IOC_STATS_SHOW_CNT:
4525         memset(ifr->ifr_data, 0, stats_size);
4526         p_tmp = ifr->ifr_data;
4527         for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4528             offset = ((uint32_t *)&sc->eth_stats +
4529                       bxe_eth_stats_arr[i].offset);
4530             switch (bxe_eth_stats_arr[i].size) {
4531             case 4:
4532                 *((uint64_t *)p_tmp) = (uint64_t)*offset;
4533                 break;
4534             case 8:
4535                 *((uint64_t *)p_tmp) = HILO_U64(*offset, *(offset + 1));
4536                 break;
4537             default:
4538                 *((uint64_t *)p_tmp) = 0;
4539             }
4540             p_tmp += sizeof(uint64_t);
4541         }
4542         return (0);
4543
4544     default:
4545         return (-1);
4546     }
4547 }
4548
4549 static void
4550 bxe_handle_chip_tq(void *context,
4551                    int  pending)
4552 {
4553     struct bxe_softc *sc = (struct bxe_softc *)context;
4554     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4555
4556     switch (work)
4557     {
4558     case CHIP_TQ_REINIT:
4559         if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
4560             /* restart the interface */
4561             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4562             bxe_periodic_stop(sc);
4563             BXE_CORE_LOCK(sc);
4564             bxe_stop_locked(sc);
4565             bxe_init_locked(sc);
4566             BXE_CORE_UNLOCK(sc);
4567         }
4568         break;
4569
4570     default:
4571         break;
4572     }
4573 }
4574
4575 /*
4576  * Handles any IOCTL calls from the operating system.
4577  *
4578  * Returns:
4579  *   0 = Success, >0 Failure
4580  */
4581 static int
4582 bxe_ioctl(struct ifnet *ifp,
4583           u_long       command,
4584           caddr_t      data)
4585 {
4586     struct bxe_softc *sc = ifp->if_softc;
4587     struct ifreq *ifr = (struct ifreq *)data;
4588     struct bxe_nvram_data *nvdata;
4589     uint32_t priv_op;
4590     int mask = 0;
4591     int reinit = 0;
4592     int error = 0;
4593
4594     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4595     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4596
4597     switch (command)
4598     {
4599     case SIOCSIFMTU:
4600         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4601               ifr->ifr_mtu);
4602
4603         if (sc->mtu == ifr->ifr_mtu) {
4604             /* nothing to change */
4605             break;
4606         }
4607
4608         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4609             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4610                   ifr->ifr_mtu, mtu_min, mtu_max);
4611             error = EINVAL;
4612             break;
4613         }
4614
4615         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4616                              (unsigned long)ifr->ifr_mtu);
4617         atomic_store_rel_long((volatile unsigned long *)&ifp->if_mtu,
4618                               (unsigned long)ifr->ifr_mtu);
4619
4620         reinit = 1;
4621         break;
4622
4623     case SIOCSIFFLAGS:
4624         /* toggle the interface state up or down */
4625         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4626
4627         BXE_CORE_LOCK(sc);
4628         /* check if the interface is up */
4629         if (ifp->if_flags & IFF_UP) {
4630             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4631                 /* set the receive mode flags */
4632                 bxe_set_rx_mode(sc);
4633             } else if(sc->state != BXE_STATE_DISABLED) {
4634                 bxe_init_locked(sc);
4635             }
4636         } else {
4637             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4638                 bxe_periodic_stop(sc);
4639                 bxe_stop_locked(sc);
4640             }
4641         }
4642         BXE_CORE_UNLOCK(sc);
4643
4644         break;
4645
4646     case SIOCADDMULTI:
4647     case SIOCDELMULTI:
4648         /* add/delete multicast addresses */
4649         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4650
4651         /* check if the interface is up */
4652         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4653             /* set the receive mode flags */
4654             BXE_CORE_LOCK(sc);
4655             bxe_set_rx_mode(sc);
4656             BXE_CORE_UNLOCK(sc); 
4657         }
4658
4659         break;
4660
4661     case SIOCSIFCAP:
4662         /* find out which capabilities have changed */
4663         mask = (ifr->ifr_reqcap ^ ifp->if_capenable);
4664
4665         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4666               mask);
4667
4668         /* toggle the LRO capabilites enable flag */
4669         if (mask & IFCAP_LRO) {
4670             ifp->if_capenable ^= IFCAP_LRO;
4671             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4672                   (ifp->if_capenable & IFCAP_LRO) ? "ON" : "OFF");
4673             reinit = 1;
4674         }
4675
4676         /* toggle the TXCSUM checksum capabilites enable flag */
4677         if (mask & IFCAP_TXCSUM) {
4678             ifp->if_capenable ^= IFCAP_TXCSUM;
4679             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4680                   (ifp->if_capenable & IFCAP_TXCSUM) ? "ON" : "OFF");
4681             if (ifp->if_capenable & IFCAP_TXCSUM) {
4682                 ifp->if_hwassist = (CSUM_IP       |
4683                                     CSUM_TCP      |
4684                                     CSUM_UDP      |
4685                                     CSUM_TSO      |
4686                                     CSUM_TCP_IPV6 |
4687                                     CSUM_UDP_IPV6);
4688             } else {
4689                 ifp->if_hwassist = 0;
4690             }
4691         }
4692
4693         /* toggle the RXCSUM checksum capabilities enable flag */
4694         if (mask & IFCAP_RXCSUM) {
4695             ifp->if_capenable ^= IFCAP_RXCSUM;
4696             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4697                   (ifp->if_capenable & IFCAP_RXCSUM) ? "ON" : "OFF");
4698             if (ifp->if_capenable & IFCAP_RXCSUM) {
4699                 ifp->if_hwassist = (CSUM_IP       |
4700                                     CSUM_TCP      |
4701                                     CSUM_UDP      |
4702                                     CSUM_TSO      |
4703                                     CSUM_TCP_IPV6 |
4704                                     CSUM_UDP_IPV6);
4705             } else {
4706                 ifp->if_hwassist = 0;
4707             }
4708         }
4709
4710         /* toggle TSO4 capabilities enabled flag */
4711         if (mask & IFCAP_TSO4) {
4712             ifp->if_capenable ^= IFCAP_TSO4;
4713             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4714                   (ifp->if_capenable & IFCAP_TSO4) ? "ON" : "OFF");
4715         }
4716
4717         /* toggle TSO6 capabilities enabled flag */
4718         if (mask & IFCAP_TSO6) {
4719             ifp->if_capenable ^= IFCAP_TSO6;
4720             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4721                   (ifp->if_capenable & IFCAP_TSO6) ? "ON" : "OFF");
4722         }
4723
4724         /* toggle VLAN_HWTSO capabilities enabled flag */
4725         if (mask & IFCAP_VLAN_HWTSO) {
4726             ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
4727             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4728                   (ifp->if_capenable & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4729         }
4730
4731         /* toggle VLAN_HWCSUM capabilities enabled flag */
4732         if (mask & IFCAP_VLAN_HWCSUM) {
4733             /* XXX investigate this... */
4734             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4735             error = EINVAL;
4736         }
4737
4738         /* toggle VLAN_MTU capabilities enable flag */
4739         if (mask & IFCAP_VLAN_MTU) {
4740             /* XXX investigate this... */
4741             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4742             error = EINVAL;
4743         }
4744
4745         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4746         if (mask & IFCAP_VLAN_HWTAGGING) {
4747             /* XXX investigate this... */
4748             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4749             error = EINVAL;
4750         }
4751
4752         /* toggle VLAN_HWFILTER capabilities enabled flag */
4753         if (mask & IFCAP_VLAN_HWFILTER) {
4754             /* XXX investigate this... */
4755             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4756             error = EINVAL;
4757         }
4758
4759         /* XXX not yet...
4760          * IFCAP_WOL_MAGIC
4761          */
4762
4763         break;
4764
4765     case SIOCSIFMEDIA:
4766     case SIOCGIFMEDIA:
4767         /* set/get interface media */
4768         BLOGD(sc, DBG_IOCTL,
4769               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4770               (command & 0xff));
4771         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4772         break;
4773
4774     case SIOCGPRIVATE_0:
4775         copyin(ifr->ifr_data, &priv_op, sizeof(priv_op));
4776
4777         switch (priv_op)
4778         {
4779         case BXE_IOC_RD_NVRAM:
4780         case BXE_IOC_WR_NVRAM:
4781             nvdata = (struct bxe_nvram_data *)ifr->ifr_data;
4782             BLOGD(sc, DBG_IOCTL,
4783                   "Received Private NVRAM ioctl addr=0x%x size=%u\n",
4784                   nvdata->offset, nvdata->len);
4785             error = bxe_ioctl_nvram(sc, priv_op, ifr);
4786             break;
4787
4788         case BXE_IOC_STATS_SHOW_NUM:
4789         case BXE_IOC_STATS_SHOW_STR:
4790         case BXE_IOC_STATS_SHOW_CNT:
4791             BLOGD(sc, DBG_IOCTL, "Received Private Stats ioctl (%d)\n",
4792                   priv_op);
4793             error = bxe_ioctl_stats_show(sc, priv_op, ifr);
4794             break;
4795
4796         default:
4797             BLOGW(sc, "Received Private Unknown ioctl (%d)\n", priv_op);
4798             error = EINVAL;
4799             break;
4800         }
4801
4802         break;
4803
4804     default:
4805         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4806               (command & 0xff));
4807         error = ether_ioctl(ifp, command, data);
4808         break;
4809     }
4810
4811     if (reinit && (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
4812         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4813               "Re-initializing hardware from IOCTL change\n");
4814         bxe_periodic_stop(sc);
4815         BXE_CORE_LOCK(sc);
4816         bxe_stop_locked(sc);
4817         bxe_init_locked(sc);
4818         BXE_CORE_UNLOCK(sc);
4819     }
4820
4821     return (error);
4822 }
4823
4824 static __noinline void
4825 bxe_dump_mbuf(struct bxe_softc *sc,
4826               struct mbuf      *m,
4827               uint8_t          contents)
4828 {
4829     char * type;
4830     int i = 0;
4831
4832     if (!(sc->debug & DBG_MBUF)) {
4833         return;
4834     }
4835
4836     if (m == NULL) {
4837         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4838         return;
4839     }
4840
4841     while (m) {
4842
4843 #if __FreeBSD_version >= 1000000
4844         BLOGD(sc, DBG_MBUF,
4845               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4846               i, m, m->m_len, m->m_flags,
4847               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4848
4849         if (m->m_flags & M_PKTHDR) {
4850              BLOGD(sc, DBG_MBUF,
4851                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4852                    i, m->m_pkthdr.len, m->m_flags,
4853                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4854                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4855                    "\22M_PROMISC\23M_NOFREE",
4856                    (int)m->m_pkthdr.csum_flags,
4857                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4858                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4859                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4860                    "\14CSUM_PSEUDO_HDR");
4861         }
4862 #else
4863         BLOGD(sc, DBG_MBUF,
4864               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4865               i, m, m->m_len, m->m_flags,
4866               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4867
4868         if (m->m_flags & M_PKTHDR) {
4869              BLOGD(sc, DBG_MBUF,
4870                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4871                    i, m->m_pkthdr.len, m->m_flags,
4872                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4873                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4874                    "\22M_PROMISC\23M_NOFREE",
4875                    (int)m->m_pkthdr.csum_flags,
4876                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4877                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4878                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4879                    "\14CSUM_PSEUDO_HDR");
4880         }
4881 #endif /* #if __FreeBSD_version >= 1000000 */
4882
4883         if (m->m_flags & M_EXT) {
4884             switch (m->m_ext.ext_type) {
4885             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4886             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4887             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4888             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4889             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4890             case EXT_PACKET:     type = "EXT_PACKET";     break;
4891             case EXT_MBUF:       type = "EXT_MBUF";       break;
4892             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4893             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4894             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4895             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4896             default:             type = "UNKNOWN";        break;
4897             }
4898
4899             BLOGD(sc, DBG_MBUF,
4900                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4901                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4902         }
4903
4904         if (contents) {
4905             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4906         }
4907
4908         m = m->m_next;
4909         i++;
4910     }
4911 }
4912
4913 /*
4914  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4915  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4916  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4917  * The headers comes in a seperate bd in FreeBSD so 13-3=10.
4918  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4919  */
4920 static int
4921 bxe_chktso_window(struct bxe_softc  *sc,
4922                   int               nsegs,
4923                   bus_dma_segment_t *segs,
4924                   struct mbuf       *m)
4925 {
4926     uint32_t num_wnds, wnd_size, wnd_sum;
4927     int32_t frag_idx, wnd_idx;
4928     unsigned short lso_mss;
4929     int defrag;
4930
4931     defrag = 0;
4932     wnd_sum = 0;
4933     wnd_size = 10;
4934     num_wnds = nsegs - wnd_size;
4935     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4936
4937     /*
4938      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4939      * first window sum of data while skipping the first assuming it is the
4940      * header in FreeBSD.
4941      */
4942     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4943         wnd_sum += htole16(segs[frag_idx].ds_len);
4944     }
4945
4946     /* check the first 10 bd window size */
4947     if (wnd_sum < lso_mss) {
4948         return (1);
4949     }
4950
4951     /* run through the windows */
4952     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4953         /* subtract the first mbuf->m_len of the last wndw(-header) */
4954         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4955         /* add the next mbuf len to the len of our new window */
4956         wnd_sum += htole16(segs[frag_idx].ds_len);
4957         if (wnd_sum < lso_mss) {
4958             return (1);
4959         }
4960     }
4961
4962     return (0);
4963 }
4964
4965 static uint8_t
4966 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4967                     struct mbuf         *m,
4968                     uint32_t            *parsing_data)
4969 {
4970     struct ether_vlan_header *eh = NULL;
4971     struct ip *ip4 = NULL;
4972     struct ip6_hdr *ip6 = NULL;
4973     caddr_t ip = NULL;
4974     struct tcphdr *th = NULL;
4975     int e_hlen, ip_hlen, l4_off;
4976     uint16_t proto;
4977
4978     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4979         /* no L4 checksum offload needed */
4980         return (0);
4981     }
4982
4983     /* get the Ethernet header */
4984     eh = mtod(m, struct ether_vlan_header *);
4985
4986     /* handle VLAN encapsulation if present */
4987     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4988         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4989         proto  = ntohs(eh->evl_proto);
4990     } else {
4991         e_hlen = ETHER_HDR_LEN;
4992         proto  = ntohs(eh->evl_encap_proto);
4993     }
4994
4995     switch (proto) {
4996     case ETHERTYPE_IP:
4997         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4998         ip4 = (m->m_len < sizeof(struct ip)) ?
4999                   (struct ip *)m->m_next->m_data :
5000                   (struct ip *)(m->m_data + e_hlen);
5001         /* ip_hl is number of 32-bit words */
5002         ip_hlen = (ip4->ip_hl << 2);
5003         ip = (caddr_t)ip4;
5004         break;
5005     case ETHERTYPE_IPV6:
5006         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
5007         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
5008                   (struct ip6_hdr *)m->m_next->m_data :
5009                   (struct ip6_hdr *)(m->m_data + e_hlen);
5010         /* XXX cannot support offload with IPv6 extensions */
5011         ip_hlen = sizeof(struct ip6_hdr);
5012         ip = (caddr_t)ip6;
5013         break;
5014     default:
5015         /* We can't offload in this case... */
5016         /* XXX error stat ??? */
5017         return (0);
5018     }
5019
5020     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5021     l4_off = (e_hlen + ip_hlen);
5022
5023     *parsing_data |=
5024         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
5025          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
5026
5027     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5028                                   CSUM_TSO |
5029                                   CSUM_TCP_IPV6)) {
5030         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5031         th = (struct tcphdr *)(ip + ip_hlen);
5032         /* th_off is number of 32-bit words */
5033         *parsing_data |= ((th->th_off <<
5034                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
5035                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
5036         return (l4_off + (th->th_off << 2)); /* entire header length */
5037     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5038                                          CSUM_UDP_IPV6)) {
5039         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5040         return (l4_off + sizeof(struct udphdr)); /* entire header length */
5041     } else {
5042         /* XXX error stat ??? */
5043         return (0);
5044     }
5045 }
5046
5047 static uint8_t
5048 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
5049                  struct mbuf                *m,
5050                  struct eth_tx_parse_bd_e1x *pbd)
5051 {
5052     struct ether_vlan_header *eh = NULL;
5053     struct ip *ip4 = NULL;
5054     struct ip6_hdr *ip6 = NULL;
5055     caddr_t ip = NULL;
5056     struct tcphdr *th = NULL;
5057     struct udphdr *uh = NULL;
5058     int e_hlen, ip_hlen;
5059     uint16_t proto;
5060     uint8_t hlen;
5061     uint16_t tmp_csum;
5062     uint32_t *tmp_uh;
5063
5064     /* get the Ethernet header */
5065     eh = mtod(m, struct ether_vlan_header *);
5066
5067     /* handle VLAN encapsulation if present */
5068     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
5069         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
5070         proto  = ntohs(eh->evl_proto);
5071     } else {
5072         e_hlen = ETHER_HDR_LEN;
5073         proto  = ntohs(eh->evl_encap_proto);
5074     }
5075
5076     switch (proto) {
5077     case ETHERTYPE_IP:
5078         /* get the IP header, if mbuf len < 20 then header in next mbuf */
5079         ip4 = (m->m_len < sizeof(struct ip)) ?
5080                   (struct ip *)m->m_next->m_data :
5081                   (struct ip *)(m->m_data + e_hlen);
5082         /* ip_hl is number of 32-bit words */
5083         ip_hlen = (ip4->ip_hl << 1);
5084         ip = (caddr_t)ip4;
5085         break;
5086     case ETHERTYPE_IPV6:
5087         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
5088         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
5089                   (struct ip6_hdr *)m->m_next->m_data :
5090                   (struct ip6_hdr *)(m->m_data + e_hlen);
5091         /* XXX cannot support offload with IPv6 extensions */
5092         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
5093         ip = (caddr_t)ip6;
5094         break;
5095     default:
5096         /* We can't offload in this case... */
5097         /* XXX error stat ??? */
5098         return (0);
5099     }
5100
5101     hlen = (e_hlen >> 1);
5102
5103     /* note that rest of global_data is indirectly zeroed here */
5104     if (m->m_flags & M_VLANTAG) {
5105         pbd->global_data =
5106             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
5107     } else {
5108         pbd->global_data = htole16(hlen);
5109     }
5110
5111     pbd->ip_hlen_w = ip_hlen;
5112
5113     hlen += pbd->ip_hlen_w;
5114
5115     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5116
5117     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5118                                   CSUM_TSO |
5119                                   CSUM_TCP_IPV6)) {
5120         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5121         /* th_off is number of 32-bit words */
5122         hlen += (uint16_t)(th->th_off << 1);
5123     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5124                                          CSUM_UDP_IPV6)) {
5125         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5126         hlen += (sizeof(struct udphdr) / 2);
5127     } else {
5128         /* valid case as only CSUM_IP was set */
5129         return (0);
5130     }
5131
5132     pbd->total_hlen_w = htole16(hlen);
5133
5134     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5135                                   CSUM_TSO |
5136                                   CSUM_TCP_IPV6)) {
5137         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5138         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5139     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5140                                          CSUM_UDP_IPV6)) {
5141         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5142
5143         /*
5144          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5145          * checksums and does not know anything about the UDP header and where
5146          * the checksum field is located. It only knows about TCP. Therefore
5147          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5148          * offload. Since the checksum field offset for TCP is 16 bytes and
5149          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5150          * bytes less than the start of the UDP header. This allows the
5151          * hardware to write the checksum in the correct spot. But the
5152          * hardware will compute a checksum which includes the last 10 bytes
5153          * of the IP header. To correct this we tweak the stack computed
5154          * pseudo checksum by folding in the calculation of the inverse
5155          * checksum for those final 10 bytes of the IP header. This allows
5156          * the correct checksum to be computed by the hardware.
5157          */
5158
5159         /* set pointer 10 bytes before UDP header */
5160         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5161
5162         /* calculate a pseudo header checksum over the first 10 bytes */
5163         tmp_csum = in_pseudo(*tmp_uh,
5164                              *(tmp_uh + 1),
5165                              *(uint16_t *)(tmp_uh + 2));
5166
5167         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5168     }
5169
5170     return (hlen * 2); /* entire header length, number of bytes */
5171 }
5172
5173 static void
5174 bxe_set_pbd_lso_e2(struct mbuf *m,
5175                    uint32_t    *parsing_data)
5176 {
5177     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5178                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5179                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5180
5181     /* XXX test for IPv6 with extension header... */
5182 }
5183
5184 static void
5185 bxe_set_pbd_lso(struct mbuf                *m,
5186                 struct eth_tx_parse_bd_e1x *pbd)
5187 {
5188     struct ether_vlan_header *eh = NULL;
5189     struct ip *ip = NULL;
5190     struct tcphdr *th = NULL;
5191     int e_hlen;
5192
5193     /* get the Ethernet header */
5194     eh = mtod(m, struct ether_vlan_header *);
5195
5196     /* handle VLAN encapsulation if present */
5197     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5198                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5199
5200     /* get the IP and TCP header, with LSO entire header in first mbuf */
5201     /* XXX assuming IPv4 */
5202     ip = (struct ip *)(m->m_data + e_hlen);
5203     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5204
5205     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5206     pbd->tcp_send_seq = ntohl(th->th_seq);
5207     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5208
5209 #if 1
5210         /* XXX IPv4 */
5211         pbd->ip_id = ntohs(ip->ip_id);
5212         pbd->tcp_pseudo_csum =
5213             ntohs(in_pseudo(ip->ip_src.s_addr,
5214                             ip->ip_dst.s_addr,
5215                             htons(IPPROTO_TCP)));
5216 #else
5217         /* XXX IPv6 */
5218         pbd->tcp_pseudo_csum =
5219             ntohs(in_pseudo(&ip6->ip6_src,
5220                             &ip6->ip6_dst,
5221                             htons(IPPROTO_TCP)));
5222 #endif
5223
5224     pbd->global_data |=
5225         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5226 }
5227
5228 /*
5229  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5230  * visible to the controller.
5231  *
5232  * If an mbuf is submitted to this routine and cannot be given to the
5233  * controller (e.g. it has too many fragments) then the function may free
5234  * the mbuf and return to the caller.
5235  *
5236  * Returns:
5237  *   0 = Success, !0 = Failure
5238  *   Note the side effect that an mbuf may be freed if it causes a problem.
5239  */
5240 static int
5241 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5242 {
5243     bus_dma_segment_t segs[32];
5244     struct mbuf *m0;
5245     struct bxe_sw_tx_bd *tx_buf;
5246     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5247     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5248     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5249     struct eth_tx_bd *tx_data_bd;
5250     struct eth_tx_bd *tx_total_pkt_size_bd;
5251     struct eth_tx_start_bd *tx_start_bd;
5252     uint16_t bd_prod, pkt_prod, total_pkt_size;
5253     uint8_t mac_type;
5254     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5255     struct bxe_softc *sc;
5256     uint16_t tx_bd_avail;
5257     struct ether_vlan_header *eh;
5258     uint32_t pbd_e2_parsing_data = 0;
5259     uint8_t hlen = 0;
5260     int tmp_bd;
5261     int i;
5262
5263     sc = fp->sc;
5264
5265 #if __FreeBSD_version >= 800000
5266     M_ASSERTPKTHDR(*m_head);
5267 #endif /* #if __FreeBSD_version >= 800000 */
5268
5269     m0 = *m_head;
5270     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5271     tx_start_bd = NULL;
5272     tx_data_bd = NULL;
5273     tx_total_pkt_size_bd = NULL;
5274
5275     /* get the H/W pointer for packets and BDs */
5276     pkt_prod = fp->tx_pkt_prod;
5277     bd_prod = fp->tx_bd_prod;
5278
5279     mac_type = UNICAST_ADDRESS;
5280
5281     /* map the mbuf into the next open DMAable memory */
5282     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5283     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5284                                     tx_buf->m_map, m0,
5285                                     segs, &nsegs, BUS_DMA_NOWAIT);
5286
5287     /* mapping errors */
5288     if(__predict_false(error != 0)) {
5289         fp->eth_q_stats.tx_dma_mapping_failure++;
5290         if (error == ENOMEM) {
5291             /* resource issue, try again later */
5292             rc = ENOMEM;
5293         } else if (error == EFBIG) {
5294             /* possibly recoverable with defragmentation */
5295             fp->eth_q_stats.mbuf_defrag_attempts++;
5296             m0 = m_defrag(*m_head, M_DONTWAIT);
5297             if (m0 == NULL) {
5298                 fp->eth_q_stats.mbuf_defrag_failures++;
5299                 rc = ENOBUFS;
5300             } else {
5301                 /* defrag successful, try mapping again */
5302                 *m_head = m0;
5303                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5304                                                 tx_buf->m_map, m0,
5305                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5306                 if (error) {
5307                     fp->eth_q_stats.tx_dma_mapping_failure++;
5308                     rc = error;
5309                 }
5310             }
5311         } else {
5312             /* unknown, unrecoverable mapping error */
5313             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5314             bxe_dump_mbuf(sc, m0, FALSE);
5315             rc = error;
5316         }
5317
5318         goto bxe_tx_encap_continue;
5319     }
5320
5321     tx_bd_avail = bxe_tx_avail(sc, fp);
5322
5323     /* make sure there is enough room in the send queue */
5324     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5325         /* Recoverable, try again later. */
5326         fp->eth_q_stats.tx_hw_queue_full++;
5327         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5328         rc = ENOMEM;
5329         goto bxe_tx_encap_continue;
5330     }
5331
5332     /* capture the current H/W TX chain high watermark */
5333     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5334                         (TX_BD_USABLE - tx_bd_avail))) {
5335         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5336     }
5337
5338     /* make sure it fits in the packet window */
5339     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5340         /*
5341          * The mbuf may be to big for the controller to handle. If the frame
5342          * is a TSO frame we'll need to do an additional check.
5343          */
5344         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5345             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5346                 goto bxe_tx_encap_continue; /* OK to send */
5347             } else {
5348                 fp->eth_q_stats.tx_window_violation_tso++;
5349             }
5350         } else {
5351             fp->eth_q_stats.tx_window_violation_std++;
5352         }
5353
5354         /* lets try to defragment this mbuf and remap it */
5355         fp->eth_q_stats.mbuf_defrag_attempts++;
5356         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5357
5358         m0 = m_defrag(*m_head, M_DONTWAIT);
5359         if (m0 == NULL) {
5360             fp->eth_q_stats.mbuf_defrag_failures++;
5361             /* Ugh, just drop the frame... :( */
5362             rc = ENOBUFS;
5363         } else {
5364             /* defrag successful, try mapping again */
5365             *m_head = m0;
5366             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5367                                             tx_buf->m_map, m0,
5368                                             segs, &nsegs, BUS_DMA_NOWAIT);
5369             if (error) {
5370                 fp->eth_q_stats.tx_dma_mapping_failure++;
5371                 /* No sense in trying to defrag/copy chain, drop it. :( */
5372                 rc = error;
5373             }
5374             else {
5375                 /* if the chain is still too long then drop it */
5376                 if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5377                     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5378                     rc = ENODEV;
5379                 }
5380             }
5381         }
5382     }
5383
5384 bxe_tx_encap_continue:
5385
5386     /* Check for errors */
5387     if (rc) {
5388         if (rc == ENOMEM) {
5389             /* recoverable try again later  */
5390         } else {
5391             fp->eth_q_stats.tx_soft_errors++;
5392             fp->eth_q_stats.mbuf_alloc_tx--;
5393             m_freem(*m_head);
5394             *m_head = NULL;
5395         }
5396
5397         return (rc);
5398     }
5399
5400     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5401     if (m0->m_flags & M_BCAST) {
5402         mac_type = BROADCAST_ADDRESS;
5403     } else if (m0->m_flags & M_MCAST) {
5404         mac_type = MULTICAST_ADDRESS;
5405     }
5406
5407     /* store the mbuf into the mbuf ring */
5408     tx_buf->m        = m0;
5409     tx_buf->first_bd = fp->tx_bd_prod;
5410     tx_buf->flags    = 0;
5411
5412     /* prepare the first transmit (start) BD for the mbuf */
5413     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5414
5415     BLOGD(sc, DBG_TX,
5416           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5417           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5418
5419     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5420     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5421     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5422     total_pkt_size += tx_start_bd->nbytes;
5423     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5424
5425     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5426
5427     /* all frames have at least Start BD + Parsing BD */
5428     nbds = nsegs + 1;
5429     tx_start_bd->nbd = htole16(nbds);
5430
5431     if (m0->m_flags & M_VLANTAG) {
5432         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5433         tx_start_bd->bd_flags.as_bitfield |=
5434             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5435     } else {
5436         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5437         if (IS_VF(sc)) {
5438             /* map ethernet header to find type and header length */
5439             eh = mtod(m0, struct ether_vlan_header *);
5440             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5441         } else {
5442             /* used by FW for packet accounting */
5443             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5444         }
5445     }
5446
5447     /*
5448      * add a parsing BD from the chain. The parsing BD is always added
5449      * though it is only used for TSO and chksum
5450      */
5451     bd_prod = TX_BD_NEXT(bd_prod);
5452
5453     if (m0->m_pkthdr.csum_flags) {
5454         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5455             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5456             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5457         }
5458
5459         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5460             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5461                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5462         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5463             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5464                                                   ETH_TX_BD_FLAGS_IS_UDP |
5465                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5466         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5467                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5468             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5469         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5470             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5471                                                   ETH_TX_BD_FLAGS_IS_UDP);
5472         }
5473     }
5474
5475     if (!CHIP_IS_E1x(sc)) {
5476         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5477         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5478
5479         if (m0->m_pkthdr.csum_flags) {
5480             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5481         }
5482
5483         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5484                  mac_type);
5485     } else {
5486         uint16_t global_data = 0;
5487
5488         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5489         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5490
5491         if (m0->m_pkthdr.csum_flags) {
5492             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5493         }
5494
5495         SET_FLAG(global_data,
5496                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5497         pbd_e1x->global_data |= htole16(global_data);
5498     }
5499
5500     /* setup the parsing BD with TSO specific info */
5501     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5502         fp->eth_q_stats.tx_ofld_frames_lso++;
5503         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5504
5505         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5506             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5507
5508             /* split the first BD into header/data making the fw job easy */
5509             nbds++;
5510             tx_start_bd->nbd = htole16(nbds);
5511             tx_start_bd->nbytes = htole16(hlen);
5512
5513             bd_prod = TX_BD_NEXT(bd_prod);
5514
5515             /* new transmit BD after the tx_parse_bd */
5516             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5517             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5518             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5519             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5520             if (tx_total_pkt_size_bd == NULL) {
5521                 tx_total_pkt_size_bd = tx_data_bd;
5522             }
5523
5524             BLOGD(sc, DBG_TX,
5525                   "TSO split header size is %d (%x:%x) nbds %d\n",
5526                   le16toh(tx_start_bd->nbytes),
5527                   le32toh(tx_start_bd->addr_hi),
5528                   le32toh(tx_start_bd->addr_lo),
5529                   nbds);
5530         }
5531
5532         if (!CHIP_IS_E1x(sc)) {
5533             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5534         } else {
5535             bxe_set_pbd_lso(m0, pbd_e1x);
5536         }
5537     }
5538
5539     if (pbd_e2_parsing_data) {
5540         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5541     }
5542
5543     /* prepare remaining BDs, start tx bd contains first seg/frag */
5544     for (i = 1; i < nsegs ; i++) {
5545         bd_prod = TX_BD_NEXT(bd_prod);
5546         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5547         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5548         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5549         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5550         if (tx_total_pkt_size_bd == NULL) {
5551             tx_total_pkt_size_bd = tx_data_bd;
5552         }
5553         total_pkt_size += tx_data_bd->nbytes;
5554     }
5555
5556     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5557
5558     if (tx_total_pkt_size_bd != NULL) {
5559         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5560     }
5561
5562     if (__predict_false(sc->debug & DBG_TX)) {
5563         tmp_bd = tx_buf->first_bd;
5564         for (i = 0; i < nbds; i++)
5565         {
5566             if (i == 0) {
5567                 BLOGD(sc, DBG_TX,
5568                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5569                       "bd_flags=0x%x hdr_nbds=%d\n",
5570                       tx_start_bd,
5571                       tmp_bd,
5572                       le16toh(tx_start_bd->nbd),
5573                       le16toh(tx_start_bd->vlan_or_ethertype),
5574                       tx_start_bd->bd_flags.as_bitfield,
5575                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5576             } else if (i == 1) {
5577                 if (pbd_e1x) {
5578                     BLOGD(sc, DBG_TX,
5579                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5580                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5581                           "tcp_seq=%u total_hlen_w=%u\n",
5582                           pbd_e1x,
5583                           tmp_bd,
5584                           pbd_e1x->global_data,
5585                           pbd_e1x->ip_hlen_w,
5586                           pbd_e1x->ip_id,
5587                           pbd_e1x->lso_mss,
5588                           pbd_e1x->tcp_flags,
5589                           pbd_e1x->tcp_pseudo_csum,
5590                           pbd_e1x->tcp_send_seq,
5591                           le16toh(pbd_e1x->total_hlen_w));
5592                 } else { /* if (pbd_e2) */
5593                     BLOGD(sc, DBG_TX,
5594                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5595                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5596                           pbd_e2,
5597                           tmp_bd,
5598                           pbd_e2->data.mac_addr.dst_hi,
5599                           pbd_e2->data.mac_addr.dst_mid,
5600                           pbd_e2->data.mac_addr.dst_lo,
5601                           pbd_e2->data.mac_addr.src_hi,
5602                           pbd_e2->data.mac_addr.src_mid,
5603                           pbd_e2->data.mac_addr.src_lo,
5604                           pbd_e2->parsing_data);
5605                 }
5606             }
5607
5608             if (i != 1) { /* skip parse db as it doesn't hold data */
5609                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5610                 BLOGD(sc, DBG_TX,
5611                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5612                       tx_data_bd,
5613                       tmp_bd,
5614                       le16toh(tx_data_bd->nbytes),
5615                       le32toh(tx_data_bd->addr_hi),
5616                       le32toh(tx_data_bd->addr_lo));
5617             }
5618
5619             tmp_bd = TX_BD_NEXT(tmp_bd);
5620         }
5621     }
5622
5623     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5624
5625     /* update TX BD producer index value for next TX */
5626     bd_prod = TX_BD_NEXT(bd_prod);
5627
5628     /*
5629      * If the chain of tx_bd's describing this frame is adjacent to or spans
5630      * an eth_tx_next_bd element then we need to increment the nbds value.
5631      */
5632     if (TX_BD_IDX(bd_prod) < nbds) {
5633         nbds++;
5634     }
5635
5636     /* don't allow reordering of writes for nbd and packets */
5637     mb();
5638
5639     fp->tx_db.data.prod += nbds;
5640
5641     /* producer points to the next free tx_bd at this point */
5642     fp->tx_pkt_prod++;
5643     fp->tx_bd_prod = bd_prod;
5644
5645     DOORBELL(sc, fp->index, fp->tx_db.raw);
5646
5647     fp->eth_q_stats.tx_pkts++;
5648
5649     /* Prevent speculative reads from getting ahead of the status block. */
5650     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5651                       0, 0, BUS_SPACE_BARRIER_READ);
5652
5653     /* Prevent speculative reads from getting ahead of the doorbell. */
5654     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5655                       0, 0, BUS_SPACE_BARRIER_READ);
5656
5657     return (0);
5658 }
5659
5660 static void
5661 bxe_tx_start_locked(struct bxe_softc    *sc,
5662                     struct ifnet        *ifp,
5663                     struct bxe_fastpath *fp)
5664 {
5665     struct mbuf *m = NULL;
5666     int tx_count = 0;
5667     uint16_t tx_bd_avail;
5668
5669     BXE_FP_TX_LOCK_ASSERT(fp);
5670
5671     /* keep adding entries while there are frames to send */
5672     while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
5673
5674         /*
5675          * check for any frames to send
5676          * dequeue can still be NULL even if queue is not empty
5677          */
5678         IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
5679         if (__predict_false(m == NULL)) {
5680             break;
5681         }
5682
5683         /* the mbuf now belongs to us */
5684         fp->eth_q_stats.mbuf_alloc_tx++;
5685
5686         /*
5687          * Put the frame into the transmit ring. If we don't have room,
5688          * place the mbuf back at the head of the TX queue, set the
5689          * OACTIVE flag, and wait for the NIC to drain the chain.
5690          */
5691         if (__predict_false(bxe_tx_encap(fp, &m))) {
5692             fp->eth_q_stats.tx_encap_failures++;
5693             if (m != NULL) {
5694                 /* mark the TX queue as full and return the frame */
5695                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5696                 IFQ_DRV_PREPEND(&ifp->if_snd, m);
5697                 fp->eth_q_stats.mbuf_alloc_tx--;
5698                 fp->eth_q_stats.tx_queue_xoff++;
5699             }
5700
5701             /* stop looking for more work */
5702             break;
5703         }
5704
5705         /* the frame was enqueued successfully */
5706         tx_count++;
5707
5708         /* send a copy of the frame to any BPF listeners. */
5709         BPF_MTAP(ifp, m);
5710
5711         tx_bd_avail = bxe_tx_avail(sc, fp);
5712
5713         /* handle any completions if we're running low */
5714         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5715             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5716             bxe_txeof(sc, fp);
5717             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5718                 break;
5719             }
5720         }
5721     }
5722
5723     /* all TX packets were dequeued and/or the tx ring is full */
5724     if (tx_count > 0) {
5725         /* reset the TX watchdog timeout timer */
5726         fp->watchdog_timer = BXE_TX_TIMEOUT;
5727     }
5728 }
5729
5730 /* Legacy (non-RSS) dispatch routine */
5731 static void
5732 bxe_tx_start(struct ifnet *ifp)
5733 {
5734     struct bxe_softc *sc;
5735     struct bxe_fastpath *fp;
5736
5737     sc = ifp->if_softc;
5738
5739     if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5740         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5741         return;
5742     }
5743
5744     if (!sc->link_vars.link_up) {
5745         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5746         return;
5747     }
5748
5749     fp = &sc->fp[0];
5750
5751     if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5752         fp->eth_q_stats.tx_queue_full_return++;
5753         return;
5754     }
5755
5756     BXE_FP_TX_LOCK(fp);
5757     bxe_tx_start_locked(sc, ifp, fp);
5758     BXE_FP_TX_UNLOCK(fp);
5759 }
5760
5761 #if __FreeBSD_version >= 800000
5762
5763 static int
5764 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5765                        struct ifnet        *ifp,
5766                        struct bxe_fastpath *fp,
5767                        struct mbuf         *m)
5768 {
5769     struct buf_ring *tx_br = fp->tx_br;
5770     struct mbuf *next;
5771     int depth, rc, tx_count;
5772     uint16_t tx_bd_avail;
5773
5774     rc = tx_count = 0;
5775
5776     BXE_FP_TX_LOCK_ASSERT(fp);
5777
5778     if (!tx_br) {
5779         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5780         return (EINVAL);
5781     }
5782
5783     if (!sc->link_vars.link_up ||
5784         (ifp->if_drv_flags &
5785         (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) != IFF_DRV_RUNNING) {
5786         rc = drbr_enqueue(ifp, tx_br, m);
5787         goto bxe_tx_mq_start_locked_exit;
5788     }
5789
5790     /* fetch the depth of the driver queue */
5791     depth = drbr_inuse(ifp, tx_br);
5792     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5793         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5794     }
5795
5796     if (m == NULL) {
5797         /* no new work, check for pending frames */
5798         next = drbr_dequeue(ifp, tx_br);
5799     } else if (drbr_needs_enqueue(ifp, tx_br)) {
5800         /* have both new and pending work, maintain packet order */
5801         rc = drbr_enqueue(ifp, tx_br, m);
5802         if (rc != 0) {
5803             fp->eth_q_stats.tx_soft_errors++;
5804             goto bxe_tx_mq_start_locked_exit;
5805         }
5806         next = drbr_dequeue(ifp, tx_br);
5807     } else {
5808         /* new work only and nothing pending */
5809         next = m;
5810     }
5811
5812     /* keep adding entries while there are frames to send */
5813     while (next != NULL) {
5814
5815         /* the mbuf now belongs to us */
5816         fp->eth_q_stats.mbuf_alloc_tx++;
5817
5818         /*
5819          * Put the frame into the transmit ring. If we don't have room,
5820          * place the mbuf back at the head of the TX queue, set the
5821          * OACTIVE flag, and wait for the NIC to drain the chain.
5822          */
5823         rc = bxe_tx_encap(fp, &next);
5824         if (__predict_false(rc != 0)) {
5825             fp->eth_q_stats.tx_encap_failures++;
5826             if (next != NULL) {
5827                 /* mark the TX queue as full and save the frame */
5828                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5829                 /* XXX this may reorder the frame */
5830                 rc = drbr_enqueue(ifp, tx_br, next);
5831                 fp->eth_q_stats.mbuf_alloc_tx--;
5832                 fp->eth_q_stats.tx_frames_deferred++;
5833             }
5834
5835             /* stop looking for more work */
5836             break;
5837         }
5838
5839         /* the transmit frame was enqueued successfully */
5840         tx_count++;
5841
5842         /* send a copy of the frame to any BPF listeners */
5843         BPF_MTAP(ifp, next);
5844
5845         tx_bd_avail = bxe_tx_avail(sc, fp);
5846
5847         /* handle any completions if we're running low */
5848         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5849             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5850             bxe_txeof(sc, fp);
5851             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5852                 break;
5853             }
5854         }
5855
5856         next = drbr_dequeue(ifp, tx_br);
5857     }
5858
5859     /* all TX packets were dequeued and/or the tx ring is full */
5860     if (tx_count > 0) {
5861         /* reset the TX watchdog timeout timer */
5862         fp->watchdog_timer = BXE_TX_TIMEOUT;
5863     }
5864
5865 bxe_tx_mq_start_locked_exit:
5866
5867     return (rc);
5868 }
5869
5870 /* Multiqueue (TSS) dispatch routine. */
5871 static int
5872 bxe_tx_mq_start(struct ifnet *ifp,
5873                 struct mbuf  *m)
5874 {
5875     struct bxe_softc *sc = ifp->if_softc;
5876     struct bxe_fastpath *fp;
5877     int fp_index, rc;
5878
5879     fp_index = 0; /* default is the first queue */
5880
5881     /* check if flowid is set */
5882
5883     if (BXE_VALID_FLOWID(m))
5884         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5885
5886     fp = &sc->fp[fp_index];
5887
5888     if (BXE_FP_TX_TRYLOCK(fp)) {
5889         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5890         BXE_FP_TX_UNLOCK(fp);
5891     } else
5892         rc = drbr_enqueue(ifp, fp->tx_br, m);
5893
5894     return (rc);
5895 }
5896
5897 static void
5898 bxe_mq_flush(struct ifnet *ifp)
5899 {
5900     struct bxe_softc *sc = ifp->if_softc;
5901     struct bxe_fastpath *fp;
5902     struct mbuf *m;
5903     int i;
5904
5905     for (i = 0; i < sc->num_queues; i++) {
5906         fp = &sc->fp[i];
5907
5908         if (fp->state != BXE_FP_STATE_OPEN) {
5909             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5910                   fp->index, fp->state);
5911             continue;
5912         }
5913
5914         if (fp->tx_br != NULL) {
5915             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5916             BXE_FP_TX_LOCK(fp);
5917             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5918                 m_freem(m);
5919             }
5920             BXE_FP_TX_UNLOCK(fp);
5921         }
5922     }
5923
5924     if_qflush(ifp);
5925 }
5926
5927 #endif /* FreeBSD_version >= 800000 */
5928
5929 static uint16_t
5930 bxe_cid_ilt_lines(struct bxe_softc *sc)
5931 {
5932     if (IS_SRIOV(sc)) {
5933         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5934     }
5935     return (L2_ILT_LINES(sc));
5936 }
5937
5938 static void
5939 bxe_ilt_set_info(struct bxe_softc *sc)
5940 {
5941     struct ilt_client_info *ilt_client;
5942     struct ecore_ilt *ilt = sc->ilt;
5943     uint16_t line = 0;
5944
5945     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5946     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5947
5948     /* CDU */
5949     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5950     ilt_client->client_num = ILT_CLIENT_CDU;
5951     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5952     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5953     ilt_client->start = line;
5954     line += bxe_cid_ilt_lines(sc);
5955
5956     if (CNIC_SUPPORT(sc)) {
5957         line += CNIC_ILT_LINES;
5958     }
5959
5960     ilt_client->end = (line - 1);
5961
5962     BLOGD(sc, DBG_LOAD,
5963           "ilt client[CDU]: start %d, end %d, "
5964           "psz 0x%x, flags 0x%x, hw psz %d\n",
5965           ilt_client->start, ilt_client->end,
5966           ilt_client->page_size,
5967           ilt_client->flags,
5968           ilog2(ilt_client->page_size >> 12));
5969
5970     /* QM */
5971     if (QM_INIT(sc->qm_cid_count)) {
5972         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5973         ilt_client->client_num = ILT_CLIENT_QM;
5974         ilt_client->page_size = QM_ILT_PAGE_SZ;
5975         ilt_client->flags = 0;
5976         ilt_client->start = line;
5977
5978         /* 4 bytes for each cid */
5979         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5980                              QM_ILT_PAGE_SZ);
5981
5982         ilt_client->end = (line - 1);
5983
5984         BLOGD(sc, DBG_LOAD,
5985               "ilt client[QM]: start %d, end %d, "
5986               "psz 0x%x, flags 0x%x, hw psz %d\n",
5987               ilt_client->start, ilt_client->end,
5988               ilt_client->page_size, ilt_client->flags,
5989               ilog2(ilt_client->page_size >> 12));
5990     }
5991
5992     if (CNIC_SUPPORT(sc)) {
5993         /* SRC */
5994         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5995         ilt_client->client_num = ILT_CLIENT_SRC;
5996         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5997         ilt_client->flags = 0;
5998         ilt_client->start = line;
5999         line += SRC_ILT_LINES;
6000         ilt_client->end = (line - 1);
6001
6002         BLOGD(sc, DBG_LOAD,
6003               "ilt client[SRC]: start %d, end %d, "
6004               "psz 0x%x, flags 0x%x, hw psz %d\n",
6005               ilt_client->start, ilt_client->end,
6006               ilt_client->page_size, ilt_client->flags,
6007               ilog2(ilt_client->page_size >> 12));
6008
6009         /* TM */
6010         ilt_client = &ilt->clients[ILT_CLIENT_TM];
6011         ilt_client->client_num = ILT_CLIENT_TM;
6012         ilt_client->page_size = TM_ILT_PAGE_SZ;
6013         ilt_client->flags = 0;
6014         ilt_client->start = line;
6015         line += TM_ILT_LINES;
6016         ilt_client->end = (line - 1);
6017
6018         BLOGD(sc, DBG_LOAD,
6019               "ilt client[TM]: start %d, end %d, "
6020               "psz 0x%x, flags 0x%x, hw psz %d\n",
6021               ilt_client->start, ilt_client->end,
6022               ilt_client->page_size, ilt_client->flags,
6023               ilog2(ilt_client->page_size >> 12));
6024     }
6025
6026     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
6027 }
6028
6029 static void
6030 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
6031 {
6032     int i;
6033     uint32_t rx_buf_size;
6034
6035     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
6036
6037     for (i = 0; i < sc->num_queues; i++) {
6038         if(rx_buf_size <= MCLBYTES){
6039             sc->fp[i].rx_buf_size = rx_buf_size;
6040             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6041         }else if (rx_buf_size <= MJUMPAGESIZE){
6042             sc->fp[i].rx_buf_size = rx_buf_size;
6043             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
6044         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
6045             sc->fp[i].rx_buf_size = MCLBYTES;
6046             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6047         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
6048             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
6049             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
6050         }else {
6051             sc->fp[i].rx_buf_size = MCLBYTES;
6052             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6053         }
6054     }
6055 }
6056
6057 static int
6058 bxe_alloc_ilt_mem(struct bxe_softc *sc)
6059 {
6060     int rc = 0;
6061
6062     if ((sc->ilt =
6063          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
6064                                     M_BXE_ILT,
6065                                     (M_NOWAIT | M_ZERO))) == NULL) {
6066         rc = 1;
6067     }
6068
6069     return (rc);
6070 }
6071
6072 static int
6073 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
6074 {
6075     int rc = 0;
6076
6077     if ((sc->ilt->lines =
6078          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6079                                     M_BXE_ILT,
6080                                     (M_NOWAIT | M_ZERO))) == NULL) {
6081         rc = 1;
6082     }
6083
6084     return (rc);
6085 }
6086
6087 static void
6088 bxe_free_ilt_mem(struct bxe_softc *sc)
6089 {
6090     if (sc->ilt != NULL) {
6091         free(sc->ilt, M_BXE_ILT);
6092         sc->ilt = NULL;
6093     }
6094 }
6095
6096 static void
6097 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6098 {
6099     if (sc->ilt->lines != NULL) {
6100         free(sc->ilt->lines, M_BXE_ILT);
6101         sc->ilt->lines = NULL;
6102     }
6103 }
6104
6105 static void
6106 bxe_free_mem(struct bxe_softc *sc)
6107 {
6108     int i;
6109
6110     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6111         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6112         sc->context[i].vcxt = NULL;
6113         sc->context[i].size = 0;
6114     }
6115
6116     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6117
6118     bxe_free_ilt_lines_mem(sc);
6119
6120 }
6121
6122 static int
6123 bxe_alloc_mem(struct bxe_softc *sc)
6124 {
6125     int context_size;
6126     int allocated;
6127     int i;
6128
6129     /*
6130      * Allocate memory for CDU context:
6131      * This memory is allocated separately and not in the generic ILT
6132      * functions because CDU differs in few aspects:
6133      * 1. There can be multiple entities allocating memory for context -
6134      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6135      * its own ILT lines.
6136      * 2. Since CDU page-size is not a single 4KB page (which is the case
6137      * for the other ILT clients), to be efficient we want to support
6138      * allocation of sub-page-size in the last entry.
6139      * 3. Context pointers are used by the driver to pass to FW / update
6140      * the context (for the other ILT clients the pointers are used just to
6141      * free the memory during unload).
6142      */
6143     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6144     for (i = 0, allocated = 0; allocated < context_size; i++) {
6145         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6146                                   (context_size - allocated));
6147
6148         if (bxe_dma_alloc(sc, sc->context[i].size,
6149                           &sc->context[i].vcxt_dma,
6150                           "cdu context") != 0) {
6151             bxe_free_mem(sc);
6152             return (-1);
6153         }
6154
6155         sc->context[i].vcxt =
6156             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6157
6158         allocated += sc->context[i].size;
6159     }
6160
6161     bxe_alloc_ilt_lines_mem(sc);
6162
6163     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6164           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6165     {
6166         for (i = 0; i < 4; i++) {
6167             BLOGD(sc, DBG_LOAD,
6168                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6169                   i,
6170                   sc->ilt->clients[i].page_size,
6171                   sc->ilt->clients[i].start,
6172                   sc->ilt->clients[i].end,
6173                   sc->ilt->clients[i].client_num,
6174                   sc->ilt->clients[i].flags);
6175         }
6176     }
6177     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6178         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6179         bxe_free_mem(sc);
6180         return (-1);
6181     }
6182
6183     return (0);
6184 }
6185
6186 static void
6187 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6188 {
6189     struct bxe_softc *sc;
6190     int i;
6191
6192     sc = fp->sc;
6193
6194     if (fp->rx_mbuf_tag == NULL) {
6195         return;
6196     }
6197
6198     /* free all mbufs and unload all maps */
6199     for (i = 0; i < RX_BD_TOTAL; i++) {
6200         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6201             bus_dmamap_sync(fp->rx_mbuf_tag,
6202                             fp->rx_mbuf_chain[i].m_map,
6203                             BUS_DMASYNC_POSTREAD);
6204             bus_dmamap_unload(fp->rx_mbuf_tag,
6205                               fp->rx_mbuf_chain[i].m_map);
6206         }
6207
6208         if (fp->rx_mbuf_chain[i].m != NULL) {
6209             m_freem(fp->rx_mbuf_chain[i].m);
6210             fp->rx_mbuf_chain[i].m = NULL;
6211             fp->eth_q_stats.mbuf_alloc_rx--;
6212         }
6213     }
6214 }
6215
6216 static void
6217 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6218 {
6219     struct bxe_softc *sc;
6220     int i, max_agg_queues;
6221
6222     sc = fp->sc;
6223
6224     if (fp->rx_mbuf_tag == NULL) {
6225         return;
6226     }
6227
6228     max_agg_queues = MAX_AGG_QS(sc);
6229
6230     /* release all mbufs and unload all DMA maps in the TPA pool */
6231     for (i = 0; i < max_agg_queues; i++) {
6232         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6233             bus_dmamap_sync(fp->rx_mbuf_tag,
6234                             fp->rx_tpa_info[i].bd.m_map,
6235                             BUS_DMASYNC_POSTREAD);
6236             bus_dmamap_unload(fp->rx_mbuf_tag,
6237                               fp->rx_tpa_info[i].bd.m_map);
6238         }
6239
6240         if (fp->rx_tpa_info[i].bd.m != NULL) {
6241             m_freem(fp->rx_tpa_info[i].bd.m);
6242             fp->rx_tpa_info[i].bd.m = NULL;
6243             fp->eth_q_stats.mbuf_alloc_tpa--;
6244         }
6245     }
6246 }
6247
6248 static void
6249 bxe_free_sge_chain(struct bxe_fastpath *fp)
6250 {
6251     struct bxe_softc *sc;
6252     int i;
6253
6254     sc = fp->sc;
6255
6256     if (fp->rx_sge_mbuf_tag == NULL) {
6257         return;
6258     }
6259
6260     /* rree all mbufs and unload all maps */
6261     for (i = 0; i < RX_SGE_TOTAL; i++) {
6262         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6263             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6264                             fp->rx_sge_mbuf_chain[i].m_map,
6265                             BUS_DMASYNC_POSTREAD);
6266             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6267                               fp->rx_sge_mbuf_chain[i].m_map);
6268         }
6269
6270         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6271             m_freem(fp->rx_sge_mbuf_chain[i].m);
6272             fp->rx_sge_mbuf_chain[i].m = NULL;
6273             fp->eth_q_stats.mbuf_alloc_sge--;
6274         }
6275     }
6276 }
6277
6278 static void
6279 bxe_free_fp_buffers(struct bxe_softc *sc)
6280 {
6281     struct bxe_fastpath *fp;
6282     int i;
6283
6284     for (i = 0; i < sc->num_queues; i++) {
6285         fp = &sc->fp[i];
6286
6287 #if __FreeBSD_version >= 800000
6288         if (fp->tx_br != NULL) {
6289             /* just in case bxe_mq_flush() wasn't called */
6290             if (mtx_initialized(&fp->tx_mtx)) {
6291                 struct mbuf *m;
6292
6293                 BXE_FP_TX_LOCK(fp);
6294                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6295                     m_freem(m);
6296                 BXE_FP_TX_UNLOCK(fp);
6297             }
6298         }
6299 #endif
6300
6301         /* free all RX buffers */
6302         bxe_free_rx_bd_chain(fp);
6303         bxe_free_tpa_pool(fp);
6304         bxe_free_sge_chain(fp);
6305
6306         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6307             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6308                   fp->eth_q_stats.mbuf_alloc_rx);
6309         }
6310
6311         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6312             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6313                   fp->eth_q_stats.mbuf_alloc_sge);
6314         }
6315
6316         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6317             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6318                   fp->eth_q_stats.mbuf_alloc_tpa);
6319         }
6320
6321         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6322             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6323                   fp->eth_q_stats.mbuf_alloc_tx);
6324         }
6325
6326         /* XXX verify all mbufs were reclaimed */
6327     }
6328 }
6329
6330 static int
6331 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6332                      uint16_t            prev_index,
6333                      uint16_t            index)
6334 {
6335     struct bxe_sw_rx_bd *rx_buf;
6336     struct eth_rx_bd *rx_bd;
6337     bus_dma_segment_t segs[1];
6338     bus_dmamap_t map;
6339     struct mbuf *m;
6340     int nsegs, rc;
6341
6342     rc = 0;
6343
6344     /* allocate the new RX BD mbuf */
6345     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6346     if (__predict_false(m == NULL)) {
6347         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6348         return (ENOBUFS);
6349     }
6350
6351     fp->eth_q_stats.mbuf_alloc_rx++;
6352
6353     /* initialize the mbuf buffer length */
6354     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6355
6356     /* map the mbuf into non-paged pool */
6357     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6358                                  fp->rx_mbuf_spare_map,
6359                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6360     if (__predict_false(rc != 0)) {
6361         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6362         m_freem(m);
6363         fp->eth_q_stats.mbuf_alloc_rx--;
6364         return (rc);
6365     }
6366
6367     /* all mbufs must map to a single segment */
6368     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6369
6370     /* release any existing RX BD mbuf mappings */
6371
6372     if (prev_index != index) {
6373         rx_buf = &fp->rx_mbuf_chain[prev_index];
6374
6375         if (rx_buf->m_map != NULL) {
6376             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6377                             BUS_DMASYNC_POSTREAD);
6378             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6379         }
6380
6381         /*
6382          * We only get here from bxe_rxeof() when the maximum number
6383          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6384          * holds the mbuf in the prev_index so it's OK to NULL it out
6385          * here without concern of a memory leak.
6386          */
6387         fp->rx_mbuf_chain[prev_index].m = NULL;
6388     }
6389
6390     rx_buf = &fp->rx_mbuf_chain[index];
6391
6392     if (rx_buf->m_map != NULL) {
6393         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6394                         BUS_DMASYNC_POSTREAD);
6395         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6396     }
6397
6398     /* save the mbuf and mapping info for a future packet */
6399     map = (prev_index != index) ?
6400               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6401     rx_buf->m_map = fp->rx_mbuf_spare_map;
6402     fp->rx_mbuf_spare_map = map;
6403     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6404                     BUS_DMASYNC_PREREAD);
6405     rx_buf->m = m;
6406
6407     rx_bd = &fp->rx_chain[index];
6408     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6409     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6410
6411     return (rc);
6412 }
6413
6414 static int
6415 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6416                       int                 queue)
6417 {
6418     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
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 the new TPA mbuf */
6426     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6427     if (__predict_false(m == NULL)) {
6428         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6429         return (ENOBUFS);
6430     }
6431
6432     fp->eth_q_stats.mbuf_alloc_tpa++;
6433
6434     /* initialize the mbuf buffer length */
6435     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6436
6437     /* map the mbuf into non-paged pool */
6438     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6439                                  fp->rx_tpa_info_mbuf_spare_map,
6440                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6441     if (__predict_false(rc != 0)) {
6442         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6443         m_free(m);
6444         fp->eth_q_stats.mbuf_alloc_tpa--;
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     /* release any existing TPA mbuf mapping */
6452     if (tpa_info->bd.m_map != NULL) {
6453         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6454                         BUS_DMASYNC_POSTREAD);
6455         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6456     }
6457
6458     /* save the mbuf and mapping info for the TPA mbuf */
6459     map = tpa_info->bd.m_map;
6460     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6461     fp->rx_tpa_info_mbuf_spare_map = map;
6462     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6463                     BUS_DMASYNC_PREREAD);
6464     tpa_info->bd.m = m;
6465     tpa_info->seg = segs[0];
6466
6467     return (rc);
6468 }
6469
6470 /*
6471  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6472  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6473  * chain.
6474  */
6475 static int
6476 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6477                       uint16_t            index)
6478 {
6479     struct bxe_sw_rx_bd *sge_buf;
6480     struct eth_rx_sge *sge;
6481     bus_dma_segment_t segs[1];
6482     bus_dmamap_t map;
6483     struct mbuf *m;
6484     int nsegs;
6485     int rc = 0;
6486
6487     /* allocate a new SGE mbuf */
6488     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6489     if (__predict_false(m == NULL)) {
6490         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6491         return (ENOMEM);
6492     }
6493
6494     fp->eth_q_stats.mbuf_alloc_sge++;
6495
6496     /* initialize the mbuf buffer length */
6497     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6498
6499     /* map the SGE mbuf into non-paged pool */
6500     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6501                                  fp->rx_sge_mbuf_spare_map,
6502                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6503     if (__predict_false(rc != 0)) {
6504         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6505         m_freem(m);
6506         fp->eth_q_stats.mbuf_alloc_sge--;
6507         return (rc);
6508     }
6509
6510     /* all mbufs must map to a single segment */
6511     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6512
6513     sge_buf = &fp->rx_sge_mbuf_chain[index];
6514
6515     /* release any existing SGE mbuf mapping */
6516     if (sge_buf->m_map != NULL) {
6517         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6518                         BUS_DMASYNC_POSTREAD);
6519         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6520     }
6521
6522     /* save the mbuf and mapping info for a future packet */
6523     map = sge_buf->m_map;
6524     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6525     fp->rx_sge_mbuf_spare_map = map;
6526     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6527                     BUS_DMASYNC_PREREAD);
6528     sge_buf->m = m;
6529
6530     sge = &fp->rx_sge_chain[index];
6531     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6532     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6533
6534     return (rc);
6535 }
6536
6537 static __noinline int
6538 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6539 {
6540     struct bxe_fastpath *fp;
6541     int i, j, rc = 0;
6542     int ring_prod, cqe_ring_prod;
6543     int max_agg_queues;
6544
6545     for (i = 0; i < sc->num_queues; i++) {
6546         fp = &sc->fp[i];
6547
6548         ring_prod = cqe_ring_prod = 0;
6549         fp->rx_bd_cons = 0;
6550         fp->rx_cq_cons = 0;
6551
6552         /* allocate buffers for the RX BDs in RX BD chain */
6553         for (j = 0; j < sc->max_rx_bufs; j++) {
6554             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6555             if (rc != 0) {
6556                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6557                       i, rc);
6558                 goto bxe_alloc_fp_buffers_error;
6559             }
6560
6561             ring_prod     = RX_BD_NEXT(ring_prod);
6562             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6563         }
6564
6565         fp->rx_bd_prod = ring_prod;
6566         fp->rx_cq_prod = cqe_ring_prod;
6567         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6568
6569         max_agg_queues = MAX_AGG_QS(sc);
6570
6571         fp->tpa_enable = TRUE;
6572
6573         /* fill the TPA pool */
6574         for (j = 0; j < max_agg_queues; j++) {
6575             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6576             if (rc != 0) {
6577                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6578                           i, j);
6579                 fp->tpa_enable = FALSE;
6580                 goto bxe_alloc_fp_buffers_error;
6581             }
6582
6583             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6584         }
6585
6586         if (fp->tpa_enable) {
6587             /* fill the RX SGE chain */
6588             ring_prod = 0;
6589             for (j = 0; j < RX_SGE_USABLE; j++) {
6590                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6591                 if (rc != 0) {
6592                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6593                               i, ring_prod);
6594                     fp->tpa_enable = FALSE;
6595                     ring_prod = 0;
6596                     goto bxe_alloc_fp_buffers_error;
6597                 }
6598
6599                 ring_prod = RX_SGE_NEXT(ring_prod);
6600             }
6601
6602             fp->rx_sge_prod = ring_prod;
6603         }
6604     }
6605
6606     return (0);
6607
6608 bxe_alloc_fp_buffers_error:
6609
6610     /* unwind what was already allocated */
6611     bxe_free_rx_bd_chain(fp);
6612     bxe_free_tpa_pool(fp);
6613     bxe_free_sge_chain(fp);
6614
6615     return (ENOBUFS);
6616 }
6617
6618 static void
6619 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6620 {
6621     bxe_dma_free(sc, &sc->fw_stats_dma);
6622
6623     sc->fw_stats_num = 0;
6624
6625     sc->fw_stats_req_size = 0;
6626     sc->fw_stats_req = NULL;
6627     sc->fw_stats_req_mapping = 0;
6628
6629     sc->fw_stats_data_size = 0;
6630     sc->fw_stats_data = NULL;
6631     sc->fw_stats_data_mapping = 0;
6632 }
6633
6634 static int
6635 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6636 {
6637     uint8_t num_queue_stats;
6638     int num_groups;
6639
6640     /* number of queues for statistics is number of eth queues */
6641     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6642
6643     /*
6644      * Total number of FW statistics requests =
6645      *   1 for port stats + 1 for PF stats + num of queues
6646      */
6647     sc->fw_stats_num = (2 + num_queue_stats);
6648
6649     /*
6650      * Request is built from stats_query_header and an array of
6651      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6652      * rules. The real number or requests is configured in the
6653      * stats_query_header.
6654      */
6655     num_groups =
6656         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6657          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6658
6659     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6660           sc->fw_stats_num, num_groups);
6661
6662     sc->fw_stats_req_size =
6663         (sizeof(struct stats_query_header) +
6664          (num_groups * sizeof(struct stats_query_cmd_group)));
6665
6666     /*
6667      * Data for statistics requests + stats_counter.
6668      * stats_counter holds per-STORM counters that are incremented when
6669      * STORM has finished with the current request. Memory for FCoE
6670      * offloaded statistics are counted anyway, even if they will not be sent.
6671      * VF stats are not accounted for here as the data of VF stats is stored
6672      * in memory allocated by the VF, not here.
6673      */
6674     sc->fw_stats_data_size =
6675         (sizeof(struct stats_counter) +
6676          sizeof(struct per_port_stats) +
6677          sizeof(struct per_pf_stats) +
6678          /* sizeof(struct fcoe_statistics_params) + */
6679          (sizeof(struct per_queue_stats) * num_queue_stats));
6680
6681     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6682                       &sc->fw_stats_dma, "fw stats") != 0) {
6683         bxe_free_fw_stats_mem(sc);
6684         return (-1);
6685     }
6686
6687     /* set up the shortcuts */
6688
6689     sc->fw_stats_req =
6690         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6691     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6692
6693     sc->fw_stats_data =
6694         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6695                                      sc->fw_stats_req_size);
6696     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6697                                  sc->fw_stats_req_size);
6698
6699     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6700           (uintmax_t)sc->fw_stats_req_mapping);
6701
6702     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6703           (uintmax_t)sc->fw_stats_data_mapping);
6704
6705     return (0);
6706 }
6707
6708 /*
6709  * Bits map:
6710  * 0-7  - Engine0 load counter.
6711  * 8-15 - Engine1 load counter.
6712  * 16   - Engine0 RESET_IN_PROGRESS bit.
6713  * 17   - Engine1 RESET_IN_PROGRESS bit.
6714  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6715  *        function on the engine
6716  * 19   - Engine1 ONE_IS_LOADED.
6717  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6718  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6719  *        for just the one belonging to its engine).
6720  */
6721 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6722 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6723 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6724 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6725 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6726 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6727 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6728 #define BXE_GLOBAL_RESET_BIT      0x00040000
6729
6730 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6731 static void
6732 bxe_set_reset_global(struct bxe_softc *sc)
6733 {
6734     uint32_t val;
6735     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6736     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6737     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6738     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6739 }
6740
6741 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6742 static void
6743 bxe_clear_reset_global(struct bxe_softc *sc)
6744 {
6745     uint32_t val;
6746     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6747     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6748     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6749     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6750 }
6751
6752 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6753 static uint8_t
6754 bxe_reset_is_global(struct bxe_softc *sc)
6755 {
6756     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6757     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6758     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6759 }
6760
6761 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6762 static void
6763 bxe_set_reset_done(struct bxe_softc *sc)
6764 {
6765     uint32_t val;
6766     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6767                                  BXE_PATH0_RST_IN_PROG_BIT;
6768
6769     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6770
6771     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6772     /* Clear the bit */
6773     val &= ~bit;
6774     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6775
6776     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6777 }
6778
6779 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6780 static void
6781 bxe_set_reset_in_progress(struct bxe_softc *sc)
6782 {
6783     uint32_t val;
6784     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6785                                  BXE_PATH0_RST_IN_PROG_BIT;
6786
6787     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6788
6789     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6790     /* Set the bit */
6791     val |= bit;
6792     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6793
6794     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6795 }
6796
6797 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6798 static uint8_t
6799 bxe_reset_is_done(struct bxe_softc *sc,
6800                   int              engine)
6801 {
6802     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6803     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6804                             BXE_PATH0_RST_IN_PROG_BIT;
6805
6806     /* return false if bit is set */
6807     return (val & bit) ? FALSE : TRUE;
6808 }
6809
6810 /* get the load status for an engine, should be run under rtnl lock */
6811 static uint8_t
6812 bxe_get_load_status(struct bxe_softc *sc,
6813                     int              engine)
6814 {
6815     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6816                              BXE_PATH0_LOAD_CNT_MASK;
6817     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6818                               BXE_PATH0_LOAD_CNT_SHIFT;
6819     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6820
6821     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6822
6823     val = ((val & mask) >> shift);
6824
6825     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6826
6827     return (val != 0);
6828 }
6829
6830 /* set pf load mark */
6831 /* XXX needs to be under rtnl lock */
6832 static void
6833 bxe_set_pf_load(struct bxe_softc *sc)
6834 {
6835     uint32_t val;
6836     uint32_t val1;
6837     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6838                                   BXE_PATH0_LOAD_CNT_MASK;
6839     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6840                                    BXE_PATH0_LOAD_CNT_SHIFT;
6841
6842     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6843
6844     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6845     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6846
6847     /* get the current counter value */
6848     val1 = ((val & mask) >> shift);
6849
6850     /* set bit of this PF */
6851     val1 |= (1 << SC_ABS_FUNC(sc));
6852
6853     /* clear the old value */
6854     val &= ~mask;
6855
6856     /* set the new one */
6857     val |= ((val1 << shift) & mask);
6858
6859     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6860
6861     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6862 }
6863
6864 /* clear pf load mark */
6865 /* XXX needs to be under rtnl lock */
6866 static uint8_t
6867 bxe_clear_pf_load(struct bxe_softc *sc)
6868 {
6869     uint32_t val1, val;
6870     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6871                                   BXE_PATH0_LOAD_CNT_MASK;
6872     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6873                                    BXE_PATH0_LOAD_CNT_SHIFT;
6874
6875     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6876     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6877     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6878
6879     /* get the current counter value */
6880     val1 = (val & mask) >> shift;
6881
6882     /* clear bit of that PF */
6883     val1 &= ~(1 << SC_ABS_FUNC(sc));
6884
6885     /* clear the old value */
6886     val &= ~mask;
6887
6888     /* set the new one */
6889     val |= ((val1 << shift) & mask);
6890
6891     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6892     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6893     return (val1 != 0);
6894 }
6895
6896 /* send load requrest to mcp and analyze response */
6897 static int
6898 bxe_nic_load_request(struct bxe_softc *sc,
6899                      uint32_t         *load_code)
6900 {
6901     /* init fw_seq */
6902     sc->fw_seq =
6903         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6904          DRV_MSG_SEQ_NUMBER_MASK);
6905
6906     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6907
6908     /* get the current FW pulse sequence */
6909     sc->fw_drv_pulse_wr_seq =
6910         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6911          DRV_PULSE_SEQ_MASK);
6912
6913     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6914           sc->fw_drv_pulse_wr_seq);
6915
6916     /* load request */
6917     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6918                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6919
6920     /* if the MCP fails to respond we must abort */
6921     if (!(*load_code)) {
6922         BLOGE(sc, "MCP response failure!\n");
6923         return (-1);
6924     }
6925
6926     /* if MCP refused then must abort */
6927     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6928         BLOGE(sc, "MCP refused load request\n");
6929         return (-1);
6930     }
6931
6932     return (0);
6933 }
6934
6935 /*
6936  * Check whether another PF has already loaded FW to chip. In virtualized
6937  * environments a pf from anoth VM may have already initialized the device
6938  * including loading FW.
6939  */
6940 static int
6941 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6942                          uint32_t         load_code)
6943 {
6944     uint32_t my_fw, loaded_fw;
6945
6946     /* is another pf loaded on this engine? */
6947     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6948         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6949         /* build my FW version dword */
6950         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6951                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6952                  (BCM_5710_FW_REVISION_VERSION << 16) +
6953                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6954
6955         /* read loaded FW from chip */
6956         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6957         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6958               loaded_fw, my_fw);
6959
6960         /* abort nic load if version mismatch */
6961         if (my_fw != loaded_fw) {
6962             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6963                   loaded_fw, my_fw);
6964             return (-1);
6965         }
6966     }
6967
6968     return (0);
6969 }
6970
6971 /* mark PMF if applicable */
6972 static void
6973 bxe_nic_load_pmf(struct bxe_softc *sc,
6974                  uint32_t         load_code)
6975 {
6976     uint32_t ncsi_oem_data_addr;
6977
6978     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6979         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6980         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6981         /*
6982          * Barrier here for ordering between the writing to sc->port.pmf here
6983          * and reading it from the periodic task.
6984          */
6985         sc->port.pmf = 1;
6986         mb();
6987     } else {
6988         sc->port.pmf = 0;
6989     }
6990
6991     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6992
6993     /* XXX needed? */
6994     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6995         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6996             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6997             if (ncsi_oem_data_addr) {
6998                 REG_WR(sc,
6999                        (ncsi_oem_data_addr +
7000                         offsetof(struct glob_ncsi_oem_data, driver_version)),
7001                        0);
7002             }
7003         }
7004     }
7005 }
7006
7007 static void
7008 bxe_read_mf_cfg(struct bxe_softc *sc)
7009 {
7010     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
7011     int abs_func;
7012     int vn;
7013
7014     if (BXE_NOMCP(sc)) {
7015         return; /* what should be the default bvalue in this case */
7016     }
7017
7018     /*
7019      * The formula for computing the absolute function number is...
7020      * For 2 port configuration (4 functions per port):
7021      *   abs_func = 2 * vn + SC_PORT + SC_PATH
7022      * For 4 port configuration (2 functions per port):
7023      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
7024      */
7025     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
7026         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
7027         if (abs_func >= E1H_FUNC_MAX) {
7028             break;
7029         }
7030         sc->devinfo.mf_info.mf_config[vn] =
7031             MFCFG_RD(sc, func_mf_config[abs_func].config);
7032     }
7033
7034     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
7035         FUNC_MF_CFG_FUNC_DISABLED) {
7036         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
7037         sc->flags |= BXE_MF_FUNC_DIS;
7038     } else {
7039         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
7040         sc->flags &= ~BXE_MF_FUNC_DIS;
7041     }
7042 }
7043
7044 /* acquire split MCP access lock register */
7045 static int bxe_acquire_alr(struct bxe_softc *sc)
7046 {
7047     uint32_t j, val;
7048
7049     for (j = 0; j < 1000; j++) {
7050         val = (1UL << 31);
7051         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
7052         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
7053         if (val & (1L << 31))
7054             break;
7055
7056         DELAY(5000);
7057     }
7058
7059     if (!(val & (1L << 31))) {
7060         BLOGE(sc, "Cannot acquire MCP access lock register\n");
7061         return (-1);
7062     }
7063
7064     return (0);
7065 }
7066
7067 /* release split MCP access lock register */
7068 static void bxe_release_alr(struct bxe_softc *sc)
7069 {
7070     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
7071 }
7072
7073 static void
7074 bxe_fan_failure(struct bxe_softc *sc)
7075 {
7076     int port = SC_PORT(sc);
7077     uint32_t ext_phy_config;
7078
7079     /* mark the failure */
7080     ext_phy_config =
7081         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7082
7083     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7084     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7085     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7086              ext_phy_config);
7087
7088     /* log the failure */
7089     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7090               "the card to prevent permanent damage. "
7091               "Please contact OEM Support for assistance\n");
7092
7093     /* XXX */
7094 #if 1
7095     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7096 #else
7097     /*
7098      * Schedule device reset (unload)
7099      * This is due to some boards consuming sufficient power when driver is
7100      * up to overheat if fan fails.
7101      */
7102     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7103     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7104 #endif
7105 }
7106
7107 /* this function is called upon a link interrupt */
7108 static void
7109 bxe_link_attn(struct bxe_softc *sc)
7110 {
7111     uint32_t pause_enabled = 0;
7112     struct host_port_stats *pstats;
7113     int cmng_fns;
7114
7115     /* Make sure that we are synced with the current statistics */
7116     bxe_stats_handle(sc, STATS_EVENT_STOP);
7117
7118     elink_link_update(&sc->link_params, &sc->link_vars);
7119
7120     if (sc->link_vars.link_up) {
7121
7122         /* dropless flow control */
7123         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7124             pause_enabled = 0;
7125
7126             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7127                 pause_enabled = 1;
7128             }
7129
7130             REG_WR(sc,
7131                    (BAR_USTRORM_INTMEM +
7132                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7133                    pause_enabled);
7134         }
7135
7136         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7137             pstats = BXE_SP(sc, port_stats);
7138             /* reset old mac stats */
7139             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7140         }
7141
7142         if (sc->state == BXE_STATE_OPEN) {
7143             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7144         }
7145     }
7146
7147     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7148         cmng_fns = bxe_get_cmng_fns_mode(sc);
7149
7150         if (cmng_fns != CMNG_FNS_NONE) {
7151             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7152             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7153         } else {
7154             /* rate shaping and fairness are disabled */
7155             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7156         }
7157     }
7158
7159     bxe_link_report_locked(sc);
7160
7161     if (IS_MF(sc)) {
7162         ; // XXX bxe_link_sync_notify(sc);
7163     }
7164 }
7165
7166 static void
7167 bxe_attn_int_asserted(struct bxe_softc *sc,
7168                       uint32_t         asserted)
7169 {
7170     int port = SC_PORT(sc);
7171     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7172                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7173     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7174                                         NIG_REG_MASK_INTERRUPT_PORT0;
7175     uint32_t aeu_mask;
7176     uint32_t nig_mask = 0;
7177     uint32_t reg_addr;
7178     uint32_t igu_acked;
7179     uint32_t cnt;
7180
7181     if (sc->attn_state & asserted) {
7182         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7183     }
7184
7185     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7186
7187     aeu_mask = REG_RD(sc, aeu_addr);
7188
7189     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7190           aeu_mask, asserted);
7191
7192     aeu_mask &= ~(asserted & 0x3ff);
7193
7194     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7195
7196     REG_WR(sc, aeu_addr, aeu_mask);
7197
7198     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7199
7200     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7201     sc->attn_state |= asserted;
7202     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7203
7204     if (asserted & ATTN_HARD_WIRED_MASK) {
7205         if (asserted & ATTN_NIG_FOR_FUNC) {
7206
7207             bxe_acquire_phy_lock(sc);
7208             /* save nig interrupt mask */
7209             nig_mask = REG_RD(sc, nig_int_mask_addr);
7210
7211             /* If nig_mask is not set, no need to call the update function */
7212             if (nig_mask) {
7213                 REG_WR(sc, nig_int_mask_addr, 0);
7214
7215                 bxe_link_attn(sc);
7216             }
7217
7218             /* handle unicore attn? */
7219         }
7220
7221         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7222             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7223         }
7224
7225         if (asserted & GPIO_2_FUNC) {
7226             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7227         }
7228
7229         if (asserted & GPIO_3_FUNC) {
7230             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7231         }
7232
7233         if (asserted & GPIO_4_FUNC) {
7234             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7235         }
7236
7237         if (port == 0) {
7238             if (asserted & ATTN_GENERAL_ATTN_1) {
7239                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7240                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7241             }
7242             if (asserted & ATTN_GENERAL_ATTN_2) {
7243                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7244                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7245             }
7246             if (asserted & ATTN_GENERAL_ATTN_3) {
7247                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7248                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7249             }
7250         } else {
7251             if (asserted & ATTN_GENERAL_ATTN_4) {
7252                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7253                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7254             }
7255             if (asserted & ATTN_GENERAL_ATTN_5) {
7256                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7257                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7258             }
7259             if (asserted & ATTN_GENERAL_ATTN_6) {
7260                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7261                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7262             }
7263         }
7264     } /* hardwired */
7265
7266     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7267         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7268     } else {
7269         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7270     }
7271
7272     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7273           asserted,
7274           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7275     REG_WR(sc, reg_addr, asserted);
7276
7277     /* now set back the mask */
7278     if (asserted & ATTN_NIG_FOR_FUNC) {
7279         /*
7280          * Verify that IGU ack through BAR was written before restoring
7281          * NIG mask. This loop should exit after 2-3 iterations max.
7282          */
7283         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7284             cnt = 0;
7285
7286             do {
7287                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7288             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7289                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7290
7291             if (!igu_acked) {
7292                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7293             }
7294
7295             mb();
7296         }
7297
7298         REG_WR(sc, nig_int_mask_addr, nig_mask);
7299
7300         bxe_release_phy_lock(sc);
7301     }
7302 }
7303
7304 static void
7305 bxe_print_next_block(struct bxe_softc *sc,
7306                      int              idx,
7307                      const char       *blk)
7308 {
7309     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7310 }
7311
7312 static int
7313 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7314                               uint32_t         sig,
7315                               int              par_num,
7316                               uint8_t          print)
7317 {
7318     uint32_t cur_bit = 0;
7319     int i = 0;
7320
7321     for (i = 0; sig; i++) {
7322         cur_bit = ((uint32_t)0x1 << i);
7323         if (sig & cur_bit) {
7324             switch (cur_bit) {
7325             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7326                 if (print)
7327                     bxe_print_next_block(sc, par_num++, "BRB");
7328                 break;
7329             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7330                 if (print)
7331                     bxe_print_next_block(sc, par_num++, "PARSER");
7332                 break;
7333             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7334                 if (print)
7335                     bxe_print_next_block(sc, par_num++, "TSDM");
7336                 break;
7337             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7338                 if (print)
7339                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7340                 break;
7341             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7342                 if (print)
7343                     bxe_print_next_block(sc, par_num++, "TCM");
7344                 break;
7345             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7346                 if (print)
7347                     bxe_print_next_block(sc, par_num++, "TSEMI");
7348                 break;
7349             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7350                 if (print)
7351                     bxe_print_next_block(sc, par_num++, "XPB");
7352                 break;
7353             }
7354
7355             /* Clear the bit */
7356             sig &= ~cur_bit;
7357         }
7358     }
7359
7360     return (par_num);
7361 }
7362
7363 static int
7364 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7365                               uint32_t         sig,
7366                               int              par_num,
7367                               uint8_t          *global,
7368                               uint8_t          print)
7369 {
7370     int i = 0;
7371     uint32_t cur_bit = 0;
7372     for (i = 0; sig; i++) {
7373         cur_bit = ((uint32_t)0x1 << i);
7374         if (sig & cur_bit) {
7375             switch (cur_bit) {
7376             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7377                 if (print)
7378                     bxe_print_next_block(sc, par_num++, "PBF");
7379                 break;
7380             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7381                 if (print)
7382                     bxe_print_next_block(sc, par_num++, "QM");
7383                 break;
7384             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7385                 if (print)
7386                     bxe_print_next_block(sc, par_num++, "TM");
7387                 break;
7388             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7389                 if (print)
7390                     bxe_print_next_block(sc, par_num++, "XSDM");
7391                 break;
7392             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7393                 if (print)
7394                     bxe_print_next_block(sc, par_num++, "XCM");
7395                 break;
7396             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7397                 if (print)
7398                     bxe_print_next_block(sc, par_num++, "XSEMI");
7399                 break;
7400             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7401                 if (print)
7402                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7403                 break;
7404             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7405                 if (print)
7406                     bxe_print_next_block(sc, par_num++, "NIG");
7407                 break;
7408             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7409                 if (print)
7410                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7411                 *global = TRUE;
7412                 break;
7413             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7414                 if (print)
7415                     bxe_print_next_block(sc, par_num++, "DEBUG");
7416                 break;
7417             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7418                 if (print)
7419                     bxe_print_next_block(sc, par_num++, "USDM");
7420                 break;
7421             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7422                 if (print)
7423                     bxe_print_next_block(sc, par_num++, "UCM");
7424                 break;
7425             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7426                 if (print)
7427                     bxe_print_next_block(sc, par_num++, "USEMI");
7428                 break;
7429             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7430                 if (print)
7431                     bxe_print_next_block(sc, par_num++, "UPB");
7432                 break;
7433             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7434                 if (print)
7435                     bxe_print_next_block(sc, par_num++, "CSDM");
7436                 break;
7437             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7438                 if (print)
7439                     bxe_print_next_block(sc, par_num++, "CCM");
7440                 break;
7441             }
7442
7443             /* Clear the bit */
7444             sig &= ~cur_bit;
7445         }
7446     }
7447
7448     return (par_num);
7449 }
7450
7451 static int
7452 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7453                               uint32_t         sig,
7454                               int              par_num,
7455                               uint8_t          print)
7456 {
7457     uint32_t cur_bit = 0;
7458     int i = 0;
7459
7460     for (i = 0; sig; i++) {
7461         cur_bit = ((uint32_t)0x1 << i);
7462         if (sig & cur_bit) {
7463             switch (cur_bit) {
7464             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7465                 if (print)
7466                     bxe_print_next_block(sc, par_num++, "CSEMI");
7467                 break;
7468             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7469                 if (print)
7470                     bxe_print_next_block(sc, par_num++, "PXP");
7471                 break;
7472             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7473                 if (print)
7474                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7475                 break;
7476             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7477                 if (print)
7478                     bxe_print_next_block(sc, par_num++, "CFC");
7479                 break;
7480             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7481                 if (print)
7482                     bxe_print_next_block(sc, par_num++, "CDU");
7483                 break;
7484             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7485                 if (print)
7486                     bxe_print_next_block(sc, par_num++, "DMAE");
7487                 break;
7488             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7489                 if (print)
7490                     bxe_print_next_block(sc, par_num++, "IGU");
7491                 break;
7492             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7493                 if (print)
7494                     bxe_print_next_block(sc, par_num++, "MISC");
7495                 break;
7496             }
7497
7498             /* Clear the bit */
7499             sig &= ~cur_bit;
7500         }
7501     }
7502
7503     return (par_num);
7504 }
7505
7506 static int
7507 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7508                               uint32_t         sig,
7509                               int              par_num,
7510                               uint8_t          *global,
7511                               uint8_t          print)
7512 {
7513     uint32_t cur_bit = 0;
7514     int i = 0;
7515
7516     for (i = 0; sig; i++) {
7517         cur_bit = ((uint32_t)0x1 << i);
7518         if (sig & cur_bit) {
7519             switch (cur_bit) {
7520             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7521                 if (print)
7522                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7523                 *global = TRUE;
7524                 break;
7525             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7526                 if (print)
7527                     bxe_print_next_block(sc, par_num++,
7528                               "MCP UMP RX");
7529                 *global = TRUE;
7530                 break;
7531             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7532                 if (print)
7533                     bxe_print_next_block(sc, par_num++,
7534                               "MCP UMP TX");
7535                 *global = TRUE;
7536                 break;
7537             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7538                 if (print)
7539                     bxe_print_next_block(sc, par_num++,
7540                               "MCP SCPAD");
7541                 *global = TRUE;
7542                 break;
7543             }
7544
7545             /* Clear the bit */
7546             sig &= ~cur_bit;
7547         }
7548     }
7549
7550     return (par_num);
7551 }
7552
7553 static int
7554 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7555                               uint32_t         sig,
7556                               int              par_num,
7557                               uint8_t          print)
7558 {
7559     uint32_t cur_bit = 0;
7560     int i = 0;
7561
7562     for (i = 0; sig; i++) {
7563         cur_bit = ((uint32_t)0x1 << i);
7564         if (sig & cur_bit) {
7565             switch (cur_bit) {
7566             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7567                 if (print)
7568                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7569                 break;
7570             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7571                 if (print)
7572                     bxe_print_next_block(sc, par_num++, "ATC");
7573                 break;
7574             }
7575
7576             /* Clear the bit */
7577             sig &= ~cur_bit;
7578         }
7579     }
7580
7581     return (par_num);
7582 }
7583
7584 static uint8_t
7585 bxe_parity_attn(struct bxe_softc *sc,
7586                 uint8_t          *global,
7587                 uint8_t          print,
7588                 uint32_t         *sig)
7589 {
7590     int par_num = 0;
7591
7592     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7593         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7594         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7595         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7596         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7597         BLOGE(sc, "Parity error: HW block parity attention:\n"
7598                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7599               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7600               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7601               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7602               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7603               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7604
7605         if (print)
7606             BLOGI(sc, "Parity errors detected in blocks: ");
7607
7608         par_num =
7609             bxe_check_blocks_with_parity0(sc, sig[0] &
7610                                           HW_PRTY_ASSERT_SET_0,
7611                                           par_num, print);
7612         par_num =
7613             bxe_check_blocks_with_parity1(sc, sig[1] &
7614                                           HW_PRTY_ASSERT_SET_1,
7615                                           par_num, global, print);
7616         par_num =
7617             bxe_check_blocks_with_parity2(sc, sig[2] &
7618                                           HW_PRTY_ASSERT_SET_2,
7619                                           par_num, print);
7620         par_num =
7621             bxe_check_blocks_with_parity3(sc, sig[3] &
7622                                           HW_PRTY_ASSERT_SET_3,
7623                                           par_num, global, print);
7624         par_num =
7625             bxe_check_blocks_with_parity4(sc, sig[4] &
7626                                           HW_PRTY_ASSERT_SET_4,
7627                                           par_num, print);
7628
7629         if (print)
7630             BLOGI(sc, "\n");
7631
7632         return (TRUE);
7633     }
7634
7635     return (FALSE);
7636 }
7637
7638 static uint8_t
7639 bxe_chk_parity_attn(struct bxe_softc *sc,
7640                     uint8_t          *global,
7641                     uint8_t          print)
7642 {
7643     struct attn_route attn = { {0} };
7644     int port = SC_PORT(sc);
7645
7646     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7647     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7648     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7649     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7650
7651     /*
7652      * Since MCP attentions can't be disabled inside the block, we need to
7653      * read AEU registers to see whether they're currently disabled
7654      */
7655     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7656                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7657                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7658                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7659
7660
7661     if (!CHIP_IS_E1x(sc))
7662         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7663
7664     return (bxe_parity_attn(sc, global, print, attn.sig));
7665 }
7666
7667 static void
7668 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7669                          uint32_t         attn)
7670 {
7671     uint32_t val;
7672
7673     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7674         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7675         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7676         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7677             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7678         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7679             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7680         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7681             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7682         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7683             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7684         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7685             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7686         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7687             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7688         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7689             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7690         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7691             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7692         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7693             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7694     }
7695
7696     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7697         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7698         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7699         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7700             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7701         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7702             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7703         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7704             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7705         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7706             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7707         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7708             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7709         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7710             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7711     }
7712
7713     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7714                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7715         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7716               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7717                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7718     }
7719 }
7720
7721 static void
7722 bxe_e1h_disable(struct bxe_softc *sc)
7723 {
7724     int port = SC_PORT(sc);
7725
7726     bxe_tx_disable(sc);
7727
7728     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7729 }
7730
7731 static void
7732 bxe_e1h_enable(struct bxe_softc *sc)
7733 {
7734     int port = SC_PORT(sc);
7735
7736     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7737
7738     // XXX bxe_tx_enable(sc);
7739 }
7740
7741 /*
7742  * called due to MCP event (on pmf):
7743  *   reread new bandwidth configuration
7744  *   configure FW
7745  *   notify others function about the change
7746  */
7747 static void
7748 bxe_config_mf_bw(struct bxe_softc *sc)
7749 {
7750     if (sc->link_vars.link_up) {
7751         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7752         // XXX bxe_link_sync_notify(sc);
7753     }
7754
7755     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7756 }
7757
7758 static void
7759 bxe_set_mf_bw(struct bxe_softc *sc)
7760 {
7761     bxe_config_mf_bw(sc);
7762     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7763 }
7764
7765 static void
7766 bxe_handle_eee_event(struct bxe_softc *sc)
7767 {
7768     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7769     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7770 }
7771
7772 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7773
7774 static void
7775 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7776 {
7777     struct eth_stats_info *ether_stat =
7778         &sc->sp->drv_info_to_mcp.ether_stat;
7779
7780     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7781             ETH_STAT_INFO_VERSION_LEN);
7782
7783     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7784     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7785                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7786                                           ether_stat->mac_local + MAC_PAD,
7787                                           MAC_PAD, ETH_ALEN);
7788
7789     ether_stat->mtu_size = sc->mtu;
7790
7791     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7792     if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
7793         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7794     }
7795
7796     // XXX ether_stat->feature_flags |= ???;
7797
7798     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7799
7800     ether_stat->txq_size = sc->tx_ring_size;
7801     ether_stat->rxq_size = sc->rx_ring_size;
7802 }
7803
7804 static void
7805 bxe_handle_drv_info_req(struct bxe_softc *sc)
7806 {
7807     enum drv_info_opcode op_code;
7808     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7809
7810     /* if drv_info version supported by MFW doesn't match - send NACK */
7811     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7812         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7813         return;
7814     }
7815
7816     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7817                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7818
7819     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7820
7821     switch (op_code) {
7822     case ETH_STATS_OPCODE:
7823         bxe_drv_info_ether_stat(sc);
7824         break;
7825     case FCOE_STATS_OPCODE:
7826     case ISCSI_STATS_OPCODE:
7827     default:
7828         /* if op code isn't supported - send NACK */
7829         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7830         return;
7831     }
7832
7833     /*
7834      * If we got drv_info attn from MFW then these fields are defined in
7835      * shmem2 for sure
7836      */
7837     SHMEM2_WR(sc, drv_info_host_addr_lo,
7838               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7839     SHMEM2_WR(sc, drv_info_host_addr_hi,
7840               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7841
7842     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7843 }
7844
7845 static void
7846 bxe_dcc_event(struct bxe_softc *sc,
7847               uint32_t         dcc_event)
7848 {
7849     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7850
7851     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7852         /*
7853          * This is the only place besides the function initialization
7854          * where the sc->flags can change so it is done without any
7855          * locks
7856          */
7857         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7858             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7859             sc->flags |= BXE_MF_FUNC_DIS;
7860             bxe_e1h_disable(sc);
7861         } else {
7862             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7863             sc->flags &= ~BXE_MF_FUNC_DIS;
7864             bxe_e1h_enable(sc);
7865         }
7866         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7867     }
7868
7869     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7870         bxe_config_mf_bw(sc);
7871         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7872     }
7873
7874     /* Report results to MCP */
7875     if (dcc_event)
7876         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7877     else
7878         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7879 }
7880
7881 static void
7882 bxe_pmf_update(struct bxe_softc *sc)
7883 {
7884     int port = SC_PORT(sc);
7885     uint32_t val;
7886
7887     sc->port.pmf = 1;
7888     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7889
7890     /*
7891      * We need the mb() to ensure the ordering between the writing to
7892      * sc->port.pmf here and reading it from the bxe_periodic_task().
7893      */
7894     mb();
7895
7896     /* queue a periodic task */
7897     // XXX schedule task...
7898
7899     // XXX bxe_dcbx_pmf_update(sc);
7900
7901     /* enable nig attention */
7902     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7903     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7904         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7905         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7906     } else if (!CHIP_IS_E1x(sc)) {
7907         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7908         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7909     }
7910
7911     bxe_stats_handle(sc, STATS_EVENT_PMF);
7912 }
7913
7914 static int
7915 bxe_mc_assert(struct bxe_softc *sc)
7916 {
7917     char last_idx;
7918     int i, rc = 0;
7919     uint32_t row0, row1, row2, row3;
7920
7921     /* XSTORM */
7922     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7923     if (last_idx)
7924         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7925
7926     /* print the asserts */
7927     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7928
7929         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7930         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7931         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7932         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7933
7934         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7935             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7936                   i, row3, row2, row1, row0);
7937             rc++;
7938         } else {
7939             break;
7940         }
7941     }
7942
7943     /* TSTORM */
7944     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7945     if (last_idx) {
7946         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7947     }
7948
7949     /* print the asserts */
7950     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7951
7952         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7953         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7954         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7955         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7956
7957         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7958             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7959                   i, row3, row2, row1, row0);
7960             rc++;
7961         } else {
7962             break;
7963         }
7964     }
7965
7966     /* CSTORM */
7967     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7968     if (last_idx) {
7969         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7970     }
7971
7972     /* print the asserts */
7973     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7974
7975         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7976         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7977         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7978         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7979
7980         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7981             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7982                   i, row3, row2, row1, row0);
7983             rc++;
7984         } else {
7985             break;
7986         }
7987     }
7988
7989     /* USTORM */
7990     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7991     if (last_idx) {
7992         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7993     }
7994
7995     /* print the asserts */
7996     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7997
7998         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7999         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
8000         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
8001         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
8002
8003         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
8004             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
8005                   i, row3, row2, row1, row0);
8006             rc++;
8007         } else {
8008             break;
8009         }
8010     }
8011
8012     return (rc);
8013 }
8014
8015 static void
8016 bxe_attn_int_deasserted3(struct bxe_softc *sc,
8017                          uint32_t         attn)
8018 {
8019     int func = SC_FUNC(sc);
8020     uint32_t val;
8021
8022     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
8023
8024         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
8025
8026             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
8027             bxe_read_mf_cfg(sc);
8028             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
8029                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
8030             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
8031
8032             if (val & DRV_STATUS_DCC_EVENT_MASK)
8033                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
8034
8035             if (val & DRV_STATUS_SET_MF_BW)
8036                 bxe_set_mf_bw(sc);
8037
8038             if (val & DRV_STATUS_DRV_INFO_REQ)
8039                 bxe_handle_drv_info_req(sc);
8040
8041             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
8042                 bxe_pmf_update(sc);
8043
8044             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
8045                 bxe_handle_eee_event(sc);
8046
8047             if (sc->link_vars.periodic_flags &
8048                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
8049                 /* sync with link */
8050                 bxe_acquire_phy_lock(sc);
8051                 sc->link_vars.periodic_flags &=
8052                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
8053                 bxe_release_phy_lock(sc);
8054                 if (IS_MF(sc))
8055                     ; // XXX bxe_link_sync_notify(sc);
8056                 bxe_link_report(sc);
8057             }
8058
8059             /*
8060              * Always call it here: bxe_link_report() will
8061              * prevent the link indication duplication.
8062              */
8063             bxe_link_status_update(sc);
8064
8065         } else if (attn & BXE_MC_ASSERT_BITS) {
8066
8067             BLOGE(sc, "MC assert!\n");
8068             bxe_mc_assert(sc);
8069             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8070             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8071             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8072             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8073             bxe_panic(sc, ("MC assert!\n"));
8074
8075         } else if (attn & BXE_MCP_ASSERT) {
8076
8077             BLOGE(sc, "MCP assert!\n");
8078             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8079             // XXX bxe_fw_dump(sc);
8080
8081         } else {
8082             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8083         }
8084     }
8085
8086     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8087         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8088         if (attn & BXE_GRC_TIMEOUT) {
8089             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8090             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8091         }
8092         if (attn & BXE_GRC_RSV) {
8093             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8094             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8095         }
8096         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8097     }
8098 }
8099
8100 static void
8101 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8102                          uint32_t         attn)
8103 {
8104     int port = SC_PORT(sc);
8105     int reg_offset;
8106     uint32_t val0, mask0, val1, mask1;
8107     uint32_t val;
8108
8109     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8110         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8111         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8112         /* CFC error attention */
8113         if (val & 0x2) {
8114             BLOGE(sc, "FATAL error from CFC\n");
8115         }
8116     }
8117
8118     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8119         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8120         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8121         /* RQ_USDMDP_FIFO_OVERFLOW */
8122         if (val & 0x18000) {
8123             BLOGE(sc, "FATAL error from PXP\n");
8124         }
8125
8126         if (!CHIP_IS_E1x(sc)) {
8127             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8128             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8129         }
8130     }
8131
8132 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8133 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8134
8135     if (attn & AEU_PXP2_HW_INT_BIT) {
8136         /*  CQ47854 workaround do not panic on
8137          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8138          */
8139         if (!CHIP_IS_E1x(sc)) {
8140             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8141             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8142             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8143             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8144             /*
8145              * If the olny PXP2_EOP_ERROR_BIT is set in
8146              * STS0 and STS1 - clear it
8147              *
8148              * probably we lose additional attentions between
8149              * STS0 and STS_CLR0, in this case user will not
8150              * be notified about them
8151              */
8152             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8153                 !(val1 & mask1))
8154                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8155
8156             /* print the register, since no one can restore it */
8157             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8158
8159             /*
8160              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8161              * then notify
8162              */
8163             if (val0 & PXP2_EOP_ERROR_BIT) {
8164                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8165
8166                 /*
8167                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8168                  * set then clear attention from PXP2 block without panic
8169                  */
8170                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8171                     ((val1 & mask1) == 0))
8172                     attn &= ~AEU_PXP2_HW_INT_BIT;
8173             }
8174         }
8175     }
8176
8177     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8178         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8179                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8180
8181         val = REG_RD(sc, reg_offset);
8182         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8183         REG_WR(sc, reg_offset, val);
8184
8185         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8186               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8187         bxe_panic(sc, ("HW block attention set2\n"));
8188     }
8189 }
8190
8191 static void
8192 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8193                          uint32_t         attn)
8194 {
8195     int port = SC_PORT(sc);
8196     int reg_offset;
8197     uint32_t val;
8198
8199     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8200         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8201         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8202         /* DORQ discard attention */
8203         if (val & 0x2) {
8204             BLOGE(sc, "FATAL error from DORQ\n");
8205         }
8206     }
8207
8208     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8209         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8210                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8211
8212         val = REG_RD(sc, reg_offset);
8213         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8214         REG_WR(sc, reg_offset, val);
8215
8216         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8217               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8218         bxe_panic(sc, ("HW block attention set1\n"));
8219     }
8220 }
8221
8222 static void
8223 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8224                          uint32_t         attn)
8225 {
8226     int port = SC_PORT(sc);
8227     int reg_offset;
8228     uint32_t val;
8229
8230     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8231                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8232
8233     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8234         val = REG_RD(sc, reg_offset);
8235         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8236         REG_WR(sc, reg_offset, val);
8237
8238         BLOGW(sc, "SPIO5 hw attention\n");
8239
8240         /* Fan failure attention */
8241         elink_hw_reset_phy(&sc->link_params);
8242         bxe_fan_failure(sc);
8243     }
8244
8245     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8246         bxe_acquire_phy_lock(sc);
8247         elink_handle_module_detect_int(&sc->link_params);
8248         bxe_release_phy_lock(sc);
8249     }
8250
8251     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8252         val = REG_RD(sc, reg_offset);
8253         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8254         REG_WR(sc, reg_offset, val);
8255
8256         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8257                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8258     }
8259 }
8260
8261 static void
8262 bxe_attn_int_deasserted(struct bxe_softc *sc,
8263                         uint32_t         deasserted)
8264 {
8265     struct attn_route attn;
8266     struct attn_route *group_mask;
8267     int port = SC_PORT(sc);
8268     int index;
8269     uint32_t reg_addr;
8270     uint32_t val;
8271     uint32_t aeu_mask;
8272     uint8_t global = FALSE;
8273
8274     /*
8275      * Need to take HW lock because MCP or other port might also
8276      * try to handle this event.
8277      */
8278     bxe_acquire_alr(sc);
8279
8280     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8281         /* XXX
8282          * In case of parity errors don't handle attentions so that
8283          * other function would "see" parity errors.
8284          */
8285         sc->recovery_state = BXE_RECOVERY_INIT;
8286         // XXX schedule a recovery task...
8287         /* disable HW interrupts */
8288         bxe_int_disable(sc);
8289         bxe_release_alr(sc);
8290         return;
8291     }
8292
8293     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8294     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8295     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8296     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8297     if (!CHIP_IS_E1x(sc)) {
8298         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8299     } else {
8300         attn.sig[4] = 0;
8301     }
8302
8303     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8304           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8305
8306     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8307         if (deasserted & (1 << index)) {
8308             group_mask = &sc->attn_group[index];
8309
8310             BLOGD(sc, DBG_INTR,
8311                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8312                   group_mask->sig[0], group_mask->sig[1],
8313                   group_mask->sig[2], group_mask->sig[3],
8314                   group_mask->sig[4]);
8315
8316             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8317             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8318             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8319             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8320             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8321         }
8322     }
8323
8324     bxe_release_alr(sc);
8325
8326     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8327         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8328                     COMMAND_REG_ATTN_BITS_CLR);
8329     } else {
8330         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8331     }
8332
8333     val = ~deasserted;
8334     BLOGD(sc, DBG_INTR,
8335           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8336           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8337     REG_WR(sc, reg_addr, val);
8338
8339     if (~sc->attn_state & deasserted) {
8340         BLOGE(sc, "IGU error\n");
8341     }
8342
8343     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8344                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8345
8346     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8347
8348     aeu_mask = REG_RD(sc, reg_addr);
8349
8350     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8351           aeu_mask, deasserted);
8352     aeu_mask |= (deasserted & 0x3ff);
8353     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8354
8355     REG_WR(sc, reg_addr, aeu_mask);
8356     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8357
8358     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8359     sc->attn_state &= ~deasserted;
8360     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8361 }
8362
8363 static void
8364 bxe_attn_int(struct bxe_softc *sc)
8365 {
8366     /* read local copy of bits */
8367     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8368     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8369     uint32_t attn_state = sc->attn_state;
8370
8371     /* look for changed bits */
8372     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8373     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8374
8375     BLOGD(sc, DBG_INTR,
8376           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8377           attn_bits, attn_ack, asserted, deasserted);
8378
8379     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8380         BLOGE(sc, "BAD attention state\n");
8381     }
8382
8383     /* handle bits that were raised */
8384     if (asserted) {
8385         bxe_attn_int_asserted(sc, asserted);
8386     }
8387
8388     if (deasserted) {
8389         bxe_attn_int_deasserted(sc, deasserted);
8390     }
8391 }
8392
8393 static uint16_t
8394 bxe_update_dsb_idx(struct bxe_softc *sc)
8395 {
8396     struct host_sp_status_block *def_sb = sc->def_sb;
8397     uint16_t rc = 0;
8398
8399     mb(); /* status block is written to by the chip */
8400
8401     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8402         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8403         rc |= BXE_DEF_SB_ATT_IDX;
8404     }
8405
8406     if (sc->def_idx != def_sb->sp_sb.running_index) {
8407         sc->def_idx = def_sb->sp_sb.running_index;
8408         rc |= BXE_DEF_SB_IDX;
8409     }
8410
8411     mb();
8412
8413     return (rc);
8414 }
8415
8416 static inline struct ecore_queue_sp_obj *
8417 bxe_cid_to_q_obj(struct bxe_softc *sc,
8418                  uint32_t         cid)
8419 {
8420     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8421     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8422 }
8423
8424 static void
8425 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8426 {
8427     struct ecore_mcast_ramrod_params rparam;
8428     int rc;
8429
8430     memset(&rparam, 0, sizeof(rparam));
8431
8432     rparam.mcast_obj = &sc->mcast_obj;
8433
8434     BXE_MCAST_LOCK(sc);
8435
8436     /* clear pending state for the last command */
8437     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8438
8439     /* if there are pending mcast commands - send them */
8440     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8441         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8442         if (rc < 0) {
8443             BLOGD(sc, DBG_SP,
8444                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8445         }
8446     }
8447
8448     BXE_MCAST_UNLOCK(sc);
8449 }
8450
8451 static void
8452 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8453                               union event_ring_elem *elem)
8454 {
8455     unsigned long ramrod_flags = 0;
8456     int rc = 0;
8457     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8458     struct ecore_vlan_mac_obj *vlan_mac_obj;
8459
8460     /* always push next commands out, don't wait here */
8461     bit_set(&ramrod_flags, RAMROD_CONT);
8462
8463     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8464     case ECORE_FILTER_MAC_PENDING:
8465         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8466         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8467         break;
8468
8469     case ECORE_FILTER_MCAST_PENDING:
8470         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8471         /*
8472          * This is only relevant for 57710 where multicast MACs are
8473          * configured as unicast MACs using the same ramrod.
8474          */
8475         bxe_handle_mcast_eqe(sc);
8476         return;
8477
8478     default:
8479         BLOGE(sc, "Unsupported classification command: %d\n",
8480               elem->message.data.eth_event.echo);
8481         return;
8482     }
8483
8484     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8485
8486     if (rc < 0) {
8487         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8488     } else if (rc > 0) {
8489         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8490     }
8491 }
8492
8493 static void
8494 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8495                        union event_ring_elem *elem)
8496 {
8497     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8498
8499     /* send rx_mode command again if was requested */
8500     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8501                                &sc->sp_state)) {
8502         bxe_set_storm_rx_mode(sc);
8503     }
8504 }
8505
8506 static void
8507 bxe_update_eq_prod(struct bxe_softc *sc,
8508                    uint16_t         prod)
8509 {
8510     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8511     wmb(); /* keep prod updates ordered */
8512 }
8513
8514 static void
8515 bxe_eq_int(struct bxe_softc *sc)
8516 {
8517     uint16_t hw_cons, sw_cons, sw_prod;
8518     union event_ring_elem *elem;
8519     uint8_t echo;
8520     uint32_t cid;
8521     uint8_t opcode;
8522     int spqe_cnt = 0;
8523     struct ecore_queue_sp_obj *q_obj;
8524     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8525     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8526
8527     hw_cons = le16toh(*sc->eq_cons_sb);
8528
8529     /*
8530      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8531      * when we get to the next-page we need to adjust so the loop
8532      * condition below will be met. The next element is the size of a
8533      * regular element and hence incrementing by 1
8534      */
8535     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8536         hw_cons++;
8537     }
8538
8539     /*
8540      * This function may never run in parallel with itself for a
8541      * specific sc and no need for a read memory barrier here.
8542      */
8543     sw_cons = sc->eq_cons;
8544     sw_prod = sc->eq_prod;
8545
8546     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8547           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8548
8549     for (;
8550          sw_cons != hw_cons;
8551          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8552
8553         elem = &sc->eq[EQ_DESC(sw_cons)];
8554
8555         /* elem CID originates from FW, actually LE */
8556         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8557         opcode = elem->message.opcode;
8558
8559         /* handle eq element */
8560         switch (opcode) {
8561
8562         case EVENT_RING_OPCODE_STAT_QUERY:
8563             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8564                   sc->stats_comp++);
8565             /* nothing to do with stats comp */
8566             goto next_spqe;
8567
8568         case EVENT_RING_OPCODE_CFC_DEL:
8569             /* handle according to cid range */
8570             /* we may want to verify here that the sc state is HALTING */
8571             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8572             q_obj = bxe_cid_to_q_obj(sc, cid);
8573             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8574                 break;
8575             }
8576             goto next_spqe;
8577
8578         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8579             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8580             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8581                 break;
8582             }
8583             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8584             goto next_spqe;
8585
8586         case EVENT_RING_OPCODE_START_TRAFFIC:
8587             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8588             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8589                 break;
8590             }
8591             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8592             goto next_spqe;
8593
8594         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8595             echo = elem->message.data.function_update_event.echo;
8596             if (echo == SWITCH_UPDATE) {
8597                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8598                 if (f_obj->complete_cmd(sc, f_obj,
8599                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8600                     break;
8601                 }
8602             }
8603             else {
8604                 BLOGD(sc, DBG_SP,
8605                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8606             }
8607             goto next_spqe;
8608
8609         case EVENT_RING_OPCODE_FORWARD_SETUP:
8610             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8611             if (q_obj->complete_cmd(sc, q_obj,
8612                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8613                 break;
8614             }
8615             goto next_spqe;
8616
8617         case EVENT_RING_OPCODE_FUNCTION_START:
8618             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8619             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8620                 break;
8621             }
8622             goto next_spqe;
8623
8624         case EVENT_RING_OPCODE_FUNCTION_STOP:
8625             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8626             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8627                 break;
8628             }
8629             goto next_spqe;
8630         }
8631
8632         switch (opcode | sc->state) {
8633         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8634         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8635             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8636             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8637             rss_raw->clear_pending(rss_raw);
8638             break;
8639
8640         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8641         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8642         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8643         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8644         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8645         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8646             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8647             bxe_handle_classification_eqe(sc, elem);
8648             break;
8649
8650         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8651         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8652         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8653             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8654             bxe_handle_mcast_eqe(sc);
8655             break;
8656
8657         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8658         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8659         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8660             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8661             bxe_handle_rx_mode_eqe(sc, elem);
8662             break;
8663
8664         default:
8665             /* unknown event log error and continue */
8666             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8667                   elem->message.opcode, sc->state);
8668         }
8669
8670 next_spqe:
8671         spqe_cnt++;
8672     } /* for */
8673
8674     mb();
8675     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8676
8677     sc->eq_cons = sw_cons;
8678     sc->eq_prod = sw_prod;
8679
8680     /* make sure that above mem writes were issued towards the memory */
8681     wmb();
8682
8683     /* update producer */
8684     bxe_update_eq_prod(sc, sc->eq_prod);
8685 }
8686
8687 static void
8688 bxe_handle_sp_tq(void *context,
8689                  int  pending)
8690 {
8691     struct bxe_softc *sc = (struct bxe_softc *)context;
8692     uint16_t status;
8693
8694     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8695
8696     /* what work needs to be performed? */
8697     status = bxe_update_dsb_idx(sc);
8698
8699     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8700
8701     /* HW attentions */
8702     if (status & BXE_DEF_SB_ATT_IDX) {
8703         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8704         bxe_attn_int(sc);
8705         status &= ~BXE_DEF_SB_ATT_IDX;
8706     }
8707
8708     /* SP events: STAT_QUERY and others */
8709     if (status & BXE_DEF_SB_IDX) {
8710         /* handle EQ completions */
8711         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8712         bxe_eq_int(sc);
8713         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8714                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8715         status &= ~BXE_DEF_SB_IDX;
8716     }
8717
8718     /* if status is non zero then something went wrong */
8719     if (__predict_false(status)) {
8720         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8721     }
8722
8723     /* ack status block only if something was actually handled */
8724     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8725                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8726
8727     /*
8728      * Must be called after the EQ processing (since eq leads to sriov
8729      * ramrod completion flows).
8730      * This flow may have been scheduled by the arrival of a ramrod
8731      * completion, or by the sriov code rescheduling itself.
8732      */
8733     // XXX bxe_iov_sp_task(sc);
8734
8735 }
8736
8737 static void
8738 bxe_handle_fp_tq(void *context,
8739                  int  pending)
8740 {
8741     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8742     struct bxe_softc *sc = fp->sc;
8743     uint8_t more_tx = FALSE;
8744     uint8_t more_rx = FALSE;
8745
8746     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8747
8748     /* XXX
8749      * IFF_DRV_RUNNING state can't be checked here since we process
8750      * slowpath events on a client queue during setup. Instead
8751      * we need to add a "process/continue" flag here that the driver
8752      * can use to tell the task here not to do anything.
8753      */
8754 #if 0
8755     if (!(sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
8756         return;
8757     }
8758 #endif
8759
8760     /* update the fastpath index */
8761     bxe_update_fp_sb_idx(fp);
8762
8763     /* XXX add loop here if ever support multiple tx CoS */
8764     /* fp->txdata[cos] */
8765     if (bxe_has_tx_work(fp)) {
8766         BXE_FP_TX_LOCK(fp);
8767         more_tx = bxe_txeof(sc, fp);
8768         BXE_FP_TX_UNLOCK(fp);
8769     }
8770
8771     if (bxe_has_rx_work(fp)) {
8772         more_rx = bxe_rxeof(sc, fp);
8773     }
8774
8775     if (more_rx /*|| more_tx*/) {
8776         /* still more work to do */
8777         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8778         return;
8779     }
8780
8781     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8782                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8783 }
8784
8785 static void
8786 bxe_task_fp(struct bxe_fastpath *fp)
8787 {
8788     struct bxe_softc *sc = fp->sc;
8789     uint8_t more_tx = FALSE;
8790     uint8_t more_rx = FALSE;
8791
8792     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8793
8794     /* update the fastpath index */
8795     bxe_update_fp_sb_idx(fp);
8796
8797     /* XXX add loop here if ever support multiple tx CoS */
8798     /* fp->txdata[cos] */
8799     if (bxe_has_tx_work(fp)) {
8800         BXE_FP_TX_LOCK(fp);
8801         more_tx = bxe_txeof(sc, fp);
8802         BXE_FP_TX_UNLOCK(fp);
8803     }
8804
8805     if (bxe_has_rx_work(fp)) {
8806         more_rx = bxe_rxeof(sc, fp);
8807     }
8808
8809     if (more_rx /*|| more_tx*/) {
8810         /* still more work to do, bail out if this ISR and process later */
8811         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8812         return;
8813     }
8814
8815     /*
8816      * Here we write the fastpath index taken before doing any tx or rx work.
8817      * It is very well possible other hw events occurred up to this point and
8818      * they were actually processed accordingly above. Since we're going to
8819      * write an older fastpath index, an interrupt is coming which we might
8820      * not do any work in.
8821      */
8822     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8823                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8824 }
8825
8826 /*
8827  * Legacy interrupt entry point.
8828  *
8829  * Verifies that the controller generated the interrupt and
8830  * then calls a separate routine to handle the various
8831  * interrupt causes: link, RX, and TX.
8832  */
8833 static void
8834 bxe_intr_legacy(void *xsc)
8835 {
8836     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8837     struct bxe_fastpath *fp;
8838     uint16_t status, mask;
8839     int i;
8840
8841     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8842
8843     /*
8844      * 0 for ustorm, 1 for cstorm
8845      * the bits returned from ack_int() are 0-15
8846      * bit 0 = attention status block
8847      * bit 1 = fast path status block
8848      * a mask of 0x2 or more = tx/rx event
8849      * a mask of 1 = slow path event
8850      */
8851
8852     status = bxe_ack_int(sc);
8853
8854     /* the interrupt is not for us */
8855     if (__predict_false(status == 0)) {
8856         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8857         return;
8858     }
8859
8860     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8861
8862     FOR_EACH_ETH_QUEUE(sc, i) {
8863         fp = &sc->fp[i];
8864         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8865         if (status & mask) {
8866             /* acknowledge and disable further fastpath interrupts */
8867             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8868             bxe_task_fp(fp);
8869             status &= ~mask;
8870         }
8871     }
8872
8873     if (__predict_false(status & 0x1)) {
8874         /* acknowledge and disable further slowpath interrupts */
8875         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8876
8877         /* schedule slowpath handler */
8878         taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8879
8880         status &= ~0x1;
8881     }
8882
8883     if (__predict_false(status)) {
8884         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8885     }
8886 }
8887
8888 /* slowpath interrupt entry point */
8889 static void
8890 bxe_intr_sp(void *xsc)
8891 {
8892     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8893
8894     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8895
8896     /* acknowledge and disable further slowpath interrupts */
8897     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8898
8899     /* schedule slowpath handler */
8900     taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8901 }
8902
8903 /* fastpath interrupt entry point */
8904 static void
8905 bxe_intr_fp(void *xfp)
8906 {
8907     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8908     struct bxe_softc *sc = fp->sc;
8909
8910     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8911
8912     BLOGD(sc, DBG_INTR,
8913           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8914           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8915
8916     /* acknowledge and disable further fastpath interrupts */
8917     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8918
8919     bxe_task_fp(fp);
8920 }
8921
8922 /* Release all interrupts allocated by the driver. */
8923 static void
8924 bxe_interrupt_free(struct bxe_softc *sc)
8925 {
8926     int i;
8927
8928     switch (sc->interrupt_mode) {
8929     case INTR_MODE_INTX:
8930         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8931         if (sc->intr[0].resource != NULL) {
8932             bus_release_resource(sc->dev,
8933                                  SYS_RES_IRQ,
8934                                  sc->intr[0].rid,
8935                                  sc->intr[0].resource);
8936         }
8937         break;
8938     case INTR_MODE_MSI:
8939         for (i = 0; i < sc->intr_count; i++) {
8940             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8941             if (sc->intr[i].resource && sc->intr[i].rid) {
8942                 bus_release_resource(sc->dev,
8943                                      SYS_RES_IRQ,
8944                                      sc->intr[i].rid,
8945                                      sc->intr[i].resource);
8946             }
8947         }
8948         pci_release_msi(sc->dev);
8949         break;
8950     case INTR_MODE_MSIX:
8951         for (i = 0; i < sc->intr_count; i++) {
8952             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8953             if (sc->intr[i].resource && sc->intr[i].rid) {
8954                 bus_release_resource(sc->dev,
8955                                      SYS_RES_IRQ,
8956                                      sc->intr[i].rid,
8957                                      sc->intr[i].resource);
8958             }
8959         }
8960         pci_release_msi(sc->dev);
8961         break;
8962     default:
8963         /* nothing to do as initial allocation failed */
8964         break;
8965     }
8966 }
8967
8968 /*
8969  * This function determines and allocates the appropriate
8970  * interrupt based on system capabilites and user request.
8971  *
8972  * The user may force a particular interrupt mode, specify
8973  * the number of receive queues, specify the method for
8974  * distribuitng received frames to receive queues, or use
8975  * the default settings which will automatically select the
8976  * best supported combination.  In addition, the OS may or
8977  * may not support certain combinations of these settings.
8978  * This routine attempts to reconcile the settings requested
8979  * by the user with the capabilites available from the system
8980  * to select the optimal combination of features.
8981  *
8982  * Returns:
8983  *   0 = Success, !0 = Failure.
8984  */
8985 static int
8986 bxe_interrupt_alloc(struct bxe_softc *sc)
8987 {
8988     int msix_count = 0;
8989     int msi_count = 0;
8990     int num_requested = 0;
8991     int num_allocated = 0;
8992     int rid, i, j;
8993     int rc;
8994
8995     /* get the number of available MSI/MSI-X interrupts from the OS */
8996     if (sc->interrupt_mode > 0) {
8997         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8998             msix_count = pci_msix_count(sc->dev);
8999         }
9000
9001         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
9002             msi_count = pci_msi_count(sc->dev);
9003         }
9004
9005         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
9006               msi_count, msix_count);
9007     }
9008
9009     do { /* try allocating MSI-X interrupt resources (at least 2) */
9010         if (sc->interrupt_mode != INTR_MODE_MSIX) {
9011             break;
9012         }
9013
9014         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
9015             (msix_count < 2)) {
9016             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9017             break;
9018         }
9019
9020         /* ask for the necessary number of MSI-X vectors */
9021         num_requested = min((sc->num_queues + 1), msix_count);
9022
9023         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
9024
9025         num_allocated = num_requested;
9026         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
9027             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
9028             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9029             break;
9030         }
9031
9032         if (num_allocated < 2) { /* possible? */
9033             BLOGE(sc, "MSI-X allocation less than 2!\n");
9034             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9035             pci_release_msi(sc->dev);
9036             break;
9037         }
9038
9039         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
9040               num_requested, num_allocated);
9041
9042         /* best effort so use the number of vectors allocated to us */
9043         sc->intr_count = num_allocated;
9044         sc->num_queues = num_allocated - 1;
9045
9046         rid = 1; /* initial resource identifier */
9047
9048         /* allocate the MSI-X vectors */
9049         for (i = 0; i < num_allocated; i++) {
9050             sc->intr[i].rid = (rid + i);
9051
9052             if ((sc->intr[i].resource =
9053                  bus_alloc_resource_any(sc->dev,
9054                                         SYS_RES_IRQ,
9055                                         &sc->intr[i].rid,
9056                                         RF_ACTIVE)) == NULL) {
9057                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
9058                       i, (rid + i));
9059
9060                 for (j = (i - 1); j >= 0; j--) {
9061                     bus_release_resource(sc->dev,
9062                                          SYS_RES_IRQ,
9063                                          sc->intr[j].rid,
9064                                          sc->intr[j].resource);
9065                 }
9066
9067                 sc->intr_count = 0;
9068                 sc->num_queues = 0;
9069                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9070                 pci_release_msi(sc->dev);
9071                 break;
9072             }
9073
9074             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9075         }
9076     } while (0);
9077
9078     do { /* try allocating MSI vector resources (at least 2) */
9079         if (sc->interrupt_mode != INTR_MODE_MSI) {
9080             break;
9081         }
9082
9083         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9084             (msi_count < 1)) {
9085             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9086             break;
9087         }
9088
9089         /* ask for a single MSI vector */
9090         num_requested = 1;
9091
9092         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9093
9094         num_allocated = num_requested;
9095         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9096             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9097             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9098             break;
9099         }
9100
9101         if (num_allocated != 1) { /* possible? */
9102             BLOGE(sc, "MSI allocation is not 1!\n");
9103             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9104             pci_release_msi(sc->dev);
9105             break;
9106         }
9107
9108         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9109               num_requested, num_allocated);
9110
9111         /* best effort so use the number of vectors allocated to us */
9112         sc->intr_count = num_allocated;
9113         sc->num_queues = num_allocated;
9114
9115         rid = 1; /* initial resource identifier */
9116
9117         sc->intr[0].rid = rid;
9118
9119         if ((sc->intr[0].resource =
9120              bus_alloc_resource_any(sc->dev,
9121                                     SYS_RES_IRQ,
9122                                     &sc->intr[0].rid,
9123                                     RF_ACTIVE)) == NULL) {
9124             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9125             sc->intr_count = 0;
9126             sc->num_queues = 0;
9127             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9128             pci_release_msi(sc->dev);
9129             break;
9130         }
9131
9132         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9133     } while (0);
9134
9135     do { /* try allocating INTx vector resources */
9136         if (sc->interrupt_mode != INTR_MODE_INTX) {
9137             break;
9138         }
9139
9140         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9141
9142         /* only one vector for INTx */
9143         sc->intr_count = 1;
9144         sc->num_queues = 1;
9145
9146         rid = 0; /* initial resource identifier */
9147
9148         sc->intr[0].rid = rid;
9149
9150         if ((sc->intr[0].resource =
9151              bus_alloc_resource_any(sc->dev,
9152                                     SYS_RES_IRQ,
9153                                     &sc->intr[0].rid,
9154                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9155             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9156             sc->intr_count = 0;
9157             sc->num_queues = 0;
9158             sc->interrupt_mode = -1; /* Failed! */
9159             break;
9160         }
9161
9162         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9163     } while (0);
9164
9165     if (sc->interrupt_mode == -1) {
9166         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9167         rc = 1;
9168     } else {
9169         BLOGD(sc, DBG_LOAD,
9170               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9171               sc->interrupt_mode, sc->num_queues);
9172         rc = 0;
9173     }
9174
9175     return (rc);
9176 }
9177
9178 static void
9179 bxe_interrupt_detach(struct bxe_softc *sc)
9180 {
9181     struct bxe_fastpath *fp;
9182     int i;
9183
9184     /* release interrupt resources */
9185     for (i = 0; i < sc->intr_count; i++) {
9186         if (sc->intr[i].resource && sc->intr[i].tag) {
9187             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9188             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9189         }
9190     }
9191
9192     for (i = 0; i < sc->num_queues; i++) {
9193         fp = &sc->fp[i];
9194         if (fp->tq) {
9195             taskqueue_drain(fp->tq, &fp->tq_task);
9196             taskqueue_free(fp->tq);
9197             fp->tq = NULL;
9198         }
9199     }
9200
9201
9202     if (sc->sp_tq) {
9203         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9204         taskqueue_free(sc->sp_tq);
9205         sc->sp_tq = NULL;
9206     }
9207 }
9208
9209 /*
9210  * Enables interrupts and attach to the ISR.
9211  *
9212  * When using multiple MSI/MSI-X vectors the first vector
9213  * is used for slowpath operations while all remaining
9214  * vectors are used for fastpath operations.  If only a
9215  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9216  * ISR must look for both slowpath and fastpath completions.
9217  */
9218 static int
9219 bxe_interrupt_attach(struct bxe_softc *sc)
9220 {
9221     struct bxe_fastpath *fp;
9222     int rc = 0;
9223     int i;
9224
9225     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9226              "bxe%d_sp_tq", sc->unit);
9227     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9228     sc->sp_tq = taskqueue_create_fast(sc->sp_tq_name, M_NOWAIT,
9229                                       taskqueue_thread_enqueue,
9230                                       &sc->sp_tq);
9231     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9232                             "%s", sc->sp_tq_name);
9233
9234
9235     for (i = 0; i < sc->num_queues; i++) {
9236         fp = &sc->fp[i];
9237         snprintf(fp->tq_name, sizeof(fp->tq_name),
9238                  "bxe%d_fp%d_tq", sc->unit, i);
9239         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9240         fp->tq = taskqueue_create_fast(fp->tq_name, M_NOWAIT,
9241                                        taskqueue_thread_enqueue,
9242                                        &fp->tq);
9243         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9244                                 "%s", fp->tq_name);
9245     }
9246
9247     /* setup interrupt handlers */
9248     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9249         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9250
9251         /*
9252          * Setup the interrupt handler. Note that we pass the driver instance
9253          * to the interrupt handler for the slowpath.
9254          */
9255         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9256                                  (INTR_TYPE_NET | INTR_MPSAFE),
9257                                  NULL, bxe_intr_sp, sc,
9258                                  &sc->intr[0].tag)) != 0) {
9259             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9260             goto bxe_interrupt_attach_exit;
9261         }
9262
9263         bus_describe_intr(sc->dev, sc->intr[0].resource,
9264                           sc->intr[0].tag, "sp");
9265
9266         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9267
9268         /* initialize the fastpath vectors (note the first was used for sp) */
9269         for (i = 0; i < sc->num_queues; i++) {
9270             fp = &sc->fp[i];
9271             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9272
9273             /*
9274              * Setup the interrupt handler. Note that we pass the
9275              * fastpath context to the interrupt handler in this
9276              * case.
9277              */
9278             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9279                                      (INTR_TYPE_NET | INTR_MPSAFE),
9280                                      NULL, bxe_intr_fp, fp,
9281                                      &sc->intr[i + 1].tag)) != 0) {
9282                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9283                       (i + 1), rc);
9284                 goto bxe_interrupt_attach_exit;
9285             }
9286
9287             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9288                               sc->intr[i + 1].tag, "fp%02d", i);
9289
9290             /* bind the fastpath instance to a cpu */
9291             if (sc->num_queues > 1) {
9292                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9293             }
9294
9295             fp->state = BXE_FP_STATE_IRQ;
9296         }
9297     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9298         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9299
9300         /*
9301          * Setup the interrupt handler. Note that we pass the
9302          * driver instance to the interrupt handler which
9303          * will handle both the slowpath and fastpath.
9304          */
9305         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9306                                  (INTR_TYPE_NET | INTR_MPSAFE),
9307                                  NULL, bxe_intr_legacy, sc,
9308                                  &sc->intr[0].tag)) != 0) {
9309             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9310             goto bxe_interrupt_attach_exit;
9311         }
9312
9313     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9314         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9315
9316         /*
9317          * Setup the interrupt handler. Note that we pass the
9318          * driver instance to the interrupt handler which
9319          * will handle both the slowpath and fastpath.
9320          */
9321         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9322                                  (INTR_TYPE_NET | INTR_MPSAFE),
9323                                  NULL, bxe_intr_legacy, sc,
9324                                  &sc->intr[0].tag)) != 0) {
9325             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9326             goto bxe_interrupt_attach_exit;
9327         }
9328     }
9329
9330 bxe_interrupt_attach_exit:
9331
9332     return (rc);
9333 }
9334
9335 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9336 static int  bxe_init_hw_common(struct bxe_softc *sc);
9337 static int  bxe_init_hw_port(struct bxe_softc *sc);
9338 static int  bxe_init_hw_func(struct bxe_softc *sc);
9339 static void bxe_reset_common(struct bxe_softc *sc);
9340 static void bxe_reset_port(struct bxe_softc *sc);
9341 static void bxe_reset_func(struct bxe_softc *sc);
9342 static int  bxe_gunzip_init(struct bxe_softc *sc);
9343 static void bxe_gunzip_end(struct bxe_softc *sc);
9344 static int  bxe_init_firmware(struct bxe_softc *sc);
9345 static void bxe_release_firmware(struct bxe_softc *sc);
9346
9347 static struct
9348 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9349     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9350     .init_hw_cmn      = bxe_init_hw_common,
9351     .init_hw_port     = bxe_init_hw_port,
9352     .init_hw_func     = bxe_init_hw_func,
9353
9354     .reset_hw_cmn     = bxe_reset_common,
9355     .reset_hw_port    = bxe_reset_port,
9356     .reset_hw_func    = bxe_reset_func,
9357
9358     .gunzip_init      = bxe_gunzip_init,
9359     .gunzip_end       = bxe_gunzip_end,
9360
9361     .init_fw          = bxe_init_firmware,
9362     .release_fw       = bxe_release_firmware,
9363 };
9364
9365 static void
9366 bxe_init_func_obj(struct bxe_softc *sc)
9367 {
9368     sc->dmae_ready = 0;
9369
9370     ecore_init_func_obj(sc,
9371                         &sc->func_obj,
9372                         BXE_SP(sc, func_rdata),
9373                         BXE_SP_MAPPING(sc, func_rdata),
9374                         BXE_SP(sc, func_afex_rdata),
9375                         BXE_SP_MAPPING(sc, func_afex_rdata),
9376                         &bxe_func_sp_drv);
9377 }
9378
9379 static int
9380 bxe_init_hw(struct bxe_softc *sc,
9381             uint32_t         load_code)
9382 {
9383     struct ecore_func_state_params func_params = { NULL };
9384     int rc;
9385
9386     /* prepare the parameters for function state transitions */
9387     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9388
9389     func_params.f_obj = &sc->func_obj;
9390     func_params.cmd = ECORE_F_CMD_HW_INIT;
9391
9392     func_params.params.hw_init.load_phase = load_code;
9393
9394     /*
9395      * Via a plethora of function pointers, we will eventually reach
9396      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9397      */
9398     rc = ecore_func_state_change(sc, &func_params);
9399
9400     return (rc);
9401 }
9402
9403 static void
9404 bxe_fill(struct bxe_softc *sc,
9405          uint32_t         addr,
9406          int              fill,
9407          uint32_t         len)
9408 {
9409     uint32_t i;
9410
9411     if (!(len % 4) && !(addr % 4)) {
9412         for (i = 0; i < len; i += 4) {
9413             REG_WR(sc, (addr + i), fill);
9414         }
9415     } else {
9416         for (i = 0; i < len; i++) {
9417             REG_WR8(sc, (addr + i), fill);
9418         }
9419     }
9420 }
9421
9422 /* writes FP SP data to FW - data_size in dwords */
9423 static void
9424 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9425                   int              fw_sb_id,
9426                   uint32_t         *sb_data_p,
9427                   uint32_t         data_size)
9428 {
9429     int index;
9430
9431     for (index = 0; index < data_size; index++) {
9432         REG_WR(sc,
9433                (BAR_CSTRORM_INTMEM +
9434                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9435                 (sizeof(uint32_t) * index)),
9436                *(sb_data_p + index));
9437     }
9438 }
9439
9440 static void
9441 bxe_zero_fp_sb(struct bxe_softc *sc,
9442                int              fw_sb_id)
9443 {
9444     struct hc_status_block_data_e2 sb_data_e2;
9445     struct hc_status_block_data_e1x sb_data_e1x;
9446     uint32_t *sb_data_p;
9447     uint32_t data_size = 0;
9448
9449     if (!CHIP_IS_E1x(sc)) {
9450         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9451         sb_data_e2.common.state = SB_DISABLED;
9452         sb_data_e2.common.p_func.vf_valid = FALSE;
9453         sb_data_p = (uint32_t *)&sb_data_e2;
9454         data_size = (sizeof(struct hc_status_block_data_e2) /
9455                      sizeof(uint32_t));
9456     } else {
9457         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9458         sb_data_e1x.common.state = SB_DISABLED;
9459         sb_data_e1x.common.p_func.vf_valid = FALSE;
9460         sb_data_p = (uint32_t *)&sb_data_e1x;
9461         data_size = (sizeof(struct hc_status_block_data_e1x) /
9462                      sizeof(uint32_t));
9463     }
9464
9465     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9466
9467     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9468              0, CSTORM_STATUS_BLOCK_SIZE);
9469     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9470              0, CSTORM_SYNC_BLOCK_SIZE);
9471 }
9472
9473 static void
9474 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9475                   struct hc_sp_status_block_data *sp_sb_data)
9476 {
9477     int i;
9478
9479     for (i = 0;
9480          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9481          i++) {
9482         REG_WR(sc,
9483                (BAR_CSTRORM_INTMEM +
9484                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9485                 (i * sizeof(uint32_t))),
9486                *((uint32_t *)sp_sb_data + i));
9487     }
9488 }
9489
9490 static void
9491 bxe_zero_sp_sb(struct bxe_softc *sc)
9492 {
9493     struct hc_sp_status_block_data sp_sb_data;
9494
9495     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9496
9497     sp_sb_data.state           = SB_DISABLED;
9498     sp_sb_data.p_func.vf_valid = FALSE;
9499
9500     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9501
9502     bxe_fill(sc,
9503              (BAR_CSTRORM_INTMEM +
9504               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9505               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9506     bxe_fill(sc,
9507              (BAR_CSTRORM_INTMEM +
9508               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9509               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9510 }
9511
9512 static void
9513 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9514                              int                       igu_sb_id,
9515                              int                       igu_seg_id)
9516 {
9517     hc_sm->igu_sb_id      = igu_sb_id;
9518     hc_sm->igu_seg_id     = igu_seg_id;
9519     hc_sm->timer_value    = 0xFF;
9520     hc_sm->time_to_expire = 0xFFFFFFFF;
9521 }
9522
9523 static void
9524 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9525 {
9526     /* zero out state machine indices */
9527
9528     /* rx indices */
9529     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9530
9531     /* tx indices */
9532     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9533     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9534     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9535     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9536
9537     /* map indices */
9538
9539     /* rx indices */
9540     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9541         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9542
9543     /* tx indices */
9544     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9545         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9546     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9547         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9548     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9549         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9550     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9551         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9552 }
9553
9554 static void
9555 bxe_init_sb(struct bxe_softc *sc,
9556             bus_addr_t       busaddr,
9557             int              vfid,
9558             uint8_t          vf_valid,
9559             int              fw_sb_id,
9560             int              igu_sb_id)
9561 {
9562     struct hc_status_block_data_e2  sb_data_e2;
9563     struct hc_status_block_data_e1x sb_data_e1x;
9564     struct hc_status_block_sm       *hc_sm_p;
9565     uint32_t *sb_data_p;
9566     int igu_seg_id;
9567     int data_size;
9568
9569     if (CHIP_INT_MODE_IS_BC(sc)) {
9570         igu_seg_id = HC_SEG_ACCESS_NORM;
9571     } else {
9572         igu_seg_id = IGU_SEG_ACCESS_NORM;
9573     }
9574
9575     bxe_zero_fp_sb(sc, fw_sb_id);
9576
9577     if (!CHIP_IS_E1x(sc)) {
9578         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9579         sb_data_e2.common.state = SB_ENABLED;
9580         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9581         sb_data_e2.common.p_func.vf_id = vfid;
9582         sb_data_e2.common.p_func.vf_valid = vf_valid;
9583         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9584         sb_data_e2.common.same_igu_sb_1b = TRUE;
9585         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9586         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9587         hc_sm_p = sb_data_e2.common.state_machine;
9588         sb_data_p = (uint32_t *)&sb_data_e2;
9589         data_size = (sizeof(struct hc_status_block_data_e2) /
9590                      sizeof(uint32_t));
9591         bxe_map_sb_state_machines(sb_data_e2.index_data);
9592     } else {
9593         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9594         sb_data_e1x.common.state = SB_ENABLED;
9595         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9596         sb_data_e1x.common.p_func.vf_id = 0xff;
9597         sb_data_e1x.common.p_func.vf_valid = FALSE;
9598         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9599         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9600         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9601         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9602         hc_sm_p = sb_data_e1x.common.state_machine;
9603         sb_data_p = (uint32_t *)&sb_data_e1x;
9604         data_size = (sizeof(struct hc_status_block_data_e1x) /
9605                      sizeof(uint32_t));
9606         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9607     }
9608
9609     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9610     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9611
9612     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9613
9614     /* write indices to HW - PCI guarantees endianity of regpairs */
9615     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9616 }
9617
9618 static inline uint8_t
9619 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9620 {
9621     if (CHIP_IS_E1x(fp->sc)) {
9622         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9623     } else {
9624         return (fp->cl_id);
9625     }
9626 }
9627
9628 static inline uint32_t
9629 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9630                            struct bxe_fastpath *fp)
9631 {
9632     uint32_t offset = BAR_USTRORM_INTMEM;
9633
9634     if (!CHIP_IS_E1x(sc)) {
9635         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9636     } else {
9637         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9638     }
9639
9640     return (offset);
9641 }
9642
9643 static void
9644 bxe_init_eth_fp(struct bxe_softc *sc,
9645                 int              idx)
9646 {
9647     struct bxe_fastpath *fp = &sc->fp[idx];
9648     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9649     unsigned long q_type = 0;
9650     int cos;
9651
9652     fp->sc    = sc;
9653     fp->index = idx;
9654
9655     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9656     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9657
9658     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9659                     (SC_L_ID(sc) + idx) :
9660                     /* want client ID same as IGU SB ID for non-E1 */
9661                     fp->igu_sb_id;
9662     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9663
9664     /* setup sb indices */
9665     if (!CHIP_IS_E1x(sc)) {
9666         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9667         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9668     } else {
9669         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9670         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9671     }
9672
9673     /* init shortcut */
9674     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9675
9676     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9677
9678     /*
9679      * XXX If multiple CoS is ever supported then each fastpath structure
9680      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9681      */
9682     for (cos = 0; cos < sc->max_cos; cos++) {
9683         cids[cos] = idx;
9684     }
9685     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9686
9687     /* nothing more for a VF to do */
9688     if (IS_VF(sc)) {
9689         return;
9690     }
9691
9692     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9693                 fp->fw_sb_id, fp->igu_sb_id);
9694
9695     bxe_update_fp_sb_idx(fp);
9696
9697     /* Configure Queue State object */
9698     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9699     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9700
9701     ecore_init_queue_obj(sc,
9702                          &sc->sp_objs[idx].q_obj,
9703                          fp->cl_id,
9704                          cids,
9705                          sc->max_cos,
9706                          SC_FUNC(sc),
9707                          BXE_SP(sc, q_rdata),
9708                          BXE_SP_MAPPING(sc, q_rdata),
9709                          q_type);
9710
9711     /* configure classification DBs */
9712     ecore_init_mac_obj(sc,
9713                        &sc->sp_objs[idx].mac_obj,
9714                        fp->cl_id,
9715                        idx,
9716                        SC_FUNC(sc),
9717                        BXE_SP(sc, mac_rdata),
9718                        BXE_SP_MAPPING(sc, mac_rdata),
9719                        ECORE_FILTER_MAC_PENDING,
9720                        &sc->sp_state,
9721                        ECORE_OBJ_TYPE_RX_TX,
9722                        &sc->macs_pool);
9723
9724     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9725           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9726 }
9727
9728 static inline void
9729 bxe_update_rx_prod(struct bxe_softc    *sc,
9730                    struct bxe_fastpath *fp,
9731                    uint16_t            rx_bd_prod,
9732                    uint16_t            rx_cq_prod,
9733                    uint16_t            rx_sge_prod)
9734 {
9735     struct ustorm_eth_rx_producers rx_prods = { 0 };
9736     uint32_t i;
9737
9738     /* update producers */
9739     rx_prods.bd_prod  = rx_bd_prod;
9740     rx_prods.cqe_prod = rx_cq_prod;
9741     rx_prods.sge_prod = rx_sge_prod;
9742
9743     /*
9744      * Make sure that the BD and SGE data is updated before updating the
9745      * producers since FW might read the BD/SGE right after the producer
9746      * is updated.
9747      * This is only applicable for weak-ordered memory model archs such
9748      * as IA-64. The following barrier is also mandatory since FW will
9749      * assumes BDs must have buffers.
9750      */
9751     wmb();
9752
9753     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9754         REG_WR(sc,
9755                (fp->ustorm_rx_prods_offset + (i * 4)),
9756                ((uint32_t *)&rx_prods)[i]);
9757     }
9758
9759     wmb(); /* keep prod updates ordered */
9760
9761     BLOGD(sc, DBG_RX,
9762           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9763           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9764 }
9765
9766 static void
9767 bxe_init_rx_rings(struct bxe_softc *sc)
9768 {
9769     struct bxe_fastpath *fp;
9770     int i;
9771
9772     for (i = 0; i < sc->num_queues; i++) {
9773         fp = &sc->fp[i];
9774
9775         fp->rx_bd_cons = 0;
9776
9777         /*
9778          * Activate the BD ring...
9779          * Warning, this will generate an interrupt (to the TSTORM)
9780          * so this can only be done after the chip is initialized
9781          */
9782         bxe_update_rx_prod(sc, fp,
9783                            fp->rx_bd_prod,
9784                            fp->rx_cq_prod,
9785                            fp->rx_sge_prod);
9786
9787         if (i != 0) {
9788             continue;
9789         }
9790
9791         if (CHIP_IS_E1(sc)) {
9792             REG_WR(sc,
9793                    (BAR_USTRORM_INTMEM +
9794                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9795                    U64_LO(fp->rcq_dma.paddr));
9796             REG_WR(sc,
9797                    (BAR_USTRORM_INTMEM +
9798                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9799                    U64_HI(fp->rcq_dma.paddr));
9800         }
9801     }
9802 }
9803
9804 static void
9805 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9806 {
9807     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9808     fp->tx_db.data.zero_fill1 = 0;
9809     fp->tx_db.data.prod = 0;
9810
9811     fp->tx_pkt_prod = 0;
9812     fp->tx_pkt_cons = 0;
9813     fp->tx_bd_prod = 0;
9814     fp->tx_bd_cons = 0;
9815     fp->eth_q_stats.tx_pkts = 0;
9816 }
9817
9818 static inline void
9819 bxe_init_tx_rings(struct bxe_softc *sc)
9820 {
9821     int i;
9822
9823     for (i = 0; i < sc->num_queues; i++) {
9824         bxe_init_tx_ring_one(&sc->fp[i]);
9825     }
9826 }
9827
9828 static void
9829 bxe_init_def_sb(struct bxe_softc *sc)
9830 {
9831     struct host_sp_status_block *def_sb = sc->def_sb;
9832     bus_addr_t mapping = sc->def_sb_dma.paddr;
9833     int igu_sp_sb_index;
9834     int igu_seg_id;
9835     int port = SC_PORT(sc);
9836     int func = SC_FUNC(sc);
9837     int reg_offset, reg_offset_en5;
9838     uint64_t section;
9839     int index, sindex;
9840     struct hc_sp_status_block_data sp_sb_data;
9841
9842     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9843
9844     if (CHIP_INT_MODE_IS_BC(sc)) {
9845         igu_sp_sb_index = DEF_SB_IGU_ID;
9846         igu_seg_id = HC_SEG_ACCESS_DEF;
9847     } else {
9848         igu_sp_sb_index = sc->igu_dsb_id;
9849         igu_seg_id = IGU_SEG_ACCESS_DEF;
9850     }
9851
9852     /* attentions */
9853     section = ((uint64_t)mapping +
9854                offsetof(struct host_sp_status_block, atten_status_block));
9855     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9856     sc->attn_state = 0;
9857
9858     reg_offset = (port) ?
9859                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9860                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9861     reg_offset_en5 = (port) ?
9862                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9863                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9864
9865     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9866         /* take care of sig[0]..sig[4] */
9867         for (sindex = 0; sindex < 4; sindex++) {
9868             sc->attn_group[index].sig[sindex] =
9869                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9870         }
9871
9872         if (!CHIP_IS_E1x(sc)) {
9873             /*
9874              * enable5 is separate from the rest of the registers,
9875              * and the address skip is 4 and not 16 between the
9876              * different groups
9877              */
9878             sc->attn_group[index].sig[4] =
9879                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9880         } else {
9881             sc->attn_group[index].sig[4] = 0;
9882         }
9883     }
9884
9885     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9886         reg_offset = (port) ?
9887                          HC_REG_ATTN_MSG1_ADDR_L :
9888                          HC_REG_ATTN_MSG0_ADDR_L;
9889         REG_WR(sc, reg_offset, U64_LO(section));
9890         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9891     } else if (!CHIP_IS_E1x(sc)) {
9892         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9893         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9894     }
9895
9896     section = ((uint64_t)mapping +
9897                offsetof(struct host_sp_status_block, sp_sb));
9898
9899     bxe_zero_sp_sb(sc);
9900
9901     /* PCI guarantees endianity of regpair */
9902     sp_sb_data.state           = SB_ENABLED;
9903     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9904     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9905     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9906     sp_sb_data.igu_seg_id      = igu_seg_id;
9907     sp_sb_data.p_func.pf_id    = func;
9908     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9909     sp_sb_data.p_func.vf_id    = 0xff;
9910
9911     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9912
9913     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9914 }
9915
9916 static void
9917 bxe_init_sp_ring(struct bxe_softc *sc)
9918 {
9919     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9920     sc->spq_prod_idx = 0;
9921     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9922     sc->spq_prod_bd = sc->spq;
9923     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9924 }
9925
9926 static void
9927 bxe_init_eq_ring(struct bxe_softc *sc)
9928 {
9929     union event_ring_elem *elem;
9930     int i;
9931
9932     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9933         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9934
9935         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9936                                                  BCM_PAGE_SIZE *
9937                                                  (i % NUM_EQ_PAGES)));
9938         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9939                                                  BCM_PAGE_SIZE *
9940                                                  (i % NUM_EQ_PAGES)));
9941     }
9942
9943     sc->eq_cons    = 0;
9944     sc->eq_prod    = NUM_EQ_DESC;
9945     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9946
9947     atomic_store_rel_long(&sc->eq_spq_left,
9948                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9949                                NUM_EQ_DESC) - 1));
9950 }
9951
9952 static void
9953 bxe_init_internal_common(struct bxe_softc *sc)
9954 {
9955     int i;
9956
9957     /*
9958      * Zero this manually as its initialization is currently missing
9959      * in the initTool.
9960      */
9961     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9962         REG_WR(sc,
9963                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9964                0);
9965     }
9966
9967     if (!CHIP_IS_E1x(sc)) {
9968         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9969                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9970     }
9971 }
9972
9973 static void
9974 bxe_init_internal(struct bxe_softc *sc,
9975                   uint32_t         load_code)
9976 {
9977     switch (load_code) {
9978     case FW_MSG_CODE_DRV_LOAD_COMMON:
9979     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9980         bxe_init_internal_common(sc);
9981         /* no break */
9982
9983     case FW_MSG_CODE_DRV_LOAD_PORT:
9984         /* nothing to do */
9985         /* no break */
9986
9987     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9988         /* internal memory per function is initialized inside bxe_pf_init */
9989         break;
9990
9991     default:
9992         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9993         break;
9994     }
9995 }
9996
9997 static void
9998 storm_memset_func_cfg(struct bxe_softc                         *sc,
9999                       struct tstorm_eth_function_common_config *tcfg,
10000                       uint16_t                                  abs_fid)
10001 {
10002     uint32_t addr;
10003     size_t size;
10004
10005     addr = (BAR_TSTRORM_INTMEM +
10006             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
10007     size = sizeof(struct tstorm_eth_function_common_config);
10008     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
10009 }
10010
10011 static void
10012 bxe_func_init(struct bxe_softc            *sc,
10013               struct bxe_func_init_params *p)
10014 {
10015     struct tstorm_eth_function_common_config tcfg = { 0 };
10016
10017     if (CHIP_IS_E1x(sc)) {
10018         storm_memset_func_cfg(sc, &tcfg, p->func_id);
10019     }
10020
10021     /* Enable the function in the FW */
10022     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
10023     storm_memset_func_en(sc, p->func_id, 1);
10024
10025     /* spq */
10026     if (p->func_flgs & FUNC_FLG_SPQ) {
10027         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
10028         REG_WR(sc,
10029                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
10030                p->spq_prod);
10031     }
10032 }
10033
10034 /*
10035  * Calculates the sum of vn_min_rates.
10036  * It's needed for further normalizing of the min_rates.
10037  * Returns:
10038  *   sum of vn_min_rates.
10039  *     or
10040  *   0 - if all the min_rates are 0.
10041  * In the later case fainess algorithm should be deactivated.
10042  * If all min rates are not zero then those that are zeroes will be set to 1.
10043  */
10044 static void
10045 bxe_calc_vn_min(struct bxe_softc       *sc,
10046                 struct cmng_init_input *input)
10047 {
10048     uint32_t vn_cfg;
10049     uint32_t vn_min_rate;
10050     int all_zero = 1;
10051     int vn;
10052
10053     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10054         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10055         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
10056                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
10057
10058         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10059             /* skip hidden VNs */
10060             vn_min_rate = 0;
10061         } else if (!vn_min_rate) {
10062             /* If min rate is zero - set it to 100 */
10063             vn_min_rate = DEF_MIN_RATE;
10064         } else {
10065             all_zero = 0;
10066         }
10067
10068         input->vnic_min_rate[vn] = vn_min_rate;
10069     }
10070
10071     /* if ETS or all min rates are zeros - disable fairness */
10072     if (BXE_IS_ETS_ENABLED(sc)) {
10073         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10074         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10075     } else if (all_zero) {
10076         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10077         BLOGD(sc, DBG_LOAD,
10078               "Fariness disabled (all MIN values are zeroes)\n");
10079     } else {
10080         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10081     }
10082 }
10083
10084 static inline uint16_t
10085 bxe_extract_max_cfg(struct bxe_softc *sc,
10086                     uint32_t         mf_cfg)
10087 {
10088     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10089                         FUNC_MF_CFG_MAX_BW_SHIFT);
10090
10091     if (!max_cfg) {
10092         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10093         max_cfg = 100;
10094     }
10095
10096     return (max_cfg);
10097 }
10098
10099 static void
10100 bxe_calc_vn_max(struct bxe_softc       *sc,
10101                 int                    vn,
10102                 struct cmng_init_input *input)
10103 {
10104     uint16_t vn_max_rate;
10105     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10106     uint32_t max_cfg;
10107
10108     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10109         vn_max_rate = 0;
10110     } else {
10111         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10112
10113         if (IS_MF_SI(sc)) {
10114             /* max_cfg in percents of linkspeed */
10115             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10116         } else { /* SD modes */
10117             /* max_cfg is absolute in 100Mb units */
10118             vn_max_rate = (max_cfg * 100);
10119         }
10120     }
10121
10122     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10123
10124     input->vnic_max_rate[vn] = vn_max_rate;
10125 }
10126
10127 static void
10128 bxe_cmng_fns_init(struct bxe_softc *sc,
10129                   uint8_t          read_cfg,
10130                   uint8_t          cmng_type)
10131 {
10132     struct cmng_init_input input;
10133     int vn;
10134
10135     memset(&input, 0, sizeof(struct cmng_init_input));
10136
10137     input.port_rate = sc->link_vars.line_speed;
10138
10139     if (cmng_type == CMNG_FNS_MINMAX) {
10140         /* read mf conf from shmem */
10141         if (read_cfg) {
10142             bxe_read_mf_cfg(sc);
10143         }
10144
10145         /* get VN min rate and enable fairness if not 0 */
10146         bxe_calc_vn_min(sc, &input);
10147
10148         /* get VN max rate */
10149         if (sc->port.pmf) {
10150             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10151                 bxe_calc_vn_max(sc, vn, &input);
10152             }
10153         }
10154
10155         /* always enable rate shaping and fairness */
10156         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10157
10158         ecore_init_cmng(&input, &sc->cmng);
10159         return;
10160     }
10161
10162     /* rate shaping and fairness are disabled */
10163     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10164 }
10165
10166 static int
10167 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10168 {
10169     if (CHIP_REV_IS_SLOW(sc)) {
10170         return (CMNG_FNS_NONE);
10171     }
10172
10173     if (IS_MF(sc)) {
10174         return (CMNG_FNS_MINMAX);
10175     }
10176
10177     return (CMNG_FNS_NONE);
10178 }
10179
10180 static void
10181 storm_memset_cmng(struct bxe_softc *sc,
10182                   struct cmng_init *cmng,
10183                   uint8_t          port)
10184 {
10185     int vn;
10186     int func;
10187     uint32_t addr;
10188     size_t size;
10189
10190     addr = (BAR_XSTRORM_INTMEM +
10191             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10192     size = sizeof(struct cmng_struct_per_port);
10193     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10194
10195     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10196         func = func_by_vn(sc, vn);
10197
10198         addr = (BAR_XSTRORM_INTMEM +
10199                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10200         size = sizeof(struct rate_shaping_vars_per_vn);
10201         ecore_storm_memset_struct(sc, addr, size,
10202                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10203
10204         addr = (BAR_XSTRORM_INTMEM +
10205                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10206         size = sizeof(struct fairness_vars_per_vn);
10207         ecore_storm_memset_struct(sc, addr, size,
10208                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10209     }
10210 }
10211
10212 static void
10213 bxe_pf_init(struct bxe_softc *sc)
10214 {
10215     struct bxe_func_init_params func_init = { 0 };
10216     struct event_ring_data eq_data = { { 0 } };
10217     uint16_t flags;
10218
10219     if (!CHIP_IS_E1x(sc)) {
10220         /* reset IGU PF statistics: MSIX + ATTN */
10221         /* PF */
10222         REG_WR(sc,
10223                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10224                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10225                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10226                0);
10227         /* ATTN */
10228         REG_WR(sc,
10229                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10230                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10231                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10232                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10233                0);
10234     }
10235
10236     /* function setup flags */
10237     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10238
10239     /*
10240      * This flag is relevant for E1x only.
10241      * E2 doesn't have a TPA configuration in a function level.
10242      */
10243     flags |= (sc->ifnet->if_capenable & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10244
10245     func_init.func_flgs = flags;
10246     func_init.pf_id     = SC_FUNC(sc);
10247     func_init.func_id   = SC_FUNC(sc);
10248     func_init.spq_map   = sc->spq_dma.paddr;
10249     func_init.spq_prod  = sc->spq_prod_idx;
10250
10251     bxe_func_init(sc, &func_init);
10252
10253     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10254
10255     /*
10256      * Congestion management values depend on the link rate.
10257      * There is no active link so initial link rate is set to 10Gbps.
10258      * When the link comes up the congestion management values are
10259      * re-calculated according to the actual link rate.
10260      */
10261     sc->link_vars.line_speed = SPEED_10000;
10262     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10263
10264     /* Only the PMF sets the HW */
10265     if (sc->port.pmf) {
10266         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10267     }
10268
10269     /* init Event Queue - PCI bus guarantees correct endainity */
10270     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10271     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10272     eq_data.producer     = sc->eq_prod;
10273     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10274     eq_data.sb_id        = DEF_SB_ID;
10275     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10276 }
10277
10278 static void
10279 bxe_hc_int_enable(struct bxe_softc *sc)
10280 {
10281     int port = SC_PORT(sc);
10282     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10283     uint32_t val = REG_RD(sc, addr);
10284     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10285     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10286                            (sc->intr_count == 1)) ? TRUE : FALSE;
10287     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10288
10289     if (msix) {
10290         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10291                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10292         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10293                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10294         if (single_msix) {
10295             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10296         }
10297     } else if (msi) {
10298         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10299         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10300                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10301                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10302     } else {
10303         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10304                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10305                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10306                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10307
10308         if (!CHIP_IS_E1(sc)) {
10309             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10310                   val, port, addr);
10311
10312             REG_WR(sc, addr, val);
10313
10314             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10315         }
10316     }
10317
10318     if (CHIP_IS_E1(sc)) {
10319         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10320     }
10321
10322     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10323           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10324
10325     REG_WR(sc, addr, val);
10326
10327     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10328     mb();
10329
10330     if (!CHIP_IS_E1(sc)) {
10331         /* init leading/trailing edge */
10332         if (IS_MF(sc)) {
10333             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10334             if (sc->port.pmf) {
10335                 /* enable nig and gpio3 attention */
10336                 val |= 0x1100;
10337             }
10338         } else {
10339             val = 0xffff;
10340         }
10341
10342         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10343         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10344     }
10345
10346     /* make sure that interrupts are indeed enabled from here on */
10347     mb();
10348 }
10349
10350 static void
10351 bxe_igu_int_enable(struct bxe_softc *sc)
10352 {
10353     uint32_t val;
10354     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10355     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10356                            (sc->intr_count == 1)) ? TRUE : FALSE;
10357     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10358
10359     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10360
10361     if (msix) {
10362         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10363                  IGU_PF_CONF_SINGLE_ISR_EN);
10364         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10365                 IGU_PF_CONF_ATTN_BIT_EN);
10366         if (single_msix) {
10367             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10368         }
10369     } else if (msi) {
10370         val &= ~IGU_PF_CONF_INT_LINE_EN;
10371         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10372                 IGU_PF_CONF_ATTN_BIT_EN |
10373                 IGU_PF_CONF_SINGLE_ISR_EN);
10374     } else {
10375         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10376         val |= (IGU_PF_CONF_INT_LINE_EN |
10377                 IGU_PF_CONF_ATTN_BIT_EN |
10378                 IGU_PF_CONF_SINGLE_ISR_EN);
10379     }
10380
10381     /* clean previous status - need to configure igu prior to ack*/
10382     if ((!msix) || single_msix) {
10383         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10384         bxe_ack_int(sc);
10385     }
10386
10387     val |= IGU_PF_CONF_FUNC_EN;
10388
10389     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10390           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10391
10392     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10393
10394     mb();
10395
10396     /* init leading/trailing edge */
10397     if (IS_MF(sc)) {
10398         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10399         if (sc->port.pmf) {
10400             /* enable nig and gpio3 attention */
10401             val |= 0x1100;
10402         }
10403     } else {
10404         val = 0xffff;
10405     }
10406
10407     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10408     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10409
10410     /* make sure that interrupts are indeed enabled from here on */
10411     mb();
10412 }
10413
10414 static void
10415 bxe_int_enable(struct bxe_softc *sc)
10416 {
10417     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10418         bxe_hc_int_enable(sc);
10419     } else {
10420         bxe_igu_int_enable(sc);
10421     }
10422 }
10423
10424 static void
10425 bxe_hc_int_disable(struct bxe_softc *sc)
10426 {
10427     int port = SC_PORT(sc);
10428     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10429     uint32_t val = REG_RD(sc, addr);
10430
10431     /*
10432      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10433      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10434      * block
10435      */
10436     if (CHIP_IS_E1(sc)) {
10437         /*
10438          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10439          * to prevent from HC sending interrupts after we exit the function
10440          */
10441         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10442
10443         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10444                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10445                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10446     } else {
10447         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10448                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10449                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10450                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10451     }
10452
10453     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10454
10455     /* flush all outstanding writes */
10456     mb();
10457
10458     REG_WR(sc, addr, val);
10459     if (REG_RD(sc, addr) != val) {
10460         BLOGE(sc, "proper val not read from HC IGU!\n");
10461     }
10462 }
10463
10464 static void
10465 bxe_igu_int_disable(struct bxe_softc *sc)
10466 {
10467     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10468
10469     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10470              IGU_PF_CONF_INT_LINE_EN |
10471              IGU_PF_CONF_ATTN_BIT_EN);
10472
10473     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10474
10475     /* flush all outstanding writes */
10476     mb();
10477
10478     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10479     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10480         BLOGE(sc, "proper val not read from IGU!\n");
10481     }
10482 }
10483
10484 static void
10485 bxe_int_disable(struct bxe_softc *sc)
10486 {
10487     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10488         bxe_hc_int_disable(sc);
10489     } else {
10490         bxe_igu_int_disable(sc);
10491     }
10492 }
10493
10494 static void
10495 bxe_nic_init(struct bxe_softc *sc,
10496              int              load_code)
10497 {
10498     int i;
10499
10500     for (i = 0; i < sc->num_queues; i++) {
10501         bxe_init_eth_fp(sc, i);
10502     }
10503
10504     rmb(); /* ensure status block indices were read */
10505
10506     bxe_init_rx_rings(sc);
10507     bxe_init_tx_rings(sc);
10508
10509     if (IS_VF(sc)) {
10510         return;
10511     }
10512
10513     /* initialize MOD_ABS interrupts */
10514     elink_init_mod_abs_int(sc, &sc->link_vars,
10515                            sc->devinfo.chip_id,
10516                            sc->devinfo.shmem_base,
10517                            sc->devinfo.shmem2_base,
10518                            SC_PORT(sc));
10519
10520     bxe_init_def_sb(sc);
10521     bxe_update_dsb_idx(sc);
10522     bxe_init_sp_ring(sc);
10523     bxe_init_eq_ring(sc);
10524     bxe_init_internal(sc, load_code);
10525     bxe_pf_init(sc);
10526     bxe_stats_init(sc);
10527
10528     /* flush all before enabling interrupts */
10529     mb();
10530
10531     bxe_int_enable(sc);
10532
10533     /* check for SPIO5 */
10534     bxe_attn_int_deasserted0(sc,
10535                              REG_RD(sc,
10536                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10537                                      SC_PORT(sc)*4)) &
10538                              AEU_INPUTS_ATTN_BITS_SPIO5);
10539 }
10540
10541 static inline void
10542 bxe_init_objs(struct bxe_softc *sc)
10543 {
10544     /* mcast rules must be added to tx if tx switching is enabled */
10545     ecore_obj_type o_type =
10546         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10547                                          ECORE_OBJ_TYPE_RX;
10548
10549     /* RX_MODE controlling object */
10550     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10551
10552     /* multicast configuration controlling object */
10553     ecore_init_mcast_obj(sc,
10554                          &sc->mcast_obj,
10555                          sc->fp[0].cl_id,
10556                          sc->fp[0].index,
10557                          SC_FUNC(sc),
10558                          SC_FUNC(sc),
10559                          BXE_SP(sc, mcast_rdata),
10560                          BXE_SP_MAPPING(sc, mcast_rdata),
10561                          ECORE_FILTER_MCAST_PENDING,
10562                          &sc->sp_state,
10563                          o_type);
10564
10565     /* Setup CAM credit pools */
10566     ecore_init_mac_credit_pool(sc,
10567                                &sc->macs_pool,
10568                                SC_FUNC(sc),
10569                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10570                                                  VNICS_PER_PATH(sc));
10571
10572     ecore_init_vlan_credit_pool(sc,
10573                                 &sc->vlans_pool,
10574                                 SC_ABS_FUNC(sc) >> 1,
10575                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10576                                                   VNICS_PER_PATH(sc));
10577
10578     /* RSS configuration object */
10579     ecore_init_rss_config_obj(sc,
10580                               &sc->rss_conf_obj,
10581                               sc->fp[0].cl_id,
10582                               sc->fp[0].index,
10583                               SC_FUNC(sc),
10584                               SC_FUNC(sc),
10585                               BXE_SP(sc, rss_rdata),
10586                               BXE_SP_MAPPING(sc, rss_rdata),
10587                               ECORE_FILTER_RSS_CONF_PENDING,
10588                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10589 }
10590
10591 /*
10592  * Initialize the function. This must be called before sending CLIENT_SETUP
10593  * for the first client.
10594  */
10595 static inline int
10596 bxe_func_start(struct bxe_softc *sc)
10597 {
10598     struct ecore_func_state_params func_params = { NULL };
10599     struct ecore_func_start_params *start_params = &func_params.params.start;
10600
10601     /* Prepare parameters for function state transitions */
10602     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10603
10604     func_params.f_obj = &sc->func_obj;
10605     func_params.cmd = ECORE_F_CMD_START;
10606
10607     /* Function parameters */
10608     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10609     start_params->sd_vlan_tag = OVLAN(sc);
10610
10611     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10612         start_params->network_cos_mode = STATIC_COS;
10613     } else { /* CHIP_IS_E1X */
10614         start_params->network_cos_mode = FW_WRR;
10615     }
10616
10617     //start_params->gre_tunnel_mode = 0;
10618     //start_params->gre_tunnel_rss  = 0;
10619
10620     return (ecore_func_state_change(sc, &func_params));
10621 }
10622
10623 static int
10624 bxe_set_power_state(struct bxe_softc *sc,
10625                     uint8_t          state)
10626 {
10627     uint16_t pmcsr;
10628
10629     /* If there is no power capability, silently succeed */
10630     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10631         BLOGW(sc, "No power capability\n");
10632         return (0);
10633     }
10634
10635     pmcsr = pci_read_config(sc->dev,
10636                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10637                             2);
10638
10639     switch (state) {
10640     case PCI_PM_D0:
10641         pci_write_config(sc->dev,
10642                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10643                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10644
10645         if (pmcsr & PCIM_PSTAT_DMASK) {
10646             /* delay required during transition out of D3hot */
10647             DELAY(20000);
10648         }
10649
10650         break;
10651
10652     case PCI_PM_D3hot:
10653         /* XXX if there are other clients above don't shut down the power */
10654
10655         /* don't shut down the power for emulation and FPGA */
10656         if (CHIP_REV_IS_SLOW(sc)) {
10657             return (0);
10658         }
10659
10660         pmcsr &= ~PCIM_PSTAT_DMASK;
10661         pmcsr |= PCIM_PSTAT_D3;
10662
10663         if (sc->wol) {
10664             pmcsr |= PCIM_PSTAT_PMEENABLE;
10665         }
10666
10667         pci_write_config(sc->dev,
10668                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10669                          pmcsr, 4);
10670
10671         /*
10672          * No more memory access after this point until device is brought back
10673          * to D0 state.
10674          */
10675         break;
10676
10677     default:
10678         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10679             state, pmcsr);
10680         return (-1);
10681     }
10682
10683     return (0);
10684 }
10685
10686
10687 /* return true if succeeded to acquire the lock */
10688 static uint8_t
10689 bxe_trylock_hw_lock(struct bxe_softc *sc,
10690                     uint32_t         resource)
10691 {
10692     uint32_t lock_status;
10693     uint32_t resource_bit = (1 << resource);
10694     int func = SC_FUNC(sc);
10695     uint32_t hw_lock_control_reg;
10696
10697     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10698
10699     /* Validating that the resource is within range */
10700     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10701         BLOGD(sc, DBG_LOAD,
10702               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10703               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10704         return (FALSE);
10705     }
10706
10707     if (func <= 5) {
10708         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10709     } else {
10710         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10711     }
10712
10713     /* try to acquire the lock */
10714     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10715     lock_status = REG_RD(sc, hw_lock_control_reg);
10716     if (lock_status & resource_bit) {
10717         return (TRUE);
10718     }
10719
10720     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10721         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10722         lock_status, resource_bit);
10723
10724     return (FALSE);
10725 }
10726
10727 /*
10728  * Get the recovery leader resource id according to the engine this function
10729  * belongs to. Currently only only 2 engines is supported.
10730  */
10731 static int
10732 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10733 {
10734     if (SC_PATH(sc)) {
10735         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10736     } else {
10737         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10738     }
10739 }
10740
10741 /* try to acquire a leader lock for current engine */
10742 static uint8_t
10743 bxe_trylock_leader_lock(struct bxe_softc *sc)
10744 {
10745     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10746 }
10747
10748 static int
10749 bxe_release_leader_lock(struct bxe_softc *sc)
10750 {
10751     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10752 }
10753
10754 /* close gates #2, #3 and #4 */
10755 static void
10756 bxe_set_234_gates(struct bxe_softc *sc,
10757                   uint8_t          close)
10758 {
10759     uint32_t val;
10760
10761     /* gates #2 and #4a are closed/opened for "not E1" only */
10762     if (!CHIP_IS_E1(sc)) {
10763         /* #4 */
10764         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10765         /* #2 */
10766         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10767     }
10768
10769     /* #3 */
10770     if (CHIP_IS_E1x(sc)) {
10771         /* prevent interrupts from HC on both ports */
10772         val = REG_RD(sc, HC_REG_CONFIG_1);
10773         REG_WR(sc, HC_REG_CONFIG_1,
10774                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10775                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10776
10777         val = REG_RD(sc, HC_REG_CONFIG_0);
10778         REG_WR(sc, HC_REG_CONFIG_0,
10779                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10780                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10781     } else {
10782         /* Prevent incomming interrupts in IGU */
10783         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10784
10785         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10786                (!close) ?
10787                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10788                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10789     }
10790
10791     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10792           close ? "closing" : "opening");
10793
10794     wmb();
10795 }
10796
10797 /* poll for pending writes bit, it should get cleared in no more than 1s */
10798 static int
10799 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10800 {
10801     uint32_t cnt = 1000;
10802     uint32_t pend_bits = 0;
10803
10804     do {
10805         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10806
10807         if (pend_bits == 0) {
10808             break;
10809         }
10810
10811         DELAY(1000);
10812     } while (--cnt > 0);
10813
10814     if (cnt == 0) {
10815         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10816         return (-1);
10817     }
10818
10819     return (0);
10820 }
10821
10822 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10823
10824 static void
10825 bxe_clp_reset_prep(struct bxe_softc *sc,
10826                    uint32_t         *magic_val)
10827 {
10828     /* Do some magic... */
10829     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10830     *magic_val = val & SHARED_MF_CLP_MAGIC;
10831     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10832 }
10833
10834 /* restore the value of the 'magic' bit */
10835 static void
10836 bxe_clp_reset_done(struct bxe_softc *sc,
10837                    uint32_t         magic_val)
10838 {
10839     /* Restore the 'magic' bit value... */
10840     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10841     MFCFG_WR(sc, shared_mf_config.clp_mb,
10842               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10843 }
10844
10845 /* prepare for MCP reset, takes care of CLP configurations */
10846 static void
10847 bxe_reset_mcp_prep(struct bxe_softc *sc,
10848                    uint32_t         *magic_val)
10849 {
10850     uint32_t shmem;
10851     uint32_t validity_offset;
10852
10853     /* set `magic' bit in order to save MF config */
10854     if (!CHIP_IS_E1(sc)) {
10855         bxe_clp_reset_prep(sc, magic_val);
10856     }
10857
10858     /* get shmem offset */
10859     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10860     validity_offset =
10861         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10862
10863     /* Clear validity map flags */
10864     if (shmem > 0) {
10865         REG_WR(sc, shmem + validity_offset, 0);
10866     }
10867 }
10868
10869 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10870 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10871
10872 static void
10873 bxe_mcp_wait_one(struct bxe_softc *sc)
10874 {
10875     /* special handling for emulation and FPGA (10 times longer) */
10876     if (CHIP_REV_IS_SLOW(sc)) {
10877         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10878     } else {
10879         DELAY((MCP_ONE_TIMEOUT) * 1000);
10880     }
10881 }
10882
10883 /* initialize shmem_base and waits for validity signature to appear */
10884 static int
10885 bxe_init_shmem(struct bxe_softc *sc)
10886 {
10887     int cnt = 0;
10888     uint32_t val = 0;
10889
10890     do {
10891         sc->devinfo.shmem_base     =
10892         sc->link_params.shmem_base =
10893             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10894
10895         if (sc->devinfo.shmem_base) {
10896             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10897             if (val & SHR_MEM_VALIDITY_MB)
10898                 return (0);
10899         }
10900
10901         bxe_mcp_wait_one(sc);
10902
10903     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10904
10905     BLOGE(sc, "BAD MCP validity signature\n");
10906
10907     return (-1);
10908 }
10909
10910 static int
10911 bxe_reset_mcp_comp(struct bxe_softc *sc,
10912                    uint32_t         magic_val)
10913 {
10914     int rc = bxe_init_shmem(sc);
10915
10916     /* Restore the `magic' bit value */
10917     if (!CHIP_IS_E1(sc)) {
10918         bxe_clp_reset_done(sc, magic_val);
10919     }
10920
10921     return (rc);
10922 }
10923
10924 static void
10925 bxe_pxp_prep(struct bxe_softc *sc)
10926 {
10927     if (!CHIP_IS_E1(sc)) {
10928         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10929         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10930         wmb();
10931     }
10932 }
10933
10934 /*
10935  * Reset the whole chip except for:
10936  *      - PCIE core
10937  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10938  *      - IGU
10939  *      - MISC (including AEU)
10940  *      - GRC
10941  *      - RBCN, RBCP
10942  */
10943 static void
10944 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10945                             uint8_t          global)
10946 {
10947     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10948     uint32_t global_bits2, stay_reset2;
10949
10950     /*
10951      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10952      * (per chip) blocks.
10953      */
10954     global_bits2 =
10955         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10956         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10957
10958     /*
10959      * Don't reset the following blocks.
10960      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10961      *            reset, as in 4 port device they might still be owned
10962      *            by the MCP (there is only one leader per path).
10963      */
10964     not_reset_mask1 =
10965         MISC_REGISTERS_RESET_REG_1_RST_HC |
10966         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10967         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10968
10969     not_reset_mask2 =
10970         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10971         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10972         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10973         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10974         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10975         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10976         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10977         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10978         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10979         MISC_REGISTERS_RESET_REG_2_PGLC |
10980         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10981         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10982         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10983         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10984         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10985         MISC_REGISTERS_RESET_REG_2_UMAC1;
10986
10987     /*
10988      * Keep the following blocks in reset:
10989      *  - all xxMACs are handled by the elink code.
10990      */
10991     stay_reset2 =
10992         MISC_REGISTERS_RESET_REG_2_XMAC |
10993         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10994
10995     /* Full reset masks according to the chip */
10996     reset_mask1 = 0xffffffff;
10997
10998     if (CHIP_IS_E1(sc))
10999         reset_mask2 = 0xffff;
11000     else if (CHIP_IS_E1H(sc))
11001         reset_mask2 = 0x1ffff;
11002     else if (CHIP_IS_E2(sc))
11003         reset_mask2 = 0xfffff;
11004     else /* CHIP_IS_E3 */
11005         reset_mask2 = 0x3ffffff;
11006
11007     /* Don't reset global blocks unless we need to */
11008     if (!global)
11009         reset_mask2 &= ~global_bits2;
11010
11011     /*
11012      * In case of attention in the QM, we need to reset PXP
11013      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
11014      * because otherwise QM reset would release 'close the gates' shortly
11015      * before resetting the PXP, then the PSWRQ would send a write
11016      * request to PGLUE. Then when PXP is reset, PGLUE would try to
11017      * read the payload data from PSWWR, but PSWWR would not
11018      * respond. The write queue in PGLUE would stuck, dmae commands
11019      * would not return. Therefore it's important to reset the second
11020      * reset register (containing the
11021      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
11022      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
11023      * bit).
11024      */
11025     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
11026            reset_mask2 & (~not_reset_mask2));
11027
11028     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
11029            reset_mask1 & (~not_reset_mask1));
11030
11031     mb();
11032     wmb();
11033
11034     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
11035            reset_mask2 & (~stay_reset2));
11036
11037     mb();
11038     wmb();
11039
11040     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
11041     wmb();
11042 }
11043
11044 static int
11045 bxe_process_kill(struct bxe_softc *sc,
11046                  uint8_t          global)
11047 {
11048     int cnt = 1000;
11049     uint32_t val = 0;
11050     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
11051     uint32_t tags_63_32 = 0;
11052
11053     /* Empty the Tetris buffer, wait for 1s */
11054     do {
11055         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
11056         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
11057         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
11058         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
11059         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
11060         if (CHIP_IS_E3(sc)) {
11061             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
11062         }
11063
11064         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11065             ((port_is_idle_0 & 0x1) == 0x1) &&
11066             ((port_is_idle_1 & 0x1) == 0x1) &&
11067             (pgl_exp_rom2 == 0xffffffff) &&
11068             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11069             break;
11070         DELAY(1000);
11071     } while (cnt-- > 0);
11072
11073     if (cnt <= 0) {
11074         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11075                   "are still outstanding read requests after 1s! "
11076                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11077                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11078               sr_cnt, blk_cnt, port_is_idle_0,
11079               port_is_idle_1, pgl_exp_rom2);
11080         return (-1);
11081     }
11082
11083     mb();
11084
11085     /* Close gates #2, #3 and #4 */
11086     bxe_set_234_gates(sc, TRUE);
11087
11088     /* Poll for IGU VQs for 57712 and newer chips */
11089     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11090         return (-1);
11091     }
11092
11093     /* XXX indicate that "process kill" is in progress to MCP */
11094
11095     /* clear "unprepared" bit */
11096     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11097     mb();
11098
11099     /* Make sure all is written to the chip before the reset */
11100     wmb();
11101
11102     /*
11103      * Wait for 1ms to empty GLUE and PCI-E core queues,
11104      * PSWHST, GRC and PSWRD Tetris buffer.
11105      */
11106     DELAY(1000);
11107
11108     /* Prepare to chip reset: */
11109     /* MCP */
11110     if (global) {
11111         bxe_reset_mcp_prep(sc, &val);
11112     }
11113
11114     /* PXP */
11115     bxe_pxp_prep(sc);
11116     mb();
11117
11118     /* reset the chip */
11119     bxe_process_kill_chip_reset(sc, global);
11120     mb();
11121
11122     /* clear errors in PGB */
11123     if (!CHIP_IS_E1(sc))
11124         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11125
11126     /* Recover after reset: */
11127     /* MCP */
11128     if (global && bxe_reset_mcp_comp(sc, val)) {
11129         return (-1);
11130     }
11131
11132     /* XXX add resetting the NO_MCP mode DB here */
11133
11134     /* Open the gates #2, #3 and #4 */
11135     bxe_set_234_gates(sc, FALSE);
11136
11137     /* XXX
11138      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11139      * re-enable attentions
11140      */
11141
11142     return (0);
11143 }
11144
11145 static int
11146 bxe_leader_reset(struct bxe_softc *sc)
11147 {
11148     int rc = 0;
11149     uint8_t global = bxe_reset_is_global(sc);
11150     uint32_t load_code;
11151
11152     /*
11153      * If not going to reset MCP, load "fake" driver to reset HW while
11154      * driver is owner of the HW.
11155      */
11156     if (!global && !BXE_NOMCP(sc)) {
11157         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11158                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11159         if (!load_code) {
11160             BLOGE(sc, "MCP response failure, aborting\n");
11161             rc = -1;
11162             goto exit_leader_reset;
11163         }
11164
11165         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11166             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11167             BLOGE(sc, "MCP unexpected response, aborting\n");
11168             rc = -1;
11169             goto exit_leader_reset2;
11170         }
11171
11172         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11173         if (!load_code) {
11174             BLOGE(sc, "MCP response failure, aborting\n");
11175             rc = -1;
11176             goto exit_leader_reset2;
11177         }
11178     }
11179
11180     /* try to recover after the failure */
11181     if (bxe_process_kill(sc, global)) {
11182         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11183         rc = -1;
11184         goto exit_leader_reset2;
11185     }
11186
11187     /*
11188      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11189      * state.
11190      */
11191     bxe_set_reset_done(sc);
11192     if (global) {
11193         bxe_clear_reset_global(sc);
11194     }
11195
11196 exit_leader_reset2:
11197
11198     /* unload "fake driver" if it was loaded */
11199     if (!global && !BXE_NOMCP(sc)) {
11200         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11201         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11202     }
11203
11204 exit_leader_reset:
11205
11206     sc->is_leader = 0;
11207     bxe_release_leader_lock(sc);
11208
11209     mb();
11210     return (rc);
11211 }
11212
11213 /*
11214  * prepare INIT transition, parameters configured:
11215  *   - HC configuration
11216  *   - Queue's CDU context
11217  */
11218 static void
11219 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11220                    struct bxe_fastpath            *fp,
11221                    struct ecore_queue_init_params *init_params)
11222 {
11223     uint8_t cos;
11224     int cxt_index, cxt_offset;
11225
11226     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11227     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11228
11229     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11230     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11231
11232     /* HC rate */
11233     init_params->rx.hc_rate =
11234         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11235     init_params->tx.hc_rate =
11236         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11237
11238     /* FW SB ID */
11239     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11240
11241     /* CQ index among the SB indices */
11242     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11243     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11244
11245     /* set maximum number of COSs supported by this queue */
11246     init_params->max_cos = sc->max_cos;
11247
11248     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11249           fp->index, init_params->max_cos);
11250
11251     /* set the context pointers queue object */
11252     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11253         /* XXX change index/cid here if ever support multiple tx CoS */
11254         /* fp->txdata[cos]->cid */
11255         cxt_index = fp->index / ILT_PAGE_CIDS;
11256         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11257         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11258     }
11259 }
11260
11261 /* set flags that are common for the Tx-only and not normal connections */
11262 static unsigned long
11263 bxe_get_common_flags(struct bxe_softc    *sc,
11264                      struct bxe_fastpath *fp,
11265                      uint8_t             zero_stats)
11266 {
11267     unsigned long flags = 0;
11268
11269     /* PF driver will always initialize the Queue to an ACTIVE state */
11270     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11271
11272     /*
11273      * tx only connections collect statistics (on the same index as the
11274      * parent connection). The statistics are zeroed when the parent
11275      * connection is initialized.
11276      */
11277
11278     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11279     if (zero_stats) {
11280         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11281     }
11282
11283     /*
11284      * tx only connections can support tx-switching, though their
11285      * CoS-ness doesn't survive the loopback
11286      */
11287     if (sc->flags & BXE_TX_SWITCHING) {
11288         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11289     }
11290
11291     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11292
11293     return (flags);
11294 }
11295
11296 static unsigned long
11297 bxe_get_q_flags(struct bxe_softc    *sc,
11298                 struct bxe_fastpath *fp,
11299                 uint8_t             leading)
11300 {
11301     unsigned long flags = 0;
11302
11303     if (IS_MF_SD(sc)) {
11304         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11305     }
11306
11307     if (sc->ifnet->if_capenable & IFCAP_LRO) {
11308         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11309         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11310     }
11311
11312     if (leading) {
11313         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11314         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11315     }
11316
11317     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11318
11319     /* merge with common flags */
11320     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11321 }
11322
11323 static void
11324 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11325                       struct bxe_fastpath               *fp,
11326                       struct ecore_general_setup_params *gen_init,
11327                       uint8_t                           cos)
11328 {
11329     gen_init->stat_id = bxe_stats_id(fp);
11330     gen_init->spcl_id = fp->cl_id;
11331     gen_init->mtu = sc->mtu;
11332     gen_init->cos = cos;
11333 }
11334
11335 static void
11336 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11337                  struct bxe_fastpath           *fp,
11338                  struct rxq_pause_params       *pause,
11339                  struct ecore_rxq_setup_params *rxq_init)
11340 {
11341     uint8_t max_sge = 0;
11342     uint16_t sge_sz = 0;
11343     uint16_t tpa_agg_size = 0;
11344
11345     pause->sge_th_lo = SGE_TH_LO(sc);
11346     pause->sge_th_hi = SGE_TH_HI(sc);
11347
11348     /* validate SGE ring has enough to cross high threshold */
11349     if (sc->dropless_fc &&
11350             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11351             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11352         BLOGW(sc, "sge ring threshold limit\n");
11353     }
11354
11355     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11356     tpa_agg_size = (2 * sc->mtu);
11357     if (tpa_agg_size < sc->max_aggregation_size) {
11358         tpa_agg_size = sc->max_aggregation_size;
11359     }
11360
11361     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11362     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11363                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11364     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11365
11366     /* pause - not for e1 */
11367     if (!CHIP_IS_E1(sc)) {
11368         pause->bd_th_lo = BD_TH_LO(sc);
11369         pause->bd_th_hi = BD_TH_HI(sc);
11370
11371         pause->rcq_th_lo = RCQ_TH_LO(sc);
11372         pause->rcq_th_hi = RCQ_TH_HI(sc);
11373
11374         /* validate rings have enough entries to cross high thresholds */
11375         if (sc->dropless_fc &&
11376             pause->bd_th_hi + FW_PREFETCH_CNT >
11377             sc->rx_ring_size) {
11378             BLOGW(sc, "rx bd ring threshold limit\n");
11379         }
11380
11381         if (sc->dropless_fc &&
11382             pause->rcq_th_hi + FW_PREFETCH_CNT >
11383             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11384             BLOGW(sc, "rcq ring threshold limit\n");
11385         }
11386
11387         pause->pri_map = 1;
11388     }
11389
11390     /* rxq setup */
11391     rxq_init->dscr_map   = fp->rx_dma.paddr;
11392     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11393     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11394     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11395
11396     /*
11397      * This should be a maximum number of data bytes that may be
11398      * placed on the BD (not including paddings).
11399      */
11400     rxq_init->buf_sz = (fp->rx_buf_size -
11401                         IP_HEADER_ALIGNMENT_PADDING);
11402
11403     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11404     rxq_init->tpa_agg_sz      = tpa_agg_size;
11405     rxq_init->sge_buf_sz      = sge_sz;
11406     rxq_init->max_sges_pkt    = max_sge;
11407     rxq_init->rss_engine_id   = SC_FUNC(sc);
11408     rxq_init->mcast_engine_id = SC_FUNC(sc);
11409
11410     /*
11411      * Maximum number or simultaneous TPA aggregation for this Queue.
11412      * For PF Clients it should be the maximum available number.
11413      * VF driver(s) may want to define it to a smaller value.
11414      */
11415     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11416
11417     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11418     rxq_init->fw_sb_id = fp->fw_sb_id;
11419
11420     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11421
11422     /*
11423      * configure silent vlan removal
11424      * if multi function mode is afex, then mask default vlan
11425      */
11426     if (IS_MF_AFEX(sc)) {
11427         rxq_init->silent_removal_value =
11428             sc->devinfo.mf_info.afex_def_vlan_tag;
11429         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11430     }
11431 }
11432
11433 static void
11434 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11435                  struct bxe_fastpath           *fp,
11436                  struct ecore_txq_setup_params *txq_init,
11437                  uint8_t                       cos)
11438 {
11439     /*
11440      * XXX If multiple CoS is ever supported then each fastpath structure
11441      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11442      * fp->txdata[cos]->tx_dma.paddr;
11443      */
11444     txq_init->dscr_map     = fp->tx_dma.paddr;
11445     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11446     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11447     txq_init->fw_sb_id     = fp->fw_sb_id;
11448
11449     /*
11450      * set the TSS leading client id for TX classfication to the
11451      * leading RSS client id
11452      */
11453     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11454 }
11455
11456 /*
11457  * This function performs 2 steps in a queue state machine:
11458  *   1) RESET->INIT
11459  *   2) INIT->SETUP
11460  */
11461 static int
11462 bxe_setup_queue(struct bxe_softc    *sc,
11463                 struct bxe_fastpath *fp,
11464                 uint8_t             leading)
11465 {
11466     struct ecore_queue_state_params q_params = { NULL };
11467     struct ecore_queue_setup_params *setup_params =
11468                         &q_params.params.setup;
11469     int rc;
11470
11471     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11472
11473     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11474
11475     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11476
11477     /* we want to wait for completion in this context */
11478     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11479
11480     /* prepare the INIT parameters */
11481     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11482
11483     /* Set the command */
11484     q_params.cmd = ECORE_Q_CMD_INIT;
11485
11486     /* Change the state to INIT */
11487     rc = ecore_queue_state_change(sc, &q_params);
11488     if (rc) {
11489         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11490         return (rc);
11491     }
11492
11493     BLOGD(sc, DBG_LOAD, "init complete\n");
11494
11495     /* now move the Queue to the SETUP state */
11496     memset(setup_params, 0, sizeof(*setup_params));
11497
11498     /* set Queue flags */
11499     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11500
11501     /* set general SETUP parameters */
11502     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11503                           FIRST_TX_COS_INDEX);
11504
11505     bxe_pf_rx_q_prep(sc, fp,
11506                      &setup_params->pause_params,
11507                      &setup_params->rxq_params);
11508
11509     bxe_pf_tx_q_prep(sc, fp,
11510                      &setup_params->txq_params,
11511                      FIRST_TX_COS_INDEX);
11512
11513     /* Set the command */
11514     q_params.cmd = ECORE_Q_CMD_SETUP;
11515
11516     /* change the state to SETUP */
11517     rc = ecore_queue_state_change(sc, &q_params);
11518     if (rc) {
11519         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11520         return (rc);
11521     }
11522
11523     return (rc);
11524 }
11525
11526 static int
11527 bxe_setup_leading(struct bxe_softc *sc)
11528 {
11529     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11530 }
11531
11532 static int
11533 bxe_config_rss_pf(struct bxe_softc            *sc,
11534                   struct ecore_rss_config_obj *rss_obj,
11535                   uint8_t                     config_hash)
11536 {
11537     struct ecore_config_rss_params params = { NULL };
11538     int i;
11539
11540     /*
11541      * Although RSS is meaningless when there is a single HW queue we
11542      * still need it enabled in order to have HW Rx hash generated.
11543      */
11544
11545     params.rss_obj = rss_obj;
11546
11547     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11548
11549     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11550
11551     /* RSS configuration */
11552     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11553     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11554     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11555     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11556     if (rss_obj->udp_rss_v4) {
11557         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11558     }
11559     if (rss_obj->udp_rss_v6) {
11560         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11561     }
11562
11563     /* Hash bits */
11564     params.rss_result_mask = MULTI_MASK;
11565
11566     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11567
11568     if (config_hash) {
11569         /* RSS keys */
11570         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11571             params.rss_key[i] = arc4random();
11572         }
11573
11574         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11575     }
11576
11577     return (ecore_config_rss(sc, &params));
11578 }
11579
11580 static int
11581 bxe_config_rss_eth(struct bxe_softc *sc,
11582                    uint8_t          config_hash)
11583 {
11584     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11585 }
11586
11587 static int
11588 bxe_init_rss_pf(struct bxe_softc *sc)
11589 {
11590     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11591     int i;
11592
11593     /*
11594      * Prepare the initial contents of the indirection table if
11595      * RSS is enabled
11596      */
11597     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11598         sc->rss_conf_obj.ind_table[i] =
11599             (sc->fp->cl_id + (i % num_eth_queues));
11600     }
11601
11602     if (sc->udp_rss) {
11603         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11604     }
11605
11606     /*
11607      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11608      * per-port, so if explicit configuration is needed, do it only
11609      * for a PMF.
11610      *
11611      * For 57712 and newer it's a per-function configuration.
11612      */
11613     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11614 }
11615
11616 static int
11617 bxe_set_mac_one(struct bxe_softc          *sc,
11618                 uint8_t                   *mac,
11619                 struct ecore_vlan_mac_obj *obj,
11620                 uint8_t                   set,
11621                 int                       mac_type,
11622                 unsigned long             *ramrod_flags)
11623 {
11624     struct ecore_vlan_mac_ramrod_params ramrod_param;
11625     int rc;
11626
11627     memset(&ramrod_param, 0, sizeof(ramrod_param));
11628
11629     /* fill in general parameters */
11630     ramrod_param.vlan_mac_obj = obj;
11631     ramrod_param.ramrod_flags = *ramrod_flags;
11632
11633     /* fill a user request section if needed */
11634     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11635         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11636
11637         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11638
11639         /* Set the command: ADD or DEL */
11640         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11641                                             ECORE_VLAN_MAC_DEL;
11642     }
11643
11644     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11645
11646     if (rc == ECORE_EXISTS) {
11647         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11648         /* do not treat adding same MAC as error */
11649         rc = 0;
11650     } else if (rc < 0) {
11651         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11652     }
11653
11654     return (rc);
11655 }
11656
11657 static int
11658 bxe_set_eth_mac(struct bxe_softc *sc,
11659                 uint8_t          set)
11660 {
11661     unsigned long ramrod_flags = 0;
11662
11663     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11664
11665     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11666
11667     /* Eth MAC is set on RSS leading client (fp[0]) */
11668     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11669                             &sc->sp_objs->mac_obj,
11670                             set, ECORE_ETH_MAC, &ramrod_flags));
11671 }
11672
11673 static int
11674 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11675 {
11676     uint32_t sel_phy_idx = 0;
11677
11678     if (sc->link_params.num_phys <= 1) {
11679         return (ELINK_INT_PHY);
11680     }
11681
11682     if (sc->link_vars.link_up) {
11683         sel_phy_idx = ELINK_EXT_PHY1;
11684         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11685         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11686             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11687              ELINK_SUPPORTED_FIBRE))
11688             sel_phy_idx = ELINK_EXT_PHY2;
11689     } else {
11690         switch (elink_phy_selection(&sc->link_params)) {
11691         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11692         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11693         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11694                sel_phy_idx = ELINK_EXT_PHY1;
11695                break;
11696         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11697         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11698                sel_phy_idx = ELINK_EXT_PHY2;
11699                break;
11700         }
11701     }
11702
11703     return (sel_phy_idx);
11704 }
11705
11706 static int
11707 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11708 {
11709     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11710
11711     /*
11712      * The selected activated PHY is always after swapping (in case PHY
11713      * swapping is enabled). So when swapping is enabled, we need to reverse
11714      * the configuration
11715      */
11716
11717     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11718         if (sel_phy_idx == ELINK_EXT_PHY1)
11719             sel_phy_idx = ELINK_EXT_PHY2;
11720         else if (sel_phy_idx == ELINK_EXT_PHY2)
11721             sel_phy_idx = ELINK_EXT_PHY1;
11722     }
11723
11724     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11725 }
11726
11727 static void
11728 bxe_set_requested_fc(struct bxe_softc *sc)
11729 {
11730     /*
11731      * Initialize link parameters structure variables
11732      * It is recommended to turn off RX FC for jumbo frames
11733      * for better performance
11734      */
11735     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11736         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11737     } else {
11738         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11739     }
11740 }
11741
11742 static void
11743 bxe_calc_fc_adv(struct bxe_softc *sc)
11744 {
11745     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11746     switch (sc->link_vars.ieee_fc &
11747             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11748     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
11749     default:
11750         sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11751                                            ADVERTISED_Pause);
11752         break;
11753
11754     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11755         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11756                                           ADVERTISED_Pause);
11757         break;
11758
11759     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11760         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11761         break;
11762     }
11763 }
11764
11765 static uint16_t
11766 bxe_get_mf_speed(struct bxe_softc *sc)
11767 {
11768     uint16_t line_speed = sc->link_vars.line_speed;
11769     if (IS_MF(sc)) {
11770         uint16_t maxCfg =
11771             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11772
11773         /* calculate the current MAX line speed limit for the MF devices */
11774         if (IS_MF_SI(sc)) {
11775             line_speed = (line_speed * maxCfg) / 100;
11776         } else { /* SD mode */
11777             uint16_t vn_max_rate = maxCfg * 100;
11778
11779             if (vn_max_rate < line_speed) {
11780                 line_speed = vn_max_rate;
11781             }
11782         }
11783     }
11784
11785     return (line_speed);
11786 }
11787
11788 static void
11789 bxe_fill_report_data(struct bxe_softc            *sc,
11790                      struct bxe_link_report_data *data)
11791 {
11792     uint16_t line_speed = bxe_get_mf_speed(sc);
11793
11794     memset(data, 0, sizeof(*data));
11795
11796     /* fill the report data with the effective line speed */
11797     data->line_speed = line_speed;
11798
11799     /* Link is down */
11800     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11801         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11802     }
11803
11804     /* Full DUPLEX */
11805     if (sc->link_vars.duplex == DUPLEX_FULL) {
11806         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11807     }
11808
11809     /* Rx Flow Control is ON */
11810     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11811         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11812     }
11813
11814     /* Tx Flow Control is ON */
11815     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11816         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11817     }
11818 }
11819
11820 /* report link status to OS, should be called under phy_lock */
11821 static void
11822 bxe_link_report_locked(struct bxe_softc *sc)
11823 {
11824     struct bxe_link_report_data cur_data;
11825
11826     /* reread mf_cfg */
11827     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11828         bxe_read_mf_cfg(sc);
11829     }
11830
11831     /* Read the current link report info */
11832     bxe_fill_report_data(sc, &cur_data);
11833
11834     /* Don't report link down or exactly the same link status twice */
11835     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11836         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11837                       &sc->last_reported_link.link_report_flags) &&
11838          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11839                       &cur_data.link_report_flags))) {
11840         return;
11841     }
11842
11843     sc->link_cnt++;
11844
11845     /* report new link params and remember the state for the next time */
11846     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11847
11848     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11849                      &cur_data.link_report_flags)) {
11850         if_link_state_change(sc->ifnet, LINK_STATE_DOWN);
11851         BLOGI(sc, "NIC Link is Down\n");
11852     } else {
11853         const char *duplex;
11854         const char *flow;
11855
11856         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11857                                    &cur_data.link_report_flags)) {
11858             duplex = "full";
11859         } else {
11860             duplex = "half";
11861         }
11862
11863         /*
11864          * Handle the FC at the end so that only these flags would be
11865          * possibly set. This way we may easily check if there is no FC
11866          * enabled.
11867          */
11868         if (cur_data.link_report_flags) {
11869             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11870                              &cur_data.link_report_flags) &&
11871                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11872                              &cur_data.link_report_flags)) {
11873                 flow = "ON - receive & transmit";
11874             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11875                                     &cur_data.link_report_flags) &&
11876                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11877                                      &cur_data.link_report_flags)) {
11878                 flow = "ON - receive";
11879             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11880                                      &cur_data.link_report_flags) &&
11881                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11882                                     &cur_data.link_report_flags)) {
11883                 flow = "ON - transmit";
11884             } else {
11885                 flow = "none"; /* possible? */
11886             }
11887         } else {
11888             flow = "none";
11889         }
11890
11891         if_link_state_change(sc->ifnet, LINK_STATE_UP);
11892         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11893               cur_data.line_speed, duplex, flow);
11894     }
11895 }
11896
11897 static void
11898 bxe_link_report(struct bxe_softc *sc)
11899 {
11900     bxe_acquire_phy_lock(sc);
11901     bxe_link_report_locked(sc);
11902     bxe_release_phy_lock(sc);
11903 }
11904
11905 static void
11906 bxe_link_status_update(struct bxe_softc *sc)
11907 {
11908     if (sc->state != BXE_STATE_OPEN) {
11909         return;
11910     }
11911
11912     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11913         elink_link_status_update(&sc->link_params, &sc->link_vars);
11914     } else {
11915         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11916                                   ELINK_SUPPORTED_10baseT_Full |
11917                                   ELINK_SUPPORTED_100baseT_Half |
11918                                   ELINK_SUPPORTED_100baseT_Full |
11919                                   ELINK_SUPPORTED_1000baseT_Full |
11920                                   ELINK_SUPPORTED_2500baseX_Full |
11921                                   ELINK_SUPPORTED_10000baseT_Full |
11922                                   ELINK_SUPPORTED_TP |
11923                                   ELINK_SUPPORTED_FIBRE |
11924                                   ELINK_SUPPORTED_Autoneg |
11925                                   ELINK_SUPPORTED_Pause |
11926                                   ELINK_SUPPORTED_Asym_Pause);
11927         sc->port.advertising[0] = sc->port.supported[0];
11928
11929         sc->link_params.sc                = sc;
11930         sc->link_params.port              = SC_PORT(sc);
11931         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11932         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11933         sc->link_params.req_line_speed[0] = SPEED_10000;
11934         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11935         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11936
11937         if (CHIP_REV_IS_FPGA(sc)) {
11938             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11939             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11940             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11941                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11942         } else {
11943             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11944             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11945             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11946                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11947         }
11948
11949         sc->link_vars.link_up = 1;
11950
11951         sc->link_vars.duplex    = DUPLEX_FULL;
11952         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11953
11954         if (IS_PF(sc)) {
11955             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11956             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11957             bxe_link_report(sc);
11958         }
11959     }
11960
11961     if (IS_PF(sc)) {
11962         if (sc->link_vars.link_up) {
11963             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11964         } else {
11965             bxe_stats_handle(sc, STATS_EVENT_STOP);
11966         }
11967         bxe_link_report(sc);
11968     } else {
11969         bxe_link_report(sc);
11970         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11971     }
11972 }
11973
11974 static int
11975 bxe_initial_phy_init(struct bxe_softc *sc,
11976                      int              load_mode)
11977 {
11978     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11979     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11980     struct elink_params *lp = &sc->link_params;
11981
11982     bxe_set_requested_fc(sc);
11983
11984     if (CHIP_REV_IS_SLOW(sc)) {
11985         uint32_t bond = CHIP_BOND_ID(sc);
11986         uint32_t feat = 0;
11987
11988         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11989             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11990         } else if (bond & 0x4) {
11991             if (CHIP_IS_E3(sc)) {
11992                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11993             } else {
11994                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11995             }
11996         } else if (bond & 0x8) {
11997             if (CHIP_IS_E3(sc)) {
11998                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11999             } else {
12000                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12001             }
12002         }
12003
12004         /* disable EMAC for E3 and above */
12005         if (bond & 0x2) {
12006             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12007         }
12008
12009         sc->link_params.feature_config_flags |= feat;
12010     }
12011
12012     bxe_acquire_phy_lock(sc);
12013
12014     if (load_mode == LOAD_DIAG) {
12015         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
12016         /* Prefer doing PHY loopback at 10G speed, if possible */
12017         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
12018             if (lp->speed_cap_mask[cfg_idx] &
12019                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
12020                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
12021             } else {
12022                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
12023             }
12024         }
12025     }
12026
12027     if (load_mode == LOAD_LOOPBACK_EXT) {
12028         lp->loopback_mode = ELINK_LOOPBACK_EXT;
12029     }
12030
12031     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
12032
12033     bxe_release_phy_lock(sc);
12034
12035     bxe_calc_fc_adv(sc);
12036
12037     if (sc->link_vars.link_up) {
12038         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12039         bxe_link_report(sc);
12040     }
12041
12042     if (!CHIP_REV_IS_SLOW(sc)) {
12043         bxe_periodic_start(sc);
12044     }
12045
12046     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
12047     return (rc);
12048 }
12049
12050 /* must be called under IF_ADDR_LOCK */
12051 static int
12052 bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
12053                          struct ecore_mcast_ramrod_params *p)
12054 {
12055     struct ifnet *ifp = sc->ifnet;
12056     int mc_count = 0;
12057     struct ifmultiaddr *ifma;
12058     struct ecore_mcast_list_elem *mc_mac;
12059
12060     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12061         if (ifma->ifma_addr->sa_family != AF_LINK) {
12062             continue;
12063         }
12064
12065         mc_count++;
12066     }
12067
12068     ECORE_LIST_INIT(&p->mcast_list);
12069     p->mcast_list_len = 0;
12070
12071     if (!mc_count) {
12072         return (0);
12073     }
12074
12075     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12076                     (M_NOWAIT | M_ZERO));
12077     if (!mc_mac) {
12078         BLOGE(sc, "Failed to allocate temp mcast list\n");
12079         return (-1);
12080     }
12081     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12082
12083     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12084         if (ifma->ifma_addr->sa_family != AF_LINK) {
12085             continue;
12086         }
12087
12088         mc_mac->mac = (uint8_t *)LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
12089         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &p->mcast_list);
12090
12091         BLOGD(sc, DBG_LOAD,
12092               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
12093               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12094               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
12095
12096         mc_mac++;
12097     }
12098
12099     p->mcast_list_len = mc_count;
12100
12101     return (0);
12102 }
12103
12104 static void
12105 bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12106 {
12107     struct ecore_mcast_list_elem *mc_mac =
12108         ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12109                                struct ecore_mcast_list_elem,
12110                                link);
12111
12112     if (mc_mac) {
12113         /* only a single free as all mc_macs are in the same heap array */
12114         free(mc_mac, M_DEVBUF);
12115     }
12116 }
12117
12118 static int
12119 bxe_set_mc_list(struct bxe_softc *sc)
12120 {
12121     struct ecore_mcast_ramrod_params rparam = { NULL };
12122     int rc = 0;
12123
12124     rparam.mcast_obj = &sc->mcast_obj;
12125
12126     BXE_MCAST_LOCK(sc);
12127
12128     /* first, clear all configured multicast MACs */
12129     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12130     if (rc < 0) {
12131         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12132         BXE_MCAST_UNLOCK(sc);
12133         return (rc);
12134     }
12135
12136     /* configure a new MACs list */
12137     rc = bxe_init_mcast_macs_list(sc, &rparam);
12138     if (rc) {
12139         BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12140         BXE_MCAST_UNLOCK(sc);
12141         return (rc);
12142     }
12143
12144     /* Now add the new MACs */
12145     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12146     if (rc < 0) {
12147         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12148     }
12149
12150     bxe_free_mcast_macs_list(&rparam);
12151
12152     BXE_MCAST_UNLOCK(sc);
12153
12154     return (rc);
12155 }
12156
12157 static int
12158 bxe_set_uc_list(struct bxe_softc *sc)
12159 {
12160     struct ifnet *ifp = sc->ifnet;
12161     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12162     struct ifaddr *ifa;
12163     unsigned long ramrod_flags = 0;
12164     int rc;
12165
12166 #if __FreeBSD_version < 800000
12167     IF_ADDR_LOCK(ifp);
12168 #else
12169     if_addr_rlock(ifp);
12170 #endif
12171
12172     /* first schedule a cleanup up of old configuration */
12173     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12174     if (rc < 0) {
12175         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12176 #if __FreeBSD_version < 800000
12177         IF_ADDR_UNLOCK(ifp);
12178 #else
12179         if_addr_runlock(ifp);
12180 #endif
12181         return (rc);
12182     }
12183
12184     ifa = ifp->if_addr;
12185     while (ifa) {
12186         if (ifa->ifa_addr->sa_family != AF_LINK) {
12187             ifa = TAILQ_NEXT(ifa, ifa_link);
12188             continue;
12189         }
12190
12191         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12192                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12193         if (rc == -EEXIST) {
12194             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12195             /* do not treat adding same MAC as an error */
12196             rc = 0;
12197         } else if (rc < 0) {
12198             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12199 #if __FreeBSD_version < 800000
12200             IF_ADDR_UNLOCK(ifp);
12201 #else
12202             if_addr_runlock(ifp);
12203 #endif
12204             return (rc);
12205         }
12206
12207         ifa = TAILQ_NEXT(ifa, ifa_link);
12208     }
12209
12210 #if __FreeBSD_version < 800000
12211     IF_ADDR_UNLOCK(ifp);
12212 #else
12213     if_addr_runlock(ifp);
12214 #endif
12215
12216     /* Execute the pending commands */
12217     bit_set(&ramrod_flags, RAMROD_CONT);
12218     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12219                             ECORE_UC_LIST_MAC, &ramrod_flags));
12220 }
12221
12222 static void
12223 bxe_set_rx_mode(struct bxe_softc *sc)
12224 {
12225     struct ifnet *ifp = sc->ifnet;
12226     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12227
12228     if (sc->state != BXE_STATE_OPEN) {
12229         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12230         return;
12231     }
12232
12233     BLOGD(sc, DBG_SP, "ifp->if_flags=0x%x\n", ifp->if_flags);
12234
12235     if (ifp->if_flags & IFF_PROMISC) {
12236         rx_mode = BXE_RX_MODE_PROMISC;
12237     } else if ((ifp->if_flags & IFF_ALLMULTI) ||
12238                ((ifp->if_amcount > BXE_MAX_MULTICAST) &&
12239                 CHIP_IS_E1(sc))) {
12240         rx_mode = BXE_RX_MODE_ALLMULTI;
12241     } else {
12242         if (IS_PF(sc)) {
12243             /* some multicasts */
12244             if (bxe_set_mc_list(sc) < 0) {
12245                 rx_mode = BXE_RX_MODE_ALLMULTI;
12246             }
12247             if (bxe_set_uc_list(sc) < 0) {
12248                 rx_mode = BXE_RX_MODE_PROMISC;
12249             }
12250         }
12251     }
12252
12253     sc->rx_mode = rx_mode;
12254
12255     /* schedule the rx_mode command */
12256     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12257         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12258         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12259         return;
12260     }
12261
12262     if (IS_PF(sc)) {
12263         bxe_set_storm_rx_mode(sc);
12264     }
12265 }
12266
12267
12268 /* update flags in shmem */
12269 static void
12270 bxe_update_drv_flags(struct bxe_softc *sc,
12271                      uint32_t         flags,
12272                      uint32_t         set)
12273 {
12274     uint32_t drv_flags;
12275
12276     if (SHMEM2_HAS(sc, drv_flags)) {
12277         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12278         drv_flags = SHMEM2_RD(sc, drv_flags);
12279
12280         if (set) {
12281             SET_FLAGS(drv_flags, flags);
12282         } else {
12283             RESET_FLAGS(drv_flags, flags);
12284         }
12285
12286         SHMEM2_WR(sc, drv_flags, drv_flags);
12287         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12288
12289         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12290     }
12291 }
12292
12293 /* periodic timer callout routine, only runs when the interface is up */
12294
12295 static void
12296 bxe_periodic_callout_func(void *xsc)
12297 {
12298     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12299     struct bxe_fastpath *fp;
12300     uint16_t tx_bd_avail;
12301     int i;
12302
12303     if (!BXE_CORE_TRYLOCK(sc)) {
12304         /* just bail and try again next time */
12305
12306         if ((sc->state == BXE_STATE_OPEN) &&
12307             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12308             /* schedule the next periodic callout */
12309             callout_reset(&sc->periodic_callout, hz,
12310                           bxe_periodic_callout_func, sc);
12311         }
12312
12313         return;
12314     }
12315
12316     if ((sc->state != BXE_STATE_OPEN) ||
12317         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12318         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12319         BXE_CORE_UNLOCK(sc);
12320         return;
12321     }
12322
12323 #if __FreeBSD_version >= 800000
12324
12325     FOR_EACH_QUEUE(sc, i) {
12326         fp = &sc->fp[i];
12327
12328         if (BXE_FP_TX_TRYLOCK(fp)) {
12329             struct ifnet *ifp = sc->ifnet;
12330             /*
12331              * If interface was stopped due to unavailable
12332              * bds, try to process some tx completions
12333              */
12334             (void) bxe_txeof(sc, fp);
12335            
12336             tx_bd_avail = bxe_tx_avail(sc, fp);
12337             if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12338                 bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
12339             }
12340             BXE_FP_TX_UNLOCK(fp);
12341         }
12342     }
12343
12344 #else
12345
12346     fp = &sc->fp[0];
12347     if (BXE_FP_TX_TRYLOCK(fp)) {
12348         struct ifnet *ifp = sc->ifnet;
12349         /*
12350          * If interface was stopped due to unavailable
12351          * bds, try to process some tx completions
12352          */
12353         (void) bxe_txeof(sc, fp);
12354            
12355         tx_bd_avail = bxe_tx_avail(sc, fp);
12356         if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12357             bxe_tx_start_locked(sc, ifp, fp);
12358         }
12359  
12360         BXE_FP_TX_UNLOCK(fp);
12361     }
12362
12363 #endif /* #if __FreeBSD_version >= 800000 */
12364
12365     /* Check for TX timeouts on any fastpath. */
12366     FOR_EACH_QUEUE(sc, i) {
12367         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12368             /* Ruh-Roh, chip was reset! */
12369             break;
12370         }
12371     }
12372
12373     if (!CHIP_REV_IS_SLOW(sc)) {
12374         /*
12375          * This barrier is needed to ensure the ordering between the writing
12376          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12377          * the reading here.
12378          */
12379         mb();
12380         if (sc->port.pmf) {
12381             bxe_acquire_phy_lock(sc);
12382             elink_period_func(&sc->link_params, &sc->link_vars);
12383             bxe_release_phy_lock(sc);
12384         }
12385     }
12386
12387     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12388         int mb_idx = SC_FW_MB_IDX(sc);
12389         uint32_t drv_pulse;
12390         uint32_t mcp_pulse;
12391
12392         ++sc->fw_drv_pulse_wr_seq;
12393         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12394
12395         drv_pulse = sc->fw_drv_pulse_wr_seq;
12396         bxe_drv_pulse(sc);
12397
12398         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12399                      MCP_PULSE_SEQ_MASK);
12400
12401         /*
12402          * The delta between driver pulse and mcp response should
12403          * be 1 (before mcp response) or 0 (after mcp response).
12404          */
12405         if ((drv_pulse != mcp_pulse) &&
12406             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12407             /* someone lost a heartbeat... */
12408             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12409                   drv_pulse, mcp_pulse);
12410         }
12411     }
12412
12413     /* state is BXE_STATE_OPEN */
12414     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12415
12416     BXE_CORE_UNLOCK(sc);
12417
12418     if ((sc->state == BXE_STATE_OPEN) &&
12419         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12420         /* schedule the next periodic callout */
12421         callout_reset(&sc->periodic_callout, hz,
12422                       bxe_periodic_callout_func, sc);
12423     }
12424 }
12425
12426 static void
12427 bxe_periodic_start(struct bxe_softc *sc)
12428 {
12429     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12430     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12431 }
12432
12433 static void
12434 bxe_periodic_stop(struct bxe_softc *sc)
12435 {
12436     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12437     callout_drain(&sc->periodic_callout);
12438 }
12439
12440 /* start the controller */
12441 static __noinline int
12442 bxe_nic_load(struct bxe_softc *sc,
12443              int              load_mode)
12444 {
12445     uint32_t val;
12446     int load_code = 0;
12447     int i, rc = 0;
12448
12449     BXE_CORE_LOCK_ASSERT(sc);
12450
12451     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12452
12453     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12454
12455     if (IS_PF(sc)) {
12456         /* must be called before memory allocation and HW init */
12457         bxe_ilt_set_info(sc);
12458     }
12459
12460     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12461
12462     bxe_set_fp_rx_buf_size(sc);
12463
12464     if (bxe_alloc_fp_buffers(sc) != 0) {
12465         BLOGE(sc, "Failed to allocate fastpath memory\n");
12466         sc->state = BXE_STATE_CLOSED;
12467         rc = ENOMEM;
12468         goto bxe_nic_load_error0;
12469     }
12470
12471     if (bxe_alloc_mem(sc) != 0) {
12472         sc->state = BXE_STATE_CLOSED;
12473         rc = ENOMEM;
12474         goto bxe_nic_load_error0;
12475     }
12476
12477     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12478         sc->state = BXE_STATE_CLOSED;
12479         rc = ENOMEM;
12480         goto bxe_nic_load_error0;
12481     }
12482
12483     if (IS_PF(sc)) {
12484         /* set pf load just before approaching the MCP */
12485         bxe_set_pf_load(sc);
12486
12487         /* if MCP exists send load request and analyze response */
12488         if (!BXE_NOMCP(sc)) {
12489             /* attempt to load pf */
12490             if (bxe_nic_load_request(sc, &load_code) != 0) {
12491                 sc->state = BXE_STATE_CLOSED;
12492                 rc = ENXIO;
12493                 goto bxe_nic_load_error1;
12494             }
12495
12496             /* what did the MCP say? */
12497             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12498                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12499                 sc->state = BXE_STATE_CLOSED;
12500                 rc = ENXIO;
12501                 goto bxe_nic_load_error2;
12502             }
12503         } else {
12504             BLOGI(sc, "Device has no MCP!\n");
12505             load_code = bxe_nic_load_no_mcp(sc);
12506         }
12507
12508         /* mark PMF if applicable */
12509         bxe_nic_load_pmf(sc, load_code);
12510
12511         /* Init Function state controlling object */
12512         bxe_init_func_obj(sc);
12513
12514         /* Initialize HW */
12515         if (bxe_init_hw(sc, load_code) != 0) {
12516             BLOGE(sc, "HW init failed\n");
12517             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12518             sc->state = BXE_STATE_CLOSED;
12519             rc = ENXIO;
12520             goto bxe_nic_load_error2;
12521         }
12522     }
12523
12524     /* set ALWAYS_ALIVE bit in shmem */
12525     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12526     bxe_drv_pulse(sc);
12527     sc->flags |= BXE_NO_PULSE;
12528
12529     /* attach interrupts */
12530     if (bxe_interrupt_attach(sc) != 0) {
12531         sc->state = BXE_STATE_CLOSED;
12532         rc = ENXIO;
12533         goto bxe_nic_load_error2;
12534     }
12535
12536     bxe_nic_init(sc, load_code);
12537
12538     /* Init per-function objects */
12539     if (IS_PF(sc)) {
12540         bxe_init_objs(sc);
12541         // XXX bxe_iov_nic_init(sc);
12542
12543         /* set AFEX default VLAN tag to an invalid value */
12544         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12545         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12546
12547         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12548         rc = bxe_func_start(sc);
12549         if (rc) {
12550             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12551             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12552             sc->state = BXE_STATE_ERROR;
12553             goto bxe_nic_load_error3;
12554         }
12555
12556         /* send LOAD_DONE command to MCP */
12557         if (!BXE_NOMCP(sc)) {
12558             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12559             if (!load_code) {
12560                 BLOGE(sc, "MCP response failure, aborting\n");
12561                 sc->state = BXE_STATE_ERROR;
12562                 rc = ENXIO;
12563                 goto bxe_nic_load_error3;
12564             }
12565         }
12566
12567         rc = bxe_setup_leading(sc);
12568         if (rc) {
12569             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12570             sc->state = BXE_STATE_ERROR;
12571             goto bxe_nic_load_error3;
12572         }
12573
12574         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12575             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12576             if (rc) {
12577                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12578                 sc->state = BXE_STATE_ERROR;
12579                 goto bxe_nic_load_error3;
12580             }
12581         }
12582
12583         rc = bxe_init_rss_pf(sc);
12584         if (rc) {
12585             BLOGE(sc, "PF RSS init failed\n");
12586             sc->state = BXE_STATE_ERROR;
12587             goto bxe_nic_load_error3;
12588         }
12589     }
12590     /* XXX VF */
12591
12592     /* now when Clients are configured we are ready to work */
12593     sc->state = BXE_STATE_OPEN;
12594
12595     /* Configure a ucast MAC */
12596     if (IS_PF(sc)) {
12597         rc = bxe_set_eth_mac(sc, TRUE);
12598     }
12599     if (rc) {
12600         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12601         sc->state = BXE_STATE_ERROR;
12602         goto bxe_nic_load_error3;
12603     }
12604
12605     if (sc->port.pmf) {
12606         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12607         if (rc) {
12608             sc->state = BXE_STATE_ERROR;
12609             goto bxe_nic_load_error3;
12610         }
12611     }
12612
12613     sc->link_params.feature_config_flags &=
12614         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12615
12616     /* start fast path */
12617
12618     /* Initialize Rx filter */
12619     bxe_set_rx_mode(sc);
12620
12621     /* start the Tx */
12622     switch (/* XXX load_mode */LOAD_OPEN) {
12623     case LOAD_NORMAL:
12624     case LOAD_OPEN:
12625         break;
12626
12627     case LOAD_DIAG:
12628     case LOAD_LOOPBACK_EXT:
12629         sc->state = BXE_STATE_DIAG;
12630         break;
12631
12632     default:
12633         break;
12634     }
12635
12636     if (sc->port.pmf) {
12637         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12638     } else {
12639         bxe_link_status_update(sc);
12640     }
12641
12642     /* start the periodic timer callout */
12643     bxe_periodic_start(sc);
12644
12645     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12646         /* mark driver is loaded in shmem2 */
12647         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12648         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12649                   (val |
12650                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12651                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12652     }
12653
12654     /* wait for all pending SP commands to complete */
12655     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12656         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12657         bxe_periodic_stop(sc);
12658         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12659         return (ENXIO);
12660     }
12661
12662     /* Tell the stack the driver is running! */
12663     sc->ifnet->if_drv_flags = IFF_DRV_RUNNING;
12664
12665     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12666
12667     return (0);
12668
12669 bxe_nic_load_error3:
12670
12671     if (IS_PF(sc)) {
12672         bxe_int_disable_sync(sc, 1);
12673
12674         /* clean out queued objects */
12675         bxe_squeeze_objects(sc);
12676     }
12677
12678     bxe_interrupt_detach(sc);
12679
12680 bxe_nic_load_error2:
12681
12682     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12683         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12684         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12685     }
12686
12687     sc->port.pmf = 0;
12688
12689 bxe_nic_load_error1:
12690
12691     /* clear pf_load status, as it was already set */
12692     if (IS_PF(sc)) {
12693         bxe_clear_pf_load(sc);
12694     }
12695
12696 bxe_nic_load_error0:
12697
12698     bxe_free_fw_stats_mem(sc);
12699     bxe_free_fp_buffers(sc);
12700     bxe_free_mem(sc);
12701
12702     return (rc);
12703 }
12704
12705 static int
12706 bxe_init_locked(struct bxe_softc *sc)
12707 {
12708     int other_engine = SC_PATH(sc) ? 0 : 1;
12709     uint8_t other_load_status, load_status;
12710     uint8_t global = FALSE;
12711     int rc;
12712
12713     BXE_CORE_LOCK_ASSERT(sc);
12714
12715     /* check if the driver is already running */
12716     if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
12717         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12718         return (0);
12719     }
12720
12721     bxe_set_power_state(sc, PCI_PM_D0);
12722
12723     /*
12724      * If parity occurred during the unload, then attentions and/or
12725      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12726      * loaded on the current engine to complete the recovery. Parity recovery
12727      * is only relevant for PF driver.
12728      */
12729     if (IS_PF(sc)) {
12730         other_load_status = bxe_get_load_status(sc, other_engine);
12731         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12732
12733         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12734             bxe_chk_parity_attn(sc, &global, TRUE)) {
12735             do {
12736                 /*
12737                  * If there are attentions and they are in global blocks, set
12738                  * the GLOBAL_RESET bit regardless whether it will be this
12739                  * function that will complete the recovery or not.
12740                  */
12741                 if (global) {
12742                     bxe_set_reset_global(sc);
12743                 }
12744
12745                 /*
12746                  * Only the first function on the current engine should try
12747                  * to recover in open. In case of attentions in global blocks
12748                  * only the first in the chip should try to recover.
12749                  */
12750                 if ((!load_status && (!global || !other_load_status)) &&
12751                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12752                     BLOGI(sc, "Recovered during init\n");
12753                     break;
12754                 }
12755
12756                 /* recovery has failed... */
12757                 bxe_set_power_state(sc, PCI_PM_D3hot);
12758                 sc->recovery_state = BXE_RECOVERY_FAILED;
12759
12760                 BLOGE(sc, "Recovery flow hasn't properly "
12761                           "completed yet, try again later. "
12762                           "If you still see this message after a "
12763                           "few retries then power cycle is required.\n");
12764
12765                 rc = ENXIO;
12766                 goto bxe_init_locked_done;
12767             } while (0);
12768         }
12769     }
12770
12771     sc->recovery_state = BXE_RECOVERY_DONE;
12772
12773     rc = bxe_nic_load(sc, LOAD_OPEN);
12774
12775 bxe_init_locked_done:
12776
12777     if (rc) {
12778         /* Tell the stack the driver is NOT running! */
12779         BLOGE(sc, "Initialization failed, "
12780                   "stack notified driver is NOT running!\n");
12781         sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
12782     }
12783
12784     return (rc);
12785 }
12786
12787 static int
12788 bxe_stop_locked(struct bxe_softc *sc)
12789 {
12790     BXE_CORE_LOCK_ASSERT(sc);
12791     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12792 }
12793
12794 /*
12795  * Handles controller initialization when called from an unlocked routine.
12796  * ifconfig calls this function.
12797  *
12798  * Returns:
12799  *   void
12800  */
12801 static void
12802 bxe_init(void *xsc)
12803 {
12804     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12805
12806     BXE_CORE_LOCK(sc);
12807     bxe_init_locked(sc);
12808     BXE_CORE_UNLOCK(sc);
12809 }
12810
12811 static int
12812 bxe_init_ifnet(struct bxe_softc *sc)
12813 {
12814     struct ifnet *ifp;
12815
12816     /* ifconfig entrypoint for media type/status reporting */
12817     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12818                  bxe_ifmedia_update,
12819                  bxe_ifmedia_status);
12820
12821     /* set the default interface values */
12822     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12823     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12824     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12825
12826     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12827
12828     /* allocate the ifnet structure */
12829     if ((ifp = if_alloc(IFT_ETHER)) == NULL) {
12830         BLOGE(sc, "Interface allocation failed!\n");
12831         return (ENXIO);
12832     }
12833
12834     ifp->if_softc = sc;
12835     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12836     ifp->if_flags = (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
12837     ifp->if_ioctl = bxe_ioctl;
12838     ifp->if_start = bxe_tx_start;
12839 #if __FreeBSD_version >= 800000
12840     ifp->if_transmit = bxe_tx_mq_start;
12841     ifp->if_qflush = bxe_mq_flush;
12842 #endif
12843 #ifdef FreeBSD8_0
12844     ifp->if_timer = 0;
12845 #endif
12846     ifp->if_init = bxe_init;
12847     ifp->if_mtu = sc->mtu;
12848     ifp->if_hwassist = (CSUM_IP       |
12849                         CSUM_TCP      |
12850                         CSUM_UDP      |
12851                         CSUM_TSO      |
12852                         CSUM_TCP_IPV6 |
12853                         CSUM_UDP_IPV6);
12854     ifp->if_capabilities =
12855 #if __FreeBSD_version < 700000
12856         (IFCAP_VLAN_MTU       |
12857          IFCAP_VLAN_HWTAGGING |
12858          IFCAP_HWCSUM         |
12859          IFCAP_JUMBO_MTU      |
12860          IFCAP_LRO);
12861 #else
12862         (IFCAP_VLAN_MTU       |
12863          IFCAP_VLAN_HWTAGGING |
12864          IFCAP_VLAN_HWTSO     |
12865          IFCAP_VLAN_HWFILTER  |
12866          IFCAP_VLAN_HWCSUM    |
12867          IFCAP_HWCSUM         |
12868          IFCAP_JUMBO_MTU      |
12869          IFCAP_LRO            |
12870          IFCAP_TSO4           |
12871          IFCAP_TSO6           |
12872          IFCAP_WOL_MAGIC);
12873 #endif
12874     ifp->if_capenable = ifp->if_capabilities;
12875     ifp->if_capenable &= ~IFCAP_WOL_MAGIC; /* XXX not yet... */
12876 #if __FreeBSD_version < 1000025
12877     ifp->if_baudrate = 1000000000;
12878 #else
12879     if_initbaudrate(ifp, IF_Gbps(10));
12880 #endif
12881     ifp->if_snd.ifq_drv_maxlen = sc->tx_ring_size;
12882
12883     IFQ_SET_MAXLEN(&ifp->if_snd, ifp->if_snd.ifq_drv_maxlen);
12884     IFQ_SET_READY(&ifp->if_snd);
12885
12886     sc->ifnet = ifp;
12887
12888     /* attach to the Ethernet interface list */
12889     ether_ifattach(ifp, sc->link_params.mac_addr);
12890
12891     return (0);
12892 }
12893
12894 static void
12895 bxe_deallocate_bars(struct bxe_softc *sc)
12896 {
12897     int i;
12898
12899     for (i = 0; i < MAX_BARS; i++) {
12900         if (sc->bar[i].resource != NULL) {
12901             bus_release_resource(sc->dev,
12902                                  SYS_RES_MEMORY,
12903                                  sc->bar[i].rid,
12904                                  sc->bar[i].resource);
12905             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12906                   i, PCIR_BAR(i));
12907         }
12908     }
12909 }
12910
12911 static int
12912 bxe_allocate_bars(struct bxe_softc *sc)
12913 {
12914     u_int flags;
12915     int i;
12916
12917     memset(sc->bar, 0, sizeof(sc->bar));
12918
12919     for (i = 0; i < MAX_BARS; i++) {
12920
12921         /* memory resources reside at BARs 0, 2, 4 */
12922         /* Run `pciconf -lb` to see mappings */
12923         if ((i != 0) && (i != 2) && (i != 4)) {
12924             continue;
12925         }
12926
12927         sc->bar[i].rid = PCIR_BAR(i);
12928
12929         flags = RF_ACTIVE;
12930         if (i == 0) {
12931             flags |= RF_SHAREABLE;
12932         }
12933
12934         if ((sc->bar[i].resource =
12935              bus_alloc_resource_any(sc->dev,
12936                                     SYS_RES_MEMORY,
12937                                     &sc->bar[i].rid,
12938                                     flags)) == NULL) {
12939             return (0);
12940         }
12941
12942         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12943         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12944         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12945
12946         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%ld) -> %p\n",
12947               i, PCIR_BAR(i),
12948               (void *)rman_get_start(sc->bar[i].resource),
12949               (void *)rman_get_end(sc->bar[i].resource),
12950               rman_get_size(sc->bar[i].resource),
12951               (void *)sc->bar[i].kva);
12952     }
12953
12954     return (0);
12955 }
12956
12957 static void
12958 bxe_get_function_num(struct bxe_softc *sc)
12959 {
12960     uint32_t val = 0;
12961
12962     /*
12963      * Read the ME register to get the function number. The ME register
12964      * holds the relative-function number and absolute-function number. The
12965      * absolute-function number appears only in E2 and above. Before that
12966      * these bits always contained zero, therefore we cannot blindly use them.
12967      */
12968
12969     val = REG_RD(sc, BAR_ME_REGISTER);
12970
12971     sc->pfunc_rel =
12972         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12973     sc->path_id =
12974         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12975
12976     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12977         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12978     } else {
12979         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12980     }
12981
12982     BLOGD(sc, DBG_LOAD,
12983           "Relative function %d, Absolute function %d, Path %d\n",
12984           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12985 }
12986
12987 static uint32_t
12988 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12989 {
12990     uint32_t shmem2_size;
12991     uint32_t offset;
12992     uint32_t mf_cfg_offset_value;
12993
12994     /* Non 57712 */
12995     offset = (SHMEM_RD(sc, func_mb) +
12996               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12997
12998     /* 57712 plus */
12999     if (sc->devinfo.shmem2_base != 0) {
13000         shmem2_size = SHMEM2_RD(sc, size);
13001         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
13002             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
13003             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
13004                 offset = mf_cfg_offset_value;
13005             }
13006         }
13007     }
13008
13009     return (offset);
13010 }
13011
13012 static uint32_t
13013 bxe_pcie_capability_read(struct bxe_softc *sc,
13014                          int    reg,
13015                          int    width)
13016 {
13017     int pcie_reg;
13018
13019     /* ensure PCIe capability is enabled */
13020     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
13021         if (pcie_reg != 0) {
13022             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
13023             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
13024         }
13025     }
13026
13027     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
13028
13029     return (0);
13030 }
13031
13032 static uint8_t
13033 bxe_is_pcie_pending(struct bxe_softc *sc)
13034 {
13035     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
13036             PCIM_EXP_STA_TRANSACTION_PND);
13037 }
13038
13039 /*
13040  * Walk the PCI capabiites list for the device to find what features are
13041  * supported. These capabilites may be enabled/disabled by firmware so it's
13042  * best to walk the list rather than make assumptions.
13043  */
13044 static void
13045 bxe_probe_pci_caps(struct bxe_softc *sc)
13046 {
13047     uint16_t link_status;
13048     int reg;
13049
13050     /* check if PCI Power Management is enabled */
13051     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
13052         if (reg != 0) {
13053             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
13054
13055             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
13056             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
13057         }
13058     }
13059
13060     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
13061
13062     /* handle PCIe 2.0 workarounds for 57710 */
13063     if (CHIP_IS_E1(sc)) {
13064         /* workaround for 57710 errata E4_57710_27462 */
13065         sc->devinfo.pcie_link_speed =
13066             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
13067
13068         /* workaround for 57710 errata E4_57710_27488 */
13069         sc->devinfo.pcie_link_width =
13070             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13071         if (sc->devinfo.pcie_link_speed > 1) {
13072             sc->devinfo.pcie_link_width =
13073                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
13074         }
13075     } else {
13076         sc->devinfo.pcie_link_speed =
13077             (link_status & PCIM_LINK_STA_SPEED);
13078         sc->devinfo.pcie_link_width =
13079             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13080     }
13081
13082     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
13083           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
13084
13085     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
13086     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
13087
13088     /* check if MSI capability is enabled */
13089     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
13090         if (reg != 0) {
13091             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13092
13093             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13094             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13095         }
13096     }
13097
13098     /* check if MSI-X capability is enabled */
13099     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13100         if (reg != 0) {
13101             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13102
13103             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13104             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13105         }
13106     }
13107 }
13108
13109 static int
13110 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13111 {
13112     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13113     uint32_t val;
13114
13115     /* get the outer vlan if we're in switch-dependent mode */
13116
13117     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13118     mf_info->ext_id = (uint16_t)val;
13119
13120     mf_info->multi_vnics_mode = 1;
13121
13122     if (!VALID_OVLAN(mf_info->ext_id)) {
13123         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13124         return (1);
13125     }
13126
13127     /* get the capabilities */
13128     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13129         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13130         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13131     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13132                FUNC_MF_CFG_PROTOCOL_FCOE) {
13133         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13134     } else {
13135         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13136     }
13137
13138     mf_info->vnics_per_port =
13139         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13140
13141     return (0);
13142 }
13143
13144 static uint32_t
13145 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13146 {
13147     uint32_t retval = 0;
13148     uint32_t val;
13149
13150     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13151
13152     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13153         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13154             retval |= MF_PROTO_SUPPORT_ETHERNET;
13155         }
13156         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13157             retval |= MF_PROTO_SUPPORT_ISCSI;
13158         }
13159         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13160             retval |= MF_PROTO_SUPPORT_FCOE;
13161         }
13162     }
13163
13164     return (retval);
13165 }
13166
13167 static int
13168 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13169 {
13170     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13171     uint32_t val;
13172
13173     /*
13174      * There is no outer vlan if we're in switch-independent mode.
13175      * If the mac is valid then assume multi-function.
13176      */
13177
13178     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13179
13180     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13181
13182     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13183
13184     mf_info->vnics_per_port =
13185         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13186
13187     return (0);
13188 }
13189
13190 static int
13191 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13192 {
13193     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13194     uint32_t e1hov_tag;
13195     uint32_t func_config;
13196     uint32_t niv_config;
13197
13198     mf_info->multi_vnics_mode = 1;
13199
13200     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13201     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13202     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13203
13204     mf_info->ext_id =
13205         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13206                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13207
13208     mf_info->default_vlan =
13209         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13210                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13211
13212     mf_info->niv_allowed_priorities =
13213         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13214                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13215
13216     mf_info->niv_default_cos =
13217         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13218                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13219
13220     mf_info->afex_vlan_mode =
13221         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13222          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13223
13224     mf_info->niv_mba_enabled =
13225         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13226          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13227
13228     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13229
13230     mf_info->vnics_per_port =
13231         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13232
13233     return (0);
13234 }
13235
13236 static int
13237 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13238 {
13239     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13240     uint32_t mf_cfg1;
13241     uint32_t mf_cfg2;
13242     uint32_t ovlan1;
13243     uint32_t ovlan2;
13244     uint8_t i, j;
13245
13246     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13247           SC_PORT(sc));
13248     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13249           mf_info->mf_config[SC_VN(sc)]);
13250     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13251           mf_info->multi_vnics_mode);
13252     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13253           mf_info->vnics_per_port);
13254     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13255           mf_info->ext_id);
13256     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13257           mf_info->min_bw[0], mf_info->min_bw[1],
13258           mf_info->min_bw[2], mf_info->min_bw[3]);
13259     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13260           mf_info->max_bw[0], mf_info->max_bw[1],
13261           mf_info->max_bw[2], mf_info->max_bw[3]);
13262     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13263           sc->mac_addr_str);
13264
13265     /* various MF mode sanity checks... */
13266
13267     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13268         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13269               SC_PORT(sc));
13270         return (1);
13271     }
13272
13273     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13274         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13275               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13276         return (1);
13277     }
13278
13279     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13280         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13281         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13282             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13283                   SC_VN(sc), OVLAN(sc));
13284             return (1);
13285         }
13286
13287         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13288             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13289                   mf_info->multi_vnics_mode, OVLAN(sc));
13290             return (1);
13291         }
13292
13293         /*
13294          * Verify all functions are either MF or SF mode. If MF, make sure
13295          * sure that all non-hidden functions have a valid ovlan. If SF,
13296          * make sure that all non-hidden functions have an invalid ovlan.
13297          */
13298         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13299             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13300             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13301             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13302                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13303                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13304                 BLOGE(sc, "mf_mode=SD function %d MF config "
13305                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13306                       i, mf_info->multi_vnics_mode, ovlan1);
13307                 return (1);
13308             }
13309         }
13310
13311         /* Verify all funcs on the same port each have a different ovlan. */
13312         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13313             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13314             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13315             /* iterate from the next function on the port to the max func */
13316             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13317                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13318                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13319                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13320                     VALID_OVLAN(ovlan1) &&
13321                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13322                     VALID_OVLAN(ovlan2) &&
13323                     (ovlan1 == ovlan2)) {
13324                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13325                               "have the same ovlan (%d)\n",
13326                           i, j, ovlan1);
13327                     return (1);
13328                 }
13329             }
13330         }
13331     } /* MULTI_FUNCTION_SD */
13332
13333     return (0);
13334 }
13335
13336 static int
13337 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13338 {
13339     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13340     uint32_t val, mac_upper;
13341     uint8_t i, vnic;
13342
13343     /* initialize mf_info defaults */
13344     mf_info->vnics_per_port   = 1;
13345     mf_info->multi_vnics_mode = FALSE;
13346     mf_info->path_has_ovlan   = FALSE;
13347     mf_info->mf_mode          = SINGLE_FUNCTION;
13348
13349     if (!CHIP_IS_MF_CAP(sc)) {
13350         return (0);
13351     }
13352
13353     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13354         BLOGE(sc, "Invalid mf_cfg_base!\n");
13355         return (1);
13356     }
13357
13358     /* get the MF mode (switch dependent / independent / single-function) */
13359
13360     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13361
13362     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13363     {
13364     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13365
13366         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13367
13368         /* check for legal upper mac bytes */
13369         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13370             mf_info->mf_mode = MULTI_FUNCTION_SI;
13371         } else {
13372             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13373         }
13374
13375         break;
13376
13377     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13378     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13379
13380         /* get outer vlan configuration */
13381         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13382
13383         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13384             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13385             mf_info->mf_mode = MULTI_FUNCTION_SD;
13386         } else {
13387             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13388         }
13389
13390         break;
13391
13392     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13393
13394         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13395         return (0);
13396
13397     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13398
13399         /*
13400          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13401          * and the MAC address is valid.
13402          */
13403         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13404
13405         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13406             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13407             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13408         } else {
13409             BLOGE(sc, "Invalid config for AFEX mode\n");
13410         }
13411
13412         break;
13413
13414     default:
13415
13416         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13417               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13418
13419         return (1);
13420     }
13421
13422     /* set path mf_mode (which could be different than function mf_mode) */
13423     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13424         mf_info->path_has_ovlan = TRUE;
13425     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13426         /*
13427          * Decide on path multi vnics mode. If we're not in MF mode and in
13428          * 4-port mode, this is good enough to check vnic-0 of the other port
13429          * on the same path
13430          */
13431         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13432             uint8_t other_port = !(PORT_ID(sc) & 1);
13433             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13434
13435             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13436
13437             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13438         }
13439     }
13440
13441     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13442         /* invalid MF config */
13443         if (SC_VN(sc) >= 1) {
13444             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13445             return (1);
13446         }
13447
13448         return (0);
13449     }
13450
13451     /* get the MF configuration */
13452     mf_info->mf_config[SC_VN(sc)] =
13453         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13454
13455     switch(mf_info->mf_mode)
13456     {
13457     case MULTI_FUNCTION_SD:
13458
13459         bxe_get_shmem_mf_cfg_info_sd(sc);
13460         break;
13461
13462     case MULTI_FUNCTION_SI:
13463
13464         bxe_get_shmem_mf_cfg_info_si(sc);
13465         break;
13466
13467     case MULTI_FUNCTION_AFEX:
13468
13469         bxe_get_shmem_mf_cfg_info_niv(sc);
13470         break;
13471
13472     default:
13473
13474         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13475               mf_info->mf_mode);
13476         return (1);
13477     }
13478
13479     /* get the congestion management parameters */
13480
13481     vnic = 0;
13482     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13483         /* get min/max bw */
13484         val = MFCFG_RD(sc, func_mf_config[i].config);
13485         mf_info->min_bw[vnic] =
13486             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13487         mf_info->max_bw[vnic] =
13488             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13489         vnic++;
13490     }
13491
13492     return (bxe_check_valid_mf_cfg(sc));
13493 }
13494
13495 static int
13496 bxe_get_shmem_info(struct bxe_softc *sc)
13497 {
13498     int port;
13499     uint32_t mac_hi, mac_lo, val;
13500
13501     port = SC_PORT(sc);
13502     mac_hi = mac_lo = 0;
13503
13504     sc->link_params.sc   = sc;
13505     sc->link_params.port = port;
13506
13507     /* get the hardware config info */
13508     sc->devinfo.hw_config =
13509         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13510     sc->devinfo.hw_config2 =
13511         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13512
13513     sc->link_params.hw_led_mode =
13514         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13515          SHARED_HW_CFG_LED_MODE_SHIFT);
13516
13517     /* get the port feature config */
13518     sc->port.config =
13519         SHMEM_RD(sc, dev_info.port_feature_config[port].config),
13520
13521     /* get the link params */
13522     sc->link_params.speed_cap_mask[0] =
13523         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13524     sc->link_params.speed_cap_mask[1] =
13525         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13526
13527     /* get the lane config */
13528     sc->link_params.lane_config =
13529         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13530
13531     /* get the link config */
13532     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13533     sc->port.link_config[ELINK_INT_PHY] = val;
13534     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13535     sc->port.link_config[ELINK_EXT_PHY1] =
13536         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13537
13538     /* get the override preemphasis flag and enable it or turn it off */
13539     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13540     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13541         sc->link_params.feature_config_flags |=
13542             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13543     } else {
13544         sc->link_params.feature_config_flags &=
13545             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13546     }
13547
13548     /* get the initial value of the link params */
13549     sc->link_params.multi_phy_config =
13550         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13551
13552     /* get external phy info */
13553     sc->port.ext_phy_config =
13554         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13555
13556     /* get the multifunction configuration */
13557     bxe_get_mf_cfg_info(sc);
13558
13559     /* get the mac address */
13560     if (IS_MF(sc)) {
13561         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13562         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13563     } else {
13564         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13565         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13566     }
13567
13568     if ((mac_lo == 0) && (mac_hi == 0)) {
13569         *sc->mac_addr_str = 0;
13570         BLOGE(sc, "No Ethernet address programmed!\n");
13571     } else {
13572         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13573         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13574         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13575         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13576         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13577         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13578         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13579                  "%02x:%02x:%02x:%02x:%02x:%02x",
13580                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13581                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13582                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13583         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13584     }
13585
13586     return (0);
13587 }
13588
13589 static void
13590 bxe_get_tunable_params(struct bxe_softc *sc)
13591 {
13592     /* sanity checks */
13593
13594     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13595         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13596         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13597         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13598         bxe_interrupt_mode = INTR_MODE_MSIX;
13599     }
13600
13601     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13602         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13603         bxe_queue_count = 0;
13604     }
13605
13606     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13607         if (bxe_max_rx_bufs == 0) {
13608             bxe_max_rx_bufs = RX_BD_USABLE;
13609         } else {
13610             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13611             bxe_max_rx_bufs = 2048;
13612         }
13613     }
13614
13615     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13616         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13617         bxe_hc_rx_ticks = 25;
13618     }
13619
13620     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13621         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13622         bxe_hc_tx_ticks = 50;
13623     }
13624
13625     if (bxe_max_aggregation_size == 0) {
13626         bxe_max_aggregation_size = TPA_AGG_SIZE;
13627     }
13628
13629     if (bxe_max_aggregation_size > 0xffff) {
13630         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13631               bxe_max_aggregation_size);
13632         bxe_max_aggregation_size = TPA_AGG_SIZE;
13633     }
13634
13635     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13636         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13637         bxe_mrrs = -1;
13638     }
13639
13640     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13641         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13642         bxe_autogreeen = 0;
13643     }
13644
13645     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13646         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13647         bxe_udp_rss = 0;
13648     }
13649
13650     /* pull in user settings */
13651
13652     sc->interrupt_mode       = bxe_interrupt_mode;
13653     sc->max_rx_bufs          = bxe_max_rx_bufs;
13654     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13655     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13656     sc->max_aggregation_size = bxe_max_aggregation_size;
13657     sc->mrrs                 = bxe_mrrs;
13658     sc->autogreeen           = bxe_autogreeen;
13659     sc->udp_rss              = bxe_udp_rss;
13660
13661     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13662         sc->num_queues = 1;
13663     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13664         sc->num_queues =
13665             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13666                 MAX_RSS_CHAINS);
13667         if (sc->num_queues > mp_ncpus) {
13668             sc->num_queues = mp_ncpus;
13669         }
13670     }
13671
13672     BLOGD(sc, DBG_LOAD,
13673           "User Config: "
13674           "debug=0x%lx "
13675           "interrupt_mode=%d "
13676           "queue_count=%d "
13677           "hc_rx_ticks=%d "
13678           "hc_tx_ticks=%d "
13679           "rx_budget=%d "
13680           "max_aggregation_size=%d "
13681           "mrrs=%d "
13682           "autogreeen=%d "
13683           "udp_rss=%d\n",
13684           bxe_debug,
13685           sc->interrupt_mode,
13686           sc->num_queues,
13687           sc->hc_rx_ticks,
13688           sc->hc_tx_ticks,
13689           bxe_rx_budget,
13690           sc->max_aggregation_size,
13691           sc->mrrs,
13692           sc->autogreeen,
13693           sc->udp_rss);
13694 }
13695
13696 static void
13697 bxe_media_detect(struct bxe_softc *sc)
13698 {
13699     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13700     switch (sc->link_params.phy[phy_idx].media_type) {
13701     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13702     case ELINK_ETH_PHY_XFP_FIBER:
13703         BLOGI(sc, "Found 10Gb Fiber media.\n");
13704         sc->media = IFM_10G_SR;
13705         break;
13706     case ELINK_ETH_PHY_SFP_1G_FIBER:
13707         BLOGI(sc, "Found 1Gb Fiber media.\n");
13708         sc->media = IFM_1000_SX;
13709         break;
13710     case ELINK_ETH_PHY_KR:
13711     case ELINK_ETH_PHY_CX4:
13712         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13713         sc->media = IFM_10G_CX4;
13714         break;
13715     case ELINK_ETH_PHY_DA_TWINAX:
13716         BLOGI(sc, "Found 10Gb Twinax media.\n");
13717         sc->media = IFM_10G_TWINAX;
13718         break;
13719     case ELINK_ETH_PHY_BASE_T:
13720         if (sc->link_params.speed_cap_mask[0] &
13721             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13722             BLOGI(sc, "Found 10GBase-T media.\n");
13723             sc->media = IFM_10G_T;
13724         } else {
13725             BLOGI(sc, "Found 1000Base-T media.\n");
13726             sc->media = IFM_1000_T;
13727         }
13728         break;
13729     case ELINK_ETH_PHY_NOT_PRESENT:
13730         BLOGI(sc, "Media not present.\n");
13731         sc->media = 0;
13732         break;
13733     case ELINK_ETH_PHY_UNSPECIFIED:
13734     default:
13735         BLOGI(sc, "Unknown media!\n");
13736         sc->media = 0;
13737         break;
13738     }
13739 }
13740
13741 #define GET_FIELD(value, fname)                     \
13742     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13743 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13744 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13745
13746 static int
13747 bxe_get_igu_cam_info(struct bxe_softc *sc)
13748 {
13749     int pfid = SC_FUNC(sc);
13750     int igu_sb_id;
13751     uint32_t val;
13752     uint8_t fid, igu_sb_cnt = 0;
13753
13754     sc->igu_base_sb = 0xff;
13755
13756     if (CHIP_INT_MODE_IS_BC(sc)) {
13757         int vn = SC_VN(sc);
13758         igu_sb_cnt = sc->igu_sb_cnt;
13759         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13760                            FP_SB_MAX_E1x);
13761         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13762                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13763         return (0);
13764     }
13765
13766     /* IGU in normal mode - read CAM */
13767     for (igu_sb_id = 0;
13768          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13769          igu_sb_id++) {
13770         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13771         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13772             continue;
13773         }
13774         fid = IGU_FID(val);
13775         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13776             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13777                 continue;
13778             }
13779             if (IGU_VEC(val) == 0) {
13780                 /* default status block */
13781                 sc->igu_dsb_id = igu_sb_id;
13782             } else {
13783                 if (sc->igu_base_sb == 0xff) {
13784                     sc->igu_base_sb = igu_sb_id;
13785                 }
13786                 igu_sb_cnt++;
13787             }
13788         }
13789     }
13790
13791     /*
13792      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13793      * that number of CAM entries will not be equal to the value advertised in
13794      * PCI. Driver should use the minimal value of both as the actual status
13795      * block count
13796      */
13797     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13798
13799     if (igu_sb_cnt == 0) {
13800         BLOGE(sc, "CAM configuration error\n");
13801         return (-1);
13802     }
13803
13804     return (0);
13805 }
13806
13807 /*
13808  * Gather various information from the device config space, the device itself,
13809  * shmem, and the user input.
13810  */
13811 static int
13812 bxe_get_device_info(struct bxe_softc *sc)
13813 {
13814     uint32_t val;
13815     int rc;
13816
13817     /* Get the data for the device */
13818     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13819     sc->devinfo.device_id    = pci_get_device(sc->dev);
13820     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13821     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13822
13823     /* get the chip revision (chip metal comes from pci config space) */
13824     sc->devinfo.chip_id     =
13825     sc->link_params.chip_id =
13826         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13827          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13828          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13829          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13830
13831     /* force 57811 according to MISC register */
13832     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13833         if (CHIP_IS_57810(sc)) {
13834             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13835                                    (sc->devinfo.chip_id & 0x0000ffff));
13836         } else if (CHIP_IS_57810_MF(sc)) {
13837             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13838                                    (sc->devinfo.chip_id & 0x0000ffff));
13839         }
13840         sc->devinfo.chip_id |= 0x1;
13841     }
13842
13843     BLOGD(sc, DBG_LOAD,
13844           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13845           sc->devinfo.chip_id,
13846           ((sc->devinfo.chip_id >> 16) & 0xffff),
13847           ((sc->devinfo.chip_id >> 12) & 0xf),
13848           ((sc->devinfo.chip_id >>  4) & 0xff),
13849           ((sc->devinfo.chip_id >>  0) & 0xf));
13850
13851     val = (REG_RD(sc, 0x2874) & 0x55);
13852     if ((sc->devinfo.chip_id & 0x1) ||
13853         (CHIP_IS_E1(sc) && val) ||
13854         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13855         sc->flags |= BXE_ONE_PORT_FLAG;
13856         BLOGD(sc, DBG_LOAD, "single port device\n");
13857     }
13858
13859     /* set the doorbell size */
13860     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13861
13862     /* determine whether the device is in 2 port or 4 port mode */
13863     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13864     if (CHIP_IS_E2E3(sc)) {
13865         /*
13866          * Read port4mode_en_ovwr[0]:
13867          *   If 1, four port mode is in port4mode_en_ovwr[1].
13868          *   If 0, four port mode is in port4mode_en[0].
13869          */
13870         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13871         if (val & 1) {
13872             val = ((val >> 1) & 1);
13873         } else {
13874             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13875         }
13876
13877         sc->devinfo.chip_port_mode =
13878             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13879
13880         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13881     }
13882
13883     /* get the function and path info for the device */
13884     bxe_get_function_num(sc);
13885
13886     /* get the shared memory base address */
13887     sc->devinfo.shmem_base     =
13888     sc->link_params.shmem_base =
13889         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13890     sc->devinfo.shmem2_base =
13891         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13892                                   MISC_REG_GENERIC_CR_0));
13893
13894     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13895           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13896
13897     if (!sc->devinfo.shmem_base) {
13898         /* this should ONLY prevent upcoming shmem reads */
13899         BLOGI(sc, "MCP not active\n");
13900         sc->flags |= BXE_NO_MCP_FLAG;
13901         return (0);
13902     }
13903
13904     /* make sure the shared memory contents are valid */
13905     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13906     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13907         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13908         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13909         return (0);
13910     }
13911     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13912
13913     /* get the bootcode version */
13914     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13915     snprintf(sc->devinfo.bc_ver_str,
13916              sizeof(sc->devinfo.bc_ver_str),
13917              "%d.%d.%d",
13918              ((sc->devinfo.bc_ver >> 24) & 0xff),
13919              ((sc->devinfo.bc_ver >> 16) & 0xff),
13920              ((sc->devinfo.bc_ver >>  8) & 0xff));
13921     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13922
13923     /* get the bootcode shmem address */
13924     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13925     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13926
13927     /* clean indirect addresses as they're not used */
13928     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13929     if (IS_PF(sc)) {
13930         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13931         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13932         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13933         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13934         if (CHIP_IS_E1x(sc)) {
13935             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13936             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13937             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13938             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13939         }
13940
13941         /*
13942          * Enable internal target-read (in case we are probed after PF
13943          * FLR). Must be done prior to any BAR read access. Only for
13944          * 57712 and up
13945          */
13946         if (!CHIP_IS_E1x(sc)) {
13947             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13948         }
13949     }
13950
13951     /* get the nvram size */
13952     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13953     sc->devinfo.flash_size =
13954         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13955     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13956
13957     /* get PCI capabilites */
13958     bxe_probe_pci_caps(sc);
13959
13960     bxe_set_power_state(sc, PCI_PM_D0);
13961
13962     /* get various configuration parameters from shmem */
13963     bxe_get_shmem_info(sc);
13964
13965     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13966         val = pci_read_config(sc->dev,
13967                               (sc->devinfo.pcie_msix_cap_reg +
13968                                PCIR_MSIX_CTRL),
13969                               2);
13970         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13971     } else {
13972         sc->igu_sb_cnt = 1;
13973     }
13974
13975     sc->igu_base_addr = BAR_IGU_INTMEM;
13976
13977     /* initialize IGU parameters */
13978     if (CHIP_IS_E1x(sc)) {
13979         sc->devinfo.int_block = INT_BLOCK_HC;
13980         sc->igu_dsb_id = DEF_SB_IGU_ID;
13981         sc->igu_base_sb = 0;
13982     } else {
13983         sc->devinfo.int_block = INT_BLOCK_IGU;
13984
13985         /* do not allow device reset during IGU info preocessing */
13986         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13987
13988         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13989
13990         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13991             int tout = 5000;
13992
13993             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13994
13995             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13996             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13997             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13998
13999             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14000                 tout--;
14001                 DELAY(1000);
14002             }
14003
14004             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14005                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
14006                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14007                 return (-1);
14008             }
14009         }
14010
14011         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
14012             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
14013             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
14014         } else {
14015             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
14016         }
14017
14018         rc = bxe_get_igu_cam_info(sc);
14019
14020         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14021
14022         if (rc) {
14023             return (rc);
14024         }
14025     }
14026
14027     /*
14028      * Get base FW non-default (fast path) status block ID. This value is
14029      * used to initialize the fw_sb_id saved on the fp/queue structure to
14030      * determine the id used by the FW.
14031      */
14032     if (CHIP_IS_E1x(sc)) {
14033         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
14034     } else {
14035         /*
14036          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
14037          * the same queue are indicated on the same IGU SB). So we prefer
14038          * FW and IGU SBs to be the same value.
14039          */
14040         sc->base_fw_ndsb = sc->igu_base_sb;
14041     }
14042
14043     BLOGD(sc, DBG_LOAD,
14044           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
14045           sc->igu_dsb_id, sc->igu_base_sb,
14046           sc->igu_sb_cnt, sc->base_fw_ndsb);
14047
14048     elink_phy_probe(&sc->link_params);
14049
14050     return (0);
14051 }
14052
14053 static void
14054 bxe_link_settings_supported(struct bxe_softc *sc,
14055                             uint32_t         switch_cfg)
14056 {
14057     uint32_t cfg_size = 0;
14058     uint32_t idx;
14059     uint8_t port = SC_PORT(sc);
14060
14061     /* aggregation of supported attributes of all external phys */
14062     sc->port.supported[0] = 0;
14063     sc->port.supported[1] = 0;
14064
14065     switch (sc->link_params.num_phys) {
14066     case 1:
14067         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
14068         cfg_size = 1;
14069         break;
14070     case 2:
14071         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
14072         cfg_size = 1;
14073         break;
14074     case 3:
14075         if (sc->link_params.multi_phy_config &
14076             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
14077             sc->port.supported[1] =
14078                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14079             sc->port.supported[0] =
14080                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14081         } else {
14082             sc->port.supported[0] =
14083                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14084             sc->port.supported[1] =
14085                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14086         }
14087         cfg_size = 2;
14088         break;
14089     }
14090
14091     if (!(sc->port.supported[0] || sc->port.supported[1])) {
14092         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14093               SHMEM_RD(sc,
14094                        dev_info.port_hw_config[port].external_phy_config),
14095               SHMEM_RD(sc,
14096                        dev_info.port_hw_config[port].external_phy_config2));
14097         return;
14098     }
14099
14100     if (CHIP_IS_E3(sc))
14101         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14102     else {
14103         switch (switch_cfg) {
14104         case ELINK_SWITCH_CFG_1G:
14105             sc->port.phy_addr =
14106                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14107             break;
14108         case ELINK_SWITCH_CFG_10G:
14109             sc->port.phy_addr =
14110                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14111             break;
14112         default:
14113             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14114                   sc->port.link_config[0]);
14115             return;
14116         }
14117     }
14118
14119     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14120
14121     /* mask what we support according to speed_cap_mask per configuration */
14122     for (idx = 0; idx < cfg_size; idx++) {
14123         if (!(sc->link_params.speed_cap_mask[idx] &
14124               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14125             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14126         }
14127
14128         if (!(sc->link_params.speed_cap_mask[idx] &
14129               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14130             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14131         }
14132
14133         if (!(sc->link_params.speed_cap_mask[idx] &
14134               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14135             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14136         }
14137
14138         if (!(sc->link_params.speed_cap_mask[idx] &
14139               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14140             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14141         }
14142
14143         if (!(sc->link_params.speed_cap_mask[idx] &
14144               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14145             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14146         }
14147
14148         if (!(sc->link_params.speed_cap_mask[idx] &
14149               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14150             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14151         }
14152
14153         if (!(sc->link_params.speed_cap_mask[idx] &
14154               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14155             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14156         }
14157
14158         if (!(sc->link_params.speed_cap_mask[idx] &
14159               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14160             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14161         }
14162     }
14163
14164     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14165           sc->port.supported[0], sc->port.supported[1]);
14166 }
14167
14168 static void
14169 bxe_link_settings_requested(struct bxe_softc *sc)
14170 {
14171     uint32_t link_config;
14172     uint32_t idx;
14173     uint32_t cfg_size = 0;
14174
14175     sc->port.advertising[0] = 0;
14176     sc->port.advertising[1] = 0;
14177
14178     switch (sc->link_params.num_phys) {
14179     case 1:
14180     case 2:
14181         cfg_size = 1;
14182         break;
14183     case 3:
14184         cfg_size = 2;
14185         break;
14186     }
14187
14188     for (idx = 0; idx < cfg_size; idx++) {
14189         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14190         link_config = sc->port.link_config[idx];
14191
14192         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14193         case PORT_FEATURE_LINK_SPEED_AUTO:
14194             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14195                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14196                 sc->port.advertising[idx] |= sc->port.supported[idx];
14197                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14198                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14199                     sc->port.advertising[idx] |=
14200                         (ELINK_SUPPORTED_100baseT_Half |
14201                          ELINK_SUPPORTED_100baseT_Full);
14202             } else {
14203                 /* force 10G, no AN */
14204                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14205                 sc->port.advertising[idx] |=
14206                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14207                 continue;
14208             }
14209             break;
14210
14211         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14212             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14213                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14214                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14215                                               ADVERTISED_TP);
14216             } else {
14217                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14218                           "speed_cap_mask=0x%08x\n",
14219                       link_config, sc->link_params.speed_cap_mask[idx]);
14220                 return;
14221             }
14222             break;
14223
14224         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14225             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14226                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14227                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14228                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14229                                               ADVERTISED_TP);
14230             } else {
14231                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14232                           "speed_cap_mask=0x%08x\n",
14233                       link_config, sc->link_params.speed_cap_mask[idx]);
14234                 return;
14235             }
14236             break;
14237
14238         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14239             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14240                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14241                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14242                                               ADVERTISED_TP);
14243             } else {
14244                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14245                           "speed_cap_mask=0x%08x\n",
14246                       link_config, sc->link_params.speed_cap_mask[idx]);
14247                 return;
14248             }
14249             break;
14250
14251         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14252             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14253                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14254                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14255                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14256                                               ADVERTISED_TP);
14257             } else {
14258                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14259                           "speed_cap_mask=0x%08x\n",
14260                       link_config, sc->link_params.speed_cap_mask[idx]);
14261                 return;
14262             }
14263             break;
14264
14265         case PORT_FEATURE_LINK_SPEED_1G:
14266             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14267                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14268                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14269                                               ADVERTISED_TP);
14270             } else {
14271                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14272                           "speed_cap_mask=0x%08x\n",
14273                       link_config, sc->link_params.speed_cap_mask[idx]);
14274                 return;
14275             }
14276             break;
14277
14278         case PORT_FEATURE_LINK_SPEED_2_5G:
14279             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14280                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14281                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14282                                               ADVERTISED_TP);
14283             } else {
14284                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14285                           "speed_cap_mask=0x%08x\n",
14286                       link_config, sc->link_params.speed_cap_mask[idx]);
14287                 return;
14288             }
14289             break;
14290
14291         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14292             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14293                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14294                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14295                                               ADVERTISED_FIBRE);
14296             } else {
14297                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14298                           "speed_cap_mask=0x%08x\n",
14299                       link_config, sc->link_params.speed_cap_mask[idx]);
14300                 return;
14301             }
14302             break;
14303
14304         case PORT_FEATURE_LINK_SPEED_20G:
14305             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14306             break;
14307
14308         default:
14309             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14310                       "speed_cap_mask=0x%08x\n",
14311                   link_config, sc->link_params.speed_cap_mask[idx]);
14312             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14313             sc->port.advertising[idx] = sc->port.supported[idx];
14314             break;
14315         }
14316
14317         sc->link_params.req_flow_ctrl[idx] =
14318             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14319
14320         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14321             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14322                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14323             } else {
14324                 bxe_set_requested_fc(sc);
14325             }
14326         }
14327
14328         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14329                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14330               sc->link_params.req_line_speed[idx],
14331               sc->link_params.req_duplex[idx],
14332               sc->link_params.req_flow_ctrl[idx],
14333               sc->port.advertising[idx]);
14334     }
14335 }
14336
14337 static void
14338 bxe_get_phy_info(struct bxe_softc *sc)
14339 {
14340     uint8_t port = SC_PORT(sc);
14341     uint32_t config = sc->port.config;
14342     uint32_t eee_mode;
14343
14344     /* shmem data already read in bxe_get_shmem_info() */
14345
14346     BLOGD(sc, DBG_LOAD, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14347                         "link_config0=0x%08x\n",
14348                sc->link_params.lane_config,
14349                sc->link_params.speed_cap_mask[0],
14350                sc->port.link_config[0]);
14351
14352     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14353     bxe_link_settings_requested(sc);
14354
14355     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14356         sc->link_params.feature_config_flags |=
14357             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14358     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14359         sc->link_params.feature_config_flags &=
14360             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14361     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14362         sc->link_params.feature_config_flags |=
14363             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14364     }
14365
14366     /* configure link feature according to nvram value */
14367     eee_mode =
14368         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14369           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14370          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14371     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14372         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14373                                     ELINK_EEE_MODE_ENABLE_LPI |
14374                                     ELINK_EEE_MODE_OUTPUT_TIME);
14375     } else {
14376         sc->link_params.eee_mode = 0;
14377     }
14378
14379     /* get the media type */
14380     bxe_media_detect(sc);
14381 }
14382
14383 static void
14384 bxe_get_params(struct bxe_softc *sc)
14385 {
14386     /* get user tunable params */
14387     bxe_get_tunable_params(sc);
14388
14389     /* select the RX and TX ring sizes */
14390     sc->tx_ring_size = TX_BD_USABLE;
14391     sc->rx_ring_size = RX_BD_USABLE;
14392
14393     /* XXX disable WoL */
14394     sc->wol = 0;
14395 }
14396
14397 static void
14398 bxe_set_modes_bitmap(struct bxe_softc *sc)
14399 {
14400     uint32_t flags = 0;
14401
14402     if (CHIP_REV_IS_FPGA(sc)) {
14403         SET_FLAGS(flags, MODE_FPGA);
14404     } else if (CHIP_REV_IS_EMUL(sc)) {
14405         SET_FLAGS(flags, MODE_EMUL);
14406     } else {
14407         SET_FLAGS(flags, MODE_ASIC);
14408     }
14409
14410     if (CHIP_IS_MODE_4_PORT(sc)) {
14411         SET_FLAGS(flags, MODE_PORT4);
14412     } else {
14413         SET_FLAGS(flags, MODE_PORT2);
14414     }
14415
14416     if (CHIP_IS_E2(sc)) {
14417         SET_FLAGS(flags, MODE_E2);
14418     } else if (CHIP_IS_E3(sc)) {
14419         SET_FLAGS(flags, MODE_E3);
14420         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14421             SET_FLAGS(flags, MODE_E3_A0);
14422         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14423             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14424         }
14425     }
14426
14427     if (IS_MF(sc)) {
14428         SET_FLAGS(flags, MODE_MF);
14429         switch (sc->devinfo.mf_info.mf_mode) {
14430         case MULTI_FUNCTION_SD:
14431             SET_FLAGS(flags, MODE_MF_SD);
14432             break;
14433         case MULTI_FUNCTION_SI:
14434             SET_FLAGS(flags, MODE_MF_SI);
14435             break;
14436         case MULTI_FUNCTION_AFEX:
14437             SET_FLAGS(flags, MODE_MF_AFEX);
14438             break;
14439         }
14440     } else {
14441         SET_FLAGS(flags, MODE_SF);
14442     }
14443
14444 #if defined(__LITTLE_ENDIAN)
14445     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14446 #else /* __BIG_ENDIAN */
14447     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14448 #endif
14449
14450     INIT_MODE_FLAGS(sc) = flags;
14451 }
14452
14453 static int
14454 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14455 {
14456     struct bxe_fastpath *fp;
14457     bus_addr_t busaddr;
14458     int max_agg_queues;
14459     int max_segments;
14460     bus_size_t max_size;
14461     bus_size_t max_seg_size;
14462     char buf[32];
14463     int rc;
14464     int i, j;
14465
14466     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14467
14468     /* allocate the parent bus DMA tag */
14469     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14470                             1,                        /* alignment */
14471                             0,                        /* boundary limit */
14472                             BUS_SPACE_MAXADDR,        /* restricted low */
14473                             BUS_SPACE_MAXADDR,        /* restricted hi */
14474                             NULL,                     /* addr filter() */
14475                             NULL,                     /* addr filter() arg */
14476                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14477                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14478                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14479                             0,                        /* flags */
14480                             NULL,                     /* lock() */
14481                             NULL,                     /* lock() arg */
14482                             &sc->parent_dma_tag);     /* returned dma tag */
14483     if (rc != 0) {
14484         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14485         return (1);
14486     }
14487
14488     /************************/
14489     /* DEFAULT STATUS BLOCK */
14490     /************************/
14491
14492     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14493                       &sc->def_sb_dma, "default status block") != 0) {
14494         /* XXX */
14495         bus_dma_tag_destroy(sc->parent_dma_tag);
14496         return (1);
14497     }
14498
14499     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14500
14501     /***************/
14502     /* EVENT QUEUE */
14503     /***************/
14504
14505     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14506                       &sc->eq_dma, "event queue") != 0) {
14507         /* XXX */
14508         bxe_dma_free(sc, &sc->def_sb_dma);
14509         sc->def_sb = NULL;
14510         bus_dma_tag_destroy(sc->parent_dma_tag);
14511         return (1);
14512     }
14513
14514     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14515
14516     /*************/
14517     /* SLOW PATH */
14518     /*************/
14519
14520     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14521                       &sc->sp_dma, "slow path") != 0) {
14522         /* XXX */
14523         bxe_dma_free(sc, &sc->eq_dma);
14524         sc->eq = NULL;
14525         bxe_dma_free(sc, &sc->def_sb_dma);
14526         sc->def_sb = NULL;
14527         bus_dma_tag_destroy(sc->parent_dma_tag);
14528         return (1);
14529     }
14530
14531     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14532
14533     /*******************/
14534     /* SLOW PATH QUEUE */
14535     /*******************/
14536
14537     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14538                       &sc->spq_dma, "slow path queue") != 0) {
14539         /* XXX */
14540         bxe_dma_free(sc, &sc->sp_dma);
14541         sc->sp = NULL;
14542         bxe_dma_free(sc, &sc->eq_dma);
14543         sc->eq = NULL;
14544         bxe_dma_free(sc, &sc->def_sb_dma);
14545         sc->def_sb = NULL;
14546         bus_dma_tag_destroy(sc->parent_dma_tag);
14547         return (1);
14548     }
14549
14550     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14551
14552     /***************************/
14553     /* FW DECOMPRESSION BUFFER */
14554     /***************************/
14555
14556     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14557                       "fw decompression buffer") != 0) {
14558         /* XXX */
14559         bxe_dma_free(sc, &sc->spq_dma);
14560         sc->spq = NULL;
14561         bxe_dma_free(sc, &sc->sp_dma);
14562         sc->sp = NULL;
14563         bxe_dma_free(sc, &sc->eq_dma);
14564         sc->eq = NULL;
14565         bxe_dma_free(sc, &sc->def_sb_dma);
14566         sc->def_sb = NULL;
14567         bus_dma_tag_destroy(sc->parent_dma_tag);
14568         return (1);
14569     }
14570
14571     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14572
14573     if ((sc->gz_strm =
14574          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14575         /* XXX */
14576         bxe_dma_free(sc, &sc->gz_buf_dma);
14577         sc->gz_buf = NULL;
14578         bxe_dma_free(sc, &sc->spq_dma);
14579         sc->spq = NULL;
14580         bxe_dma_free(sc, &sc->sp_dma);
14581         sc->sp = NULL;
14582         bxe_dma_free(sc, &sc->eq_dma);
14583         sc->eq = NULL;
14584         bxe_dma_free(sc, &sc->def_sb_dma);
14585         sc->def_sb = NULL;
14586         bus_dma_tag_destroy(sc->parent_dma_tag);
14587         return (1);
14588     }
14589
14590     /*************/
14591     /* FASTPATHS */
14592     /*************/
14593
14594     /* allocate DMA memory for each fastpath structure */
14595     for (i = 0; i < sc->num_queues; i++) {
14596         fp = &sc->fp[i];
14597         fp->sc    = sc;
14598         fp->index = i;
14599
14600         /*******************/
14601         /* FP STATUS BLOCK */
14602         /*******************/
14603
14604         snprintf(buf, sizeof(buf), "fp %d status block", i);
14605         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14606                           &fp->sb_dma, buf) != 0) {
14607             /* XXX unwind and free previous fastpath allocations */
14608             BLOGE(sc, "Failed to alloc %s\n", buf);
14609             return (1);
14610         } else {
14611             if (CHIP_IS_E2E3(sc)) {
14612                 fp->status_block.e2_sb =
14613                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14614             } else {
14615                 fp->status_block.e1x_sb =
14616                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14617             }
14618         }
14619
14620         /******************/
14621         /* FP TX BD CHAIN */
14622         /******************/
14623
14624         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14625         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14626                           &fp->tx_dma, buf) != 0) {
14627             /* XXX unwind and free previous fastpath allocations */
14628             BLOGE(sc, "Failed to alloc %s\n", buf);
14629             return (1);
14630         } else {
14631             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14632         }
14633
14634         /* link together the tx bd chain pages */
14635         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14636             /* index into the tx bd chain array to last entry per page */
14637             struct eth_tx_next_bd *tx_next_bd =
14638                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14639             /* point to the next page and wrap from last page */
14640             busaddr = (fp->tx_dma.paddr +
14641                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14642             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14643             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14644         }
14645
14646         /******************/
14647         /* FP RX BD CHAIN */
14648         /******************/
14649
14650         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14651         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14652                           &fp->rx_dma, buf) != 0) {
14653             /* XXX unwind and free previous fastpath allocations */
14654             BLOGE(sc, "Failed to alloc %s\n", buf);
14655             return (1);
14656         } else {
14657             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14658         }
14659
14660         /* link together the rx bd chain pages */
14661         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14662             /* index into the rx bd chain array to last entry per page */
14663             struct eth_rx_bd *rx_bd =
14664                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14665             /* point to the next page and wrap from last page */
14666             busaddr = (fp->rx_dma.paddr +
14667                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14668             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14669             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14670         }
14671
14672         /*******************/
14673         /* FP RX RCQ CHAIN */
14674         /*******************/
14675
14676         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14677         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14678                           &fp->rcq_dma, buf) != 0) {
14679             /* XXX unwind and free previous fastpath allocations */
14680             BLOGE(sc, "Failed to alloc %s\n", buf);
14681             return (1);
14682         } else {
14683             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14684         }
14685
14686         /* link together the rcq chain pages */
14687         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14688             /* index into the rcq chain array to last entry per page */
14689             struct eth_rx_cqe_next_page *rx_cqe_next =
14690                 (struct eth_rx_cqe_next_page *)
14691                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14692             /* point to the next page and wrap from last page */
14693             busaddr = (fp->rcq_dma.paddr +
14694                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14695             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14696             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14697         }
14698
14699         /*******************/
14700         /* FP RX SGE CHAIN */
14701         /*******************/
14702
14703         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14704         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14705                           &fp->rx_sge_dma, buf) != 0) {
14706             /* XXX unwind and free previous fastpath allocations */
14707             BLOGE(sc, "Failed to alloc %s\n", buf);
14708             return (1);
14709         } else {
14710             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14711         }
14712
14713         /* link together the sge chain pages */
14714         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14715             /* index into the rcq chain array to last entry per page */
14716             struct eth_rx_sge *rx_sge =
14717                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14718             /* point to the next page and wrap from last page */
14719             busaddr = (fp->rx_sge_dma.paddr +
14720                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14721             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14722             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14723         }
14724
14725         /***********************/
14726         /* FP TX MBUF DMA MAPS */
14727         /***********************/
14728
14729         /* set required sizes before mapping to conserve resources */
14730         if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
14731             max_size     = BXE_TSO_MAX_SIZE;
14732             max_segments = BXE_TSO_MAX_SEGMENTS;
14733             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14734         } else {
14735             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14736             max_segments = BXE_MAX_SEGMENTS;
14737             max_seg_size = MCLBYTES;
14738         }
14739
14740         /* create a dma tag for the tx mbufs */
14741         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14742                                 1,                  /* alignment */
14743                                 0,                  /* boundary limit */
14744                                 BUS_SPACE_MAXADDR,  /* restricted low */
14745                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14746                                 NULL,               /* addr filter() */
14747                                 NULL,               /* addr filter() arg */
14748                                 max_size,           /* max map size */
14749                                 max_segments,       /* num discontinuous */
14750                                 max_seg_size,       /* max seg size */
14751                                 0,                  /* flags */
14752                                 NULL,               /* lock() */
14753                                 NULL,               /* lock() arg */
14754                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14755         if (rc != 0) {
14756             /* XXX unwind and free previous fastpath allocations */
14757             BLOGE(sc, "Failed to create dma tag for "
14758                       "'fp %d tx mbufs' (%d)\n", i, rc);
14759             return (1);
14760         }
14761
14762         /* create dma maps for each of the tx mbuf clusters */
14763         for (j = 0; j < TX_BD_TOTAL; j++) {
14764             if (bus_dmamap_create(fp->tx_mbuf_tag,
14765                                   BUS_DMA_NOWAIT,
14766                                   &fp->tx_mbuf_chain[j].m_map)) {
14767                 /* XXX unwind and free previous fastpath allocations */
14768                 BLOGE(sc, "Failed to create dma map for "
14769                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14770                 return (1);
14771             }
14772         }
14773
14774         /***********************/
14775         /* FP RX MBUF DMA MAPS */
14776         /***********************/
14777
14778         /* create a dma tag for the rx mbufs */
14779         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14780                                 1,                  /* alignment */
14781                                 0,                  /* boundary limit */
14782                                 BUS_SPACE_MAXADDR,  /* restricted low */
14783                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14784                                 NULL,               /* addr filter() */
14785                                 NULL,               /* addr filter() arg */
14786                                 MJUM9BYTES,         /* max map size */
14787                                 1,                  /* num discontinuous */
14788                                 MJUM9BYTES,         /* max seg size */
14789                                 0,                  /* flags */
14790                                 NULL,               /* lock() */
14791                                 NULL,               /* lock() arg */
14792                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14793         if (rc != 0) {
14794             /* XXX unwind and free previous fastpath allocations */
14795             BLOGE(sc, "Failed to create dma tag for "
14796                       "'fp %d rx mbufs' (%d)\n", i, rc);
14797             return (1);
14798         }
14799
14800         /* create dma maps for each of the rx mbuf clusters */
14801         for (j = 0; j < RX_BD_TOTAL; j++) {
14802             if (bus_dmamap_create(fp->rx_mbuf_tag,
14803                                   BUS_DMA_NOWAIT,
14804                                   &fp->rx_mbuf_chain[j].m_map)) {
14805                 /* XXX unwind and free previous fastpath allocations */
14806                 BLOGE(sc, "Failed to create dma map for "
14807                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14808                 return (1);
14809             }
14810         }
14811
14812         /* create dma map for the spare rx mbuf cluster */
14813         if (bus_dmamap_create(fp->rx_mbuf_tag,
14814                               BUS_DMA_NOWAIT,
14815                               &fp->rx_mbuf_spare_map)) {
14816             /* XXX unwind and free previous fastpath allocations */
14817             BLOGE(sc, "Failed to create dma map for "
14818                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14819             return (1);
14820         }
14821
14822         /***************************/
14823         /* FP RX SGE MBUF DMA MAPS */
14824         /***************************/
14825
14826         /* create a dma tag for the rx sge mbufs */
14827         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14828                                 1,                  /* alignment */
14829                                 0,                  /* boundary limit */
14830                                 BUS_SPACE_MAXADDR,  /* restricted low */
14831                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14832                                 NULL,               /* addr filter() */
14833                                 NULL,               /* addr filter() arg */
14834                                 BCM_PAGE_SIZE,      /* max map size */
14835                                 1,                  /* num discontinuous */
14836                                 BCM_PAGE_SIZE,      /* max seg size */
14837                                 0,                  /* flags */
14838                                 NULL,               /* lock() */
14839                                 NULL,               /* lock() arg */
14840                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14841         if (rc != 0) {
14842             /* XXX unwind and free previous fastpath allocations */
14843             BLOGE(sc, "Failed to create dma tag for "
14844                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14845             return (1);
14846         }
14847
14848         /* create dma maps for the rx sge mbuf clusters */
14849         for (j = 0; j < RX_SGE_TOTAL; j++) {
14850             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14851                                   BUS_DMA_NOWAIT,
14852                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14853                 /* XXX unwind and free previous fastpath allocations */
14854                 BLOGE(sc, "Failed to create dma map for "
14855                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14856                 return (1);
14857             }
14858         }
14859
14860         /* create dma map for the spare rx sge mbuf cluster */
14861         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14862                               BUS_DMA_NOWAIT,
14863                               &fp->rx_sge_mbuf_spare_map)) {
14864             /* XXX unwind and free previous fastpath allocations */
14865             BLOGE(sc, "Failed to create dma map for "
14866                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14867             return (1);
14868         }
14869
14870         /***************************/
14871         /* FP RX TPA MBUF DMA MAPS */
14872         /***************************/
14873
14874         /* create dma maps for the rx tpa mbuf clusters */
14875         max_agg_queues = MAX_AGG_QS(sc);
14876
14877         for (j = 0; j < max_agg_queues; j++) {
14878             if (bus_dmamap_create(fp->rx_mbuf_tag,
14879                                   BUS_DMA_NOWAIT,
14880                                   &fp->rx_tpa_info[j].bd.m_map)) {
14881                 /* XXX unwind and free previous fastpath allocations */
14882                 BLOGE(sc, "Failed to create dma map for "
14883                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14884                 return (1);
14885             }
14886         }
14887
14888         /* create dma map for the spare rx tpa mbuf cluster */
14889         if (bus_dmamap_create(fp->rx_mbuf_tag,
14890                               BUS_DMA_NOWAIT,
14891                               &fp->rx_tpa_info_mbuf_spare_map)) {
14892             /* XXX unwind and free previous fastpath allocations */
14893             BLOGE(sc, "Failed to create dma map for "
14894                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14895             return (1);
14896         }
14897
14898         bxe_init_sge_ring_bit_mask(fp);
14899     }
14900
14901     return (0);
14902 }
14903
14904 static void
14905 bxe_free_hsi_mem(struct bxe_softc *sc)
14906 {
14907     struct bxe_fastpath *fp;
14908     int max_agg_queues;
14909     int i, j;
14910
14911     if (sc->parent_dma_tag == NULL) {
14912         return; /* assume nothing was allocated */
14913     }
14914
14915     for (i = 0; i < sc->num_queues; i++) {
14916         fp = &sc->fp[i];
14917
14918         /*******************/
14919         /* FP STATUS BLOCK */
14920         /*******************/
14921
14922         bxe_dma_free(sc, &fp->sb_dma);
14923         memset(&fp->status_block, 0, sizeof(fp->status_block));
14924
14925         /******************/
14926         /* FP TX BD CHAIN */
14927         /******************/
14928
14929         bxe_dma_free(sc, &fp->tx_dma);
14930         fp->tx_chain = NULL;
14931
14932         /******************/
14933         /* FP RX BD CHAIN */
14934         /******************/
14935
14936         bxe_dma_free(sc, &fp->rx_dma);
14937         fp->rx_chain = NULL;
14938
14939         /*******************/
14940         /* FP RX RCQ CHAIN */
14941         /*******************/
14942
14943         bxe_dma_free(sc, &fp->rcq_dma);
14944         fp->rcq_chain = NULL;
14945
14946         /*******************/
14947         /* FP RX SGE CHAIN */
14948         /*******************/
14949
14950         bxe_dma_free(sc, &fp->rx_sge_dma);
14951         fp->rx_sge_chain = NULL;
14952
14953         /***********************/
14954         /* FP TX MBUF DMA MAPS */
14955         /***********************/
14956
14957         if (fp->tx_mbuf_tag != NULL) {
14958             for (j = 0; j < TX_BD_TOTAL; j++) {
14959                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14960                     bus_dmamap_unload(fp->tx_mbuf_tag,
14961                                       fp->tx_mbuf_chain[j].m_map);
14962                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14963                                        fp->tx_mbuf_chain[j].m_map);
14964                 }
14965             }
14966
14967             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14968             fp->tx_mbuf_tag = NULL;
14969         }
14970
14971         /***********************/
14972         /* FP RX MBUF DMA MAPS */
14973         /***********************/
14974
14975         if (fp->rx_mbuf_tag != NULL) {
14976             for (j = 0; j < RX_BD_TOTAL; j++) {
14977                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14978                     bus_dmamap_unload(fp->rx_mbuf_tag,
14979                                       fp->rx_mbuf_chain[j].m_map);
14980                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14981                                        fp->rx_mbuf_chain[j].m_map);
14982                 }
14983             }
14984
14985             if (fp->rx_mbuf_spare_map != NULL) {
14986                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14987                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14988             }
14989
14990             /***************************/
14991             /* FP RX TPA MBUF DMA MAPS */
14992             /***************************/
14993
14994             max_agg_queues = MAX_AGG_QS(sc);
14995
14996             for (j = 0; j < max_agg_queues; j++) {
14997                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14998                     bus_dmamap_unload(fp->rx_mbuf_tag,
14999                                       fp->rx_tpa_info[j].bd.m_map);
15000                     bus_dmamap_destroy(fp->rx_mbuf_tag,
15001                                        fp->rx_tpa_info[j].bd.m_map);
15002                 }
15003             }
15004
15005             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
15006                 bus_dmamap_unload(fp->rx_mbuf_tag,
15007                                   fp->rx_tpa_info_mbuf_spare_map);
15008                 bus_dmamap_destroy(fp->rx_mbuf_tag,
15009                                    fp->rx_tpa_info_mbuf_spare_map);
15010             }
15011
15012             bus_dma_tag_destroy(fp->rx_mbuf_tag);
15013             fp->rx_mbuf_tag = NULL;
15014         }
15015
15016         /***************************/
15017         /* FP RX SGE MBUF DMA MAPS */
15018         /***************************/
15019
15020         if (fp->rx_sge_mbuf_tag != NULL) {
15021             for (j = 0; j < RX_SGE_TOTAL; j++) {
15022                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
15023                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15024                                       fp->rx_sge_mbuf_chain[j].m_map);
15025                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15026                                        fp->rx_sge_mbuf_chain[j].m_map);
15027                 }
15028             }
15029
15030             if (fp->rx_sge_mbuf_spare_map != NULL) {
15031                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15032                                   fp->rx_sge_mbuf_spare_map);
15033                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15034                                    fp->rx_sge_mbuf_spare_map);
15035             }
15036
15037             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
15038             fp->rx_sge_mbuf_tag = NULL;
15039         }
15040     }
15041
15042     /***************************/
15043     /* FW DECOMPRESSION BUFFER */
15044     /***************************/
15045
15046     bxe_dma_free(sc, &sc->gz_buf_dma);
15047     sc->gz_buf = NULL;
15048     free(sc->gz_strm, M_DEVBUF);
15049     sc->gz_strm = NULL;
15050
15051     /*******************/
15052     /* SLOW PATH QUEUE */
15053     /*******************/
15054
15055     bxe_dma_free(sc, &sc->spq_dma);
15056     sc->spq = NULL;
15057
15058     /*************/
15059     /* SLOW PATH */
15060     /*************/
15061
15062     bxe_dma_free(sc, &sc->sp_dma);
15063     sc->sp = NULL;
15064
15065     /***************/
15066     /* EVENT QUEUE */
15067     /***************/
15068
15069     bxe_dma_free(sc, &sc->eq_dma);
15070     sc->eq = NULL;
15071
15072     /************************/
15073     /* DEFAULT STATUS BLOCK */
15074     /************************/
15075
15076     bxe_dma_free(sc, &sc->def_sb_dma);
15077     sc->def_sb = NULL;
15078
15079     bus_dma_tag_destroy(sc->parent_dma_tag);
15080     sc->parent_dma_tag = NULL;
15081 }
15082
15083 /*
15084  * Previous driver DMAE transaction may have occurred when pre-boot stage
15085  * ended and boot began. This would invalidate the addresses of the
15086  * transaction, resulting in was-error bit set in the PCI causing all
15087  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15088  * the interrupt which detected this from the pglueb and the was-done bit
15089  */
15090 static void
15091 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15092 {
15093     uint32_t val;
15094
15095     if (!CHIP_IS_E1x(sc)) {
15096         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15097         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15098             BLOGD(sc, DBG_LOAD,
15099                   "Clearing 'was-error' bit that was set in pglueb");
15100             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15101         }
15102     }
15103 }
15104
15105 static int
15106 bxe_prev_mcp_done(struct bxe_softc *sc)
15107 {
15108     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15109                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15110     if (!rc) {
15111         BLOGE(sc, "MCP response failure, aborting\n");
15112         return (-1);
15113     }
15114
15115     return (0);
15116 }
15117
15118 static struct bxe_prev_list_node *
15119 bxe_prev_path_get_entry(struct bxe_softc *sc)
15120 {
15121     struct bxe_prev_list_node *tmp;
15122
15123     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15124         if ((sc->pcie_bus == tmp->bus) &&
15125             (sc->pcie_device == tmp->slot) &&
15126             (SC_PATH(sc) == tmp->path)) {
15127             return (tmp);
15128         }
15129     }
15130
15131     return (NULL);
15132 }
15133
15134 static uint8_t
15135 bxe_prev_is_path_marked(struct bxe_softc *sc)
15136 {
15137     struct bxe_prev_list_node *tmp;
15138     int rc = FALSE;
15139
15140     mtx_lock(&bxe_prev_mtx);
15141
15142     tmp = bxe_prev_path_get_entry(sc);
15143     if (tmp) {
15144         if (tmp->aer) {
15145             BLOGD(sc, DBG_LOAD,
15146                   "Path %d/%d/%d was marked by AER\n",
15147                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15148         } else {
15149             rc = TRUE;
15150             BLOGD(sc, DBG_LOAD,
15151                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15152                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15153         }
15154     }
15155
15156     mtx_unlock(&bxe_prev_mtx);
15157
15158     return (rc);
15159 }
15160
15161 static int
15162 bxe_prev_mark_path(struct bxe_softc *sc,
15163                    uint8_t          after_undi)
15164 {
15165     struct bxe_prev_list_node *tmp;
15166
15167     mtx_lock(&bxe_prev_mtx);
15168
15169     /* Check whether the entry for this path already exists */
15170     tmp = bxe_prev_path_get_entry(sc);
15171     if (tmp) {
15172         if (!tmp->aer) {
15173             BLOGD(sc, DBG_LOAD,
15174                   "Re-marking AER in path %d/%d/%d\n",
15175                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15176         } else {
15177             BLOGD(sc, DBG_LOAD,
15178                   "Removing AER indication from path %d/%d/%d\n",
15179                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15180             tmp->aer = 0;
15181         }
15182
15183         mtx_unlock(&bxe_prev_mtx);
15184         return (0);
15185     }
15186
15187     mtx_unlock(&bxe_prev_mtx);
15188
15189     /* Create an entry for this path and add it */
15190     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15191                  (M_NOWAIT | M_ZERO));
15192     if (!tmp) {
15193         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15194         return (-1);
15195     }
15196
15197     tmp->bus  = sc->pcie_bus;
15198     tmp->slot = sc->pcie_device;
15199     tmp->path = SC_PATH(sc);
15200     tmp->aer  = 0;
15201     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15202
15203     mtx_lock(&bxe_prev_mtx);
15204
15205     BLOGD(sc, DBG_LOAD,
15206           "Marked path %d/%d/%d - finished previous unload\n",
15207           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15208     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15209
15210     mtx_unlock(&bxe_prev_mtx);
15211
15212     return (0);
15213 }
15214
15215 static int
15216 bxe_do_flr(struct bxe_softc *sc)
15217 {
15218     int i;
15219
15220     /* only E2 and onwards support FLR */
15221     if (CHIP_IS_E1x(sc)) {
15222         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15223         return (-1);
15224     }
15225
15226     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15227     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15228         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15229               sc->devinfo.bc_ver);
15230         return (-1);
15231     }
15232
15233     /* Wait for Transaction Pending bit clean */
15234     for (i = 0; i < 4; i++) {
15235         if (i) {
15236             DELAY(((1 << (i - 1)) * 100) * 1000);
15237         }
15238
15239         if (!bxe_is_pcie_pending(sc)) {
15240             goto clear;
15241         }
15242     }
15243
15244     BLOGE(sc, "PCIE transaction is not cleared, "
15245               "proceeding with reset anyway\n");
15246
15247 clear:
15248
15249     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15250     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15251
15252     return (0);
15253 }
15254
15255 struct bxe_mac_vals {
15256     uint32_t xmac_addr;
15257     uint32_t xmac_val;
15258     uint32_t emac_addr;
15259     uint32_t emac_val;
15260     uint32_t umac_addr;
15261     uint32_t umac_val;
15262     uint32_t bmac_addr;
15263     uint32_t bmac_val[2];
15264 };
15265
15266 static void
15267 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15268                           struct bxe_mac_vals *vals)
15269 {
15270     uint32_t val, base_addr, offset, mask, reset_reg;
15271     uint8_t mac_stopped = FALSE;
15272     uint8_t port = SC_PORT(sc);
15273     uint32_t wb_data[2];
15274
15275     /* reset addresses as they also mark which values were changed */
15276     vals->bmac_addr = 0;
15277     vals->umac_addr = 0;
15278     vals->xmac_addr = 0;
15279     vals->emac_addr = 0;
15280
15281     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15282
15283     if (!CHIP_IS_E3(sc)) {
15284         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15285         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15286         if ((mask & reset_reg) && val) {
15287             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15288             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15289                                     : NIG_REG_INGRESS_BMAC0_MEM;
15290             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15291                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15292
15293             /*
15294              * use rd/wr since we cannot use dmae. This is safe
15295              * since MCP won't access the bus due to the request
15296              * to unload, and no function on the path can be
15297              * loaded at this time.
15298              */
15299             wb_data[0] = REG_RD(sc, base_addr + offset);
15300             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15301             vals->bmac_addr = base_addr + offset;
15302             vals->bmac_val[0] = wb_data[0];
15303             vals->bmac_val[1] = wb_data[1];
15304             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15305             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15306             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15307         }
15308
15309         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15310         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15311         vals->emac_val = REG_RD(sc, vals->emac_addr);
15312         REG_WR(sc, vals->emac_addr, 0);
15313         mac_stopped = TRUE;
15314     } else {
15315         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15316             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15317             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15318             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15319             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15320             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15321             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15322             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15323             REG_WR(sc, vals->xmac_addr, 0);
15324             mac_stopped = TRUE;
15325         }
15326
15327         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15328         if (mask & reset_reg) {
15329             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15330             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15331             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15332             vals->umac_val = REG_RD(sc, vals->umac_addr);
15333             REG_WR(sc, vals->umac_addr, 0);
15334             mac_stopped = TRUE;
15335         }
15336     }
15337
15338     if (mac_stopped) {
15339         DELAY(20000);
15340     }
15341 }
15342
15343 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15344 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15345 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15346 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15347
15348 static void
15349 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15350                          uint8_t          port,
15351                          uint8_t          inc)
15352 {
15353     uint16_t rcq, bd;
15354     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15355
15356     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15357     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15358
15359     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15360     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15361
15362     BLOGD(sc, DBG_LOAD,
15363           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15364           port, bd, rcq);
15365 }
15366
15367 static int
15368 bxe_prev_unload_common(struct bxe_softc *sc)
15369 {
15370     uint32_t reset_reg, tmp_reg = 0, rc;
15371     uint8_t prev_undi = FALSE;
15372     struct bxe_mac_vals mac_vals;
15373     uint32_t timer_count = 1000;
15374     uint32_t prev_brb;
15375
15376     /*
15377      * It is possible a previous function received 'common' answer,
15378      * but hasn't loaded yet, therefore creating a scenario of
15379      * multiple functions receiving 'common' on the same path.
15380      */
15381     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15382
15383     memset(&mac_vals, 0, sizeof(mac_vals));
15384
15385     if (bxe_prev_is_path_marked(sc)) {
15386         return (bxe_prev_mcp_done(sc));
15387     }
15388
15389     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15390
15391     /* Reset should be performed after BRB is emptied */
15392     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15393         /* Close the MAC Rx to prevent BRB from filling up */
15394         bxe_prev_unload_close_mac(sc, &mac_vals);
15395
15396         /* close LLH filters towards the BRB */
15397         elink_set_rx_filter(&sc->link_params, 0);
15398
15399         /*
15400          * Check if the UNDI driver was previously loaded.
15401          * UNDI driver initializes CID offset for normal bell to 0x7
15402          */
15403         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15404             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15405             if (tmp_reg == 0x7) {
15406                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15407                 prev_undi = TRUE;
15408                 /* clear the UNDI indication */
15409                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15410                 /* clear possible idle check errors */
15411                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15412             }
15413         }
15414
15415         /* wait until BRB is empty */
15416         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15417         while (timer_count) {
15418             prev_brb = tmp_reg;
15419
15420             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15421             if (!tmp_reg) {
15422                 break;
15423             }
15424
15425             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15426
15427             /* reset timer as long as BRB actually gets emptied */
15428             if (prev_brb > tmp_reg) {
15429                 timer_count = 1000;
15430             } else {
15431                 timer_count--;
15432             }
15433
15434             /* If UNDI resides in memory, manually increment it */
15435             if (prev_undi) {
15436                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15437             }
15438
15439             DELAY(10);
15440         }
15441
15442         if (!timer_count) {
15443             BLOGE(sc, "Failed to empty BRB\n");
15444         }
15445     }
15446
15447     /* No packets are in the pipeline, path is ready for reset */
15448     bxe_reset_common(sc);
15449
15450     if (mac_vals.xmac_addr) {
15451         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15452     }
15453     if (mac_vals.umac_addr) {
15454         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15455     }
15456     if (mac_vals.emac_addr) {
15457         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15458     }
15459     if (mac_vals.bmac_addr) {
15460         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15461         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15462     }
15463
15464     rc = bxe_prev_mark_path(sc, prev_undi);
15465     if (rc) {
15466         bxe_prev_mcp_done(sc);
15467         return (rc);
15468     }
15469
15470     return (bxe_prev_mcp_done(sc));
15471 }
15472
15473 static int
15474 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15475 {
15476     int rc;
15477
15478     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15479
15480     /* Test if previous unload process was already finished for this path */
15481     if (bxe_prev_is_path_marked(sc)) {
15482         return (bxe_prev_mcp_done(sc));
15483     }
15484
15485     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15486
15487     /*
15488      * If function has FLR capabilities, and existing FW version matches
15489      * the one required, then FLR will be sufficient to clean any residue
15490      * left by previous driver
15491      */
15492     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15493     if (!rc) {
15494         /* fw version is good */
15495         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15496         rc = bxe_do_flr(sc);
15497     }
15498
15499     if (!rc) {
15500         /* FLR was performed */
15501         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15502         return (0);
15503     }
15504
15505     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15506
15507     /* Close the MCP request, return failure*/
15508     rc = bxe_prev_mcp_done(sc);
15509     if (!rc) {
15510         rc = BXE_PREV_WAIT_NEEDED;
15511     }
15512
15513     return (rc);
15514 }
15515
15516 static int
15517 bxe_prev_unload(struct bxe_softc *sc)
15518 {
15519     int time_counter = 10;
15520     uint32_t fw, hw_lock_reg, hw_lock_val;
15521     uint32_t rc = 0;
15522
15523     /*
15524      * Clear HW from errors which may have resulted from an interrupted
15525      * DMAE transaction.
15526      */
15527     bxe_prev_interrupted_dmae(sc);
15528
15529     /* Release previously held locks */
15530     hw_lock_reg =
15531         (SC_FUNC(sc) <= 5) ?
15532             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15533             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15534
15535     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15536     if (hw_lock_val) {
15537         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15538             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15539             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15540                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15541         }
15542         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15543         REG_WR(sc, hw_lock_reg, 0xffffffff);
15544     } else {
15545         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15546     }
15547
15548     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15549         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15550         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15551     }
15552
15553     do {
15554         /* Lock MCP using an unload request */
15555         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15556         if (!fw) {
15557             BLOGE(sc, "MCP response failure, aborting\n");
15558             rc = -1;
15559             break;
15560         }
15561
15562         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15563             rc = bxe_prev_unload_common(sc);
15564             break;
15565         }
15566
15567         /* non-common reply from MCP night require looping */
15568         rc = bxe_prev_unload_uncommon(sc);
15569         if (rc != BXE_PREV_WAIT_NEEDED) {
15570             break;
15571         }
15572
15573         DELAY(20000);
15574     } while (--time_counter);
15575
15576     if (!time_counter || rc) {
15577         BLOGE(sc, "Failed to unload previous driver!"
15578             " time_counter %d rc %d\n", time_counter, rc);
15579         rc = -1;
15580     }
15581
15582     return (rc);
15583 }
15584
15585 void
15586 bxe_dcbx_set_state(struct bxe_softc *sc,
15587                    uint8_t          dcb_on,
15588                    uint32_t         dcbx_enabled)
15589 {
15590     if (!CHIP_IS_E1x(sc)) {
15591         sc->dcb_state = dcb_on;
15592         sc->dcbx_enabled = dcbx_enabled;
15593     } else {
15594         sc->dcb_state = FALSE;
15595         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15596     }
15597     BLOGD(sc, DBG_LOAD,
15598           "DCB state [%s:%s]\n",
15599           dcb_on ? "ON" : "OFF",
15600           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15601           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15602           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15603           "on-chip with negotiation" : "invalid");
15604 }
15605
15606 /* must be called after sriov-enable */
15607 static int
15608 bxe_set_qm_cid_count(struct bxe_softc *sc)
15609 {
15610     int cid_count = BXE_L2_MAX_CID(sc);
15611
15612     if (IS_SRIOV(sc)) {
15613         cid_count += BXE_VF_CIDS;
15614     }
15615
15616     if (CNIC_SUPPORT(sc)) {
15617         cid_count += CNIC_CID_MAX;
15618     }
15619
15620     return (roundup(cid_count, QM_CID_ROUND));
15621 }
15622
15623 static void
15624 bxe_init_multi_cos(struct bxe_softc *sc)
15625 {
15626     int pri, cos;
15627
15628     uint32_t pri_map = 0; /* XXX change to user config */
15629
15630     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15631         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15632         if (cos < sc->max_cos) {
15633             sc->prio_to_cos[pri] = cos;
15634         } else {
15635             BLOGW(sc, "Invalid COS %d for priority %d "
15636                       "(max COS is %d), setting to 0\n",
15637                   cos, pri, (sc->max_cos - 1));
15638             sc->prio_to_cos[pri] = 0;
15639         }
15640     }
15641 }
15642
15643 static int
15644 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15645 {
15646     struct bxe_softc *sc;
15647     int error, result;
15648
15649     result = 0;
15650     error = sysctl_handle_int(oidp, &result, 0, req);
15651
15652     if (error || !req->newptr) {
15653         return (error);
15654     }
15655
15656     if (result == 1) {
15657         uint32_t  temp;
15658         sc = (struct bxe_softc *)arg1;
15659
15660         BLOGI(sc, "... dumping driver state ...\n");
15661         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15662         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15663     }
15664
15665     return (error);
15666 }
15667
15668 static int
15669 bxe_sysctl_trigger_grcdump(SYSCTL_HANDLER_ARGS)
15670 {
15671     struct bxe_softc *sc;
15672     int error, result;
15673
15674     result = 0;
15675     error = sysctl_handle_int(oidp, &result, 0, req);
15676
15677     if (error || !req->newptr) {
15678         return (error);
15679     }
15680
15681     if (result == 1) {
15682         sc = (struct bxe_softc *)arg1;
15683
15684         BLOGI(sc, "... grcdump start ...\n");
15685         bxe_grc_dump(sc);
15686         BLOGI(sc, "... grcdump done ...\n");
15687     }
15688
15689     return (error);
15690 }
15691
15692 static int
15693 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15694 {
15695     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15696     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15697     uint32_t *offset;
15698     uint64_t value = 0;
15699     int index = (int)arg2;
15700
15701     if (index >= BXE_NUM_ETH_STATS) {
15702         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15703         return (-1);
15704     }
15705
15706     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15707
15708     switch (bxe_eth_stats_arr[index].size) {
15709     case 4:
15710         value = (uint64_t)*offset;
15711         break;
15712     case 8:
15713         value = HILO_U64(*offset, *(offset + 1));
15714         break;
15715     default:
15716         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15717               index, bxe_eth_stats_arr[index].size);
15718         return (-1);
15719     }
15720
15721     return (sysctl_handle_64(oidp, &value, 0, req));
15722 }
15723
15724 static int
15725 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15726 {
15727     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15728     uint32_t *eth_stats;
15729     uint32_t *offset;
15730     uint64_t value = 0;
15731     uint32_t q_stat = (uint32_t)arg2;
15732     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15733     uint32_t index = (q_stat & 0xffff);
15734
15735     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15736
15737     if (index >= BXE_NUM_ETH_Q_STATS) {
15738         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15739         return (-1);
15740     }
15741
15742     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15743
15744     switch (bxe_eth_q_stats_arr[index].size) {
15745     case 4:
15746         value = (uint64_t)*offset;
15747         break;
15748     case 8:
15749         value = HILO_U64(*offset, *(offset + 1));
15750         break;
15751     default:
15752         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15753               index, bxe_eth_q_stats_arr[index].size);
15754         return (-1);
15755     }
15756
15757     return (sysctl_handle_64(oidp, &value, 0, req));
15758 }
15759
15760 static void
15761 bxe_add_sysctls(struct bxe_softc *sc)
15762 {
15763     struct sysctl_ctx_list *ctx;
15764     struct sysctl_oid_list *children;
15765     struct sysctl_oid *queue_top, *queue;
15766     struct sysctl_oid_list *queue_top_children, *queue_children;
15767     char queue_num_buf[32];
15768     uint32_t q_stat;
15769     int i, j;
15770
15771     ctx = device_get_sysctl_ctx(sc->dev);
15772     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15773
15774     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15775                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15776                       "version");
15777
15778     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15779              BCM_5710_FW_MAJOR_VERSION,
15780              BCM_5710_FW_MINOR_VERSION,
15781              BCM_5710_FW_REVISION_VERSION,
15782              BCM_5710_FW_ENGINEERING_VERSION);
15783
15784     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15785         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15786          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15787          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15788          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15789                                                                 "Unknown"));
15790     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15791                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15792                     "multifunction vnics per port");
15793
15794     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15795         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15796          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15797          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15798                                               "???GT/s"),
15799         sc->devinfo.pcie_link_width);
15800
15801     sc->debug = bxe_debug;
15802
15803 #if __FreeBSD_version >= 900000
15804     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15805                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15806                       "bootcode version");
15807     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15808                       CTLFLAG_RD, sc->fw_ver_str, 0,
15809                       "firmware version");
15810     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15811                       CTLFLAG_RD, sc->mf_mode_str, 0,
15812                       "multifunction mode");
15813     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15814                       CTLFLAG_RD, sc->mac_addr_str, 0,
15815                       "mac address");
15816     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15817                       CTLFLAG_RD, sc->pci_link_str, 0,
15818                       "pci link status");
15819     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
15820                     CTLFLAG_RW, &sc->debug,
15821                     "debug logging mode");
15822 #else
15823     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15824                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15825                       "bootcode version");
15826     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15827                       CTLFLAG_RD, &sc->fw_ver_str, 0,
15828                       "firmware version");
15829     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15830                       CTLFLAG_RD, &sc->mf_mode_str, 0,
15831                       "multifunction mode");
15832     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15833                       CTLFLAG_RD, &sc->mac_addr_str, 0,
15834                       "mac address");
15835     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15836                       CTLFLAG_RD, &sc->pci_link_str, 0,
15837                       "pci link status");
15838     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15839                     CTLFLAG_RW, &sc->debug, 0,
15840                     "debug logging mode");
15841 #endif /* #if __FreeBSD_version >= 900000 */
15842
15843     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "trigger_grcdump",
15844                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15845                     bxe_sysctl_trigger_grcdump, "IU",
15846                     "set by driver when a grcdump is needed");
15847
15848     sc->grcdump_done = 0;
15849     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15850                    CTLFLAG_RW, &sc->grcdump_done, 0,
15851                    "set by driver when grcdump is done");
15852
15853     sc->rx_budget = bxe_rx_budget;
15854     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15855                     CTLFLAG_RW, &sc->rx_budget, 0,
15856                     "rx processing budget");
15857
15858     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15859                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15860                     bxe_sysctl_state, "IU", "dump driver state");
15861
15862     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15863         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15864                         bxe_eth_stats_arr[i].string,
15865                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15866                         bxe_sysctl_eth_stat, "LU",
15867                         bxe_eth_stats_arr[i].string);
15868     }
15869
15870     /* add a new parent node for all queues "dev.bxe.#.queue" */
15871     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15872                                 CTLFLAG_RD, NULL, "queue");
15873     queue_top_children = SYSCTL_CHILDREN(queue_top);
15874
15875     for (i = 0; i < sc->num_queues; i++) {
15876         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15877         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15878         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15879                                 queue_num_buf, CTLFLAG_RD, NULL,
15880                                 "single queue");
15881         queue_children = SYSCTL_CHILDREN(queue);
15882
15883         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15884             q_stat = ((i << 16) | j);
15885             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15886                             bxe_eth_q_stats_arr[j].string,
15887                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15888                             bxe_sysctl_eth_q_stat, "LU",
15889                             bxe_eth_q_stats_arr[j].string);
15890         }
15891     }
15892 }
15893
15894 static int
15895 bxe_alloc_buf_rings(struct bxe_softc *sc)
15896 {
15897 #if __FreeBSD_version >= 800000
15898
15899     int i;
15900     struct bxe_fastpath *fp;
15901
15902     for (i = 0; i < sc->num_queues; i++) {
15903
15904         fp = &sc->fp[i];
15905
15906         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15907                                    M_NOWAIT, &fp->tx_mtx);
15908         if (fp->tx_br == NULL)
15909             return (-1);
15910     }
15911 #endif
15912     return (0);
15913 }
15914
15915 static void
15916 bxe_free_buf_rings(struct bxe_softc *sc)
15917 {
15918 #if __FreeBSD_version >= 800000
15919
15920     int i;
15921     struct bxe_fastpath *fp;
15922
15923     for (i = 0; i < sc->num_queues; i++) {
15924
15925         fp = &sc->fp[i];
15926
15927         if (fp->tx_br) {
15928             buf_ring_free(fp->tx_br, M_DEVBUF);
15929             fp->tx_br = NULL;
15930         }
15931     }
15932
15933 #endif
15934 }
15935
15936 static void
15937 bxe_init_fp_mutexs(struct bxe_softc *sc)
15938 {
15939     int i;
15940     struct bxe_fastpath *fp;
15941
15942     for (i = 0; i < sc->num_queues; i++) {
15943
15944         fp = &sc->fp[i];
15945
15946         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15947             "bxe%d_fp%d_tx_lock", sc->unit, i);
15948         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15949
15950         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15951             "bxe%d_fp%d_rx_lock", sc->unit, i);
15952         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15953     }
15954 }
15955
15956 static void
15957 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15958 {
15959     int i;
15960     struct bxe_fastpath *fp;
15961
15962     for (i = 0; i < sc->num_queues; i++) {
15963
15964         fp = &sc->fp[i];
15965
15966         if (mtx_initialized(&fp->tx_mtx)) {
15967             mtx_destroy(&fp->tx_mtx);
15968         }
15969
15970         if (mtx_initialized(&fp->rx_mtx)) {
15971             mtx_destroy(&fp->rx_mtx);
15972         }
15973     }
15974 }
15975
15976
15977 /*
15978  * Device attach function.
15979  *
15980  * Allocates device resources, performs secondary chip identification, and
15981  * initializes driver instance variables. This function is called from driver
15982  * load after a successful probe.
15983  *
15984  * Returns:
15985  *   0 = Success, >0 = Failure
15986  */
15987 static int
15988 bxe_attach(device_t dev)
15989 {
15990     struct bxe_softc *sc;
15991
15992     sc = device_get_softc(dev);
15993
15994     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15995
15996     sc->state = BXE_STATE_CLOSED;
15997
15998     sc->dev  = dev;
15999     sc->unit = device_get_unit(dev);
16000
16001     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
16002
16003     sc->pcie_bus    = pci_get_bus(dev);
16004     sc->pcie_device = pci_get_slot(dev);
16005     sc->pcie_func   = pci_get_function(dev);
16006
16007     /* enable bus master capability */
16008     pci_enable_busmaster(dev);
16009
16010     /* get the BARs */
16011     if (bxe_allocate_bars(sc) != 0) {
16012         return (ENXIO);
16013     }
16014
16015     /* initialize the mutexes */
16016     bxe_init_mutexes(sc);
16017
16018     /* prepare the periodic callout */
16019     callout_init(&sc->periodic_callout, 0);
16020
16021     /* prepare the chip taskqueue */
16022     sc->chip_tq_flags = CHIP_TQ_NONE;
16023     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
16024              "bxe%d_chip_tq", sc->unit);
16025     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
16026     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
16027                                    taskqueue_thread_enqueue,
16028                                    &sc->chip_tq);
16029     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
16030                             "%s", sc->chip_tq_name);
16031
16032     /* get device info and set params */
16033     if (bxe_get_device_info(sc) != 0) {
16034         BLOGE(sc, "getting device info\n");
16035         bxe_deallocate_bars(sc);
16036         pci_disable_busmaster(dev);
16037         return (ENXIO);
16038     }
16039
16040     /* get final misc params */
16041     bxe_get_params(sc);
16042
16043     /* set the default MTU (changed via ifconfig) */
16044     sc->mtu = ETHERMTU;
16045
16046     bxe_set_modes_bitmap(sc);
16047
16048     /* XXX
16049      * If in AFEX mode and the function is configured for FCoE
16050      * then bail... no L2 allowed.
16051      */
16052
16053     /* get phy settings from shmem and 'and' against admin settings */
16054     bxe_get_phy_info(sc);
16055
16056     /* initialize the FreeBSD ifnet interface */
16057     if (bxe_init_ifnet(sc) != 0) {
16058         bxe_release_mutexes(sc);
16059         bxe_deallocate_bars(sc);
16060         pci_disable_busmaster(dev);
16061         return (ENXIO);
16062     }
16063
16064     if (bxe_add_cdev(sc) != 0) {
16065         if (sc->ifnet != NULL) {
16066             ether_ifdetach(sc->ifnet);
16067         }
16068         ifmedia_removeall(&sc->ifmedia);
16069         bxe_release_mutexes(sc);
16070         bxe_deallocate_bars(sc);
16071         pci_disable_busmaster(dev);
16072         return (ENXIO);
16073     }
16074
16075     /* allocate device interrupts */
16076     if (bxe_interrupt_alloc(sc) != 0) {
16077         bxe_del_cdev(sc);
16078         if (sc->ifnet != NULL) {
16079             ether_ifdetach(sc->ifnet);
16080         }
16081         ifmedia_removeall(&sc->ifmedia);
16082         bxe_release_mutexes(sc);
16083         bxe_deallocate_bars(sc);
16084         pci_disable_busmaster(dev);
16085         return (ENXIO);
16086     }
16087
16088     bxe_init_fp_mutexs(sc);
16089
16090     if (bxe_alloc_buf_rings(sc) != 0) {
16091         bxe_free_buf_rings(sc);
16092         bxe_interrupt_free(sc);
16093         bxe_del_cdev(sc);
16094         if (sc->ifnet != NULL) {
16095             ether_ifdetach(sc->ifnet);
16096         }
16097         ifmedia_removeall(&sc->ifmedia);
16098         bxe_release_mutexes(sc);
16099         bxe_deallocate_bars(sc);
16100         pci_disable_busmaster(dev);
16101         return (ENXIO);
16102     }
16103
16104     /* allocate ilt */
16105     if (bxe_alloc_ilt_mem(sc) != 0) {
16106         bxe_free_buf_rings(sc);
16107         bxe_interrupt_free(sc);
16108         bxe_del_cdev(sc);
16109         if (sc->ifnet != NULL) {
16110             ether_ifdetach(sc->ifnet);
16111         }
16112         ifmedia_removeall(&sc->ifmedia);
16113         bxe_release_mutexes(sc);
16114         bxe_deallocate_bars(sc);
16115         pci_disable_busmaster(dev);
16116         return (ENXIO);
16117     }
16118
16119     /* allocate the host hardware/software hsi structures */
16120     if (bxe_alloc_hsi_mem(sc) != 0) {
16121         bxe_free_ilt_mem(sc);
16122         bxe_free_buf_rings(sc);
16123         bxe_interrupt_free(sc);
16124         bxe_del_cdev(sc);
16125         if (sc->ifnet != NULL) {
16126             ether_ifdetach(sc->ifnet);
16127         }
16128         ifmedia_removeall(&sc->ifmedia);
16129         bxe_release_mutexes(sc);
16130         bxe_deallocate_bars(sc);
16131         pci_disable_busmaster(dev);
16132         return (ENXIO);
16133     }
16134
16135     /* need to reset chip if UNDI was active */
16136     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16137         /* init fw_seq */
16138         sc->fw_seq =
16139             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16140              DRV_MSG_SEQ_NUMBER_MASK);
16141         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16142         bxe_prev_unload(sc);
16143     }
16144
16145 #if 1
16146     /* XXX */
16147     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16148 #else
16149     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16150         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16151         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16152         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16153         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16154         bxe_dcbx_init_params(sc);
16155     } else {
16156         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16157     }
16158 #endif
16159
16160     /* calculate qm_cid_count */
16161     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16162     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16163
16164     sc->max_cos = 1;
16165     bxe_init_multi_cos(sc);
16166
16167     bxe_add_sysctls(sc);
16168
16169     return (0);
16170 }
16171
16172 /*
16173  * Device detach function.
16174  *
16175  * Stops the controller, resets the controller, and releases resources.
16176  *
16177  * Returns:
16178  *   0 = Success, >0 = Failure
16179  */
16180 static int
16181 bxe_detach(device_t dev)
16182 {
16183     struct bxe_softc *sc;
16184     struct ifnet *ifp;
16185
16186     sc = device_get_softc(dev);
16187
16188     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16189
16190     ifp = sc->ifnet;
16191     if (ifp != NULL && ifp->if_vlantrunk != NULL) {
16192         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16193         return(EBUSY);
16194     }
16195
16196     bxe_del_cdev(sc);
16197
16198     /* stop the periodic callout */
16199     bxe_periodic_stop(sc);
16200
16201     /* stop the chip taskqueue */
16202     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16203     if (sc->chip_tq) {
16204         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16205         taskqueue_free(sc->chip_tq);
16206         sc->chip_tq = NULL;
16207     }
16208
16209     /* stop and reset the controller if it was open */
16210     if (sc->state != BXE_STATE_CLOSED) {
16211         BXE_CORE_LOCK(sc);
16212         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16213         sc->state = BXE_STATE_DISABLED;
16214         BXE_CORE_UNLOCK(sc);
16215     }
16216
16217     /* release the network interface */
16218     if (ifp != NULL) {
16219         ether_ifdetach(ifp);
16220     }
16221     ifmedia_removeall(&sc->ifmedia);
16222
16223     /* XXX do the following based on driver state... */
16224
16225     /* free the host hardware/software hsi structures */
16226     bxe_free_hsi_mem(sc);
16227
16228     /* free ilt */
16229     bxe_free_ilt_mem(sc);
16230
16231     bxe_free_buf_rings(sc);
16232
16233     /* release the interrupts */
16234     bxe_interrupt_free(sc);
16235
16236     /* Release the mutexes*/
16237     bxe_destroy_fp_mutexs(sc);
16238     bxe_release_mutexes(sc);
16239
16240
16241     /* Release the PCIe BAR mapped memory */
16242     bxe_deallocate_bars(sc);
16243
16244     /* Release the FreeBSD interface. */
16245     if (sc->ifnet != NULL) {
16246         if_free(sc->ifnet);
16247     }
16248
16249     pci_disable_busmaster(dev);
16250
16251     return (0);
16252 }
16253
16254 /*
16255  * Device shutdown function.
16256  *
16257  * Stops and resets the controller.
16258  *
16259  * Returns:
16260  *   Nothing
16261  */
16262 static int
16263 bxe_shutdown(device_t dev)
16264 {
16265     struct bxe_softc *sc;
16266
16267     sc = device_get_softc(dev);
16268
16269     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16270
16271     /* stop the periodic callout */
16272     bxe_periodic_stop(sc);
16273
16274     BXE_CORE_LOCK(sc);
16275     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16276     BXE_CORE_UNLOCK(sc);
16277
16278     return (0);
16279 }
16280
16281 void
16282 bxe_igu_ack_sb(struct bxe_softc *sc,
16283                uint8_t          igu_sb_id,
16284                uint8_t          segment,
16285                uint16_t         index,
16286                uint8_t          op,
16287                uint8_t          update)
16288 {
16289     uint32_t igu_addr = sc->igu_base_addr;
16290     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16291     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16292 }
16293
16294 static void
16295 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16296                      uint8_t          func,
16297                      uint8_t          idu_sb_id,
16298                      uint8_t          is_pf)
16299 {
16300     uint32_t data, ctl, cnt = 100;
16301     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16302     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16303     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16304     uint32_t sb_bit =  1 << (idu_sb_id%32);
16305     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16306     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16307
16308     /* Not supported in BC mode */
16309     if (CHIP_INT_MODE_IS_BC(sc)) {
16310         return;
16311     }
16312
16313     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16314              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16315             IGU_REGULAR_CLEANUP_SET |
16316             IGU_REGULAR_BCLEANUP);
16317
16318     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16319            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16320            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16321
16322     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16323             data, igu_addr_data);
16324     REG_WR(sc, igu_addr_data, data);
16325
16326     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16327                       BUS_SPACE_BARRIER_WRITE);
16328     mb();
16329
16330     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16331             ctl, igu_addr_ctl);
16332     REG_WR(sc, igu_addr_ctl, ctl);
16333
16334     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16335                       BUS_SPACE_BARRIER_WRITE);
16336     mb();
16337
16338     /* wait for clean up to finish */
16339     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16340         DELAY(20000);
16341     }
16342
16343     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16344         BLOGD(sc, DBG_LOAD,
16345               "Unable to finish IGU cleanup: "
16346               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16347               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16348     }
16349 }
16350
16351 static void
16352 bxe_igu_clear_sb(struct bxe_softc *sc,
16353                  uint8_t          idu_sb_id)
16354 {
16355     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16356 }
16357
16358
16359
16360
16361
16362
16363
16364 /*******************/
16365 /* ECORE CALLBACKS */
16366 /*******************/
16367
16368 static void
16369 bxe_reset_common(struct bxe_softc *sc)
16370 {
16371     uint32_t val = 0x1400;
16372
16373     /* reset_common */
16374     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16375
16376     if (CHIP_IS_E3(sc)) {
16377         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16378         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16379     }
16380
16381     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16382 }
16383
16384 static void
16385 bxe_common_init_phy(struct bxe_softc *sc)
16386 {
16387     uint32_t shmem_base[2];
16388     uint32_t shmem2_base[2];
16389
16390     /* Avoid common init in case MFW supports LFA */
16391     if (SHMEM2_RD(sc, size) >
16392         (uint32_t)offsetof(struct shmem2_region,
16393                            lfa_host_addr[SC_PORT(sc)])) {
16394         return;
16395     }
16396
16397     shmem_base[0]  = sc->devinfo.shmem_base;
16398     shmem2_base[0] = sc->devinfo.shmem2_base;
16399
16400     if (!CHIP_IS_E1x(sc)) {
16401         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16402         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16403     }
16404
16405     bxe_acquire_phy_lock(sc);
16406     elink_common_init_phy(sc, shmem_base, shmem2_base,
16407                           sc->devinfo.chip_id, 0);
16408     bxe_release_phy_lock(sc);
16409 }
16410
16411 static void
16412 bxe_pf_disable(struct bxe_softc *sc)
16413 {
16414     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16415
16416     val &= ~IGU_PF_CONF_FUNC_EN;
16417
16418     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16419     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16420     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16421 }
16422
16423 static void
16424 bxe_init_pxp(struct bxe_softc *sc)
16425 {
16426     uint16_t devctl;
16427     int r_order, w_order;
16428
16429     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16430
16431     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16432
16433     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16434
16435     if (sc->mrrs == -1) {
16436         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16437     } else {
16438         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16439         r_order = sc->mrrs;
16440     }
16441
16442     ecore_init_pxp_arb(sc, r_order, w_order);
16443 }
16444
16445 static uint32_t
16446 bxe_get_pretend_reg(struct bxe_softc *sc)
16447 {
16448     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16449     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16450     return (base + (SC_ABS_FUNC(sc)) * stride);
16451 }
16452
16453 /*
16454  * Called only on E1H or E2.
16455  * When pretending to be PF, the pretend value is the function number 0..7.
16456  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16457  * combination.
16458  */
16459 static int
16460 bxe_pretend_func(struct bxe_softc *sc,
16461                  uint16_t         pretend_func_val)
16462 {
16463     uint32_t pretend_reg;
16464
16465     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16466         return (-1);
16467     }
16468
16469     /* get my own pretend register */
16470     pretend_reg = bxe_get_pretend_reg(sc);
16471     REG_WR(sc, pretend_reg, pretend_func_val);
16472     REG_RD(sc, pretend_reg);
16473     return (0);
16474 }
16475
16476 static void
16477 bxe_iov_init_dmae(struct bxe_softc *sc)
16478 {
16479     return;
16480 }
16481
16482 static void
16483 bxe_iov_init_dq(struct bxe_softc *sc)
16484 {
16485     return;
16486 }
16487
16488 /* send a NIG loopback debug packet */
16489 static void
16490 bxe_lb_pckt(struct bxe_softc *sc)
16491 {
16492     uint32_t wb_write[3];
16493
16494     /* Ethernet source and destination addresses */
16495     wb_write[0] = 0x55555555;
16496     wb_write[1] = 0x55555555;
16497     wb_write[2] = 0x20;     /* SOP */
16498     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16499
16500     /* NON-IP protocol */
16501     wb_write[0] = 0x09000000;
16502     wb_write[1] = 0x55555555;
16503     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16504     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16505 }
16506
16507 /*
16508  * Some of the internal memories are not directly readable from the driver.
16509  * To test them we send debug packets.
16510  */
16511 static int
16512 bxe_int_mem_test(struct bxe_softc *sc)
16513 {
16514     int factor;
16515     int count, i;
16516     uint32_t val = 0;
16517
16518     if (CHIP_REV_IS_FPGA(sc)) {
16519         factor = 120;
16520     } else if (CHIP_REV_IS_EMUL(sc)) {
16521         factor = 200;
16522     } else {
16523         factor = 1;
16524     }
16525
16526     /* disable inputs of parser neighbor blocks */
16527     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16528     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16529     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16530     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16531
16532     /*  write 0 to parser credits for CFC search request */
16533     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16534
16535     /* send Ethernet packet */
16536     bxe_lb_pckt(sc);
16537
16538     /* TODO do i reset NIG statistic? */
16539     /* Wait until NIG register shows 1 packet of size 0x10 */
16540     count = 1000 * factor;
16541     while (count) {
16542         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16543         val = *BXE_SP(sc, wb_data[0]);
16544         if (val == 0x10) {
16545             break;
16546         }
16547
16548         DELAY(10000);
16549         count--;
16550     }
16551
16552     if (val != 0x10) {
16553         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16554         return (-1);
16555     }
16556
16557     /* wait until PRS register shows 1 packet */
16558     count = (1000 * factor);
16559     while (count) {
16560         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16561         if (val == 1) {
16562             break;
16563         }
16564
16565         DELAY(10000);
16566         count--;
16567     }
16568
16569     if (val != 0x1) {
16570         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16571         return (-2);
16572     }
16573
16574     /* Reset and init BRB, PRS */
16575     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16576     DELAY(50000);
16577     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16578     DELAY(50000);
16579     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16580     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16581
16582     /* Disable inputs of parser neighbor blocks */
16583     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16584     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16585     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16586     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16587
16588     /* Write 0 to parser credits for CFC search request */
16589     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16590
16591     /* send 10 Ethernet packets */
16592     for (i = 0; i < 10; i++) {
16593         bxe_lb_pckt(sc);
16594     }
16595
16596     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16597     count = (1000 * factor);
16598     while (count) {
16599         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16600         val = *BXE_SP(sc, wb_data[0]);
16601         if (val == 0xb0) {
16602             break;
16603         }
16604
16605         DELAY(10000);
16606         count--;
16607     }
16608
16609     if (val != 0xb0) {
16610         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16611         return (-3);
16612     }
16613
16614     /* Wait until PRS register shows 2 packets */
16615     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16616     if (val != 2) {
16617         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16618     }
16619
16620     /* Write 1 to parser credits for CFC search request */
16621     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16622
16623     /* Wait until PRS register shows 3 packets */
16624     DELAY(10000 * factor);
16625
16626     /* Wait until NIG register shows 1 packet of size 0x10 */
16627     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16628     if (val != 3) {
16629         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16630     }
16631
16632     /* clear NIG EOP FIFO */
16633     for (i = 0; i < 11; i++) {
16634         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16635     }
16636
16637     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16638     if (val != 1) {
16639         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16640         return (-4);
16641     }
16642
16643     /* Reset and init BRB, PRS, NIG */
16644     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16645     DELAY(50000);
16646     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16647     DELAY(50000);
16648     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16649     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16650     if (!CNIC_SUPPORT(sc)) {
16651         /* set NIC mode */
16652         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16653     }
16654
16655     /* Enable inputs of parser neighbor blocks */
16656     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16657     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16658     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16659     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16660
16661     return (0);
16662 }
16663
16664 static void
16665 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16666 {
16667     int is_required;
16668     uint32_t val;
16669     int port;
16670
16671     is_required = 0;
16672     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16673            SHARED_HW_CFG_FAN_FAILURE_MASK);
16674
16675     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16676         is_required = 1;
16677     }
16678     /*
16679      * The fan failure mechanism is usually related to the PHY type since
16680      * the power consumption of the board is affected by the PHY. Currently,
16681      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16682      */
16683     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16684         for (port = PORT_0; port < PORT_MAX; port++) {
16685             is_required |= elink_fan_failure_det_req(sc,
16686                                                      sc->devinfo.shmem_base,
16687                                                      sc->devinfo.shmem2_base,
16688                                                      port);
16689         }
16690     }
16691
16692     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16693
16694     if (is_required == 0) {
16695         return;
16696     }
16697
16698     /* Fan failure is indicated by SPIO 5 */
16699     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16700
16701     /* set to active low mode */
16702     val = REG_RD(sc, MISC_REG_SPIO_INT);
16703     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16704     REG_WR(sc, MISC_REG_SPIO_INT, val);
16705
16706     /* enable interrupt to signal the IGU */
16707     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16708     val |= MISC_SPIO_SPIO5;
16709     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16710 }
16711
16712 static void
16713 bxe_enable_blocks_attention(struct bxe_softc *sc)
16714 {
16715     uint32_t val;
16716
16717     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16718     if (!CHIP_IS_E1x(sc)) {
16719         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16720     } else {
16721         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16722     }
16723     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16724     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16725     /*
16726      * mask read length error interrupts in brb for parser
16727      * (parsing unit and 'checksum and crc' unit)
16728      * these errors are legal (PU reads fixed length and CAC can cause
16729      * read length error on truncated packets)
16730      */
16731     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16732     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16733     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16734     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16735     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16736     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16737 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16738 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16739     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16740     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16741     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16742 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16743 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16744     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16745     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16746     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16747     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16748 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16749 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16750
16751     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16752            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16753            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16754     if (!CHIP_IS_E1x(sc)) {
16755         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16756                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16757     }
16758     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16759
16760     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16761     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16762     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16763 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16764
16765     if (!CHIP_IS_E1x(sc)) {
16766         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16767         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16768     }
16769
16770     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16771     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16772 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16773     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16774 }
16775
16776 /**
16777  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16778  *
16779  * @sc:     driver handle
16780  */
16781 static int
16782 bxe_init_hw_common(struct bxe_softc *sc)
16783 {
16784     uint8_t abs_func_id;
16785     uint32_t val;
16786
16787     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16788           SC_ABS_FUNC(sc));
16789
16790     /*
16791      * take the RESET lock to protect undi_unload flow from accessing
16792      * registers while we are resetting the chip
16793      */
16794     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16795
16796     bxe_reset_common(sc);
16797
16798     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16799
16800     val = 0xfffc;
16801     if (CHIP_IS_E3(sc)) {
16802         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16803         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16804     }
16805
16806     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16807
16808     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16809
16810     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16811     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16812
16813     if (!CHIP_IS_E1x(sc)) {
16814         /*
16815          * 4-port mode or 2-port mode we need to turn off master-enable for
16816          * everyone. After that we turn it back on for self. So, we disregard
16817          * multi-function, and always disable all functions on the given path,
16818          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16819          */
16820         for (abs_func_id = SC_PATH(sc);
16821              abs_func_id < (E2_FUNC_MAX * 2);
16822              abs_func_id += 2) {
16823             if (abs_func_id == SC_ABS_FUNC(sc)) {
16824                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16825                 continue;
16826             }
16827
16828             bxe_pretend_func(sc, abs_func_id);
16829
16830             /* clear pf enable */
16831             bxe_pf_disable(sc);
16832
16833             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16834         }
16835     }
16836
16837     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16838
16839     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16840
16841     if (CHIP_IS_E1(sc)) {
16842         /*
16843          * enable HW interrupt from PXP on USDM overflow
16844          * bit 16 on INT_MASK_0
16845          */
16846         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16847     }
16848
16849     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16850     bxe_init_pxp(sc);
16851
16852 #ifdef __BIG_ENDIAN
16853     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16854     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16855     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16856     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16857     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16858     /* make sure this value is 0 */
16859     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16860
16861     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16862     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16863     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16864     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16865     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16866 #endif
16867
16868     ecore_ilt_init_page_size(sc, INITOP_SET);
16869
16870     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16871         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16872     }
16873
16874     /* let the HW do it's magic... */
16875     DELAY(100000);
16876
16877     /* finish PXP init */
16878     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16879     if (val != 1) {
16880         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16881             val);
16882         return (-1);
16883     }
16884     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16885     if (val != 1) {
16886         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16887         return (-1);
16888     }
16889
16890     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16891
16892     /*
16893      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16894      * entries with value "0" and valid bit on. This needs to be done by the
16895      * first PF that is loaded in a path (i.e. common phase)
16896      */
16897     if (!CHIP_IS_E1x(sc)) {
16898 /*
16899  * In E2 there is a bug in the timers block that can cause function 6 / 7
16900  * (i.e. vnic3) to start even if it is marked as "scan-off".
16901  * This occurs when a different function (func2,3) is being marked
16902  * as "scan-off". Real-life scenario for example: if a driver is being
16903  * load-unloaded while func6,7 are down. This will cause the timer to access
16904  * the ilt, translate to a logical address and send a request to read/write.
16905  * Since the ilt for the function that is down is not valid, this will cause
16906  * a translation error which is unrecoverable.
16907  * The Workaround is intended to make sure that when this happens nothing
16908  * fatal will occur. The workaround:
16909  *  1.  First PF driver which loads on a path will:
16910  *      a.  After taking the chip out of reset, by using pretend,
16911  *          it will write "0" to the following registers of
16912  *          the other vnics.
16913  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16914  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16915  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16916  *          And for itself it will write '1' to
16917  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16918  *          dmae-operations (writing to pram for example.)
16919  *          note: can be done for only function 6,7 but cleaner this
16920  *            way.
16921  *      b.  Write zero+valid to the entire ILT.
16922  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16923  *          VNIC3 (of that port). The range allocated will be the
16924  *          entire ILT. This is needed to prevent  ILT range error.
16925  *  2.  Any PF driver load flow:
16926  *      a.  ILT update with the physical addresses of the allocated
16927  *          logical pages.
16928  *      b.  Wait 20msec. - note that this timeout is needed to make
16929  *          sure there are no requests in one of the PXP internal
16930  *          queues with "old" ILT addresses.
16931  *      c.  PF enable in the PGLC.
16932  *      d.  Clear the was_error of the PF in the PGLC. (could have
16933  *          occurred while driver was down)
16934  *      e.  PF enable in the CFC (WEAK + STRONG)
16935  *      f.  Timers scan enable
16936  *  3.  PF driver unload flow:
16937  *      a.  Clear the Timers scan_en.
16938  *      b.  Polling for scan_on=0 for that PF.
16939  *      c.  Clear the PF enable bit in the PXP.
16940  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16941  *      e.  Write zero+valid to all ILT entries (The valid bit must
16942  *          stay set)
16943  *      f.  If this is VNIC 3 of a port then also init
16944  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16945  *          to the last enrty in the ILT.
16946  *
16947  *      Notes:
16948  *      Currently the PF error in the PGLC is non recoverable.
16949  *      In the future the there will be a recovery routine for this error.
16950  *      Currently attention is masked.
16951  *      Having an MCP lock on the load/unload process does not guarantee that
16952  *      there is no Timer disable during Func6/7 enable. This is because the
16953  *      Timers scan is currently being cleared by the MCP on FLR.
16954  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16955  *      there is error before clearing it. But the flow above is simpler and
16956  *      more general.
16957  *      All ILT entries are written by zero+valid and not just PF6/7
16958  *      ILT entries since in the future the ILT entries allocation for
16959  *      PF-s might be dynamic.
16960  */
16961         struct ilt_client_info ilt_cli;
16962         struct ecore_ilt ilt;
16963
16964         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16965         memset(&ilt, 0, sizeof(struct ecore_ilt));
16966
16967         /* initialize dummy TM client */
16968         ilt_cli.start      = 0;
16969         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16970         ilt_cli.client_num = ILT_CLIENT_TM;
16971
16972         /*
16973          * Step 1: set zeroes to all ilt page entries with valid bit on
16974          * Step 2: set the timers first/last ilt entry to point
16975          * to the entire range to prevent ILT range error for 3rd/4th
16976          * vnic (this code assumes existence of the vnic)
16977          *
16978          * both steps performed by call to ecore_ilt_client_init_op()
16979          * with dummy TM client
16980          *
16981          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16982          * and his brother are split registers
16983          */
16984
16985         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16986         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16987         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16988
16989         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16990         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16991         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16992     }
16993
16994     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16995     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16996
16997     if (!CHIP_IS_E1x(sc)) {
16998         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16999                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
17000
17001         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
17002         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
17003
17004         /* let the HW do it's magic... */
17005         do {
17006             DELAY(200000);
17007             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
17008         } while (factor-- && (val != 1));
17009
17010         if (val != 1) {
17011             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
17012             return (-1);
17013         }
17014     }
17015
17016     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
17017
17018     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
17019
17020     bxe_iov_init_dmae(sc);
17021
17022     /* clean the DMAE memory */
17023     sc->dmae_ready = 1;
17024     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
17025
17026     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
17027
17028     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
17029
17030     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
17031
17032     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
17033
17034     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
17035     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17036     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17037     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17038
17039     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17040
17041     /* QM queues pointers table */
17042     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17043
17044     /* soft reset pulse */
17045     REG_WR(sc, QM_REG_SOFT_RESET, 1);
17046     REG_WR(sc, QM_REG_SOFT_RESET, 0);
17047
17048     if (CNIC_SUPPORT(sc))
17049         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17050
17051     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17052     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17053     if (!CHIP_REV_IS_SLOW(sc)) {
17054         /* enable hw interrupt from doorbell Q */
17055         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17056     }
17057
17058     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17059
17060     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17061     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17062
17063     if (!CHIP_IS_E1(sc)) {
17064         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17065     }
17066
17067     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17068         if (IS_MF_AFEX(sc)) {
17069             /*
17070              * configure that AFEX and VLAN headers must be
17071              * received in AFEX mode
17072              */
17073             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17074             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17075             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17076             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17077             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17078         } else {
17079             /*
17080              * Bit-map indicating which L2 hdrs may appear
17081              * after the basic Ethernet header
17082              */
17083             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17084                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17085         }
17086     }
17087
17088     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17089     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17090     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17091     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17092
17093     if (!CHIP_IS_E1x(sc)) {
17094         /* reset VFC memories */
17095         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17096                VFC_MEMORIES_RST_REG_CAM_RST |
17097                VFC_MEMORIES_RST_REG_RAM_RST);
17098         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17099                VFC_MEMORIES_RST_REG_CAM_RST |
17100                VFC_MEMORIES_RST_REG_RAM_RST);
17101
17102         DELAY(20000);
17103     }
17104
17105     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17106     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17107     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17108     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17109
17110     /* sync semi rtc */
17111     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17112            0x80000000);
17113     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17114            0x80000000);
17115
17116     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17117     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17118     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17119
17120     if (!CHIP_IS_E1x(sc)) {
17121         if (IS_MF_AFEX(sc)) {
17122             /*
17123              * configure that AFEX and VLAN headers must be
17124              * sent in AFEX mode
17125              */
17126             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17127             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17128             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17129             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17130             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17131         } else {
17132             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17133                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17134         }
17135     }
17136
17137     REG_WR(sc, SRC_REG_SOFT_RST, 1);
17138
17139     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17140
17141     if (CNIC_SUPPORT(sc)) {
17142         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17143         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17144         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17145         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17146         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17147         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17148         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17149         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17150         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17151         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17152     }
17153     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17154
17155     if (sizeof(union cdu_context) != 1024) {
17156         /* we currently assume that a context is 1024 bytes */
17157         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17158               (long)sizeof(union cdu_context));
17159     }
17160
17161     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17162     val = (4 << 24) + (0 << 12) + 1024;
17163     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17164
17165     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17166
17167     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17168     /* enable context validation interrupt from CFC */
17169     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17170
17171     /* set the thresholds to prevent CFC/CDU race */
17172     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17173     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17174
17175     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17176         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17177     }
17178
17179     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17180     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17181
17182     /* Reset PCIE errors for debug */
17183     REG_WR(sc, 0x2814, 0xffffffff);
17184     REG_WR(sc, 0x3820, 0xffffffff);
17185
17186     if (!CHIP_IS_E1x(sc)) {
17187         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17188                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17189                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17190         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17191                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17192                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17193                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17194         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17195                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17196                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17197                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17198     }
17199
17200     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17201
17202     if (!CHIP_IS_E1(sc)) {
17203         /* in E3 this done in per-port section */
17204         if (!CHIP_IS_E3(sc))
17205             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17206     }
17207
17208     if (CHIP_IS_E1H(sc)) {
17209         /* not applicable for E2 (and above ...) */
17210         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17211     }
17212
17213     if (CHIP_REV_IS_SLOW(sc)) {
17214         DELAY(200000);
17215     }
17216
17217     /* finish CFC init */
17218     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17219     if (val != 1) {
17220         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17221         return (-1);
17222     }
17223     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17224     if (val != 1) {
17225         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17226         return (-1);
17227     }
17228     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17229     if (val != 1) {
17230         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17231         return (-1);
17232     }
17233     REG_WR(sc, CFC_REG_DEBUG0, 0);
17234
17235     if (CHIP_IS_E1(sc)) {
17236         /* read NIG statistic to see if this is our first up since powerup */
17237         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17238         val = *BXE_SP(sc, wb_data[0]);
17239
17240         /* do internal memory self test */
17241         if ((val == 0) && bxe_int_mem_test(sc)) {
17242             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17243             return (-1);
17244         }
17245     }
17246
17247     bxe_setup_fan_failure_detection(sc);
17248
17249     /* clear PXP2 attentions */
17250     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17251
17252     bxe_enable_blocks_attention(sc);
17253
17254     if (!CHIP_REV_IS_SLOW(sc)) {
17255         ecore_enable_blocks_parity(sc);
17256     }
17257
17258     if (!BXE_NOMCP(sc)) {
17259         if (CHIP_IS_E1x(sc)) {
17260             bxe_common_init_phy(sc);
17261         }
17262     }
17263
17264     return (0);
17265 }
17266
17267 /**
17268  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17269  *
17270  * @sc:     driver handle
17271  */
17272 static int
17273 bxe_init_hw_common_chip(struct bxe_softc *sc)
17274 {
17275     int rc = bxe_init_hw_common(sc);
17276
17277     if (rc) {
17278         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17279         return (rc);
17280     }
17281
17282     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17283     if (!BXE_NOMCP(sc)) {
17284         bxe_common_init_phy(sc);
17285     }
17286
17287     return (0);
17288 }
17289
17290 static int
17291 bxe_init_hw_port(struct bxe_softc *sc)
17292 {
17293     int port = SC_PORT(sc);
17294     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17295     uint32_t low, high;
17296     uint32_t val;
17297
17298     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17299
17300     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17301
17302     ecore_init_block(sc, BLOCK_MISC, init_phase);
17303     ecore_init_block(sc, BLOCK_PXP, init_phase);
17304     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17305
17306     /*
17307      * Timers bug workaround: disables the pf_master bit in pglue at
17308      * common phase, we need to enable it here before any dmae access are
17309      * attempted. Therefore we manually added the enable-master to the
17310      * port phase (it also happens in the function phase)
17311      */
17312     if (!CHIP_IS_E1x(sc)) {
17313         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17314     }
17315
17316     ecore_init_block(sc, BLOCK_ATC, init_phase);
17317     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17318     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17319     ecore_init_block(sc, BLOCK_QM, init_phase);
17320
17321     ecore_init_block(sc, BLOCK_TCM, init_phase);
17322     ecore_init_block(sc, BLOCK_UCM, init_phase);
17323     ecore_init_block(sc, BLOCK_CCM, init_phase);
17324     ecore_init_block(sc, BLOCK_XCM, init_phase);
17325
17326     /* QM cid (connection) count */
17327     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17328
17329     if (CNIC_SUPPORT(sc)) {
17330         ecore_init_block(sc, BLOCK_TM, init_phase);
17331         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17332         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17333     }
17334
17335     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17336
17337     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17338
17339     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17340         if (IS_MF(sc)) {
17341             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17342         } else if (sc->mtu > 4096) {
17343             if (BXE_ONE_PORT(sc)) {
17344                 low = 160;
17345             } else {
17346                 val = sc->mtu;
17347                 /* (24*1024 + val*4)/256 */
17348                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17349             }
17350         } else {
17351             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17352         }
17353         high = (low + 56); /* 14*1024/256 */
17354         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17355         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17356     }
17357
17358     if (CHIP_IS_MODE_4_PORT(sc)) {
17359         REG_WR(sc, SC_PORT(sc) ?
17360                BRB1_REG_MAC_GUARANTIED_1 :
17361                BRB1_REG_MAC_GUARANTIED_0, 40);
17362     }
17363
17364     ecore_init_block(sc, BLOCK_PRS, init_phase);
17365     if (CHIP_IS_E3B0(sc)) {
17366         if (IS_MF_AFEX(sc)) {
17367             /* configure headers for AFEX mode */
17368             REG_WR(sc, SC_PORT(sc) ?
17369                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17370                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17371             REG_WR(sc, SC_PORT(sc) ?
17372                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17373                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17374             REG_WR(sc, SC_PORT(sc) ?
17375                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17376                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17377         } else {
17378             /* Ovlan exists only if we are in multi-function +
17379              * switch-dependent mode, in switch-independent there
17380              * is no ovlan headers
17381              */
17382             REG_WR(sc, SC_PORT(sc) ?
17383                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17384                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17385                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17386         }
17387     }
17388
17389     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17390     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17391     ecore_init_block(sc, BLOCK_USDM, init_phase);
17392     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17393
17394     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17395     ecore_init_block(sc, BLOCK_USEM, init_phase);
17396     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17397     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17398
17399     ecore_init_block(sc, BLOCK_UPB, init_phase);
17400     ecore_init_block(sc, BLOCK_XPB, init_phase);
17401
17402     ecore_init_block(sc, BLOCK_PBF, init_phase);
17403
17404     if (CHIP_IS_E1x(sc)) {
17405         /* configure PBF to work without PAUSE mtu 9000 */
17406         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17407
17408         /* update threshold */
17409         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17410         /* update init credit */
17411         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17412
17413         /* probe changes */
17414         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17415         DELAY(50);
17416         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17417     }
17418
17419     if (CNIC_SUPPORT(sc)) {
17420         ecore_init_block(sc, BLOCK_SRC, init_phase);
17421     }
17422
17423     ecore_init_block(sc, BLOCK_CDU, init_phase);
17424     ecore_init_block(sc, BLOCK_CFC, init_phase);
17425
17426     if (CHIP_IS_E1(sc)) {
17427         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17428         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17429     }
17430     ecore_init_block(sc, BLOCK_HC, init_phase);
17431
17432     ecore_init_block(sc, BLOCK_IGU, init_phase);
17433
17434     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17435     /* init aeu_mask_attn_func_0/1:
17436      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17437      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17438      *             bits 4-7 are used for "per vn group attention" */
17439     val = IS_MF(sc) ? 0xF7 : 0x7;
17440     /* Enable DCBX attention for all but E1 */
17441     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17442     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17443
17444     ecore_init_block(sc, BLOCK_NIG, init_phase);
17445
17446     if (!CHIP_IS_E1x(sc)) {
17447         /* Bit-map indicating which L2 hdrs may appear after the
17448          * basic Ethernet header
17449          */
17450         if (IS_MF_AFEX(sc)) {
17451             REG_WR(sc, SC_PORT(sc) ?
17452                    NIG_REG_P1_HDRS_AFTER_BASIC :
17453                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17454         } else {
17455             REG_WR(sc, SC_PORT(sc) ?
17456                    NIG_REG_P1_HDRS_AFTER_BASIC :
17457                    NIG_REG_P0_HDRS_AFTER_BASIC,
17458                    IS_MF_SD(sc) ? 7 : 6);
17459         }
17460
17461         if (CHIP_IS_E3(sc)) {
17462             REG_WR(sc, SC_PORT(sc) ?
17463                    NIG_REG_LLH1_MF_MODE :
17464                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17465         }
17466     }
17467     if (!CHIP_IS_E3(sc)) {
17468         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17469     }
17470
17471     if (!CHIP_IS_E1(sc)) {
17472         /* 0x2 disable mf_ov, 0x1 enable */
17473         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17474                (IS_MF_SD(sc) ? 0x1 : 0x2));
17475
17476         if (!CHIP_IS_E1x(sc)) {
17477             val = 0;
17478             switch (sc->devinfo.mf_info.mf_mode) {
17479             case MULTI_FUNCTION_SD:
17480                 val = 1;
17481                 break;
17482             case MULTI_FUNCTION_SI:
17483             case MULTI_FUNCTION_AFEX:
17484                 val = 2;
17485                 break;
17486             }
17487
17488             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17489                         NIG_REG_LLH0_CLS_TYPE), val);
17490         }
17491         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17492         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17493         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17494     }
17495
17496     /* If SPIO5 is set to generate interrupts, enable it for this port */
17497     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17498     if (val & MISC_SPIO_SPIO5) {
17499         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17500                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17501         val = REG_RD(sc, reg_addr);
17502         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17503         REG_WR(sc, reg_addr, val);
17504     }
17505
17506     return (0);
17507 }
17508
17509 static uint32_t
17510 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17511                        uint32_t         reg,
17512                        uint32_t         expected,
17513                        uint32_t         poll_count)
17514 {
17515     uint32_t cur_cnt = poll_count;
17516     uint32_t val;
17517
17518     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17519         DELAY(FLR_WAIT_INTERVAL);
17520     }
17521
17522     return (val);
17523 }
17524
17525 static int
17526 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17527                               uint32_t         reg,
17528                               char             *msg,
17529                               uint32_t         poll_cnt)
17530 {
17531     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17532
17533     if (val != 0) {
17534         BLOGE(sc, "%s usage count=%d\n", msg, val);
17535         return (1);
17536     }
17537
17538     return (0);
17539 }
17540
17541 /* Common routines with VF FLR cleanup */
17542 static uint32_t
17543 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17544 {
17545     /* adjust polling timeout */
17546     if (CHIP_REV_IS_EMUL(sc)) {
17547         return (FLR_POLL_CNT * 2000);
17548     }
17549
17550     if (CHIP_REV_IS_FPGA(sc)) {
17551         return (FLR_POLL_CNT * 120);
17552     }
17553
17554     return (FLR_POLL_CNT);
17555 }
17556
17557 static int
17558 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17559                            uint32_t         poll_cnt)
17560 {
17561     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17562     if (bxe_flr_clnup_poll_hw_counter(sc,
17563                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17564                                       "CFC PF usage counter timed out",
17565                                       poll_cnt)) {
17566         return (1);
17567     }
17568
17569     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17570     if (bxe_flr_clnup_poll_hw_counter(sc,
17571                                       DORQ_REG_PF_USAGE_CNT,
17572                                       "DQ PF usage counter timed out",
17573                                       poll_cnt)) {
17574         return (1);
17575     }
17576
17577     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17578     if (bxe_flr_clnup_poll_hw_counter(sc,
17579                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17580                                       "QM PF usage counter timed out",
17581                                       poll_cnt)) {
17582         return (1);
17583     }
17584
17585     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17586     if (bxe_flr_clnup_poll_hw_counter(sc,
17587                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17588                                       "Timers VNIC usage counter timed out",
17589                                       poll_cnt)) {
17590         return (1);
17591     }
17592
17593     if (bxe_flr_clnup_poll_hw_counter(sc,
17594                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17595                                       "Timers NUM_SCANS usage counter timed out",
17596                                       poll_cnt)) {
17597         return (1);
17598     }
17599
17600     /* Wait DMAE PF usage counter to zero */
17601     if (bxe_flr_clnup_poll_hw_counter(sc,
17602                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17603                                       "DMAE dommand register timed out",
17604                                       poll_cnt)) {
17605         return (1);
17606     }
17607
17608     return (0);
17609 }
17610
17611 #define OP_GEN_PARAM(param)                                            \
17612     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17613 #define OP_GEN_TYPE(type)                                           \
17614     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17615 #define OP_GEN_AGG_VECT(index)                                             \
17616     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17617
17618 static int
17619 bxe_send_final_clnup(struct bxe_softc *sc,
17620                      uint8_t          clnup_func,
17621                      uint32_t         poll_cnt)
17622 {
17623     uint32_t op_gen_command = 0;
17624     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17625                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17626     int ret = 0;
17627
17628     if (REG_RD(sc, comp_addr)) {
17629         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17630         return (1);
17631     }
17632
17633     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17634     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17635     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17636     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17637
17638     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17639     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17640
17641     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17642         BLOGE(sc, "FW final cleanup did not succeed\n");
17643         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17644               (REG_RD(sc, comp_addr)));
17645         bxe_panic(sc, ("FLR cleanup failed\n"));
17646         return (1);
17647     }
17648
17649     /* Zero completion for nxt FLR */
17650     REG_WR(sc, comp_addr, 0);
17651
17652     return (ret);
17653 }
17654
17655 static void
17656 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17657                        struct pbf_pN_buf_regs *regs,
17658                        uint32_t               poll_count)
17659 {
17660     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17661     uint32_t cur_cnt = poll_count;
17662
17663     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17664     crd = crd_start = REG_RD(sc, regs->crd);
17665     init_crd = REG_RD(sc, regs->init_crd);
17666
17667     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17668     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17669     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17670
17671     while ((crd != init_crd) &&
17672            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17673             (init_crd - crd_start))) {
17674         if (cur_cnt--) {
17675             DELAY(FLR_WAIT_INTERVAL);
17676             crd = REG_RD(sc, regs->crd);
17677             crd_freed = REG_RD(sc, regs->crd_freed);
17678         } else {
17679             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17680             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17681             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17682             break;
17683         }
17684     }
17685
17686     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17687           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17688 }
17689
17690 static void
17691 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17692                        struct pbf_pN_cmd_regs *regs,
17693                        uint32_t               poll_count)
17694 {
17695     uint32_t occup, to_free, freed, freed_start;
17696     uint32_t cur_cnt = poll_count;
17697
17698     occup = to_free = REG_RD(sc, regs->lines_occup);
17699     freed = freed_start = REG_RD(sc, regs->lines_freed);
17700
17701     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17702     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17703
17704     while (occup &&
17705            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17706         if (cur_cnt--) {
17707             DELAY(FLR_WAIT_INTERVAL);
17708             occup = REG_RD(sc, regs->lines_occup);
17709             freed = REG_RD(sc, regs->lines_freed);
17710         } else {
17711             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17712             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17713             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17714             break;
17715         }
17716     }
17717
17718     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17719           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17720 }
17721
17722 static void
17723 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17724 {
17725     struct pbf_pN_cmd_regs cmd_regs[] = {
17726         {0, (CHIP_IS_E3B0(sc)) ?
17727             PBF_REG_TQ_OCCUPANCY_Q0 :
17728             PBF_REG_P0_TQ_OCCUPANCY,
17729             (CHIP_IS_E3B0(sc)) ?
17730             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17731             PBF_REG_P0_TQ_LINES_FREED_CNT},
17732         {1, (CHIP_IS_E3B0(sc)) ?
17733             PBF_REG_TQ_OCCUPANCY_Q1 :
17734             PBF_REG_P1_TQ_OCCUPANCY,
17735             (CHIP_IS_E3B0(sc)) ?
17736             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17737             PBF_REG_P1_TQ_LINES_FREED_CNT},
17738         {4, (CHIP_IS_E3B0(sc)) ?
17739             PBF_REG_TQ_OCCUPANCY_LB_Q :
17740             PBF_REG_P4_TQ_OCCUPANCY,
17741             (CHIP_IS_E3B0(sc)) ?
17742             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17743             PBF_REG_P4_TQ_LINES_FREED_CNT}
17744     };
17745
17746     struct pbf_pN_buf_regs buf_regs[] = {
17747         {0, (CHIP_IS_E3B0(sc)) ?
17748             PBF_REG_INIT_CRD_Q0 :
17749             PBF_REG_P0_INIT_CRD ,
17750             (CHIP_IS_E3B0(sc)) ?
17751             PBF_REG_CREDIT_Q0 :
17752             PBF_REG_P0_CREDIT,
17753             (CHIP_IS_E3B0(sc)) ?
17754             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17755             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17756         {1, (CHIP_IS_E3B0(sc)) ?
17757             PBF_REG_INIT_CRD_Q1 :
17758             PBF_REG_P1_INIT_CRD,
17759             (CHIP_IS_E3B0(sc)) ?
17760             PBF_REG_CREDIT_Q1 :
17761             PBF_REG_P1_CREDIT,
17762             (CHIP_IS_E3B0(sc)) ?
17763             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17764             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17765         {4, (CHIP_IS_E3B0(sc)) ?
17766             PBF_REG_INIT_CRD_LB_Q :
17767             PBF_REG_P4_INIT_CRD,
17768             (CHIP_IS_E3B0(sc)) ?
17769             PBF_REG_CREDIT_LB_Q :
17770             PBF_REG_P4_CREDIT,
17771             (CHIP_IS_E3B0(sc)) ?
17772             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17773             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17774     };
17775
17776     int i;
17777
17778     /* Verify the command queues are flushed P0, P1, P4 */
17779     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17780         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17781     }
17782
17783     /* Verify the transmission buffers are flushed P0, P1, P4 */
17784     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17785         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17786     }
17787 }
17788
17789 static void
17790 bxe_hw_enable_status(struct bxe_softc *sc)
17791 {
17792     uint32_t val;
17793
17794     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17795     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17796
17797     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17798     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17799
17800     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17801     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17802
17803     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17804     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17805
17806     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17807     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17808
17809     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17810     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17811
17812     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17813     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17814
17815     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17816     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17817 }
17818
17819 static int
17820 bxe_pf_flr_clnup(struct bxe_softc *sc)
17821 {
17822     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17823
17824     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17825
17826     /* Re-enable PF target read access */
17827     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17828
17829     /* Poll HW usage counters */
17830     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17831     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17832         return (-1);
17833     }
17834
17835     /* Zero the igu 'trailing edge' and 'leading edge' */
17836
17837     /* Send the FW cleanup command */
17838     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17839         return (-1);
17840     }
17841
17842     /* ATC cleanup */
17843
17844     /* Verify TX hw is flushed */
17845     bxe_tx_hw_flushed(sc, poll_cnt);
17846
17847     /* Wait 100ms (not adjusted according to platform) */
17848     DELAY(100000);
17849
17850     /* Verify no pending pci transactions */
17851     if (bxe_is_pcie_pending(sc)) {
17852         BLOGE(sc, "PCIE Transactions still pending\n");
17853     }
17854
17855     /* Debug */
17856     bxe_hw_enable_status(sc);
17857
17858     /*
17859      * Master enable - Due to WB DMAE writes performed before this
17860      * register is re-initialized as part of the regular function init
17861      */
17862     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17863
17864     return (0);
17865 }
17866
17867 static int
17868 bxe_init_hw_func(struct bxe_softc *sc)
17869 {
17870     int port = SC_PORT(sc);
17871     int func = SC_FUNC(sc);
17872     int init_phase = PHASE_PF0 + func;
17873     struct ecore_ilt *ilt = sc->ilt;
17874     uint16_t cdu_ilt_start;
17875     uint32_t addr, val;
17876     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17877     int i, main_mem_width, rc;
17878
17879     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17880
17881     /* FLR cleanup */
17882     if (!CHIP_IS_E1x(sc)) {
17883         rc = bxe_pf_flr_clnup(sc);
17884         if (rc) {
17885             BLOGE(sc, "FLR cleanup failed!\n");
17886             // XXX bxe_fw_dump(sc);
17887             // XXX bxe_idle_chk(sc);
17888             return (rc);
17889         }
17890     }
17891
17892     /* set MSI reconfigure capability */
17893     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17894         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17895         val = REG_RD(sc, addr);
17896         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17897         REG_WR(sc, addr, val);
17898     }
17899
17900     ecore_init_block(sc, BLOCK_PXP, init_phase);
17901     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17902
17903     ilt = sc->ilt;
17904     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17905
17906     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17907         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17908         ilt->lines[cdu_ilt_start + i].page_mapping =
17909             sc->context[i].vcxt_dma.paddr;
17910         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17911     }
17912     ecore_ilt_init_op(sc, INITOP_SET);
17913
17914     /* Set NIC mode */
17915     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17916     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17917
17918     if (!CHIP_IS_E1x(sc)) {
17919         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17920
17921         /* Turn on a single ISR mode in IGU if driver is going to use
17922          * INT#x or MSI
17923          */
17924         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17925             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17926         }
17927
17928         /*
17929          * Timers workaround bug: function init part.
17930          * Need to wait 20msec after initializing ILT,
17931          * needed to make sure there are no requests in
17932          * one of the PXP internal queues with "old" ILT addresses
17933          */
17934         DELAY(20000);
17935
17936         /*
17937          * Master enable - Due to WB DMAE writes performed before this
17938          * register is re-initialized as part of the regular function
17939          * init
17940          */
17941         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17942         /* Enable the function in IGU */
17943         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17944     }
17945
17946     sc->dmae_ready = 1;
17947
17948     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17949
17950     if (!CHIP_IS_E1x(sc))
17951         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17952
17953     ecore_init_block(sc, BLOCK_ATC, init_phase);
17954     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17955     ecore_init_block(sc, BLOCK_NIG, init_phase);
17956     ecore_init_block(sc, BLOCK_SRC, init_phase);
17957     ecore_init_block(sc, BLOCK_MISC, init_phase);
17958     ecore_init_block(sc, BLOCK_TCM, init_phase);
17959     ecore_init_block(sc, BLOCK_UCM, init_phase);
17960     ecore_init_block(sc, BLOCK_CCM, init_phase);
17961     ecore_init_block(sc, BLOCK_XCM, init_phase);
17962     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17963     ecore_init_block(sc, BLOCK_USEM, init_phase);
17964     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17965     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17966
17967     if (!CHIP_IS_E1x(sc))
17968         REG_WR(sc, QM_REG_PF_EN, 1);
17969
17970     if (!CHIP_IS_E1x(sc)) {
17971         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17972         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17973         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17974         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17975     }
17976     ecore_init_block(sc, BLOCK_QM, init_phase);
17977
17978     ecore_init_block(sc, BLOCK_TM, init_phase);
17979     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17980
17981     bxe_iov_init_dq(sc);
17982
17983     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17984     ecore_init_block(sc, BLOCK_PRS, init_phase);
17985     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17986     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17987     ecore_init_block(sc, BLOCK_USDM, init_phase);
17988     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17989     ecore_init_block(sc, BLOCK_UPB, init_phase);
17990     ecore_init_block(sc, BLOCK_XPB, init_phase);
17991     ecore_init_block(sc, BLOCK_PBF, init_phase);
17992     if (!CHIP_IS_E1x(sc))
17993         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17994
17995     ecore_init_block(sc, BLOCK_CDU, init_phase);
17996
17997     ecore_init_block(sc, BLOCK_CFC, init_phase);
17998
17999     if (!CHIP_IS_E1x(sc))
18000         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
18001
18002     if (IS_MF(sc)) {
18003         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
18004         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
18005     }
18006
18007     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
18008
18009     /* HC init per function */
18010     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18011         if (CHIP_IS_E1H(sc)) {
18012             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18013
18014             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18015             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18016         }
18017         ecore_init_block(sc, BLOCK_HC, init_phase);
18018
18019     } else {
18020         int num_segs, sb_idx, prod_offset;
18021
18022         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18023
18024         if (!CHIP_IS_E1x(sc)) {
18025             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18026             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18027         }
18028
18029         ecore_init_block(sc, BLOCK_IGU, init_phase);
18030
18031         if (!CHIP_IS_E1x(sc)) {
18032             int dsb_idx = 0;
18033             /**
18034              * Producer memory:
18035              * E2 mode: address 0-135 match to the mapping memory;
18036              * 136 - PF0 default prod; 137 - PF1 default prod;
18037              * 138 - PF2 default prod; 139 - PF3 default prod;
18038              * 140 - PF0 attn prod;    141 - PF1 attn prod;
18039              * 142 - PF2 attn prod;    143 - PF3 attn prod;
18040              * 144-147 reserved.
18041              *
18042              * E1.5 mode - In backward compatible mode;
18043              * for non default SB; each even line in the memory
18044              * holds the U producer and each odd line hold
18045              * the C producer. The first 128 producers are for
18046              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18047              * producers are for the DSB for each PF.
18048              * Each PF has five segments: (the order inside each
18049              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18050              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18051              * 144-147 attn prods;
18052              */
18053             /* non-default-status-blocks */
18054             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18055                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18056             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18057                 prod_offset = (sc->igu_base_sb + sb_idx) *
18058                     num_segs;
18059
18060                 for (i = 0; i < num_segs; i++) {
18061                     addr = IGU_REG_PROD_CONS_MEMORY +
18062                             (prod_offset + i) * 4;
18063                     REG_WR(sc, addr, 0);
18064                 }
18065                 /* send consumer update with value 0 */
18066                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18067                            USTORM_ID, 0, IGU_INT_NOP, 1);
18068                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18069             }
18070
18071             /* default-status-blocks */
18072             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18073                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18074
18075             if (CHIP_IS_MODE_4_PORT(sc))
18076                 dsb_idx = SC_FUNC(sc);
18077             else
18078                 dsb_idx = SC_VN(sc);
18079
18080             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18081                        IGU_BC_BASE_DSB_PROD + dsb_idx :
18082                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
18083
18084             /*
18085              * igu prods come in chunks of E1HVN_MAX (4) -
18086              * does not matters what is the current chip mode
18087              */
18088             for (i = 0; i < (num_segs * E1HVN_MAX);
18089                  i += E1HVN_MAX) {
18090                 addr = IGU_REG_PROD_CONS_MEMORY +
18091                             (prod_offset + i)*4;
18092                 REG_WR(sc, addr, 0);
18093             }
18094             /* send consumer update with 0 */
18095             if (CHIP_INT_MODE_IS_BC(sc)) {
18096                 bxe_ack_sb(sc, sc->igu_dsb_id,
18097                            USTORM_ID, 0, IGU_INT_NOP, 1);
18098                 bxe_ack_sb(sc, sc->igu_dsb_id,
18099                            CSTORM_ID, 0, IGU_INT_NOP, 1);
18100                 bxe_ack_sb(sc, sc->igu_dsb_id,
18101                            XSTORM_ID, 0, IGU_INT_NOP, 1);
18102                 bxe_ack_sb(sc, sc->igu_dsb_id,
18103                            TSTORM_ID, 0, IGU_INT_NOP, 1);
18104                 bxe_ack_sb(sc, sc->igu_dsb_id,
18105                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18106             } else {
18107                 bxe_ack_sb(sc, sc->igu_dsb_id,
18108                            USTORM_ID, 0, IGU_INT_NOP, 1);
18109                 bxe_ack_sb(sc, sc->igu_dsb_id,
18110                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18111             }
18112             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18113
18114             /* !!! these should become driver const once
18115                rf-tool supports split-68 const */
18116             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18117             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18118             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18119             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18120             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18121             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18122         }
18123     }
18124
18125     /* Reset PCIE errors for debug */
18126     REG_WR(sc, 0x2114, 0xffffffff);
18127     REG_WR(sc, 0x2120, 0xffffffff);
18128
18129     if (CHIP_IS_E1x(sc)) {
18130         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18131         main_mem_base = HC_REG_MAIN_MEMORY +
18132                 SC_PORT(sc) * (main_mem_size * 4);
18133         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18134         main_mem_width = 8;
18135
18136         val = REG_RD(sc, main_mem_prty_clr);
18137         if (val) {
18138             BLOGD(sc, DBG_LOAD,
18139                   "Parity errors in HC block during function init (0x%x)!\n",
18140                   val);
18141         }
18142
18143         /* Clear "false" parity errors in MSI-X table */
18144         for (i = main_mem_base;
18145              i < main_mem_base + main_mem_size * 4;
18146              i += main_mem_width) {
18147             bxe_read_dmae(sc, i, main_mem_width / 4);
18148             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18149                            i, main_mem_width / 4);
18150         }
18151         /* Clear HC parity attention */
18152         REG_RD(sc, main_mem_prty_clr);
18153     }
18154
18155 #if 1
18156     /* Enable STORMs SP logging */
18157     REG_WR8(sc, BAR_USTRORM_INTMEM +
18158            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18159     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18160            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18161     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18162            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18163     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18164            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18165 #endif
18166
18167     elink_phy_probe(&sc->link_params);
18168
18169     return (0);
18170 }
18171
18172 static void
18173 bxe_link_reset(struct bxe_softc *sc)
18174 {
18175     if (!BXE_NOMCP(sc)) {
18176         bxe_acquire_phy_lock(sc);
18177         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18178         bxe_release_phy_lock(sc);
18179     } else {
18180         if (!CHIP_REV_IS_SLOW(sc)) {
18181             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18182         }
18183     }
18184 }
18185
18186 static void
18187 bxe_reset_port(struct bxe_softc *sc)
18188 {
18189     int port = SC_PORT(sc);
18190     uint32_t val;
18191
18192     /* reset physical Link */
18193     bxe_link_reset(sc);
18194
18195     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18196
18197     /* Do not rcv packets to BRB */
18198     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18199     /* Do not direct rcv packets that are not for MCP to the BRB */
18200     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18201                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18202
18203     /* Configure AEU */
18204     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18205
18206     DELAY(100000);
18207
18208     /* Check for BRB port occupancy */
18209     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18210     if (val) {
18211         BLOGD(sc, DBG_LOAD,
18212               "BRB1 is not empty, %d blocks are occupied\n", val);
18213     }
18214
18215     /* TODO: Close Doorbell port? */
18216 }
18217
18218 static void
18219 bxe_ilt_wr(struct bxe_softc *sc,
18220            uint32_t         index,
18221            bus_addr_t       addr)
18222 {
18223     int reg;
18224     uint32_t wb_write[2];
18225
18226     if (CHIP_IS_E1(sc)) {
18227         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18228     } else {
18229         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18230     }
18231
18232     wb_write[0] = ONCHIP_ADDR1(addr);
18233     wb_write[1] = ONCHIP_ADDR2(addr);
18234     REG_WR_DMAE(sc, reg, wb_write, 2);
18235 }
18236
18237 static void
18238 bxe_clear_func_ilt(struct bxe_softc *sc,
18239                    uint32_t         func)
18240 {
18241     uint32_t i, base = FUNC_ILT_BASE(func);
18242     for (i = base; i < base + ILT_PER_FUNC; i++) {
18243         bxe_ilt_wr(sc, i, 0);
18244     }
18245 }
18246
18247 static void
18248 bxe_reset_func(struct bxe_softc *sc)
18249 {
18250     struct bxe_fastpath *fp;
18251     int port = SC_PORT(sc);
18252     int func = SC_FUNC(sc);
18253     int i;
18254
18255     /* Disable the function in the FW */
18256     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18257     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18258     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18259     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18260
18261     /* FP SBs */
18262     FOR_EACH_ETH_QUEUE(sc, i) {
18263         fp = &sc->fp[i];
18264         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18265                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18266                 SB_DISABLED);
18267     }
18268
18269     /* SP SB */
18270     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18271             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18272             SB_DISABLED);
18273
18274     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18275         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18276     }
18277
18278     /* Configure IGU */
18279     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18280         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18281         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18282     } else {
18283         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18284         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18285     }
18286
18287     if (CNIC_LOADED(sc)) {
18288         /* Disable Timer scan */
18289         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18290         /*
18291          * Wait for at least 10ms and up to 2 second for the timers
18292          * scan to complete
18293          */
18294         for (i = 0; i < 200; i++) {
18295             DELAY(10000);
18296             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18297                 break;
18298         }
18299     }
18300
18301     /* Clear ILT */
18302     bxe_clear_func_ilt(sc, func);
18303
18304     /*
18305      * Timers workaround bug for E2: if this is vnic-3,
18306      * we need to set the entire ilt range for this timers.
18307      */
18308     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18309         struct ilt_client_info ilt_cli;
18310         /* use dummy TM client */
18311         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18312         ilt_cli.start = 0;
18313         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18314         ilt_cli.client_num = ILT_CLIENT_TM;
18315
18316         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18317     }
18318
18319     /* this assumes that reset_port() called before reset_func()*/
18320     if (!CHIP_IS_E1x(sc)) {
18321         bxe_pf_disable(sc);
18322     }
18323
18324     sc->dmae_ready = 0;
18325 }
18326
18327 static int
18328 bxe_gunzip_init(struct bxe_softc *sc)
18329 {
18330     return (0);
18331 }
18332
18333 static void
18334 bxe_gunzip_end(struct bxe_softc *sc)
18335 {
18336     return;
18337 }
18338
18339 static int
18340 bxe_init_firmware(struct bxe_softc *sc)
18341 {
18342     if (CHIP_IS_E1(sc)) {
18343         ecore_init_e1_firmware(sc);
18344         sc->iro_array = e1_iro_arr;
18345     } else if (CHIP_IS_E1H(sc)) {
18346         ecore_init_e1h_firmware(sc);
18347         sc->iro_array = e1h_iro_arr;
18348     } else if (!CHIP_IS_E1x(sc)) {
18349         ecore_init_e2_firmware(sc);
18350         sc->iro_array = e2_iro_arr;
18351     } else {
18352         BLOGE(sc, "Unsupported chip revision\n");
18353         return (-1);
18354     }
18355
18356     return (0);
18357 }
18358
18359 static void
18360 bxe_release_firmware(struct bxe_softc *sc)
18361 {
18362     /* Do nothing */
18363     return;
18364 }
18365
18366 static int
18367 ecore_gunzip(struct bxe_softc *sc,
18368              const uint8_t    *zbuf,
18369              int              len)
18370 {
18371     /* XXX : Implement... */
18372     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18373     return (FALSE);
18374 }
18375
18376 static void
18377 ecore_reg_wr_ind(struct bxe_softc *sc,
18378                  uint32_t         addr,
18379                  uint32_t         val)
18380 {
18381     bxe_reg_wr_ind(sc, addr, val);
18382 }
18383
18384 static void
18385 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18386                           bus_addr_t       phys_addr,
18387                           uint32_t         addr,
18388                           uint32_t         len)
18389 {
18390     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18391 }
18392
18393 void
18394 ecore_storm_memset_struct(struct bxe_softc *sc,
18395                           uint32_t         addr,
18396                           size_t           size,
18397                           uint32_t         *data)
18398 {
18399     uint8_t i;
18400     for (i = 0; i < size/4; i++) {
18401         REG_WR(sc, addr + (i * 4), data[i]);
18402     }
18403 }
18404
18405
18406 /*
18407  * character device - ioctl interface definitions
18408  */
18409
18410
18411 #include "bxe_dump.h"
18412 #include "bxe_ioctl.h"
18413 #include <sys/conf.h>
18414
18415 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18416                 struct thread *td);
18417
18418 static struct cdevsw bxe_cdevsw = {
18419     .d_version = D_VERSION,
18420     .d_ioctl = bxe_eioctl,
18421     .d_name = "bxecnic",
18422 };
18423
18424 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18425
18426
18427 #define DUMP_ALL_PRESETS        0x1FFF
18428 #define DUMP_MAX_PRESETS        13
18429 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18430 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18431 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18432 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18433 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18434
18435 #define IS_REG_IN_PRESET(presets, idx)  \
18436                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18437
18438
18439 static int
18440 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18441 {
18442     if (CHIP_IS_E1(sc))
18443         return dump_num_registers[0][preset-1];
18444     else if (CHIP_IS_E1H(sc))
18445         return dump_num_registers[1][preset-1];
18446     else if (CHIP_IS_E2(sc))
18447         return dump_num_registers[2][preset-1];
18448     else if (CHIP_IS_E3A0(sc))
18449         return dump_num_registers[3][preset-1];
18450     else if (CHIP_IS_E3B0(sc))
18451         return dump_num_registers[4][preset-1];
18452     else
18453         return 0;
18454 }
18455
18456 static int
18457 bxe_get_total_regs_len32(struct bxe_softc *sc)
18458 {
18459     uint32_t preset_idx;
18460     int regdump_len32 = 0;
18461
18462
18463     /* Calculate the total preset regs length */
18464     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18465         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18466     }
18467
18468     return regdump_len32;
18469 }
18470
18471 static const uint32_t *
18472 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18473 {
18474     if (CHIP_IS_E2(sc))
18475         return page_vals_e2;
18476     else if (CHIP_IS_E3(sc))
18477         return page_vals_e3;
18478     else
18479         return NULL;
18480 }
18481
18482 static uint32_t
18483 __bxe_get_page_reg_num(struct bxe_softc *sc)
18484 {
18485     if (CHIP_IS_E2(sc))
18486         return PAGE_MODE_VALUES_E2;
18487     else if (CHIP_IS_E3(sc))
18488         return PAGE_MODE_VALUES_E3;
18489     else
18490         return 0;
18491 }
18492
18493 static const uint32_t *
18494 __bxe_get_page_write_ar(struct bxe_softc *sc)
18495 {
18496     if (CHIP_IS_E2(sc))
18497         return page_write_regs_e2;
18498     else if (CHIP_IS_E3(sc))
18499         return page_write_regs_e3;
18500     else
18501         return NULL;
18502 }
18503
18504 static uint32_t
18505 __bxe_get_page_write_num(struct bxe_softc *sc)
18506 {
18507     if (CHIP_IS_E2(sc))
18508         return PAGE_WRITE_REGS_E2;
18509     else if (CHIP_IS_E3(sc))
18510         return PAGE_WRITE_REGS_E3;
18511     else
18512         return 0;
18513 }
18514
18515 static const struct reg_addr *
18516 __bxe_get_page_read_ar(struct bxe_softc *sc)
18517 {
18518     if (CHIP_IS_E2(sc))
18519         return page_read_regs_e2;
18520     else if (CHIP_IS_E3(sc))
18521         return page_read_regs_e3;
18522     else
18523         return NULL;
18524 }
18525
18526 static uint32_t
18527 __bxe_get_page_read_num(struct bxe_softc *sc)
18528 {
18529     if (CHIP_IS_E2(sc))
18530         return PAGE_READ_REGS_E2;
18531     else if (CHIP_IS_E3(sc))
18532         return PAGE_READ_REGS_E3;
18533     else
18534         return 0;
18535 }
18536
18537 static bool
18538 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18539 {
18540     if (CHIP_IS_E1(sc))
18541         return IS_E1_REG(reg_info->chips);
18542     else if (CHIP_IS_E1H(sc))
18543         return IS_E1H_REG(reg_info->chips);
18544     else if (CHIP_IS_E2(sc))
18545         return IS_E2_REG(reg_info->chips);
18546     else if (CHIP_IS_E3A0(sc))
18547         return IS_E3A0_REG(reg_info->chips);
18548     else if (CHIP_IS_E3B0(sc))
18549         return IS_E3B0_REG(reg_info->chips);
18550     else
18551         return 0;
18552 }
18553
18554 static bool
18555 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18556 {
18557     if (CHIP_IS_E1(sc))
18558         return IS_E1_REG(wreg_info->chips);
18559     else if (CHIP_IS_E1H(sc))
18560         return IS_E1H_REG(wreg_info->chips);
18561     else if (CHIP_IS_E2(sc))
18562         return IS_E2_REG(wreg_info->chips);
18563     else if (CHIP_IS_E3A0(sc))
18564         return IS_E3A0_REG(wreg_info->chips);
18565     else if (CHIP_IS_E3B0(sc))
18566         return IS_E3B0_REG(wreg_info->chips);
18567     else
18568         return 0;
18569 }
18570
18571 /**
18572  * bxe_read_pages_regs - read "paged" registers
18573  *
18574  * @bp          device handle
18575  * @p           output buffer
18576  *
18577  * Reads "paged" memories: memories that may only be read by first writing to a
18578  * specific address ("write address") and then reading from a specific address
18579  * ("read address"). There may be more than one write address per "page" and
18580  * more than one read address per write address.
18581  */
18582 static void
18583 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18584 {
18585     uint32_t i, j, k, n;
18586
18587     /* addresses of the paged registers */
18588     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18589     /* number of paged registers */
18590     int num_pages = __bxe_get_page_reg_num(sc);
18591     /* write addresses */
18592     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18593     /* number of write addresses */
18594     int write_num = __bxe_get_page_write_num(sc);
18595     /* read addresses info */
18596     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18597     /* number of read addresses */
18598     int read_num = __bxe_get_page_read_num(sc);
18599     uint32_t addr, size;
18600
18601     for (i = 0; i < num_pages; i++) {
18602         for (j = 0; j < write_num; j++) {
18603             REG_WR(sc, write_addr[j], page_addr[i]);
18604
18605             for (k = 0; k < read_num; k++) {
18606                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18607                     size = read_addr[k].size;
18608                     for (n = 0; n < size; n++) {
18609                         addr = read_addr[k].addr + n*4;
18610                         *p++ = REG_RD(sc, addr);
18611                     }
18612                 }
18613             }
18614         }
18615     }
18616     return;
18617 }
18618
18619
18620 static int
18621 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18622 {
18623     uint32_t i, j, addr;
18624     const struct wreg_addr *wreg_addr_p = NULL;
18625
18626     if (CHIP_IS_E1(sc))
18627         wreg_addr_p = &wreg_addr_e1;
18628     else if (CHIP_IS_E1H(sc))
18629         wreg_addr_p = &wreg_addr_e1h;
18630     else if (CHIP_IS_E2(sc))
18631         wreg_addr_p = &wreg_addr_e2;
18632     else if (CHIP_IS_E3A0(sc))
18633         wreg_addr_p = &wreg_addr_e3;
18634     else if (CHIP_IS_E3B0(sc))
18635         wreg_addr_p = &wreg_addr_e3b0;
18636     else
18637         return (-1);
18638
18639     /* Read the idle_chk registers */
18640     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18641         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18642             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18643             for (j = 0; j < idle_reg_addrs[i].size; j++)
18644                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18645         }
18646     }
18647
18648     /* Read the regular registers */
18649     for (i = 0; i < REGS_COUNT; i++) {
18650         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18651             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18652             for (j = 0; j < reg_addrs[i].size; j++)
18653                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18654         }
18655     }
18656
18657     /* Read the CAM registers */
18658     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18659         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18660         for (i = 0; i < wreg_addr_p->size; i++) {
18661             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18662
18663             /* In case of wreg_addr register, read additional
18664                registers from read_regs array
18665              */
18666             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18667                 addr = *(wreg_addr_p->read_regs);
18668                 *p++ = REG_RD(sc, addr + j*4);
18669             }
18670         }
18671     }
18672
18673     /* Paged registers are supported in E2 & E3 only */
18674     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18675         /* Read "paged" registers */
18676         bxe_read_pages_regs(sc, p, preset);
18677     }
18678
18679     return 0;
18680 }
18681
18682 static int
18683 bxe_grc_dump(struct bxe_softc *sc)
18684 {
18685     int rval = 0;
18686     uint32_t preset_idx;
18687     uint8_t *buf;
18688     uint32_t size;
18689     struct  dump_header *d_hdr;
18690
18691     if (sc->grcdump_done)
18692         return (rval);
18693     
18694     ecore_disable_blocks_parity(sc);
18695
18696     buf = sc->grc_dump;
18697     d_hdr = sc->grc_dump;
18698
18699     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18700     d_hdr->version = BNX2X_DUMP_VERSION;
18701     d_hdr->preset = DUMP_ALL_PRESETS;
18702
18703     if (CHIP_IS_E1(sc)) {
18704         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18705     } else if (CHIP_IS_E1H(sc)) {
18706         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18707     } else if (CHIP_IS_E2(sc)) {
18708         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18709                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18710     } else if (CHIP_IS_E3A0(sc)) {
18711         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18712                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18713     } else if (CHIP_IS_E3B0(sc)) {
18714         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18715                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18716     }
18717
18718     buf += sizeof(struct  dump_header);
18719
18720     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18721
18722         /* Skip presets with IOR */
18723         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18724             (preset_idx == 11))
18725             continue;
18726
18727         rval = bxe_get_preset_regs(sc, sc->grc_dump, preset_idx);
18728
18729         if (rval)
18730             break;
18731
18732         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18733
18734         buf += size;
18735     }
18736
18737     ecore_clear_blocks_parity(sc);
18738     ecore_enable_blocks_parity(sc);
18739
18740     sc->grcdump_done = 1;
18741     return(rval);
18742 }
18743
18744 static int
18745 bxe_add_cdev(struct bxe_softc *sc)
18746 {
18747     int grc_dump_size;
18748
18749     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18750                                 sizeof(struct  dump_header);
18751
18752     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18753
18754     if (sc->grc_dump == NULL)
18755         return (-1);
18756
18757     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18758                             sc->ifnet->if_dunit,
18759                             UID_ROOT,
18760                             GID_WHEEL,
18761                             0600,
18762                             "%s",
18763                             if_name(sc->ifnet));
18764
18765     if (sc->ioctl_dev == NULL) {
18766
18767         free(sc->grc_dump, M_DEVBUF);
18768
18769         return (-1);
18770     }
18771
18772     sc->ioctl_dev->si_drv1 = sc;
18773
18774     return (0);
18775 }
18776
18777 static void
18778 bxe_del_cdev(struct bxe_softc *sc)
18779 {
18780     if (sc->ioctl_dev != NULL)
18781         destroy_dev(sc->ioctl_dev);
18782
18783     if (sc->grc_dump == NULL)
18784         free(sc->grc_dump, M_DEVBUF);
18785
18786     return;
18787 }
18788
18789 static int
18790 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18791         struct thread *td)
18792 {
18793     struct bxe_softc    *sc;
18794     int                 rval = 0;
18795     device_t            pci_dev;
18796     bxe_grcdump_t       *dump = NULL;
18797     int grc_dump_size;
18798
18799     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
18800         return ENXIO;
18801
18802     pci_dev= sc->dev;
18803
18804     dump = (bxe_grcdump_t *)data;
18805
18806     switch(cmd) {
18807
18808         case BXE_GRC_DUMP_SIZE:
18809             dump->pci_func = sc->pcie_func;
18810             dump->grcdump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18811                                         sizeof(struct  dump_header);
18812             break;
18813
18814         case BXE_GRC_DUMP:
18815             
18816             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18817                                 sizeof(struct  dump_header);
18818
18819             if ((sc->grc_dump == NULL) || (dump->grcdump == NULL) ||
18820                 (dump->grcdump_size < grc_dump_size) || (!sc->grcdump_done)) {
18821                 rval = EINVAL;
18822                 break;
18823             }
18824             dump->grcdump_dwords = grc_dump_size >> 2;
18825             rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
18826             sc->grcdump_done = 0;
18827
18828             break;
18829
18830         default:
18831             break;
18832     }
18833
18834     return (rval);
18835 }