bxe.c revision 307972
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: stable/11/sys/dev/bxe/bxe.c 307972 2016-10-26 17:53:12Z davidcs $");
29
30#define BXE_DRIVER_VERSION "1.78.89"
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
79struct pbf_pN_buf_regs {
80    int pN;
81    uint32_t init_crd;
82    uint32_t crd;
83    uint32_t crd_freed;
84};
85
86struct 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
96static 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
180MALLOC_DECLARE(M_BXE_ILT);
181MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
182
183/*
184 * FreeBSD device entry points.
185 */
186static int bxe_probe(device_t);
187static int bxe_attach(device_t);
188static int bxe_detach(device_t);
189static int bxe_shutdown(device_t);
190
191/*
192 * FreeBSD KLD module/device interface event handler method.
193 */
194static 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 */
209static 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 */
219static devclass_t bxe_devclass;
220
221MODULE_DEPEND(bxe, pci, 1, 1, 1);
222MODULE_DEPEND(bxe, ether, 1, 1, 1);
223DRIVER_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
228struct mtx bxe_prev_mtx;
229MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
230struct 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};
238static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
239
240static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
241
242/* Tunable device values... */
243
244SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
245
246/* Debug */
247unsigned long bxe_debug = 0;
248SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, CTLFLAG_RDTUN,
249             &bxe_debug, 0, "Debug logging mode");
250
251/* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
252static int bxe_interrupt_mode = INTR_MODE_MSIX;
253SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
254           &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
255
256/* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
257static int bxe_queue_count = 4;
258SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
259           &bxe_queue_count, 0, "Multi-Queue queue count");
260
261/* max number of buffers per queue (default RX_BD_USABLE) */
262static int bxe_max_rx_bufs = 0;
263SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
264           &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
265
266/* Host interrupt coalescing RX tick timer (usecs) */
267static int bxe_hc_rx_ticks = 25;
268SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
269           &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
270
271/* Host interrupt coalescing TX tick timer (usecs) */
272static int bxe_hc_tx_ticks = 50;
273SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
274           &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
275
276/* Maximum number of Rx packets to process at a time */
277static int bxe_rx_budget = 0xffffffff;
278SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
279           &bxe_rx_budget, 0, "Rx processing budget");
280
281/* Maximum LRO aggregation size */
282static int bxe_max_aggregation_size = 0;
283SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
284           &bxe_max_aggregation_size, 0, "max aggregation size");
285
286/* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
287static int bxe_mrrs = -1;
288SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
289           &bxe_mrrs, 0, "PCIe maximum read request size");
290
291/* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
292static int bxe_autogreeen = 0;
293SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
294           &bxe_autogreeen, 0, "AutoGrEEEn support");
295
296/* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
297static int bxe_udp_rss = 0;
298SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
299           &bxe_udp_rss, 0, "UDP RSS support");
300
301
302#define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
303
304#define STATS_OFFSET32(stat_name)                   \
305    (offsetof(struct bxe_eth_stats, stat_name) / 4)
306
307#define Q_STATS_OFFSET32(stat_name)                   \
308    (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
309
310static const struct {
311    uint32_t offset;
312    uint32_t size;
313    uint32_t flags;
314#define STATS_FLAGS_PORT  1
315#define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
316#define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
317    char string[STAT_NAME_LEN];
318} bxe_eth_stats_arr[] = {
319    { STATS_OFFSET32(total_bytes_received_hi),
320                8, STATS_FLAGS_BOTH, "rx_bytes" },
321    { STATS_OFFSET32(error_bytes_received_hi),
322                8, STATS_FLAGS_BOTH, "rx_error_bytes" },
323    { STATS_OFFSET32(total_unicast_packets_received_hi),
324                8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
325    { STATS_OFFSET32(total_multicast_packets_received_hi),
326                8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
327    { STATS_OFFSET32(total_broadcast_packets_received_hi),
328                8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
329    { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
330                8, STATS_FLAGS_PORT, "rx_crc_errors" },
331    { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
332                8, STATS_FLAGS_PORT, "rx_align_errors" },
333    { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
334                8, STATS_FLAGS_PORT, "rx_undersize_packets" },
335    { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
336                8, STATS_FLAGS_PORT, "rx_oversize_packets" },
337    { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
338                8, STATS_FLAGS_PORT, "rx_fragments" },
339    { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
340                8, STATS_FLAGS_PORT, "rx_jabbers" },
341    { STATS_OFFSET32(no_buff_discard_hi),
342                8, STATS_FLAGS_BOTH, "rx_discards" },
343    { STATS_OFFSET32(mac_filter_discard),
344                4, STATS_FLAGS_PORT, "rx_filtered_packets" },
345    { STATS_OFFSET32(mf_tag_discard),
346                4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
347    { STATS_OFFSET32(pfc_frames_received_hi),
348                8, STATS_FLAGS_PORT, "pfc_frames_received" },
349    { STATS_OFFSET32(pfc_frames_sent_hi),
350                8, STATS_FLAGS_PORT, "pfc_frames_sent" },
351    { STATS_OFFSET32(brb_drop_hi),
352                8, STATS_FLAGS_PORT, "rx_brb_discard" },
353    { STATS_OFFSET32(brb_truncate_hi),
354                8, STATS_FLAGS_PORT, "rx_brb_truncate" },
355    { STATS_OFFSET32(pause_frames_received_hi),
356                8, STATS_FLAGS_PORT, "rx_pause_frames" },
357    { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
358                8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
359    { STATS_OFFSET32(nig_timer_max),
360                4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
361    { STATS_OFFSET32(total_bytes_transmitted_hi),
362                8, STATS_FLAGS_BOTH, "tx_bytes" },
363    { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
364                8, STATS_FLAGS_PORT, "tx_error_bytes" },
365    { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
366                8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
367    { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
368                8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
369    { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
370                8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
371    { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
372                8, STATS_FLAGS_PORT, "tx_mac_errors" },
373    { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
374                8, STATS_FLAGS_PORT, "tx_carrier_errors" },
375    { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
376                8, STATS_FLAGS_PORT, "tx_single_collisions" },
377    { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
378                8, STATS_FLAGS_PORT, "tx_multi_collisions" },
379    { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
380                8, STATS_FLAGS_PORT, "tx_deferred" },
381    { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
382                8, STATS_FLAGS_PORT, "tx_excess_collisions" },
383    { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
384                8, STATS_FLAGS_PORT, "tx_late_collisions" },
385    { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
386                8, STATS_FLAGS_PORT, "tx_total_collisions" },
387    { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
388                8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
389    { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
390                8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
391    { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
392                8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
393    { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
394                8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
395    { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
396                8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
397    { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
398                8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
399    { STATS_OFFSET32(etherstatspktsover1522octets_hi),
400                8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
401    { STATS_OFFSET32(pause_frames_sent_hi),
402                8, STATS_FLAGS_PORT, "tx_pause_frames" },
403    { STATS_OFFSET32(total_tpa_aggregations_hi),
404                8, STATS_FLAGS_FUNC, "tpa_aggregations" },
405    { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
406                8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
407    { STATS_OFFSET32(total_tpa_bytes_hi),
408                8, STATS_FLAGS_FUNC, "tpa_bytes"},
409    { STATS_OFFSET32(eee_tx_lpi),
410                4, STATS_FLAGS_PORT, "eee_tx_lpi"},
411    { STATS_OFFSET32(rx_calls),
412                4, STATS_FLAGS_FUNC, "rx_calls"},
413    { STATS_OFFSET32(rx_pkts),
414                4, STATS_FLAGS_FUNC, "rx_pkts"},
415    { STATS_OFFSET32(rx_tpa_pkts),
416                4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
417    { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
418                4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
419    { STATS_OFFSET32(rx_bxe_service_rxsgl),
420                4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
421    { STATS_OFFSET32(rx_jumbo_sge_pkts),
422                4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
423    { STATS_OFFSET32(rx_soft_errors),
424                4, STATS_FLAGS_FUNC, "rx_soft_errors"},
425    { STATS_OFFSET32(rx_hw_csum_errors),
426                4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
427    { STATS_OFFSET32(rx_ofld_frames_csum_ip),
428                4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
429    { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
430                4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
431    { STATS_OFFSET32(rx_budget_reached),
432                4, STATS_FLAGS_FUNC, "rx_budget_reached"},
433    { STATS_OFFSET32(tx_pkts),
434                4, STATS_FLAGS_FUNC, "tx_pkts"},
435    { STATS_OFFSET32(tx_soft_errors),
436                4, STATS_FLAGS_FUNC, "tx_soft_errors"},
437    { STATS_OFFSET32(tx_ofld_frames_csum_ip),
438                4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
439    { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
440                4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
441    { STATS_OFFSET32(tx_ofld_frames_csum_udp),
442                4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
443    { STATS_OFFSET32(tx_ofld_frames_lso),
444                4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
445    { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
446                4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
447    { STATS_OFFSET32(tx_encap_failures),
448                4, STATS_FLAGS_FUNC, "tx_encap_failures"},
449    { STATS_OFFSET32(tx_hw_queue_full),
450                4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
451    { STATS_OFFSET32(tx_hw_max_queue_depth),
452                4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
453    { STATS_OFFSET32(tx_dma_mapping_failure),
454                4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
455    { STATS_OFFSET32(tx_max_drbr_queue_depth),
456                4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
457    { STATS_OFFSET32(tx_window_violation_std),
458                4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
459    { STATS_OFFSET32(tx_window_violation_tso),
460                4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
461    { STATS_OFFSET32(tx_chain_lost_mbuf),
462                4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
463    { STATS_OFFSET32(tx_frames_deferred),
464                4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
465    { STATS_OFFSET32(tx_queue_xoff),
466                4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
467    { STATS_OFFSET32(mbuf_defrag_attempts),
468                4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
469    { STATS_OFFSET32(mbuf_defrag_failures),
470                4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
471    { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
472                4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
473    { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
474                4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
475    { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
476                4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
477    { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
478                4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
479    { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
480                4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
481    { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
482                4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
483    { STATS_OFFSET32(mbuf_alloc_tx),
484                4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
485    { STATS_OFFSET32(mbuf_alloc_rx),
486                4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
487    { STATS_OFFSET32(mbuf_alloc_sge),
488                4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
489    { STATS_OFFSET32(mbuf_alloc_tpa),
490                4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"},
491    { STATS_OFFSET32(tx_queue_full_return),
492                4, STATS_FLAGS_FUNC, "tx_queue_full_return"},
493    { STATS_OFFSET32(tx_request_link_down_failures),
494                4, STATS_FLAGS_FUNC, "tx_request_link_down_failures"},
495    { STATS_OFFSET32(bd_avail_too_less_failures),
496                4, STATS_FLAGS_FUNC, "bd_avail_too_less_failures"},
497    { STATS_OFFSET32(tx_mq_not_empty),
498                4, STATS_FLAGS_FUNC, "tx_mq_not_empty"}
499
500};
501
502static const struct {
503    uint32_t offset;
504    uint32_t size;
505    char string[STAT_NAME_LEN];
506} bxe_eth_q_stats_arr[] = {
507    { Q_STATS_OFFSET32(total_bytes_received_hi),
508                8, "rx_bytes" },
509    { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
510                8, "rx_ucast_packets" },
511    { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
512                8, "rx_mcast_packets" },
513    { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
514                8, "rx_bcast_packets" },
515    { Q_STATS_OFFSET32(no_buff_discard_hi),
516                8, "rx_discards" },
517    { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
518                8, "tx_bytes" },
519    { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
520                8, "tx_ucast_packets" },
521    { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
522                8, "tx_mcast_packets" },
523    { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
524                8, "tx_bcast_packets" },
525    { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
526                8, "tpa_aggregations" },
527    { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
528                8, "tpa_aggregated_frames"},
529    { Q_STATS_OFFSET32(total_tpa_bytes_hi),
530                8, "tpa_bytes"},
531    { Q_STATS_OFFSET32(rx_calls),
532                4, "rx_calls"},
533    { Q_STATS_OFFSET32(rx_pkts),
534                4, "rx_pkts"},
535    { Q_STATS_OFFSET32(rx_tpa_pkts),
536                4, "rx_tpa_pkts"},
537    { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
538                4, "rx_erroneous_jumbo_sge_pkts"},
539    { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
540                4, "rx_bxe_service_rxsgl"},
541    { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
542                4, "rx_jumbo_sge_pkts"},
543    { Q_STATS_OFFSET32(rx_soft_errors),
544                4, "rx_soft_errors"},
545    { Q_STATS_OFFSET32(rx_hw_csum_errors),
546                4, "rx_hw_csum_errors"},
547    { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
548                4, "rx_ofld_frames_csum_ip"},
549    { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
550                4, "rx_ofld_frames_csum_tcp_udp"},
551    { Q_STATS_OFFSET32(rx_budget_reached),
552                4, "rx_budget_reached"},
553    { Q_STATS_OFFSET32(tx_pkts),
554                4, "tx_pkts"},
555    { Q_STATS_OFFSET32(tx_soft_errors),
556                4, "tx_soft_errors"},
557    { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
558                4, "tx_ofld_frames_csum_ip"},
559    { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
560                4, "tx_ofld_frames_csum_tcp"},
561    { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
562                4, "tx_ofld_frames_csum_udp"},
563    { Q_STATS_OFFSET32(tx_ofld_frames_lso),
564                4, "tx_ofld_frames_lso"},
565    { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
566                4, "tx_ofld_frames_lso_hdr_splits"},
567    { Q_STATS_OFFSET32(tx_encap_failures),
568                4, "tx_encap_failures"},
569    { Q_STATS_OFFSET32(tx_hw_queue_full),
570                4, "tx_hw_queue_full"},
571    { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
572                4, "tx_hw_max_queue_depth"},
573    { Q_STATS_OFFSET32(tx_dma_mapping_failure),
574                4, "tx_dma_mapping_failure"},
575    { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
576                4, "tx_max_drbr_queue_depth"},
577    { Q_STATS_OFFSET32(tx_window_violation_std),
578                4, "tx_window_violation_std"},
579    { Q_STATS_OFFSET32(tx_window_violation_tso),
580                4, "tx_window_violation_tso"},
581    { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
582                4, "tx_chain_lost_mbuf"},
583    { Q_STATS_OFFSET32(tx_frames_deferred),
584                4, "tx_frames_deferred"},
585    { Q_STATS_OFFSET32(tx_queue_xoff),
586                4, "tx_queue_xoff"},
587    { Q_STATS_OFFSET32(mbuf_defrag_attempts),
588                4, "mbuf_defrag_attempts"},
589    { Q_STATS_OFFSET32(mbuf_defrag_failures),
590                4, "mbuf_defrag_failures"},
591    { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
592                4, "mbuf_rx_bd_alloc_failed"},
593    { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
594                4, "mbuf_rx_bd_mapping_failed"},
595    { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
596                4, "mbuf_rx_tpa_alloc_failed"},
597    { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
598                4, "mbuf_rx_tpa_mapping_failed"},
599    { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
600                4, "mbuf_rx_sge_alloc_failed"},
601    { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
602                4, "mbuf_rx_sge_mapping_failed"},
603    { Q_STATS_OFFSET32(mbuf_alloc_tx),
604                4, "mbuf_alloc_tx"},
605    { Q_STATS_OFFSET32(mbuf_alloc_rx),
606                4, "mbuf_alloc_rx"},
607    { Q_STATS_OFFSET32(mbuf_alloc_sge),
608                4, "mbuf_alloc_sge"},
609    { Q_STATS_OFFSET32(mbuf_alloc_tpa),
610                4, "mbuf_alloc_tpa"},
611    { Q_STATS_OFFSET32(tx_queue_full_return),
612                4, "tx_queue_full_return"},
613    { Q_STATS_OFFSET32(tx_request_link_down_failures),
614                4, "tx_request_link_down_failures"},
615    { Q_STATS_OFFSET32(bd_avail_too_less_failures),
616                4, "bd_avail_too_less_failures"},
617    { Q_STATS_OFFSET32(tx_mq_not_empty),
618                4, "tx_mq_not_empty"}
619
620};
621
622#define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
623#define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
624
625
626static void    bxe_cmng_fns_init(struct bxe_softc *sc,
627                                 uint8_t          read_cfg,
628                                 uint8_t          cmng_type);
629static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
630static void    storm_memset_cmng(struct bxe_softc *sc,
631                                 struct cmng_init *cmng,
632                                 uint8_t          port);
633static void    bxe_set_reset_global(struct bxe_softc *sc);
634static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
635static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
636                                 int              engine);
637static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
638static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
639                                   uint8_t          *global,
640                                   uint8_t          print);
641static void    bxe_int_disable(struct bxe_softc *sc);
642static int     bxe_release_leader_lock(struct bxe_softc *sc);
643static void    bxe_pf_disable(struct bxe_softc *sc);
644static void    bxe_free_fp_buffers(struct bxe_softc *sc);
645static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
646                                      struct bxe_fastpath *fp,
647                                      uint16_t            rx_bd_prod,
648                                      uint16_t            rx_cq_prod,
649                                      uint16_t            rx_sge_prod);
650static void    bxe_link_report_locked(struct bxe_softc *sc);
651static void    bxe_link_report(struct bxe_softc *sc);
652static void    bxe_link_status_update(struct bxe_softc *sc);
653static void    bxe_periodic_callout_func(void *xsc);
654static void    bxe_periodic_start(struct bxe_softc *sc);
655static void    bxe_periodic_stop(struct bxe_softc *sc);
656static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
657                                    uint16_t prev_index,
658                                    uint16_t index);
659static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
660                                     int                 queue);
661static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
662                                     uint16_t            index);
663static uint8_t bxe_txeof(struct bxe_softc *sc,
664                         struct bxe_fastpath *fp);
665static void    bxe_task_fp(struct bxe_fastpath *fp);
666static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
667                                     struct mbuf      *m,
668                                     uint8_t          contents);
669static int     bxe_alloc_mem(struct bxe_softc *sc);
670static void    bxe_free_mem(struct bxe_softc *sc);
671static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
672static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
673static int     bxe_interrupt_attach(struct bxe_softc *sc);
674static void    bxe_interrupt_detach(struct bxe_softc *sc);
675static void    bxe_set_rx_mode(struct bxe_softc *sc);
676static int     bxe_init_locked(struct bxe_softc *sc);
677static int     bxe_stop_locked(struct bxe_softc *sc);
678static __noinline int bxe_nic_load(struct bxe_softc *sc,
679                                   int              load_mode);
680static __noinline int bxe_nic_unload(struct bxe_softc *sc,
681                                     uint32_t         unload_mode,
682                                     uint8_t          keep_link);
683
684static void bxe_handle_sp_tq(void *context, int pending);
685static void bxe_handle_fp_tq(void *context, int pending);
686
687static int bxe_add_cdev(struct bxe_softc *sc);
688static void bxe_del_cdev(struct bxe_softc *sc);
689static int bxe_alloc_buf_rings(struct bxe_softc *sc);
690static void bxe_free_buf_rings(struct bxe_softc *sc);
691
692/* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
693uint32_t
694calc_crc32(uint8_t  *crc32_packet,
695           uint32_t crc32_length,
696           uint32_t crc32_seed,
697           uint8_t  complement)
698{
699   uint32_t byte         = 0;
700   uint32_t bit          = 0;
701   uint8_t  msb          = 0;
702   uint32_t temp         = 0;
703   uint32_t shft         = 0;
704   uint8_t  current_byte = 0;
705   uint32_t crc32_result = crc32_seed;
706   const uint32_t CRC32_POLY = 0x1edc6f41;
707
708   if ((crc32_packet == NULL) ||
709       (crc32_length == 0) ||
710       ((crc32_length % 8) != 0))
711    {
712        return (crc32_result);
713    }
714
715    for (byte = 0; byte < crc32_length; byte = byte + 1)
716    {
717        current_byte = crc32_packet[byte];
718        for (bit = 0; bit < 8; bit = bit + 1)
719        {
720            /* msb = crc32_result[31]; */
721            msb = (uint8_t)(crc32_result >> 31);
722
723            crc32_result = crc32_result << 1;
724
725            /* it (msb != current_byte[bit]) */
726            if (msb != (0x1 & (current_byte >> bit)))
727            {
728                crc32_result = crc32_result ^ CRC32_POLY;
729                /* crc32_result[0] = 1 */
730                crc32_result |= 1;
731            }
732        }
733    }
734
735    /* Last step is to:
736     * 1. "mirror" every bit
737     * 2. swap the 4 bytes
738     * 3. complement each bit
739     */
740
741    /* Mirror */
742    temp = crc32_result;
743    shft = sizeof(crc32_result) * 8 - 1;
744
745    for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
746    {
747        temp <<= 1;
748        temp |= crc32_result & 1;
749        shft-- ;
750    }
751
752    /* temp[31-bit] = crc32_result[bit] */
753    temp <<= shft;
754
755    /* Swap */
756    /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
757    {
758        uint32_t t0, t1, t2, t3;
759        t0 = (0x000000ff & (temp >> 24));
760        t1 = (0x0000ff00 & (temp >> 8));
761        t2 = (0x00ff0000 & (temp << 8));
762        t3 = (0xff000000 & (temp << 24));
763        crc32_result = t0 | t1 | t2 | t3;
764    }
765
766    /* Complement */
767    if (complement)
768    {
769        crc32_result = ~crc32_result;
770    }
771
772    return (crc32_result);
773}
774
775int
776bxe_test_bit(int                    nr,
777             volatile unsigned long *addr)
778{
779    return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
780}
781
782void
783bxe_set_bit(unsigned int           nr,
784            volatile unsigned long *addr)
785{
786    atomic_set_acq_long(addr, (1 << nr));
787}
788
789void
790bxe_clear_bit(int                    nr,
791              volatile unsigned long *addr)
792{
793    atomic_clear_acq_long(addr, (1 << nr));
794}
795
796int
797bxe_test_and_set_bit(int                    nr,
798                       volatile unsigned long *addr)
799{
800    unsigned long x;
801    nr = (1 << nr);
802    do {
803        x = *addr;
804    } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
805    // if (x & nr) bit_was_set; else bit_was_not_set;
806    return (x & nr);
807}
808
809int
810bxe_test_and_clear_bit(int                    nr,
811                       volatile unsigned long *addr)
812{
813    unsigned long x;
814    nr = (1 << nr);
815    do {
816        x = *addr;
817    } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
818    // if (x & nr) bit_was_set; else bit_was_not_set;
819    return (x & nr);
820}
821
822int
823bxe_cmpxchg(volatile int *addr,
824            int          old,
825            int          new)
826{
827    int x;
828    do {
829        x = *addr;
830    } while (atomic_cmpset_acq_int(addr, old, new) == 0);
831    return (x);
832}
833
834/*
835 * Get DMA memory from the OS.
836 *
837 * Validates that the OS has provided DMA buffers in response to a
838 * bus_dmamap_load call and saves the physical address of those buffers.
839 * When the callback is used the OS will return 0 for the mapping function
840 * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
841 * failures back to the caller.
842 *
843 * Returns:
844 *   Nothing.
845 */
846static void
847bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
848{
849    struct bxe_dma *dma = arg;
850
851    if (error) {
852        dma->paddr = 0;
853        dma->nseg  = 0;
854        BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
855    } else {
856        dma->paddr = segs->ds_addr;
857        dma->nseg  = nseg;
858    }
859}
860
861/*
862 * Allocate a block of memory and map it for DMA. No partial completions
863 * allowed and release any resources acquired if we can't acquire all
864 * resources.
865 *
866 * Returns:
867 *   0 = Success, !0 = Failure
868 */
869int
870bxe_dma_alloc(struct bxe_softc *sc,
871              bus_size_t       size,
872              struct bxe_dma   *dma,
873              const char       *msg)
874{
875    int rc;
876
877    if (dma->size > 0) {
878        BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
879              (unsigned long)dma->size);
880        return (1);
881    }
882
883    memset(dma, 0, sizeof(*dma)); /* sanity */
884    dma->sc   = sc;
885    dma->size = size;
886    snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
887
888    rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
889                            BCM_PAGE_SIZE,      /* alignment */
890                            0,                  /* boundary limit */
891                            BUS_SPACE_MAXADDR,  /* restricted low */
892                            BUS_SPACE_MAXADDR,  /* restricted hi */
893                            NULL,               /* addr filter() */
894                            NULL,               /* addr filter() arg */
895                            size,               /* max map size */
896                            1,                  /* num discontinuous */
897                            size,               /* max seg size */
898                            BUS_DMA_ALLOCNOW,   /* flags */
899                            NULL,               /* lock() */
900                            NULL,               /* lock() arg */
901                            &dma->tag);         /* returned dma tag */
902    if (rc != 0) {
903        BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
904        memset(dma, 0, sizeof(*dma));
905        return (1);
906    }
907
908    rc = bus_dmamem_alloc(dma->tag,
909                          (void **)&dma->vaddr,
910                          (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
911                          &dma->map);
912    if (rc != 0) {
913        BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
914        bus_dma_tag_destroy(dma->tag);
915        memset(dma, 0, sizeof(*dma));
916        return (1);
917    }
918
919    rc = bus_dmamap_load(dma->tag,
920                         dma->map,
921                         dma->vaddr,
922                         size,
923                         bxe_dma_map_addr, /* BLOGD in here */
924                         dma,
925                         BUS_DMA_NOWAIT);
926    if (rc != 0) {
927        BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
928        bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
929        bus_dma_tag_destroy(dma->tag);
930        memset(dma, 0, sizeof(*dma));
931        return (1);
932    }
933
934    return (0);
935}
936
937void
938bxe_dma_free(struct bxe_softc *sc,
939             struct bxe_dma   *dma)
940{
941    if (dma->size > 0) {
942        DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
943
944        bus_dmamap_sync(dma->tag, dma->map,
945                        (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
946        bus_dmamap_unload(dma->tag, dma->map);
947        bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
948        bus_dma_tag_destroy(dma->tag);
949    }
950
951    memset(dma, 0, sizeof(*dma));
952}
953
954/*
955 * These indirect read and write routines are only during init.
956 * The locking is handled by the MCP.
957 */
958
959void
960bxe_reg_wr_ind(struct bxe_softc *sc,
961               uint32_t         addr,
962               uint32_t         val)
963{
964    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
965    pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
966    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
967}
968
969uint32_t
970bxe_reg_rd_ind(struct bxe_softc *sc,
971               uint32_t         addr)
972{
973    uint32_t val;
974
975    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
976    val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
977    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
978
979    return (val);
980}
981
982static int
983bxe_acquire_hw_lock(struct bxe_softc *sc,
984                    uint32_t         resource)
985{
986    uint32_t lock_status;
987    uint32_t resource_bit = (1 << resource);
988    int func = SC_FUNC(sc);
989    uint32_t hw_lock_control_reg;
990    int cnt;
991
992    /* validate the resource is within range */
993    if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
994        BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
995            " resource_bit 0x%x\n", resource, resource_bit);
996        return (-1);
997    }
998
999    if (func <= 5) {
1000        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1001    } else {
1002        hw_lock_control_reg =
1003                (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1004    }
1005
1006    /* validate the resource is not already taken */
1007    lock_status = REG_RD(sc, hw_lock_control_reg);
1008    if (lock_status & resource_bit) {
1009        BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1010              resource, lock_status, resource_bit);
1011        return (-1);
1012    }
1013
1014    /* try every 5ms for 5 seconds */
1015    for (cnt = 0; cnt < 1000; cnt++) {
1016        REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1017        lock_status = REG_RD(sc, hw_lock_control_reg);
1018        if (lock_status & resource_bit) {
1019            return (0);
1020        }
1021        DELAY(5000);
1022    }
1023
1024    BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1025        resource, resource_bit);
1026    return (-1);
1027}
1028
1029static int
1030bxe_release_hw_lock(struct bxe_softc *sc,
1031                    uint32_t         resource)
1032{
1033    uint32_t lock_status;
1034    uint32_t resource_bit = (1 << resource);
1035    int func = SC_FUNC(sc);
1036    uint32_t hw_lock_control_reg;
1037
1038    /* validate the resource is within range */
1039    if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1040        BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1041            " resource_bit 0x%x\n", resource, resource_bit);
1042        return (-1);
1043    }
1044
1045    if (func <= 5) {
1046        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1047    } else {
1048        hw_lock_control_reg =
1049                (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1050    }
1051
1052    /* validate the resource is currently taken */
1053    lock_status = REG_RD(sc, hw_lock_control_reg);
1054    if (!(lock_status & resource_bit)) {
1055        BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1056              resource, lock_status, resource_bit);
1057        return (-1);
1058    }
1059
1060    REG_WR(sc, hw_lock_control_reg, resource_bit);
1061    return (0);
1062}
1063static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1064{
1065	BXE_PHY_LOCK(sc);
1066	bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1067}
1068
1069static void bxe_release_phy_lock(struct bxe_softc *sc)
1070{
1071	bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1072	BXE_PHY_UNLOCK(sc);
1073}
1074/*
1075 * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1076 * had we done things the other way around, if two pfs from the same port
1077 * would attempt to access nvram at the same time, we could run into a
1078 * scenario such as:
1079 * pf A takes the port lock.
1080 * pf B succeeds in taking the same lock since they are from the same port.
1081 * pf A takes the per pf misc lock. Performs eeprom access.
1082 * pf A finishes. Unlocks the per pf misc lock.
1083 * Pf B takes the lock and proceeds to perform it's own access.
1084 * pf A unlocks the per port lock, while pf B is still working (!).
1085 * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1086 * access corrupted by pf B).*
1087 */
1088static int
1089bxe_acquire_nvram_lock(struct bxe_softc *sc)
1090{
1091    int port = SC_PORT(sc);
1092    int count, i;
1093    uint32_t val = 0;
1094
1095    /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1096    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1097
1098    /* adjust timeout for emulation/FPGA */
1099    count = NVRAM_TIMEOUT_COUNT;
1100    if (CHIP_REV_IS_SLOW(sc)) {
1101        count *= 100;
1102    }
1103
1104    /* request access to nvram interface */
1105    REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1106           (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1107
1108    for (i = 0; i < count*10; i++) {
1109        val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1110        if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1111            break;
1112        }
1113
1114        DELAY(5);
1115    }
1116
1117    if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1118        BLOGE(sc, "Cannot get access to nvram interface "
1119            "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1120            port, val);
1121        return (-1);
1122    }
1123
1124    return (0);
1125}
1126
1127static int
1128bxe_release_nvram_lock(struct bxe_softc *sc)
1129{
1130    int port = SC_PORT(sc);
1131    int count, i;
1132    uint32_t val = 0;
1133
1134    /* adjust timeout for emulation/FPGA */
1135    count = NVRAM_TIMEOUT_COUNT;
1136    if (CHIP_REV_IS_SLOW(sc)) {
1137        count *= 100;
1138    }
1139
1140    /* relinquish nvram interface */
1141    REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1142           (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1143
1144    for (i = 0; i < count*10; i++) {
1145        val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1146        if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1147            break;
1148        }
1149
1150        DELAY(5);
1151    }
1152
1153    if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1154        BLOGE(sc, "Cannot free access to nvram interface "
1155            "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1156            port, val);
1157        return (-1);
1158    }
1159
1160    /* release HW lock: protect against other PFs in PF Direct Assignment */
1161    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1162
1163    return (0);
1164}
1165
1166static void
1167bxe_enable_nvram_access(struct bxe_softc *sc)
1168{
1169    uint32_t val;
1170
1171    val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1172
1173    /* enable both bits, even on read */
1174    REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1175           (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1176}
1177
1178static void
1179bxe_disable_nvram_access(struct bxe_softc *sc)
1180{
1181    uint32_t val;
1182
1183    val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1184
1185    /* disable both bits, even after read */
1186    REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1187           (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1188                    MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1189}
1190
1191static int
1192bxe_nvram_read_dword(struct bxe_softc *sc,
1193                     uint32_t         offset,
1194                     uint32_t         *ret_val,
1195                     uint32_t         cmd_flags)
1196{
1197    int count, i, rc;
1198    uint32_t val;
1199
1200    /* build the command word */
1201    cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1202
1203    /* need to clear DONE bit separately */
1204    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1205
1206    /* address of the NVRAM to read from */
1207    REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1208           (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1209
1210    /* issue a read command */
1211    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1212
1213    /* adjust timeout for emulation/FPGA */
1214    count = NVRAM_TIMEOUT_COUNT;
1215    if (CHIP_REV_IS_SLOW(sc)) {
1216        count *= 100;
1217    }
1218
1219    /* wait for completion */
1220    *ret_val = 0;
1221    rc = -1;
1222    for (i = 0; i < count; i++) {
1223        DELAY(5);
1224        val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1225
1226        if (val & MCPR_NVM_COMMAND_DONE) {
1227            val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1228            /* we read nvram data in cpu order
1229             * but ethtool sees it as an array of bytes
1230             * converting to big-endian will do the work
1231             */
1232            *ret_val = htobe32(val);
1233            rc = 0;
1234            break;
1235        }
1236    }
1237
1238    if (rc == -1) {
1239        BLOGE(sc, "nvram read timeout expired "
1240            "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1241            offset, cmd_flags, val);
1242    }
1243
1244    return (rc);
1245}
1246
1247static int
1248bxe_nvram_read(struct bxe_softc *sc,
1249               uint32_t         offset,
1250               uint8_t          *ret_buf,
1251               int              buf_size)
1252{
1253    uint32_t cmd_flags;
1254    uint32_t val;
1255    int rc;
1256
1257    if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1258        BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1259              offset, buf_size);
1260        return (-1);
1261    }
1262
1263    if ((offset + buf_size) > sc->devinfo.flash_size) {
1264        BLOGE(sc, "Invalid parameter, "
1265                  "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1266              offset, buf_size, sc->devinfo.flash_size);
1267        return (-1);
1268    }
1269
1270    /* request access to nvram interface */
1271    rc = bxe_acquire_nvram_lock(sc);
1272    if (rc) {
1273        return (rc);
1274    }
1275
1276    /* enable access to nvram interface */
1277    bxe_enable_nvram_access(sc);
1278
1279    /* read the first word(s) */
1280    cmd_flags = MCPR_NVM_COMMAND_FIRST;
1281    while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1282        rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1283        memcpy(ret_buf, &val, 4);
1284
1285        /* advance to the next dword */
1286        offset += sizeof(uint32_t);
1287        ret_buf += sizeof(uint32_t);
1288        buf_size -= sizeof(uint32_t);
1289        cmd_flags = 0;
1290    }
1291
1292    if (rc == 0) {
1293        cmd_flags |= MCPR_NVM_COMMAND_LAST;
1294        rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1295        memcpy(ret_buf, &val, 4);
1296    }
1297
1298    /* disable access to nvram interface */
1299    bxe_disable_nvram_access(sc);
1300    bxe_release_nvram_lock(sc);
1301
1302    return (rc);
1303}
1304
1305static int
1306bxe_nvram_write_dword(struct bxe_softc *sc,
1307                      uint32_t         offset,
1308                      uint32_t         val,
1309                      uint32_t         cmd_flags)
1310{
1311    int count, i, rc;
1312
1313    /* build the command word */
1314    cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1315
1316    /* need to clear DONE bit separately */
1317    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1318
1319    /* write the data */
1320    REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1321
1322    /* address of the NVRAM to write to */
1323    REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1324           (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1325
1326    /* issue the write command */
1327    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1328
1329    /* adjust timeout for emulation/FPGA */
1330    count = NVRAM_TIMEOUT_COUNT;
1331    if (CHIP_REV_IS_SLOW(sc)) {
1332        count *= 100;
1333    }
1334
1335    /* wait for completion */
1336    rc = -1;
1337    for (i = 0; i < count; i++) {
1338        DELAY(5);
1339        val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1340        if (val & MCPR_NVM_COMMAND_DONE) {
1341            rc = 0;
1342            break;
1343        }
1344    }
1345
1346    if (rc == -1) {
1347        BLOGE(sc, "nvram write timeout expired "
1348            "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1349            offset, cmd_flags, val);
1350    }
1351
1352    return (rc);
1353}
1354
1355#define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1356
1357static int
1358bxe_nvram_write1(struct bxe_softc *sc,
1359                 uint32_t         offset,
1360                 uint8_t          *data_buf,
1361                 int              buf_size)
1362{
1363    uint32_t cmd_flags;
1364    uint32_t align_offset;
1365    uint32_t val;
1366    int rc;
1367
1368    if ((offset + buf_size) > sc->devinfo.flash_size) {
1369        BLOGE(sc, "Invalid parameter, "
1370                  "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1371              offset, buf_size, sc->devinfo.flash_size);
1372        return (-1);
1373    }
1374
1375    /* request access to nvram interface */
1376    rc = bxe_acquire_nvram_lock(sc);
1377    if (rc) {
1378        return (rc);
1379    }
1380
1381    /* enable access to nvram interface */
1382    bxe_enable_nvram_access(sc);
1383
1384    cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1385    align_offset = (offset & ~0x03);
1386    rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1387
1388    if (rc == 0) {
1389        val &= ~(0xff << BYTE_OFFSET(offset));
1390        val |= (*data_buf << BYTE_OFFSET(offset));
1391
1392        /* nvram data is returned as an array of bytes
1393         * convert it back to cpu order
1394         */
1395        val = be32toh(val);
1396
1397        rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1398    }
1399
1400    /* disable access to nvram interface */
1401    bxe_disable_nvram_access(sc);
1402    bxe_release_nvram_lock(sc);
1403
1404    return (rc);
1405}
1406
1407static int
1408bxe_nvram_write(struct bxe_softc *sc,
1409                uint32_t         offset,
1410                uint8_t          *data_buf,
1411                int              buf_size)
1412{
1413    uint32_t cmd_flags;
1414    uint32_t val;
1415    uint32_t written_so_far;
1416    int rc;
1417
1418    if (buf_size == 1) {
1419        return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1420    }
1421
1422    if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1423        BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1424              offset, buf_size);
1425        return (-1);
1426    }
1427
1428    if (buf_size == 0) {
1429        return (0); /* nothing to do */
1430    }
1431
1432    if ((offset + buf_size) > sc->devinfo.flash_size) {
1433        BLOGE(sc, "Invalid parameter, "
1434                  "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1435              offset, buf_size, sc->devinfo.flash_size);
1436        return (-1);
1437    }
1438
1439    /* request access to nvram interface */
1440    rc = bxe_acquire_nvram_lock(sc);
1441    if (rc) {
1442        return (rc);
1443    }
1444
1445    /* enable access to nvram interface */
1446    bxe_enable_nvram_access(sc);
1447
1448    written_so_far = 0;
1449    cmd_flags = MCPR_NVM_COMMAND_FIRST;
1450    while ((written_so_far < buf_size) && (rc == 0)) {
1451        if (written_so_far == (buf_size - sizeof(uint32_t))) {
1452            cmd_flags |= MCPR_NVM_COMMAND_LAST;
1453        } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1454            cmd_flags |= MCPR_NVM_COMMAND_LAST;
1455        } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1456            cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1457        }
1458
1459        memcpy(&val, data_buf, 4);
1460
1461        rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1462
1463        /* advance to the next dword */
1464        offset += sizeof(uint32_t);
1465        data_buf += sizeof(uint32_t);
1466        written_so_far += sizeof(uint32_t);
1467        cmd_flags = 0;
1468    }
1469
1470    /* disable access to nvram interface */
1471    bxe_disable_nvram_access(sc);
1472    bxe_release_nvram_lock(sc);
1473
1474    return (rc);
1475}
1476
1477/* copy command into DMAE command memory and set DMAE command Go */
1478void
1479bxe_post_dmae(struct bxe_softc    *sc,
1480              struct dmae_cmd *dmae,
1481              int                 idx)
1482{
1483    uint32_t cmd_offset;
1484    int i;
1485
1486    cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1487    for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1488        REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1489    }
1490
1491    REG_WR(sc, dmae_reg_go_c[idx], 1);
1492}
1493
1494uint32_t
1495bxe_dmae_opcode_add_comp(uint32_t opcode,
1496                         uint8_t  comp_type)
1497{
1498    return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1499                      DMAE_CMD_C_TYPE_ENABLE));
1500}
1501
1502uint32_t
1503bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1504{
1505    return (opcode & ~DMAE_CMD_SRC_RESET);
1506}
1507
1508uint32_t
1509bxe_dmae_opcode(struct bxe_softc *sc,
1510                uint8_t          src_type,
1511                uint8_t          dst_type,
1512                uint8_t          with_comp,
1513                uint8_t          comp_type)
1514{
1515    uint32_t opcode = 0;
1516
1517    opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1518               (dst_type << DMAE_CMD_DST_SHIFT));
1519
1520    opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1521
1522    opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1523
1524    opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1525               (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1526
1527    opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1528
1529#ifdef __BIG_ENDIAN
1530    opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1531#else
1532    opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1533#endif
1534
1535    if (with_comp) {
1536        opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1537    }
1538
1539    return (opcode);
1540}
1541
1542static void
1543bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1544                        struct dmae_cmd *dmae,
1545                        uint8_t             src_type,
1546                        uint8_t             dst_type)
1547{
1548    memset(dmae, 0, sizeof(struct dmae_cmd));
1549
1550    /* set the opcode */
1551    dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1552                                   TRUE, DMAE_COMP_PCI);
1553
1554    /* fill in the completion parameters */
1555    dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1556    dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1557    dmae->comp_val     = DMAE_COMP_VAL;
1558}
1559
1560/* issue a DMAE command over the init channel and wait for completion */
1561static int
1562bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1563                         struct dmae_cmd *dmae)
1564{
1565    uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1566    int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1567
1568    BXE_DMAE_LOCK(sc);
1569
1570    /* reset completion */
1571    *wb_comp = 0;
1572
1573    /* post the command on the channel used for initializations */
1574    bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1575
1576    /* wait for completion */
1577    DELAY(5);
1578
1579    while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1580        if (!timeout ||
1581            (sc->recovery_state != BXE_RECOVERY_DONE &&
1582             sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1583            BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1584                *wb_comp, sc->recovery_state);
1585            BXE_DMAE_UNLOCK(sc);
1586            return (DMAE_TIMEOUT);
1587        }
1588
1589        timeout--;
1590        DELAY(50);
1591    }
1592
1593    if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1594        BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1595                *wb_comp, sc->recovery_state);
1596        BXE_DMAE_UNLOCK(sc);
1597        return (DMAE_PCI_ERROR);
1598    }
1599
1600    BXE_DMAE_UNLOCK(sc);
1601    return (0);
1602}
1603
1604void
1605bxe_read_dmae(struct bxe_softc *sc,
1606              uint32_t         src_addr,
1607              uint32_t         len32)
1608{
1609    struct dmae_cmd dmae;
1610    uint32_t *data;
1611    int i, rc;
1612
1613    DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1614
1615    if (!sc->dmae_ready) {
1616        data = BXE_SP(sc, wb_data[0]);
1617
1618        for (i = 0; i < len32; i++) {
1619            data[i] = (CHIP_IS_E1(sc)) ?
1620                          bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1621                          REG_RD(sc, (src_addr + (i * 4)));
1622        }
1623
1624        return;
1625    }
1626
1627    /* set opcode and fixed command fields */
1628    bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1629
1630    /* fill in addresses and len */
1631    dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1632    dmae.src_addr_hi = 0;
1633    dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1634    dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1635    dmae.len         = len32;
1636
1637    /* issue the command and wait for completion */
1638    if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1639        bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1640    }
1641}
1642
1643void
1644bxe_write_dmae(struct bxe_softc *sc,
1645               bus_addr_t       dma_addr,
1646               uint32_t         dst_addr,
1647               uint32_t         len32)
1648{
1649    struct dmae_cmd dmae;
1650    int rc;
1651
1652    if (!sc->dmae_ready) {
1653        DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1654
1655        if (CHIP_IS_E1(sc)) {
1656            ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1657        } else {
1658            ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1659        }
1660
1661        return;
1662    }
1663
1664    /* set opcode and fixed command fields */
1665    bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1666
1667    /* fill in addresses and len */
1668    dmae.src_addr_lo = U64_LO(dma_addr);
1669    dmae.src_addr_hi = U64_HI(dma_addr);
1670    dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1671    dmae.dst_addr_hi = 0;
1672    dmae.len         = len32;
1673
1674    /* issue the command and wait for completion */
1675    if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1676        bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1677    }
1678}
1679
1680void
1681bxe_write_dmae_phys_len(struct bxe_softc *sc,
1682                        bus_addr_t       phys_addr,
1683                        uint32_t         addr,
1684                        uint32_t         len)
1685{
1686    int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1687    int offset = 0;
1688
1689    while (len > dmae_wr_max) {
1690        bxe_write_dmae(sc,
1691                       (phys_addr + offset), /* src DMA address */
1692                       (addr + offset),      /* dst GRC address */
1693                       dmae_wr_max);
1694        offset += (dmae_wr_max * 4);
1695        len -= dmae_wr_max;
1696    }
1697
1698    bxe_write_dmae(sc,
1699                   (phys_addr + offset), /* src DMA address */
1700                   (addr + offset),      /* dst GRC address */
1701                   len);
1702}
1703
1704void
1705bxe_set_ctx_validation(struct bxe_softc   *sc,
1706                       struct eth_context *cxt,
1707                       uint32_t           cid)
1708{
1709    /* ustorm cxt validation */
1710    cxt->ustorm_ag_context.cdu_usage =
1711        CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1712            CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1713    /* xcontext validation */
1714    cxt->xstorm_ag_context.cdu_reserved =
1715        CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1716            CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1717}
1718
1719static void
1720bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1721                            uint8_t          port,
1722                            uint8_t          fw_sb_id,
1723                            uint8_t          sb_index,
1724                            uint8_t          ticks)
1725{
1726    uint32_t addr =
1727        (BAR_CSTRORM_INTMEM +
1728         CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1729
1730    REG_WR8(sc, addr, ticks);
1731
1732    BLOGD(sc, DBG_LOAD,
1733          "port %d fw_sb_id %d sb_index %d ticks %d\n",
1734          port, fw_sb_id, sb_index, ticks);
1735}
1736
1737static void
1738bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1739                            uint8_t          port,
1740                            uint16_t         fw_sb_id,
1741                            uint8_t          sb_index,
1742                            uint8_t          disable)
1743{
1744    uint32_t enable_flag =
1745        (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1746    uint32_t addr =
1747        (BAR_CSTRORM_INTMEM +
1748         CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1749    uint8_t flags;
1750
1751    /* clear and set */
1752    flags = REG_RD8(sc, addr);
1753    flags &= ~HC_INDEX_DATA_HC_ENABLED;
1754    flags |= enable_flag;
1755    REG_WR8(sc, addr, flags);
1756
1757    BLOGD(sc, DBG_LOAD,
1758          "port %d fw_sb_id %d sb_index %d disable %d\n",
1759          port, fw_sb_id, sb_index, disable);
1760}
1761
1762void
1763bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1764                             uint8_t          fw_sb_id,
1765                             uint8_t          sb_index,
1766                             uint8_t          disable,
1767                             uint16_t         usec)
1768{
1769    int port = SC_PORT(sc);
1770    uint8_t ticks = (usec / 4); /* XXX ??? */
1771
1772    bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1773
1774    disable = (disable) ? 1 : ((usec) ? 0 : 1);
1775    bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1776}
1777
1778void
1779elink_cb_udelay(struct bxe_softc *sc,
1780                uint32_t         usecs)
1781{
1782    DELAY(usecs);
1783}
1784
1785uint32_t
1786elink_cb_reg_read(struct bxe_softc *sc,
1787                  uint32_t         reg_addr)
1788{
1789    return (REG_RD(sc, reg_addr));
1790}
1791
1792void
1793elink_cb_reg_write(struct bxe_softc *sc,
1794                   uint32_t         reg_addr,
1795                   uint32_t         val)
1796{
1797    REG_WR(sc, reg_addr, val);
1798}
1799
1800void
1801elink_cb_reg_wb_write(struct bxe_softc *sc,
1802                      uint32_t         offset,
1803                      uint32_t         *wb_write,
1804                      uint16_t         len)
1805{
1806    REG_WR_DMAE(sc, offset, wb_write, len);
1807}
1808
1809void
1810elink_cb_reg_wb_read(struct bxe_softc *sc,
1811                     uint32_t         offset,
1812                     uint32_t         *wb_write,
1813                     uint16_t         len)
1814{
1815    REG_RD_DMAE(sc, offset, wb_write, len);
1816}
1817
1818uint8_t
1819elink_cb_path_id(struct bxe_softc *sc)
1820{
1821    return (SC_PATH(sc));
1822}
1823
1824void
1825elink_cb_event_log(struct bxe_softc     *sc,
1826                   const elink_log_id_t elink_log_id,
1827                   ...)
1828{
1829    /* XXX */
1830    BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1831}
1832
1833static int
1834bxe_set_spio(struct bxe_softc *sc,
1835             int              spio,
1836             uint32_t         mode)
1837{
1838    uint32_t spio_reg;
1839
1840    /* Only 2 SPIOs are configurable */
1841    if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1842        BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1843        return (-1);
1844    }
1845
1846    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1847
1848    /* read SPIO and mask except the float bits */
1849    spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1850
1851    switch (mode) {
1852    case MISC_SPIO_OUTPUT_LOW:
1853        BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1854        /* clear FLOAT and set CLR */
1855        spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1856        spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1857        break;
1858
1859    case MISC_SPIO_OUTPUT_HIGH:
1860        BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1861        /* clear FLOAT and set SET */
1862        spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1863        spio_reg |=  (spio << MISC_SPIO_SET_POS);
1864        break;
1865
1866    case MISC_SPIO_INPUT_HI_Z:
1867        BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1868        /* set FLOAT */
1869        spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1870        break;
1871
1872    default:
1873        break;
1874    }
1875
1876    REG_WR(sc, MISC_REG_SPIO, spio_reg);
1877    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1878
1879    return (0);
1880}
1881
1882static int
1883bxe_gpio_read(struct bxe_softc *sc,
1884              int              gpio_num,
1885              uint8_t          port)
1886{
1887    /* The GPIO should be swapped if swap register is set and active */
1888    int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1889                      REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1890    int gpio_shift = (gpio_num +
1891                      (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1892    uint32_t gpio_mask = (1 << gpio_shift);
1893    uint32_t gpio_reg;
1894
1895    if (gpio_num > MISC_REGISTERS_GPIO_3) {
1896        BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1897            " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1898            gpio_mask);
1899        return (-1);
1900    }
1901
1902    /* read GPIO value */
1903    gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1904
1905    /* get the requested pin value */
1906    return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1907}
1908
1909static int
1910bxe_gpio_write(struct bxe_softc *sc,
1911               int              gpio_num,
1912               uint32_t         mode,
1913               uint8_t          port)
1914{
1915    /* The GPIO should be swapped if swap register is set and active */
1916    int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1917                      REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1918    int gpio_shift = (gpio_num +
1919                      (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1920    uint32_t gpio_mask = (1 << gpio_shift);
1921    uint32_t gpio_reg;
1922
1923    if (gpio_num > MISC_REGISTERS_GPIO_3) {
1924        BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1925            " gpio_shift %d gpio_mask 0x%x\n",
1926            gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1927        return (-1);
1928    }
1929
1930    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1931
1932    /* read GPIO and mask except the float bits */
1933    gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1934
1935    switch (mode) {
1936    case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1937        BLOGD(sc, DBG_PHY,
1938              "Set GPIO %d (shift %d) -> output low\n",
1939              gpio_num, gpio_shift);
1940        /* clear FLOAT and set CLR */
1941        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1942        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1943        break;
1944
1945    case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1946        BLOGD(sc, DBG_PHY,
1947              "Set GPIO %d (shift %d) -> output high\n",
1948              gpio_num, gpio_shift);
1949        /* clear FLOAT and set SET */
1950        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1951        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1952        break;
1953
1954    case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1955        BLOGD(sc, DBG_PHY,
1956              "Set GPIO %d (shift %d) -> input\n",
1957              gpio_num, gpio_shift);
1958        /* set FLOAT */
1959        gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1960        break;
1961
1962    default:
1963        break;
1964    }
1965
1966    REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1967    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1968
1969    return (0);
1970}
1971
1972static int
1973bxe_gpio_mult_write(struct bxe_softc *sc,
1974                    uint8_t          pins,
1975                    uint32_t         mode)
1976{
1977    uint32_t gpio_reg;
1978
1979    /* any port swapping should be handled by caller */
1980
1981    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1982
1983    /* read GPIO and mask except the float bits */
1984    gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1985    gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1986    gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
1987    gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
1988
1989    switch (mode) {
1990    case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1991        BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
1992        /* set CLR */
1993        gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
1994        break;
1995
1996    case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1997        BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
1998        /* set SET */
1999        gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2000        break;
2001
2002    case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2003        BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2004        /* set FLOAT */
2005        gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2006        break;
2007
2008    default:
2009        BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2010            " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2011        bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2012        return (-1);
2013    }
2014
2015    REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2016    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2017
2018    return (0);
2019}
2020
2021static int
2022bxe_gpio_int_write(struct bxe_softc *sc,
2023                   int              gpio_num,
2024                   uint32_t         mode,
2025                   uint8_t          port)
2026{
2027    /* The GPIO should be swapped if swap register is set and active */
2028    int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2029                      REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2030    int gpio_shift = (gpio_num +
2031                      (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2032    uint32_t gpio_mask = (1 << gpio_shift);
2033    uint32_t gpio_reg;
2034
2035    if (gpio_num > MISC_REGISTERS_GPIO_3) {
2036        BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2037            " gpio_shift %d gpio_mask 0x%x\n",
2038            gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2039        return (-1);
2040    }
2041
2042    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2043
2044    /* read GPIO int */
2045    gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2046
2047    switch (mode) {
2048    case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2049        BLOGD(sc, DBG_PHY,
2050              "Clear GPIO INT %d (shift %d) -> output low\n",
2051              gpio_num, gpio_shift);
2052        /* clear SET and set CLR */
2053        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2054        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2055        break;
2056
2057    case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2058        BLOGD(sc, DBG_PHY,
2059              "Set GPIO INT %d (shift %d) -> output high\n",
2060              gpio_num, gpio_shift);
2061        /* clear CLR and set SET */
2062        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2063        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2064        break;
2065
2066    default:
2067        break;
2068    }
2069
2070    REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2071    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2072
2073    return (0);
2074}
2075
2076uint32_t
2077elink_cb_gpio_read(struct bxe_softc *sc,
2078                   uint16_t         gpio_num,
2079                   uint8_t          port)
2080{
2081    return (bxe_gpio_read(sc, gpio_num, port));
2082}
2083
2084uint8_t
2085elink_cb_gpio_write(struct bxe_softc *sc,
2086                    uint16_t         gpio_num,
2087                    uint8_t          mode, /* 0=low 1=high */
2088                    uint8_t          port)
2089{
2090    return (bxe_gpio_write(sc, gpio_num, mode, port));
2091}
2092
2093uint8_t
2094elink_cb_gpio_mult_write(struct bxe_softc *sc,
2095                         uint8_t          pins,
2096                         uint8_t          mode) /* 0=low 1=high */
2097{
2098    return (bxe_gpio_mult_write(sc, pins, mode));
2099}
2100
2101uint8_t
2102elink_cb_gpio_int_write(struct bxe_softc *sc,
2103                        uint16_t         gpio_num,
2104                        uint8_t          mode, /* 0=low 1=high */
2105                        uint8_t          port)
2106{
2107    return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2108}
2109
2110void
2111elink_cb_notify_link_changed(struct bxe_softc *sc)
2112{
2113    REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2114                (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2115}
2116
2117/* send the MCP a request, block until there is a reply */
2118uint32_t
2119elink_cb_fw_command(struct bxe_softc *sc,
2120                    uint32_t         command,
2121                    uint32_t         param)
2122{
2123    int mb_idx = SC_FW_MB_IDX(sc);
2124    uint32_t seq;
2125    uint32_t rc = 0;
2126    uint32_t cnt = 1;
2127    uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2128
2129    BXE_FWMB_LOCK(sc);
2130
2131    seq = ++sc->fw_seq;
2132    SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2133    SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2134
2135    BLOGD(sc, DBG_PHY,
2136          "wrote command 0x%08x to FW MB param 0x%08x\n",
2137          (command | seq), param);
2138
2139    /* Let the FW do it's magic. GIve it up to 5 seconds... */
2140    do {
2141        DELAY(delay * 1000);
2142        rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2143    } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2144
2145    BLOGD(sc, DBG_PHY,
2146          "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2147          cnt*delay, rc, seq);
2148
2149    /* is this a reply to our command? */
2150    if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2151        rc &= FW_MSG_CODE_MASK;
2152    } else {
2153        /* Ruh-roh! */
2154        BLOGE(sc, "FW failed to respond!\n");
2155        // XXX bxe_fw_dump(sc);
2156        rc = 0;
2157    }
2158
2159    BXE_FWMB_UNLOCK(sc);
2160    return (rc);
2161}
2162
2163static uint32_t
2164bxe_fw_command(struct bxe_softc *sc,
2165               uint32_t         command,
2166               uint32_t         param)
2167{
2168    return (elink_cb_fw_command(sc, command, param));
2169}
2170
2171static void
2172__storm_memset_dma_mapping(struct bxe_softc *sc,
2173                           uint32_t         addr,
2174                           bus_addr_t       mapping)
2175{
2176    REG_WR(sc, addr, U64_LO(mapping));
2177    REG_WR(sc, (addr + 4), U64_HI(mapping));
2178}
2179
2180static void
2181storm_memset_spq_addr(struct bxe_softc *sc,
2182                      bus_addr_t       mapping,
2183                      uint16_t         abs_fid)
2184{
2185    uint32_t addr = (XSEM_REG_FAST_MEMORY +
2186                     XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2187    __storm_memset_dma_mapping(sc, addr, mapping);
2188}
2189
2190static void
2191storm_memset_vf_to_pf(struct bxe_softc *sc,
2192                      uint16_t         abs_fid,
2193                      uint16_t         pf_id)
2194{
2195    REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2196    REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2197    REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2198    REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2199}
2200
2201static void
2202storm_memset_func_en(struct bxe_softc *sc,
2203                     uint16_t         abs_fid,
2204                     uint8_t          enable)
2205{
2206    REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2207    REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2208    REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2209    REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2210}
2211
2212static void
2213storm_memset_eq_data(struct bxe_softc       *sc,
2214                     struct event_ring_data *eq_data,
2215                     uint16_t               pfid)
2216{
2217    uint32_t addr;
2218    size_t size;
2219
2220    addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2221    size = sizeof(struct event_ring_data);
2222    ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2223}
2224
2225static void
2226storm_memset_eq_prod(struct bxe_softc *sc,
2227                     uint16_t         eq_prod,
2228                     uint16_t         pfid)
2229{
2230    uint32_t addr = (BAR_CSTRORM_INTMEM +
2231                     CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2232    REG_WR16(sc, addr, eq_prod);
2233}
2234
2235/*
2236 * Post a slowpath command.
2237 *
2238 * A slowpath command is used to propagate a configuration change through
2239 * the controller in a controlled manner, allowing each STORM processor and
2240 * other H/W blocks to phase in the change.  The commands sent on the
2241 * slowpath are referred to as ramrods.  Depending on the ramrod used the
2242 * completion of the ramrod will occur in different ways.  Here's a
2243 * breakdown of ramrods and how they complete:
2244 *
2245 * RAMROD_CMD_ID_ETH_PORT_SETUP
2246 *   Used to setup the leading connection on a port.  Completes on the
2247 *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2248 *
2249 * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2250 *   Used to setup an additional connection on a port.  Completes on the
2251 *   RCQ of the multi-queue/RSS connection being initialized.
2252 *
2253 * RAMROD_CMD_ID_ETH_STAT_QUERY
2254 *   Used to force the storm processors to update the statistics database
2255 *   in host memory.  This ramrod is send on the leading connection CID and
2256 *   completes as an index increment of the CSTORM on the default status
2257 *   block.
2258 *
2259 * RAMROD_CMD_ID_ETH_UPDATE
2260 *   Used to update the state of the leading connection, usually to udpate
2261 *   the RSS indirection table.  Completes on the RCQ of the leading
2262 *   connection. (Not currently used under FreeBSD until OS support becomes
2263 *   available.)
2264 *
2265 * RAMROD_CMD_ID_ETH_HALT
2266 *   Used when tearing down a connection prior to driver unload.  Completes
2267 *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2268 *   use this on the leading connection.
2269 *
2270 * RAMROD_CMD_ID_ETH_SET_MAC
2271 *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2272 *   the RCQ of the leading connection.
2273 *
2274 * RAMROD_CMD_ID_ETH_CFC_DEL
2275 *   Used when tearing down a conneciton prior to driver unload.  Completes
2276 *   on the RCQ of the leading connection (since the current connection
2277 *   has been completely removed from controller memory).
2278 *
2279 * RAMROD_CMD_ID_ETH_PORT_DEL
2280 *   Used to tear down the leading connection prior to driver unload,
2281 *   typically fp[0].  Completes as an index increment of the CSTORM on the
2282 *   default status block.
2283 *
2284 * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2285 *   Used for connection offload.  Completes on the RCQ of the multi-queue
2286 *   RSS connection that is being offloaded.  (Not currently used under
2287 *   FreeBSD.)
2288 *
2289 * There can only be one command pending per function.
2290 *
2291 * Returns:
2292 *   0 = Success, !0 = Failure.
2293 */
2294
2295/* must be called under the spq lock */
2296static inline
2297struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2298{
2299    struct eth_spe *next_spe = sc->spq_prod_bd;
2300
2301    if (sc->spq_prod_bd == sc->spq_last_bd) {
2302        /* wrap back to the first eth_spq */
2303        sc->spq_prod_bd = sc->spq;
2304        sc->spq_prod_idx = 0;
2305    } else {
2306        sc->spq_prod_bd++;
2307        sc->spq_prod_idx++;
2308    }
2309
2310    return (next_spe);
2311}
2312
2313/* must be called under the spq lock */
2314static inline
2315void bxe_sp_prod_update(struct bxe_softc *sc)
2316{
2317    int func = SC_FUNC(sc);
2318
2319    /*
2320     * Make sure that BD data is updated before writing the producer.
2321     * BD data is written to the memory, the producer is read from the
2322     * memory, thus we need a full memory barrier to ensure the ordering.
2323     */
2324    mb();
2325
2326    REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2327             sc->spq_prod_idx);
2328
2329    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2330                      BUS_SPACE_BARRIER_WRITE);
2331}
2332
2333/**
2334 * bxe_is_contextless_ramrod - check if the current command ends on EQ
2335 *
2336 * @cmd:      command to check
2337 * @cmd_type: command type
2338 */
2339static inline
2340int bxe_is_contextless_ramrod(int cmd,
2341                              int cmd_type)
2342{
2343    if ((cmd_type == NONE_CONNECTION_TYPE) ||
2344        (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2345        (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2346        (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2347        (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2348        (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2349        (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2350        return (TRUE);
2351    } else {
2352        return (FALSE);
2353    }
2354}
2355
2356/**
2357 * bxe_sp_post - place a single command on an SP ring
2358 *
2359 * @sc:         driver handle
2360 * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2361 * @cid:        SW CID the command is related to
2362 * @data_hi:    command private data address (high 32 bits)
2363 * @data_lo:    command private data address (low 32 bits)
2364 * @cmd_type:   command type (e.g. NONE, ETH)
2365 *
2366 * SP data is handled as if it's always an address pair, thus data fields are
2367 * not swapped to little endian in upper functions. Instead this function swaps
2368 * data as if it's two uint32 fields.
2369 */
2370int
2371bxe_sp_post(struct bxe_softc *sc,
2372            int              command,
2373            int              cid,
2374            uint32_t         data_hi,
2375            uint32_t         data_lo,
2376            int              cmd_type)
2377{
2378    struct eth_spe *spe;
2379    uint16_t type;
2380    int common;
2381
2382    common = bxe_is_contextless_ramrod(command, cmd_type);
2383
2384    BXE_SP_LOCK(sc);
2385
2386    if (common) {
2387        if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2388            BLOGE(sc, "EQ ring is full!\n");
2389            BXE_SP_UNLOCK(sc);
2390            return (-1);
2391        }
2392    } else {
2393        if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2394            BLOGE(sc, "SPQ ring is full!\n");
2395            BXE_SP_UNLOCK(sc);
2396            return (-1);
2397        }
2398    }
2399
2400    spe = bxe_sp_get_next(sc);
2401
2402    /* CID needs port number to be encoded int it */
2403    spe->hdr.conn_and_cmd_data =
2404        htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2405
2406    type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2407
2408    /* TBD: Check if it works for VFs */
2409    type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2410             SPE_HDR_T_FUNCTION_ID);
2411
2412    spe->hdr.type = htole16(type);
2413
2414    spe->data.update_data_addr.hi = htole32(data_hi);
2415    spe->data.update_data_addr.lo = htole32(data_lo);
2416
2417    /*
2418     * It's ok if the actual decrement is issued towards the memory
2419     * somewhere between the lock and unlock. Thus no more explict
2420     * memory barrier is needed.
2421     */
2422    if (common) {
2423        atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2424    } else {
2425        atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2426    }
2427
2428    BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2429    BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2430          BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2431    BLOGD(sc, DBG_SP,
2432          "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2433          sc->spq_prod_idx,
2434          (uint32_t)U64_HI(sc->spq_dma.paddr),
2435          (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2436          command,
2437          common,
2438          HW_CID(sc, cid),
2439          data_hi,
2440          data_lo,
2441          type,
2442          atomic_load_acq_long(&sc->cq_spq_left),
2443          atomic_load_acq_long(&sc->eq_spq_left));
2444
2445    bxe_sp_prod_update(sc);
2446
2447    BXE_SP_UNLOCK(sc);
2448    return (0);
2449}
2450
2451/**
2452 * bxe_debug_print_ind_table - prints the indirection table configuration.
2453 *
2454 * @sc: driver hanlde
2455 * @p:  pointer to rss configuration
2456 */
2457
2458/*
2459 * FreeBSD Device probe function.
2460 *
2461 * Compares the device found to the driver's list of supported devices and
2462 * reports back to the bsd loader whether this is the right driver for the device.
2463 * This is the driver entry function called from the "kldload" command.
2464 *
2465 * Returns:
2466 *   BUS_PROBE_DEFAULT on success, positive value on failure.
2467 */
2468static int
2469bxe_probe(device_t dev)
2470{
2471    struct bxe_device_type *t;
2472    char *descbuf;
2473    uint16_t did, sdid, svid, vid;
2474
2475    /* Find our device structure */
2476    t = bxe_devs;
2477
2478    /* Get the data for the device to be probed. */
2479    vid  = pci_get_vendor(dev);
2480    did  = pci_get_device(dev);
2481    svid = pci_get_subvendor(dev);
2482    sdid = pci_get_subdevice(dev);
2483
2484    /* Look through the list of known devices for a match. */
2485    while (t->bxe_name != NULL) {
2486        if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2487            ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2488            ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2489            descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2490            if (descbuf == NULL)
2491                return (ENOMEM);
2492
2493            /* Print out the device identity. */
2494            snprintf(descbuf, BXE_DEVDESC_MAX,
2495                     "%s (%c%d) BXE v:%s\n", t->bxe_name,
2496                     (((pci_read_config(dev, PCIR_REVID, 4) &
2497                        0xf0) >> 4) + 'A'),
2498                     (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2499                     BXE_DRIVER_VERSION);
2500
2501            device_set_desc_copy(dev, descbuf);
2502            free(descbuf, M_TEMP);
2503            return (BUS_PROBE_DEFAULT);
2504        }
2505        t++;
2506    }
2507
2508    return (ENXIO);
2509}
2510
2511static void
2512bxe_init_mutexes(struct bxe_softc *sc)
2513{
2514#ifdef BXE_CORE_LOCK_SX
2515    snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2516             "bxe%d_core_lock", sc->unit);
2517    sx_init(&sc->core_sx, sc->core_sx_name);
2518#else
2519    snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2520             "bxe%d_core_lock", sc->unit);
2521    mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2522#endif
2523
2524    snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2525             "bxe%d_sp_lock", sc->unit);
2526    mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2527
2528    snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2529             "bxe%d_dmae_lock", sc->unit);
2530    mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2531
2532    snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2533             "bxe%d_phy_lock", sc->unit);
2534    mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2535
2536    snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2537             "bxe%d_fwmb_lock", sc->unit);
2538    mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2539
2540    snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2541             "bxe%d_print_lock", sc->unit);
2542    mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2543
2544    snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2545             "bxe%d_stats_lock", sc->unit);
2546    mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2547
2548    snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2549             "bxe%d_mcast_lock", sc->unit);
2550    mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2551}
2552
2553static void
2554bxe_release_mutexes(struct bxe_softc *sc)
2555{
2556#ifdef BXE_CORE_LOCK_SX
2557    sx_destroy(&sc->core_sx);
2558#else
2559    if (mtx_initialized(&sc->core_mtx)) {
2560        mtx_destroy(&sc->core_mtx);
2561    }
2562#endif
2563
2564    if (mtx_initialized(&sc->sp_mtx)) {
2565        mtx_destroy(&sc->sp_mtx);
2566    }
2567
2568    if (mtx_initialized(&sc->dmae_mtx)) {
2569        mtx_destroy(&sc->dmae_mtx);
2570    }
2571
2572    if (mtx_initialized(&sc->port.phy_mtx)) {
2573        mtx_destroy(&sc->port.phy_mtx);
2574    }
2575
2576    if (mtx_initialized(&sc->fwmb_mtx)) {
2577        mtx_destroy(&sc->fwmb_mtx);
2578    }
2579
2580    if (mtx_initialized(&sc->print_mtx)) {
2581        mtx_destroy(&sc->print_mtx);
2582    }
2583
2584    if (mtx_initialized(&sc->stats_mtx)) {
2585        mtx_destroy(&sc->stats_mtx);
2586    }
2587
2588    if (mtx_initialized(&sc->mcast_mtx)) {
2589        mtx_destroy(&sc->mcast_mtx);
2590    }
2591}
2592
2593static void
2594bxe_tx_disable(struct bxe_softc* sc)
2595{
2596    if_t ifp = sc->ifp;
2597
2598    /* tell the stack the driver is stopped and TX queue is full */
2599    if (ifp !=  NULL) {
2600        if_setdrvflags(ifp, 0);
2601    }
2602}
2603
2604static void
2605bxe_drv_pulse(struct bxe_softc *sc)
2606{
2607    SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2608             sc->fw_drv_pulse_wr_seq);
2609}
2610
2611static inline uint16_t
2612bxe_tx_avail(struct bxe_softc *sc,
2613             struct bxe_fastpath *fp)
2614{
2615    int16_t  used;
2616    uint16_t prod;
2617    uint16_t cons;
2618
2619    prod = fp->tx_bd_prod;
2620    cons = fp->tx_bd_cons;
2621
2622    used = SUB_S16(prod, cons);
2623
2624    return (int16_t)(sc->tx_ring_size) - used;
2625}
2626
2627static inline int
2628bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2629{
2630    uint16_t hw_cons;
2631
2632    mb(); /* status block fields can change */
2633    hw_cons = le16toh(*fp->tx_cons_sb);
2634    return (hw_cons != fp->tx_pkt_cons);
2635}
2636
2637static inline uint8_t
2638bxe_has_tx_work(struct bxe_fastpath *fp)
2639{
2640    /* expand this for multi-cos if ever supported */
2641    return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2642}
2643
2644static inline int
2645bxe_has_rx_work(struct bxe_fastpath *fp)
2646{
2647    uint16_t rx_cq_cons_sb;
2648
2649    mb(); /* status block fields can change */
2650    rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2651    if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2652        rx_cq_cons_sb++;
2653    return (fp->rx_cq_cons != rx_cq_cons_sb);
2654}
2655
2656static void
2657bxe_sp_event(struct bxe_softc    *sc,
2658             struct bxe_fastpath *fp,
2659             union eth_rx_cqe    *rr_cqe)
2660{
2661    int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2662    int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2663    enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2664    struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2665
2666    BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2667          fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2668
2669    switch (command) {
2670    case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2671        BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2672        drv_cmd = ECORE_Q_CMD_UPDATE;
2673        break;
2674
2675    case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2676        BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2677        drv_cmd = ECORE_Q_CMD_SETUP;
2678        break;
2679
2680    case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2681        BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2682        drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2683        break;
2684
2685    case (RAMROD_CMD_ID_ETH_HALT):
2686        BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2687        drv_cmd = ECORE_Q_CMD_HALT;
2688        break;
2689
2690    case (RAMROD_CMD_ID_ETH_TERMINATE):
2691        BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2692        drv_cmd = ECORE_Q_CMD_TERMINATE;
2693        break;
2694
2695    case (RAMROD_CMD_ID_ETH_EMPTY):
2696        BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2697        drv_cmd = ECORE_Q_CMD_EMPTY;
2698        break;
2699
2700    default:
2701        BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2702              command, fp->index);
2703        return;
2704    }
2705
2706    if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2707        q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2708        /*
2709         * q_obj->complete_cmd() failure means that this was
2710         * an unexpected completion.
2711         *
2712         * In this case we don't want to increase the sc->spq_left
2713         * because apparently we haven't sent this command the first
2714         * place.
2715         */
2716        // bxe_panic(sc, ("Unexpected SP completion\n"));
2717        return;
2718    }
2719
2720    atomic_add_acq_long(&sc->cq_spq_left, 1);
2721
2722    BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2723          atomic_load_acq_long(&sc->cq_spq_left));
2724}
2725
2726/*
2727 * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2728 * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2729 * the current aggregation queue as in-progress.
2730 */
2731static void
2732bxe_tpa_start(struct bxe_softc            *sc,
2733              struct bxe_fastpath         *fp,
2734              uint16_t                    queue,
2735              uint16_t                    cons,
2736              uint16_t                    prod,
2737              struct eth_fast_path_rx_cqe *cqe)
2738{
2739    struct bxe_sw_rx_bd tmp_bd;
2740    struct bxe_sw_rx_bd *rx_buf;
2741    struct eth_rx_bd *rx_bd;
2742    int max_agg_queues;
2743    struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2744    uint16_t index;
2745
2746    BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2747                       "cons=%d prod=%d\n",
2748          fp->index, queue, cons, prod);
2749
2750    max_agg_queues = MAX_AGG_QS(sc);
2751
2752    KASSERT((queue < max_agg_queues),
2753            ("fp[%02d] invalid aggr queue (%d >= %d)!",
2754             fp->index, queue, max_agg_queues));
2755
2756    KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2757            ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2758             fp->index, queue));
2759
2760    /* copy the existing mbuf and mapping from the TPA pool */
2761    tmp_bd = tpa_info->bd;
2762
2763    if (tmp_bd.m == NULL) {
2764        uint32_t *tmp;
2765
2766        tmp = (uint32_t *)cqe;
2767
2768        BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2769              fp->index, queue, cons, prod);
2770        BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2771            *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2772
2773        /* XXX Error handling? */
2774        return;
2775    }
2776
2777    /* change the TPA queue to the start state */
2778    tpa_info->state            = BXE_TPA_STATE_START;
2779    tpa_info->placement_offset = cqe->placement_offset;
2780    tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2781    tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2782    tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2783
2784    fp->rx_tpa_queue_used |= (1 << queue);
2785
2786    /*
2787     * If all the buffer descriptors are filled with mbufs then fill in
2788     * the current consumer index with a new BD. Else if a maximum Rx
2789     * buffer limit is imposed then fill in the next producer index.
2790     */
2791    index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2792                prod : cons;
2793
2794    /* move the received mbuf and mapping to TPA pool */
2795    tpa_info->bd = fp->rx_mbuf_chain[cons];
2796
2797    /* release any existing RX BD mbuf mappings */
2798    if (cons != index) {
2799        rx_buf = &fp->rx_mbuf_chain[cons];
2800
2801        if (rx_buf->m_map != NULL) {
2802            bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2803                            BUS_DMASYNC_POSTREAD);
2804            bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2805        }
2806
2807        /*
2808         * We get here when the maximum number of rx buffers is less than
2809         * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2810         * it out here without concern of a memory leak.
2811         */
2812        fp->rx_mbuf_chain[cons].m = NULL;
2813    }
2814
2815    /* update the Rx SW BD with the mbuf info from the TPA pool */
2816    fp->rx_mbuf_chain[index] = tmp_bd;
2817
2818    /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2819    rx_bd = &fp->rx_chain[index];
2820    rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2821    rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2822}
2823
2824/*
2825 * When a TPA aggregation is completed, loop through the individual mbufs
2826 * of the aggregation, combining them into a single mbuf which will be sent
2827 * up the stack. Refill all freed SGEs with mbufs as we go along.
2828 */
2829static int
2830bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2831                   struct bxe_fastpath       *fp,
2832                   struct bxe_sw_tpa_info    *tpa_info,
2833                   uint16_t                  queue,
2834                   uint16_t                  pages,
2835                   struct mbuf               *m,
2836			       struct eth_end_agg_rx_cqe *cqe,
2837                   uint16_t                  cqe_idx)
2838{
2839    struct mbuf *m_frag;
2840    uint32_t frag_len, frag_size, i;
2841    uint16_t sge_idx;
2842    int rc = 0;
2843    int j;
2844
2845    frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2846
2847    BLOGD(sc, DBG_LRO,
2848          "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2849          fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2850
2851    /* make sure the aggregated frame is not too big to handle */
2852    if (pages > 8 * PAGES_PER_SGE) {
2853
2854        uint32_t *tmp = (uint32_t *)cqe;
2855
2856        BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2857                  "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2858              fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2859              tpa_info->len_on_bd, frag_size);
2860
2861        BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2862            *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2863
2864        bxe_panic(sc, ("sge page count error\n"));
2865        return (EINVAL);
2866    }
2867
2868    /*
2869     * Scan through the scatter gather list pulling individual mbufs into a
2870     * single mbuf for the host stack.
2871     */
2872    for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2873        sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2874
2875        /*
2876         * Firmware gives the indices of the SGE as if the ring is an array
2877         * (meaning that the "next" element will consume 2 indices).
2878         */
2879        frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2880
2881        BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2882                           "sge_idx=%d frag_size=%d frag_len=%d\n",
2883              fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2884
2885        m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2886
2887        /* allocate a new mbuf for the SGE */
2888        rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2889        if (rc) {
2890            /* Leave all remaining SGEs in the ring! */
2891            return (rc);
2892        }
2893
2894        /* update the fragment length */
2895        m_frag->m_len = frag_len;
2896
2897        /* concatenate the fragment to the head mbuf */
2898        m_cat(m, m_frag);
2899        fp->eth_q_stats.mbuf_alloc_sge--;
2900
2901        /* update the TPA mbuf size and remaining fragment size */
2902        m->m_pkthdr.len += frag_len;
2903        frag_size -= frag_len;
2904    }
2905
2906    BLOGD(sc, DBG_LRO,
2907          "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2908          fp->index, queue, frag_size);
2909
2910    return (rc);
2911}
2912
2913static inline void
2914bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2915{
2916    int i, j;
2917
2918    for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2919        int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2920
2921        for (j = 0; j < 2; j++) {
2922            BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2923            idx--;
2924        }
2925    }
2926}
2927
2928static inline void
2929bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2930{
2931    /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2932    memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2933
2934    /*
2935     * Clear the two last indices in the page to 1. These are the indices that
2936     * correspond to the "next" element, hence will never be indicated and
2937     * should be removed from the calculations.
2938     */
2939    bxe_clear_sge_mask_next_elems(fp);
2940}
2941
2942static inline void
2943bxe_update_last_max_sge(struct bxe_fastpath *fp,
2944                        uint16_t            idx)
2945{
2946    uint16_t last_max = fp->last_max_sge;
2947
2948    if (SUB_S16(idx, last_max) > 0) {
2949        fp->last_max_sge = idx;
2950    }
2951}
2952
2953static inline void
2954bxe_update_sge_prod(struct bxe_softc          *sc,
2955                    struct bxe_fastpath       *fp,
2956                    uint16_t                  sge_len,
2957                    union eth_sgl_or_raw_data *cqe)
2958{
2959    uint16_t last_max, last_elem, first_elem;
2960    uint16_t delta = 0;
2961    uint16_t i;
2962
2963    if (!sge_len) {
2964        return;
2965    }
2966
2967    /* first mark all used pages */
2968    for (i = 0; i < sge_len; i++) {
2969        BIT_VEC64_CLEAR_BIT(fp->sge_mask,
2970                            RX_SGE(le16toh(cqe->sgl[i])));
2971    }
2972
2973    BLOGD(sc, DBG_LRO,
2974          "fp[%02d] fp_cqe->sgl[%d] = %d\n",
2975          fp->index, sge_len - 1,
2976          le16toh(cqe->sgl[sge_len - 1]));
2977
2978    /* assume that the last SGE index is the biggest */
2979    bxe_update_last_max_sge(fp,
2980                            le16toh(cqe->sgl[sge_len - 1]));
2981
2982    last_max = RX_SGE(fp->last_max_sge);
2983    last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
2984    first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
2985
2986    /* if ring is not full */
2987    if (last_elem + 1 != first_elem) {
2988        last_elem++;
2989    }
2990
2991    /* now update the prod */
2992    for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
2993        if (__predict_true(fp->sge_mask[i])) {
2994            break;
2995        }
2996
2997        fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
2998        delta += BIT_VEC64_ELEM_SZ;
2999    }
3000
3001    if (delta > 0) {
3002        fp->rx_sge_prod += delta;
3003        /* clear page-end entries */
3004        bxe_clear_sge_mask_next_elems(fp);
3005    }
3006
3007    BLOGD(sc, DBG_LRO,
3008          "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3009          fp->index, fp->last_max_sge, fp->rx_sge_prod);
3010}
3011
3012/*
3013 * The aggregation on the current TPA queue has completed. Pull the individual
3014 * mbuf fragments together into a single mbuf, perform all necessary checksum
3015 * calculations, and send the resuting mbuf to the stack.
3016 */
3017static void
3018bxe_tpa_stop(struct bxe_softc          *sc,
3019             struct bxe_fastpath       *fp,
3020             struct bxe_sw_tpa_info    *tpa_info,
3021             uint16_t                  queue,
3022             uint16_t                  pages,
3023			 struct eth_end_agg_rx_cqe *cqe,
3024             uint16_t                  cqe_idx)
3025{
3026    if_t ifp = sc->ifp;
3027    struct mbuf *m;
3028    int rc = 0;
3029
3030    BLOGD(sc, DBG_LRO,
3031          "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3032          fp->index, queue, tpa_info->placement_offset,
3033          le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3034
3035    m = tpa_info->bd.m;
3036
3037    /* allocate a replacement before modifying existing mbuf */
3038    rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3039    if (rc) {
3040        /* drop the frame and log an error */
3041        fp->eth_q_stats.rx_soft_errors++;
3042        goto bxe_tpa_stop_exit;
3043    }
3044
3045    /* we have a replacement, fixup the current mbuf */
3046    m_adj(m, tpa_info->placement_offset);
3047    m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3048
3049    /* mark the checksums valid (taken care of by the firmware) */
3050    fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3051    fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3052    m->m_pkthdr.csum_data = 0xffff;
3053    m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3054                               CSUM_IP_VALID   |
3055                               CSUM_DATA_VALID |
3056                               CSUM_PSEUDO_HDR);
3057
3058    /* aggregate all of the SGEs into a single mbuf */
3059    rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3060    if (rc) {
3061        /* drop the packet and log an error */
3062        fp->eth_q_stats.rx_soft_errors++;
3063        m_freem(m);
3064    } else {
3065        if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3066            m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3067            m->m_flags |= M_VLANTAG;
3068        }
3069
3070        /* assign packet to this interface interface */
3071        if_setrcvif(m, ifp);
3072
3073#if __FreeBSD_version >= 800000
3074        /* specify what RSS queue was used for this flow */
3075        m->m_pkthdr.flowid = fp->index;
3076        BXE_SET_FLOWID(m);
3077#endif
3078
3079        if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3080        fp->eth_q_stats.rx_tpa_pkts++;
3081
3082        /* pass the frame to the stack */
3083        if_input(ifp, m);
3084    }
3085
3086    /* we passed an mbuf up the stack or dropped the frame */
3087    fp->eth_q_stats.mbuf_alloc_tpa--;
3088
3089bxe_tpa_stop_exit:
3090
3091    fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3092    fp->rx_tpa_queue_used &= ~(1 << queue);
3093}
3094
3095static uint8_t
3096bxe_service_rxsgl(
3097                 struct bxe_fastpath *fp,
3098                 uint16_t len,
3099                 uint16_t lenonbd,
3100                 struct mbuf *m,
3101                 struct eth_fast_path_rx_cqe *cqe_fp)
3102{
3103    struct mbuf *m_frag;
3104    uint16_t frags, frag_len;
3105    uint16_t sge_idx = 0;
3106    uint16_t j;
3107    uint8_t i, rc = 0;
3108    uint32_t frag_size;
3109
3110    /* adjust the mbuf */
3111    m->m_len = lenonbd;
3112
3113    frag_size =  len - lenonbd;
3114    frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3115
3116    for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3117        sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3118
3119        m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3120        frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3121        m_frag->m_len = frag_len;
3122
3123       /* allocate a new mbuf for the SGE */
3124        rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3125        if (rc) {
3126            /* Leave all remaining SGEs in the ring! */
3127            return (rc);
3128        }
3129        fp->eth_q_stats.mbuf_alloc_sge--;
3130
3131        /* concatenate the fragment to the head mbuf */
3132        m_cat(m, m_frag);
3133
3134        frag_size -= frag_len;
3135    }
3136
3137    bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3138
3139    return rc;
3140}
3141
3142static uint8_t
3143bxe_rxeof(struct bxe_softc    *sc,
3144          struct bxe_fastpath *fp)
3145{
3146    if_t ifp = sc->ifp;
3147    uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3148    uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3149    int rx_pkts = 0;
3150    int rc = 0;
3151
3152    BXE_FP_RX_LOCK(fp);
3153
3154    /* CQ "next element" is of the size of the regular element */
3155    hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3156    if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3157        hw_cq_cons++;
3158    }
3159
3160    bd_cons = fp->rx_bd_cons;
3161    bd_prod = fp->rx_bd_prod;
3162    bd_prod_fw = bd_prod;
3163    sw_cq_cons = fp->rx_cq_cons;
3164    sw_cq_prod = fp->rx_cq_prod;
3165
3166    /*
3167     * Memory barrier necessary as speculative reads of the rx
3168     * buffer can be ahead of the index in the status block
3169     */
3170    rmb();
3171
3172    BLOGD(sc, DBG_RX,
3173          "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3174          fp->index, hw_cq_cons, sw_cq_cons);
3175
3176    while (sw_cq_cons != hw_cq_cons) {
3177        struct bxe_sw_rx_bd *rx_buf = NULL;
3178        union eth_rx_cqe *cqe;
3179        struct eth_fast_path_rx_cqe *cqe_fp;
3180        uint8_t cqe_fp_flags;
3181        enum eth_rx_cqe_type cqe_fp_type;
3182        uint16_t len, lenonbd,  pad;
3183        struct mbuf *m = NULL;
3184
3185        comp_ring_cons = RCQ(sw_cq_cons);
3186        bd_prod = RX_BD(bd_prod);
3187        bd_cons = RX_BD(bd_cons);
3188
3189        cqe          = &fp->rcq_chain[comp_ring_cons];
3190        cqe_fp       = &cqe->fast_path_cqe;
3191        cqe_fp_flags = cqe_fp->type_error_flags;
3192        cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3193
3194        BLOGD(sc, DBG_RX,
3195              "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3196              "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3197              "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3198              fp->index,
3199              hw_cq_cons,
3200              sw_cq_cons,
3201              bd_prod,
3202              bd_cons,
3203              CQE_TYPE(cqe_fp_flags),
3204              cqe_fp_flags,
3205              cqe_fp->status_flags,
3206              le32toh(cqe_fp->rss_hash_result),
3207              le16toh(cqe_fp->vlan_tag),
3208              le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3209              le16toh(cqe_fp->len_on_bd));
3210
3211        /* is this a slowpath msg? */
3212        if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3213            bxe_sp_event(sc, fp, cqe);
3214            goto next_cqe;
3215        }
3216
3217        rx_buf = &fp->rx_mbuf_chain[bd_cons];
3218
3219        if (!CQE_TYPE_FAST(cqe_fp_type)) {
3220            struct bxe_sw_tpa_info *tpa_info;
3221            uint16_t frag_size, pages;
3222            uint8_t queue;
3223
3224            if (CQE_TYPE_START(cqe_fp_type)) {
3225                bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3226                              bd_cons, bd_prod, cqe_fp);
3227                m = NULL; /* packet not ready yet */
3228                goto next_rx;
3229            }
3230
3231            KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3232                    ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3233
3234            queue = cqe->end_agg_cqe.queue_index;
3235            tpa_info = &fp->rx_tpa_info[queue];
3236
3237            BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3238                  fp->index, queue);
3239
3240            frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3241                         tpa_info->len_on_bd);
3242            pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3243
3244            bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3245                         &cqe->end_agg_cqe, comp_ring_cons);
3246
3247            bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3248
3249            goto next_cqe;
3250        }
3251
3252        /* non TPA */
3253
3254        /* is this an error packet? */
3255        if (__predict_false(cqe_fp_flags &
3256                            ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3257            BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3258            fp->eth_q_stats.rx_soft_errors++;
3259            goto next_rx;
3260        }
3261
3262        len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3263        lenonbd = le16toh(cqe_fp->len_on_bd);
3264        pad = cqe_fp->placement_offset;
3265
3266        m = rx_buf->m;
3267
3268        if (__predict_false(m == NULL)) {
3269            BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3270                  bd_cons, fp->index);
3271            goto next_rx;
3272        }
3273
3274        /* XXX double copy if packet length under a threshold */
3275
3276        /*
3277         * If all the buffer descriptors are filled with mbufs then fill in
3278         * the current consumer index with a new BD. Else if a maximum Rx
3279         * buffer limit is imposed then fill in the next producer index.
3280         */
3281        rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3282                                  (sc->max_rx_bufs != RX_BD_USABLE) ?
3283                                      bd_prod : bd_cons);
3284        if (rc != 0) {
3285
3286            /* we simply reuse the received mbuf and don't post it to the stack */
3287            m = NULL;
3288
3289            BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3290                  fp->index, rc);
3291            fp->eth_q_stats.rx_soft_errors++;
3292
3293            if (sc->max_rx_bufs != RX_BD_USABLE) {
3294                /* copy this consumer index to the producer index */
3295                memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3296                       sizeof(struct bxe_sw_rx_bd));
3297                memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3298            }
3299
3300            goto next_rx;
3301        }
3302
3303        /* current mbuf was detached from the bd */
3304        fp->eth_q_stats.mbuf_alloc_rx--;
3305
3306        /* we allocated a replacement mbuf, fixup the current one */
3307        m_adj(m, pad);
3308        m->m_pkthdr.len = m->m_len = len;
3309
3310        if ((len > 60) && (len > lenonbd)) {
3311            fp->eth_q_stats.rx_bxe_service_rxsgl++;
3312            rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3313            if (rc)
3314                break;
3315            fp->eth_q_stats.rx_jumbo_sge_pkts++;
3316        } else if (lenonbd < len) {
3317            fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3318        }
3319
3320        /* assign packet to this interface interface */
3321	if_setrcvif(m, ifp);
3322
3323        /* assume no hardware checksum has complated */
3324        m->m_pkthdr.csum_flags = 0;
3325
3326        /* validate checksum if offload enabled */
3327        if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
3328            /* check for a valid IP frame */
3329            if (!(cqe->fast_path_cqe.status_flags &
3330                  ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3331                m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3332                if (__predict_false(cqe_fp_flags &
3333                                    ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3334                    fp->eth_q_stats.rx_hw_csum_errors++;
3335                } else {
3336                    fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3337                    m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3338                }
3339            }
3340
3341            /* check for a valid TCP/UDP frame */
3342            if (!(cqe->fast_path_cqe.status_flags &
3343                  ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3344                if (__predict_false(cqe_fp_flags &
3345                                    ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3346                    fp->eth_q_stats.rx_hw_csum_errors++;
3347                } else {
3348                    fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3349                    m->m_pkthdr.csum_data = 0xFFFF;
3350                    m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3351                                               CSUM_PSEUDO_HDR);
3352                }
3353            }
3354        }
3355
3356        /* if there is a VLAN tag then flag that info */
3357        if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3358            m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3359            m->m_flags |= M_VLANTAG;
3360        }
3361
3362#if __FreeBSD_version >= 800000
3363        /* specify what RSS queue was used for this flow */
3364        m->m_pkthdr.flowid = fp->index;
3365        BXE_SET_FLOWID(m);
3366#endif
3367
3368next_rx:
3369
3370        bd_cons    = RX_BD_NEXT(bd_cons);
3371        bd_prod    = RX_BD_NEXT(bd_prod);
3372        bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3373
3374        /* pass the frame to the stack */
3375        if (__predict_true(m != NULL)) {
3376            if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3377            rx_pkts++;
3378            if_input(ifp, m);
3379        }
3380
3381next_cqe:
3382
3383        sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3384        sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3385
3386        /* limit spinning on the queue */
3387        if (rc != 0)
3388            break;
3389
3390        if (rx_pkts == sc->rx_budget) {
3391            fp->eth_q_stats.rx_budget_reached++;
3392            break;
3393        }
3394    } /* while work to do */
3395
3396    fp->rx_bd_cons = bd_cons;
3397    fp->rx_bd_prod = bd_prod_fw;
3398    fp->rx_cq_cons = sw_cq_cons;
3399    fp->rx_cq_prod = sw_cq_prod;
3400
3401    /* Update producers */
3402    bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3403
3404    fp->eth_q_stats.rx_pkts += rx_pkts;
3405    fp->eth_q_stats.rx_calls++;
3406
3407    BXE_FP_RX_UNLOCK(fp);
3408
3409    return (sw_cq_cons != hw_cq_cons);
3410}
3411
3412static uint16_t
3413bxe_free_tx_pkt(struct bxe_softc    *sc,
3414                struct bxe_fastpath *fp,
3415                uint16_t            idx)
3416{
3417    struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3418    struct eth_tx_start_bd *tx_start_bd;
3419    uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3420    uint16_t new_cons;
3421    int nbd;
3422
3423    /* unmap the mbuf from non-paged memory */
3424    bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3425
3426    tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3427    nbd = le16toh(tx_start_bd->nbd) - 1;
3428
3429    new_cons = (tx_buf->first_bd + nbd);
3430
3431    /* free the mbuf */
3432    if (__predict_true(tx_buf->m != NULL)) {
3433        m_freem(tx_buf->m);
3434        fp->eth_q_stats.mbuf_alloc_tx--;
3435    } else {
3436        fp->eth_q_stats.tx_chain_lost_mbuf++;
3437    }
3438
3439    tx_buf->m = NULL;
3440    tx_buf->first_bd = 0;
3441
3442    return (new_cons);
3443}
3444
3445/* transmit timeout watchdog */
3446static int
3447bxe_watchdog(struct bxe_softc    *sc,
3448             struct bxe_fastpath *fp)
3449{
3450    BXE_FP_TX_LOCK(fp);
3451
3452    if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3453        BXE_FP_TX_UNLOCK(fp);
3454        return (0);
3455    }
3456
3457    BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3458    if(sc->trigger_grcdump) {
3459         /* taking grcdump */
3460         bxe_grc_dump(sc);
3461    }
3462
3463    BXE_FP_TX_UNLOCK(fp);
3464
3465    atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3466    taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3467
3468    return (-1);
3469}
3470
3471/* processes transmit completions */
3472static uint8_t
3473bxe_txeof(struct bxe_softc    *sc,
3474          struct bxe_fastpath *fp)
3475{
3476    if_t ifp = sc->ifp;
3477    uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3478    uint16_t tx_bd_avail;
3479
3480    BXE_FP_TX_LOCK_ASSERT(fp);
3481
3482    bd_cons = fp->tx_bd_cons;
3483    hw_cons = le16toh(*fp->tx_cons_sb);
3484    sw_cons = fp->tx_pkt_cons;
3485
3486    while (sw_cons != hw_cons) {
3487        pkt_cons = TX_BD(sw_cons);
3488
3489        BLOGD(sc, DBG_TX,
3490              "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3491              fp->index, hw_cons, sw_cons, pkt_cons);
3492
3493        bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3494
3495        sw_cons++;
3496    }
3497
3498    fp->tx_pkt_cons = sw_cons;
3499    fp->tx_bd_cons  = bd_cons;
3500
3501    BLOGD(sc, DBG_TX,
3502          "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3503          fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3504
3505    mb();
3506
3507    tx_bd_avail = bxe_tx_avail(sc, fp);
3508
3509    if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3510        if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
3511    } else {
3512        if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
3513    }
3514
3515    if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3516        /* reset the watchdog timer if there are pending transmits */
3517        fp->watchdog_timer = BXE_TX_TIMEOUT;
3518        return (TRUE);
3519    } else {
3520        /* clear watchdog when there are no pending transmits */
3521        fp->watchdog_timer = 0;
3522        return (FALSE);
3523    }
3524}
3525
3526static void
3527bxe_drain_tx_queues(struct bxe_softc *sc)
3528{
3529    struct bxe_fastpath *fp;
3530    int i, count;
3531
3532    /* wait until all TX fastpath tasks have completed */
3533    for (i = 0; i < sc->num_queues; i++) {
3534        fp = &sc->fp[i];
3535
3536        count = 1000;
3537
3538        while (bxe_has_tx_work(fp)) {
3539
3540            BXE_FP_TX_LOCK(fp);
3541            bxe_txeof(sc, fp);
3542            BXE_FP_TX_UNLOCK(fp);
3543
3544            if (count == 0) {
3545                BLOGE(sc, "Timeout waiting for fp[%d] "
3546                          "transmits to complete!\n", i);
3547                bxe_panic(sc, ("tx drain failure\n"));
3548                return;
3549            }
3550
3551            count--;
3552            DELAY(1000);
3553            rmb();
3554        }
3555    }
3556
3557    return;
3558}
3559
3560static int
3561bxe_del_all_macs(struct bxe_softc          *sc,
3562                 struct ecore_vlan_mac_obj *mac_obj,
3563                 int                       mac_type,
3564                 uint8_t                   wait_for_comp)
3565{
3566    unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3567    int rc;
3568
3569    /* wait for completion of requested */
3570    if (wait_for_comp) {
3571        bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3572    }
3573
3574    /* Set the mac type of addresses we want to clear */
3575    bxe_set_bit(mac_type, &vlan_mac_flags);
3576
3577    rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3578    if (rc < 0) {
3579        BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3580            rc, mac_type, wait_for_comp);
3581    }
3582
3583    return (rc);
3584}
3585
3586static int
3587bxe_fill_accept_flags(struct bxe_softc *sc,
3588                      uint32_t         rx_mode,
3589                      unsigned long    *rx_accept_flags,
3590                      unsigned long    *tx_accept_flags)
3591{
3592    /* Clear the flags first */
3593    *rx_accept_flags = 0;
3594    *tx_accept_flags = 0;
3595
3596    switch (rx_mode) {
3597    case BXE_RX_MODE_NONE:
3598        /*
3599         * 'drop all' supersedes any accept flags that may have been
3600         * passed to the function.
3601         */
3602        break;
3603
3604    case BXE_RX_MODE_NORMAL:
3605        bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3606        bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3607        bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3608
3609        /* internal switching mode */
3610        bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3611        bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3612        bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3613
3614        break;
3615
3616    case BXE_RX_MODE_ALLMULTI:
3617        bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3618        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3619        bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3620
3621        /* internal switching mode */
3622        bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3623        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3624        bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3625
3626        break;
3627
3628    case BXE_RX_MODE_PROMISC:
3629        /*
3630         * According to deffinition of SI mode, iface in promisc mode
3631         * should receive matched and unmatched (in resolution of port)
3632         * unicast packets.
3633         */
3634        bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3635        bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3636        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3637        bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3638
3639        /* internal switching mode */
3640        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3641        bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3642
3643        if (IS_MF_SI(sc)) {
3644            bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3645        } else {
3646            bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3647        }
3648
3649        break;
3650
3651    default:
3652        BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3653        return (-1);
3654    }
3655
3656    /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3657    if (rx_mode != BXE_RX_MODE_NONE) {
3658        bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3659        bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3660    }
3661
3662    return (0);
3663}
3664
3665static int
3666bxe_set_q_rx_mode(struct bxe_softc *sc,
3667                  uint8_t          cl_id,
3668                  unsigned long    rx_mode_flags,
3669                  unsigned long    rx_accept_flags,
3670                  unsigned long    tx_accept_flags,
3671                  unsigned long    ramrod_flags)
3672{
3673    struct ecore_rx_mode_ramrod_params ramrod_param;
3674    int rc;
3675
3676    memset(&ramrod_param, 0, sizeof(ramrod_param));
3677
3678    /* Prepare ramrod parameters */
3679    ramrod_param.cid = 0;
3680    ramrod_param.cl_id = cl_id;
3681    ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3682    ramrod_param.func_id = SC_FUNC(sc);
3683
3684    ramrod_param.pstate = &sc->sp_state;
3685    ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3686
3687    ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3688    ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3689
3690    bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3691
3692    ramrod_param.ramrod_flags = ramrod_flags;
3693    ramrod_param.rx_mode_flags = rx_mode_flags;
3694
3695    ramrod_param.rx_accept_flags = rx_accept_flags;
3696    ramrod_param.tx_accept_flags = tx_accept_flags;
3697
3698    rc = ecore_config_rx_mode(sc, &ramrod_param);
3699    if (rc < 0) {
3700        BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3701            "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3702            "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3703            (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3704            (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3705        return (rc);
3706    }
3707
3708    return (0);
3709}
3710
3711static int
3712bxe_set_storm_rx_mode(struct bxe_softc *sc)
3713{
3714    unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3715    unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3716    int rc;
3717
3718    rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3719                               &tx_accept_flags);
3720    if (rc) {
3721        return (rc);
3722    }
3723
3724    bxe_set_bit(RAMROD_RX, &ramrod_flags);
3725    bxe_set_bit(RAMROD_TX, &ramrod_flags);
3726
3727    /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3728    return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3729                              rx_accept_flags, tx_accept_flags,
3730                              ramrod_flags));
3731}
3732
3733/* returns the "mcp load_code" according to global load_count array */
3734static int
3735bxe_nic_load_no_mcp(struct bxe_softc *sc)
3736{
3737    int path = SC_PATH(sc);
3738    int port = SC_PORT(sc);
3739
3740    BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3741          path, load_count[path][0], load_count[path][1],
3742          load_count[path][2]);
3743    load_count[path][0]++;
3744    load_count[path][1 + port]++;
3745    BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3746          path, load_count[path][0], load_count[path][1],
3747          load_count[path][2]);
3748    if (load_count[path][0] == 1) {
3749        return (FW_MSG_CODE_DRV_LOAD_COMMON);
3750    } else if (load_count[path][1 + port] == 1) {
3751        return (FW_MSG_CODE_DRV_LOAD_PORT);
3752    } else {
3753        return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3754    }
3755}
3756
3757/* returns the "mcp load_code" according to global load_count array */
3758static int
3759bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3760{
3761    int port = SC_PORT(sc);
3762    int path = SC_PATH(sc);
3763
3764    BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3765          path, load_count[path][0], load_count[path][1],
3766          load_count[path][2]);
3767    load_count[path][0]--;
3768    load_count[path][1 + port]--;
3769    BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3770          path, load_count[path][0], load_count[path][1],
3771          load_count[path][2]);
3772    if (load_count[path][0] == 0) {
3773        return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3774    } else if (load_count[path][1 + port] == 0) {
3775        return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3776    } else {
3777        return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3778    }
3779}
3780
3781/* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3782static uint32_t
3783bxe_send_unload_req(struct bxe_softc *sc,
3784                    int              unload_mode)
3785{
3786    uint32_t reset_code = 0;
3787
3788    /* Select the UNLOAD request mode */
3789    if (unload_mode == UNLOAD_NORMAL) {
3790        reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3791    } else {
3792        reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3793    }
3794
3795    /* Send the request to the MCP */
3796    if (!BXE_NOMCP(sc)) {
3797        reset_code = bxe_fw_command(sc, reset_code, 0);
3798    } else {
3799        reset_code = bxe_nic_unload_no_mcp(sc);
3800    }
3801
3802    return (reset_code);
3803}
3804
3805/* send UNLOAD_DONE command to the MCP */
3806static void
3807bxe_send_unload_done(struct bxe_softc *sc,
3808                     uint8_t          keep_link)
3809{
3810    uint32_t reset_param =
3811        keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3812
3813    /* Report UNLOAD_DONE to MCP */
3814    if (!BXE_NOMCP(sc)) {
3815        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3816    }
3817}
3818
3819static int
3820bxe_func_wait_started(struct bxe_softc *sc)
3821{
3822    int tout = 50;
3823
3824    if (!sc->port.pmf) {
3825        return (0);
3826    }
3827
3828    /*
3829     * (assumption: No Attention from MCP at this stage)
3830     * PMF probably in the middle of TX disable/enable transaction
3831     * 1. Sync IRS for default SB
3832     * 2. Sync SP queue - this guarantees us that attention handling started
3833     * 3. Wait, that TX disable/enable transaction completes
3834     *
3835     * 1+2 guarantee that if DCBX attention was scheduled it already changed
3836     * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3837     * received completion for the transaction the state is TX_STOPPED.
3838     * State will return to STARTED after completion of TX_STOPPED-->STARTED
3839     * transaction.
3840     */
3841
3842    /* XXX make sure default SB ISR is done */
3843    /* need a way to synchronize an irq (intr_mtx?) */
3844
3845    /* XXX flush any work queues */
3846
3847    while (ecore_func_get_state(sc, &sc->func_obj) !=
3848           ECORE_F_STATE_STARTED && tout--) {
3849        DELAY(20000);
3850    }
3851
3852    if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3853        /*
3854         * Failed to complete the transaction in a "good way"
3855         * Force both transactions with CLR bit.
3856         */
3857        struct ecore_func_state_params func_params = { NULL };
3858
3859        BLOGE(sc, "Unexpected function state! "
3860                  "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3861
3862        func_params.f_obj = &sc->func_obj;
3863        bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3864
3865        /* STARTED-->TX_STOPPED */
3866        func_params.cmd = ECORE_F_CMD_TX_STOP;
3867        ecore_func_state_change(sc, &func_params);
3868
3869        /* TX_STOPPED-->STARTED */
3870        func_params.cmd = ECORE_F_CMD_TX_START;
3871        return (ecore_func_state_change(sc, &func_params));
3872    }
3873
3874    return (0);
3875}
3876
3877static int
3878bxe_stop_queue(struct bxe_softc *sc,
3879               int              index)
3880{
3881    struct bxe_fastpath *fp = &sc->fp[index];
3882    struct ecore_queue_state_params q_params = { NULL };
3883    int rc;
3884
3885    BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3886
3887    q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3888    /* We want to wait for completion in this context */
3889    bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3890
3891    /* Stop the primary connection: */
3892
3893    /* ...halt the connection */
3894    q_params.cmd = ECORE_Q_CMD_HALT;
3895    rc = ecore_queue_state_change(sc, &q_params);
3896    if (rc) {
3897        return (rc);
3898    }
3899
3900    /* ...terminate the connection */
3901    q_params.cmd = ECORE_Q_CMD_TERMINATE;
3902    memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3903    q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3904    rc = ecore_queue_state_change(sc, &q_params);
3905    if (rc) {
3906        return (rc);
3907    }
3908
3909    /* ...delete cfc entry */
3910    q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3911    memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3912    q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3913    return (ecore_queue_state_change(sc, &q_params));
3914}
3915
3916/* wait for the outstanding SP commands */
3917static inline uint8_t
3918bxe_wait_sp_comp(struct bxe_softc *sc,
3919                 unsigned long    mask)
3920{
3921    unsigned long tmp;
3922    int tout = 5000; /* wait for 5 secs tops */
3923
3924    while (tout--) {
3925        mb();
3926        if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3927            return (TRUE);
3928        }
3929
3930        DELAY(1000);
3931    }
3932
3933    mb();
3934
3935    tmp = atomic_load_acq_long(&sc->sp_state);
3936    if (tmp & mask) {
3937        BLOGE(sc, "Filtering completion timed out: "
3938                  "sp_state 0x%lx, mask 0x%lx\n",
3939              tmp, mask);
3940        return (FALSE);
3941    }
3942
3943    return (FALSE);
3944}
3945
3946static int
3947bxe_func_stop(struct bxe_softc *sc)
3948{
3949    struct ecore_func_state_params func_params = { NULL };
3950    int rc;
3951
3952    /* prepare parameters for function state transitions */
3953    bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3954    func_params.f_obj = &sc->func_obj;
3955    func_params.cmd = ECORE_F_CMD_STOP;
3956
3957    /*
3958     * Try to stop the function the 'good way'. If it fails (in case
3959     * of a parity error during bxe_chip_cleanup()) and we are
3960     * not in a debug mode, perform a state transaction in order to
3961     * enable further HW_RESET transaction.
3962     */
3963    rc = ecore_func_state_change(sc, &func_params);
3964    if (rc) {
3965        BLOGE(sc, "FUNC_STOP ramrod failed. "
3966                  "Running a dry transaction (%d)\n", rc);
3967        bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3968        return (ecore_func_state_change(sc, &func_params));
3969    }
3970
3971    return (0);
3972}
3973
3974static int
3975bxe_reset_hw(struct bxe_softc *sc,
3976             uint32_t         load_code)
3977{
3978    struct ecore_func_state_params func_params = { NULL };
3979
3980    /* Prepare parameters for function state transitions */
3981    bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3982
3983    func_params.f_obj = &sc->func_obj;
3984    func_params.cmd = ECORE_F_CMD_HW_RESET;
3985
3986    func_params.params.hw_init.load_phase = load_code;
3987
3988    return (ecore_func_state_change(sc, &func_params));
3989}
3990
3991static void
3992bxe_int_disable_sync(struct bxe_softc *sc,
3993                     int              disable_hw)
3994{
3995    if (disable_hw) {
3996        /* prevent the HW from sending interrupts */
3997        bxe_int_disable(sc);
3998    }
3999
4000    /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4001    /* make sure all ISRs are done */
4002
4003    /* XXX make sure sp_task is not running */
4004    /* cancel and flush work queues */
4005}
4006
4007static void
4008bxe_chip_cleanup(struct bxe_softc *sc,
4009                 uint32_t         unload_mode,
4010                 uint8_t          keep_link)
4011{
4012    int port = SC_PORT(sc);
4013    struct ecore_mcast_ramrod_params rparam = { NULL };
4014    uint32_t reset_code;
4015    int i, rc = 0;
4016
4017    bxe_drain_tx_queues(sc);
4018
4019    /* give HW time to discard old tx messages */
4020    DELAY(1000);
4021
4022    /* Clean all ETH MACs */
4023    rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4024    if (rc < 0) {
4025        BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4026    }
4027
4028    /* Clean up UC list  */
4029    rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4030    if (rc < 0) {
4031        BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4032    }
4033
4034    /* Disable LLH */
4035    if (!CHIP_IS_E1(sc)) {
4036        REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4037    }
4038
4039    /* Set "drop all" to stop Rx */
4040
4041    /*
4042     * We need to take the BXE_MCAST_LOCK() here in order to prevent
4043     * a race between the completion code and this code.
4044     */
4045    BXE_MCAST_LOCK(sc);
4046
4047    if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4048        bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4049    } else {
4050        bxe_set_storm_rx_mode(sc);
4051    }
4052
4053    /* Clean up multicast configuration */
4054    rparam.mcast_obj = &sc->mcast_obj;
4055    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4056    if (rc < 0) {
4057        BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4058    }
4059
4060    BXE_MCAST_UNLOCK(sc);
4061
4062    // XXX bxe_iov_chip_cleanup(sc);
4063
4064    /*
4065     * Send the UNLOAD_REQUEST to the MCP. This will return if
4066     * this function should perform FUNCTION, PORT, or COMMON HW
4067     * reset.
4068     */
4069    reset_code = bxe_send_unload_req(sc, unload_mode);
4070
4071    /*
4072     * (assumption: No Attention from MCP at this stage)
4073     * PMF probably in the middle of TX disable/enable transaction
4074     */
4075    rc = bxe_func_wait_started(sc);
4076    if (rc) {
4077        BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4078    }
4079
4080    /*
4081     * Close multi and leading connections
4082     * Completions for ramrods are collected in a synchronous way
4083     */
4084    for (i = 0; i < sc->num_queues; i++) {
4085        if (bxe_stop_queue(sc, i)) {
4086            goto unload_error;
4087        }
4088    }
4089
4090    /*
4091     * If SP settings didn't get completed so far - something
4092     * very wrong has happen.
4093     */
4094    if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4095        BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4096    }
4097
4098unload_error:
4099
4100    rc = bxe_func_stop(sc);
4101    if (rc) {
4102        BLOGE(sc, "Function stop failed!(%d)\n", rc);
4103    }
4104
4105    /* disable HW interrupts */
4106    bxe_int_disable_sync(sc, TRUE);
4107
4108    /* detach interrupts */
4109    bxe_interrupt_detach(sc);
4110
4111    /* Reset the chip */
4112    rc = bxe_reset_hw(sc, reset_code);
4113    if (rc) {
4114        BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4115    }
4116
4117    /* Report UNLOAD_DONE to MCP */
4118    bxe_send_unload_done(sc, keep_link);
4119}
4120
4121static void
4122bxe_disable_close_the_gate(struct bxe_softc *sc)
4123{
4124    uint32_t val;
4125    int port = SC_PORT(sc);
4126
4127    BLOGD(sc, DBG_LOAD,
4128          "Disabling 'close the gates'\n");
4129
4130    if (CHIP_IS_E1(sc)) {
4131        uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4132                               MISC_REG_AEU_MASK_ATTN_FUNC_0;
4133        val = REG_RD(sc, addr);
4134        val &= ~(0x300);
4135        REG_WR(sc, addr, val);
4136    } else {
4137        val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4138        val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4139                 MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4140        REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4141    }
4142}
4143
4144/*
4145 * Cleans the object that have internal lists without sending
4146 * ramrods. Should be run when interrutps are disabled.
4147 */
4148static void
4149bxe_squeeze_objects(struct bxe_softc *sc)
4150{
4151    unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4152    struct ecore_mcast_ramrod_params rparam = { NULL };
4153    struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4154    int rc;
4155
4156    /* Cleanup MACs' object first... */
4157
4158    /* Wait for completion of requested */
4159    bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4160    /* Perform a dry cleanup */
4161    bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4162
4163    /* Clean ETH primary MAC */
4164    bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4165    rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4166                             &ramrod_flags);
4167    if (rc != 0) {
4168        BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4169    }
4170
4171    /* Cleanup UC list */
4172    vlan_mac_flags = 0;
4173    bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4174    rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4175                             &ramrod_flags);
4176    if (rc != 0) {
4177        BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4178    }
4179
4180    /* Now clean mcast object... */
4181
4182    rparam.mcast_obj = &sc->mcast_obj;
4183    bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4184
4185    /* Add a DEL command... */
4186    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4187    if (rc < 0) {
4188        BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4189    }
4190
4191    /* now wait until all pending commands are cleared */
4192
4193    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4194    while (rc != 0) {
4195        if (rc < 0) {
4196            BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4197            return;
4198        }
4199
4200        rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4201    }
4202}
4203
4204/* stop the controller */
4205static __noinline int
4206bxe_nic_unload(struct bxe_softc *sc,
4207               uint32_t         unload_mode,
4208               uint8_t          keep_link)
4209{
4210    uint8_t global = FALSE;
4211    uint32_t val;
4212    int i;
4213
4214    BXE_CORE_LOCK_ASSERT(sc);
4215
4216    if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
4217
4218    for (i = 0; i < sc->num_queues; i++) {
4219        struct bxe_fastpath *fp;
4220
4221        fp = &sc->fp[i];
4222        BXE_FP_TX_LOCK(fp);
4223        BXE_FP_TX_UNLOCK(fp);
4224    }
4225
4226    BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4227
4228    /* mark driver as unloaded in shmem2 */
4229    if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4230        val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4231        SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4232                  val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4233    }
4234
4235    if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4236        (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4237        /*
4238         * We can get here if the driver has been unloaded
4239         * during parity error recovery and is either waiting for a
4240         * leader to complete or for other functions to unload and
4241         * then ifconfig down has been issued. In this case we want to
4242         * unload and let other functions to complete a recovery
4243         * process.
4244         */
4245        sc->recovery_state = BXE_RECOVERY_DONE;
4246        sc->is_leader = 0;
4247        bxe_release_leader_lock(sc);
4248        mb();
4249
4250        BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4251        BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4252            " state = 0x%x\n", sc->recovery_state, sc->state);
4253        return (-1);
4254    }
4255
4256    /*
4257     * Nothing to do during unload if previous bxe_nic_load()
4258     * did not completed successfully - all resourses are released.
4259     */
4260    if ((sc->state == BXE_STATE_CLOSED) ||
4261        (sc->state == BXE_STATE_ERROR)) {
4262        return (0);
4263    }
4264
4265    sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4266    mb();
4267
4268    /* stop tx */
4269    bxe_tx_disable(sc);
4270
4271    sc->rx_mode = BXE_RX_MODE_NONE;
4272    /* XXX set rx mode ??? */
4273
4274    if (IS_PF(sc) && !sc->grcdump_done) {
4275        /* set ALWAYS_ALIVE bit in shmem */
4276        sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4277
4278        bxe_drv_pulse(sc);
4279
4280        bxe_stats_handle(sc, STATS_EVENT_STOP);
4281        bxe_save_statistics(sc);
4282    }
4283
4284    /* wait till consumers catch up with producers in all queues */
4285    bxe_drain_tx_queues(sc);
4286
4287    /* if VF indicate to PF this function is going down (PF will delete sp
4288     * elements and clear initializations
4289     */
4290    if (IS_VF(sc)) {
4291        ; /* bxe_vfpf_close_vf(sc); */
4292    } else if (unload_mode != UNLOAD_RECOVERY) {
4293        /* if this is a normal/close unload need to clean up chip */
4294        if (!sc->grcdump_done)
4295            bxe_chip_cleanup(sc, unload_mode, keep_link);
4296    } else {
4297        /* Send the UNLOAD_REQUEST to the MCP */
4298        bxe_send_unload_req(sc, unload_mode);
4299
4300        /*
4301         * Prevent transactions to host from the functions on the
4302         * engine that doesn't reset global blocks in case of global
4303         * attention once gloabl blocks are reset and gates are opened
4304         * (the engine which leader will perform the recovery
4305         * last).
4306         */
4307        if (!CHIP_IS_E1x(sc)) {
4308            bxe_pf_disable(sc);
4309        }
4310
4311        /* disable HW interrupts */
4312        bxe_int_disable_sync(sc, TRUE);
4313
4314        /* detach interrupts */
4315        bxe_interrupt_detach(sc);
4316
4317        /* Report UNLOAD_DONE to MCP */
4318        bxe_send_unload_done(sc, FALSE);
4319    }
4320
4321    /*
4322     * At this stage no more interrupts will arrive so we may safely clean
4323     * the queue'able objects here in case they failed to get cleaned so far.
4324     */
4325    if (IS_PF(sc)) {
4326        bxe_squeeze_objects(sc);
4327    }
4328
4329    /* There should be no more pending SP commands at this stage */
4330    sc->sp_state = 0;
4331
4332    sc->port.pmf = 0;
4333
4334    bxe_free_fp_buffers(sc);
4335
4336    if (IS_PF(sc)) {
4337        bxe_free_mem(sc);
4338    }
4339
4340    bxe_free_fw_stats_mem(sc);
4341
4342    sc->state = BXE_STATE_CLOSED;
4343
4344    /*
4345     * Check if there are pending parity attentions. If there are - set
4346     * RECOVERY_IN_PROGRESS.
4347     */
4348    if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4349        bxe_set_reset_in_progress(sc);
4350
4351        /* Set RESET_IS_GLOBAL if needed */
4352        if (global) {
4353            bxe_set_reset_global(sc);
4354        }
4355    }
4356
4357    /*
4358     * The last driver must disable a "close the gate" if there is no
4359     * parity attention or "process kill" pending.
4360     */
4361    if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4362        bxe_reset_is_done(sc, SC_PATH(sc))) {
4363        bxe_disable_close_the_gate(sc);
4364    }
4365
4366    BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4367
4368    return (0);
4369}
4370
4371/*
4372 * Called by the OS to set various media options (i.e. link, speed, etc.) when
4373 * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4374 */
4375static int
4376bxe_ifmedia_update(struct ifnet  *ifp)
4377{
4378    struct bxe_softc *sc = (struct bxe_softc *)if_getsoftc(ifp);
4379    struct ifmedia *ifm;
4380
4381    ifm = &sc->ifmedia;
4382
4383    /* We only support Ethernet media type. */
4384    if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4385        return (EINVAL);
4386    }
4387
4388    switch (IFM_SUBTYPE(ifm->ifm_media)) {
4389    case IFM_AUTO:
4390         break;
4391    case IFM_10G_CX4:
4392    case IFM_10G_SR:
4393    case IFM_10G_T:
4394    case IFM_10G_TWINAX:
4395    default:
4396        /* We don't support changing the media type. */
4397        BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4398              IFM_SUBTYPE(ifm->ifm_media));
4399        return (EINVAL);
4400    }
4401
4402    return (0);
4403}
4404
4405/*
4406 * Called by the OS to get the current media status (i.e. link, speed, etc.).
4407 */
4408static void
4409bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4410{
4411    struct bxe_softc *sc = if_getsoftc(ifp);
4412
4413    /* Report link down if the driver isn't running. */
4414    if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0) {
4415        ifmr->ifm_active |= IFM_NONE;
4416        return;
4417    }
4418
4419    /* Setup the default interface info. */
4420    ifmr->ifm_status = IFM_AVALID;
4421    ifmr->ifm_active = IFM_ETHER;
4422
4423    if (sc->link_vars.link_up) {
4424        ifmr->ifm_status |= IFM_ACTIVE;
4425    } else {
4426        ifmr->ifm_active |= IFM_NONE;
4427        return;
4428    }
4429
4430    ifmr->ifm_active |= sc->media;
4431
4432    if (sc->link_vars.duplex == DUPLEX_FULL) {
4433        ifmr->ifm_active |= IFM_FDX;
4434    } else {
4435        ifmr->ifm_active |= IFM_HDX;
4436    }
4437}
4438
4439static void
4440bxe_handle_chip_tq(void *context,
4441                   int  pending)
4442{
4443    struct bxe_softc *sc = (struct bxe_softc *)context;
4444    long work = atomic_load_acq_long(&sc->chip_tq_flags);
4445
4446    switch (work)
4447    {
4448
4449    case CHIP_TQ_REINIT:
4450        if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
4451            /* restart the interface */
4452            BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4453            bxe_periodic_stop(sc);
4454            BXE_CORE_LOCK(sc);
4455            bxe_stop_locked(sc);
4456            bxe_init_locked(sc);
4457            BXE_CORE_UNLOCK(sc);
4458        }
4459        break;
4460
4461    default:
4462        break;
4463    }
4464}
4465
4466/*
4467 * Handles any IOCTL calls from the operating system.
4468 *
4469 * Returns:
4470 *   0 = Success, >0 Failure
4471 */
4472static int
4473bxe_ioctl(if_t ifp,
4474          u_long       command,
4475          caddr_t      data)
4476{
4477    struct bxe_softc *sc = if_getsoftc(ifp);
4478    struct ifreq *ifr = (struct ifreq *)data;
4479    int mask = 0;
4480    int reinit = 0;
4481    int error = 0;
4482
4483    int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4484    int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4485
4486    switch (command)
4487    {
4488    case SIOCSIFMTU:
4489        BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4490              ifr->ifr_mtu);
4491
4492        if (sc->mtu == ifr->ifr_mtu) {
4493            /* nothing to change */
4494            break;
4495        }
4496
4497        if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4498            BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4499                  ifr->ifr_mtu, mtu_min, mtu_max);
4500            error = EINVAL;
4501            break;
4502        }
4503
4504        atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4505                             (unsigned long)ifr->ifr_mtu);
4506	/*
4507        atomic_store_rel_long((volatile unsigned long *)&if_getmtu(ifp),
4508                              (unsigned long)ifr->ifr_mtu);
4509	XXX - Not sure why it needs to be atomic
4510	*/
4511	if_setmtu(ifp, ifr->ifr_mtu);
4512        reinit = 1;
4513        break;
4514
4515    case SIOCSIFFLAGS:
4516        /* toggle the interface state up or down */
4517        BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4518
4519	BXE_CORE_LOCK(sc);
4520        /* check if the interface is up */
4521        if (if_getflags(ifp) & IFF_UP) {
4522            if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4523                /* set the receive mode flags */
4524                bxe_set_rx_mode(sc);
4525            } else if(sc->state != BXE_STATE_DISABLED) {
4526		bxe_init_locked(sc);
4527            }
4528        } else {
4529            if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4530		bxe_periodic_stop(sc);
4531		bxe_stop_locked(sc);
4532            }
4533        }
4534	BXE_CORE_UNLOCK(sc);
4535
4536        break;
4537
4538    case SIOCADDMULTI:
4539    case SIOCDELMULTI:
4540        /* add/delete multicast addresses */
4541        BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4542
4543        /* check if the interface is up */
4544        if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4545            /* set the receive mode flags */
4546	    BXE_CORE_LOCK(sc);
4547            bxe_set_rx_mode(sc);
4548	    BXE_CORE_UNLOCK(sc);
4549        }
4550
4551        break;
4552
4553    case SIOCSIFCAP:
4554        /* find out which capabilities have changed */
4555        mask = (ifr->ifr_reqcap ^ if_getcapenable(ifp));
4556
4557        BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4558              mask);
4559
4560        /* toggle the LRO capabilites enable flag */
4561        if (mask & IFCAP_LRO) {
4562	    if_togglecapenable(ifp, IFCAP_LRO);
4563            BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4564                  (if_getcapenable(ifp) & IFCAP_LRO) ? "ON" : "OFF");
4565            reinit = 1;
4566        }
4567
4568        /* toggle the TXCSUM checksum capabilites enable flag */
4569        if (mask & IFCAP_TXCSUM) {
4570	    if_togglecapenable(ifp, IFCAP_TXCSUM);
4571            BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4572                  (if_getcapenable(ifp) & IFCAP_TXCSUM) ? "ON" : "OFF");
4573            if (if_getcapenable(ifp) & IFCAP_TXCSUM) {
4574                if_sethwassistbits(ifp, (CSUM_IP      |
4575                                    CSUM_TCP      |
4576                                    CSUM_UDP      |
4577                                    CSUM_TSO      |
4578                                    CSUM_TCP_IPV6 |
4579                                    CSUM_UDP_IPV6), 0);
4580            } else {
4581		if_clearhwassist(ifp); /* XXX */
4582            }
4583        }
4584
4585        /* toggle the RXCSUM checksum capabilities enable flag */
4586        if (mask & IFCAP_RXCSUM) {
4587	    if_togglecapenable(ifp, IFCAP_RXCSUM);
4588            BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4589                  (if_getcapenable(ifp) & IFCAP_RXCSUM) ? "ON" : "OFF");
4590            if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
4591                if_sethwassistbits(ifp, (CSUM_IP      |
4592                                    CSUM_TCP      |
4593                                    CSUM_UDP      |
4594                                    CSUM_TSO      |
4595                                    CSUM_TCP_IPV6 |
4596                                    CSUM_UDP_IPV6), 0);
4597            } else {
4598		if_clearhwassist(ifp); /* XXX */
4599            }
4600        }
4601
4602        /* toggle TSO4 capabilities enabled flag */
4603        if (mask & IFCAP_TSO4) {
4604            if_togglecapenable(ifp, IFCAP_TSO4);
4605            BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4606                  (if_getcapenable(ifp) & IFCAP_TSO4) ? "ON" : "OFF");
4607        }
4608
4609        /* toggle TSO6 capabilities enabled flag */
4610        if (mask & IFCAP_TSO6) {
4611	    if_togglecapenable(ifp, IFCAP_TSO6);
4612            BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4613                  (if_getcapenable(ifp) & IFCAP_TSO6) ? "ON" : "OFF");
4614        }
4615
4616        /* toggle VLAN_HWTSO capabilities enabled flag */
4617        if (mask & IFCAP_VLAN_HWTSO) {
4618
4619	    if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
4620            BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4621                  (if_getcapenable(ifp) & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4622        }
4623
4624        /* toggle VLAN_HWCSUM capabilities enabled flag */
4625        if (mask & IFCAP_VLAN_HWCSUM) {
4626            /* XXX investigate this... */
4627            BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4628            error = EINVAL;
4629        }
4630
4631        /* toggle VLAN_MTU capabilities enable flag */
4632        if (mask & IFCAP_VLAN_MTU) {
4633            /* XXX investigate this... */
4634            BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4635            error = EINVAL;
4636        }
4637
4638        /* toggle VLAN_HWTAGGING capabilities enabled flag */
4639        if (mask & IFCAP_VLAN_HWTAGGING) {
4640            /* XXX investigate this... */
4641            BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4642            error = EINVAL;
4643        }
4644
4645        /* toggle VLAN_HWFILTER capabilities enabled flag */
4646        if (mask & IFCAP_VLAN_HWFILTER) {
4647            /* XXX investigate this... */
4648            BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4649            error = EINVAL;
4650        }
4651
4652        /* XXX not yet...
4653         * IFCAP_WOL_MAGIC
4654         */
4655
4656        break;
4657
4658    case SIOCSIFMEDIA:
4659    case SIOCGIFMEDIA:
4660        /* set/get interface media */
4661        BLOGD(sc, DBG_IOCTL,
4662              "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4663              (command & 0xff));
4664        error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4665        break;
4666
4667    default:
4668        BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4669              (command & 0xff));
4670        error = ether_ioctl(ifp, command, data);
4671        break;
4672    }
4673
4674    if (reinit && (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4675        BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4676              "Re-initializing hardware from IOCTL change\n");
4677	bxe_periodic_stop(sc);
4678	BXE_CORE_LOCK(sc);
4679	bxe_stop_locked(sc);
4680	bxe_init_locked(sc);
4681	BXE_CORE_UNLOCK(sc);
4682    }
4683
4684    return (error);
4685}
4686
4687static __noinline void
4688bxe_dump_mbuf(struct bxe_softc *sc,
4689              struct mbuf      *m,
4690              uint8_t          contents)
4691{
4692    char * type;
4693    int i = 0;
4694
4695    if (!(sc->debug & DBG_MBUF)) {
4696        return;
4697    }
4698
4699    if (m == NULL) {
4700        BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4701        return;
4702    }
4703
4704    while (m) {
4705
4706#if __FreeBSD_version >= 1000000
4707        BLOGD(sc, DBG_MBUF,
4708              "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4709              i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4710
4711        if (m->m_flags & M_PKTHDR) {
4712             BLOGD(sc, DBG_MBUF,
4713                   "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4714                   i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4715                   (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4716        }
4717#else
4718        BLOGD(sc, DBG_MBUF,
4719              "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4720              i, m, m->m_len, m->m_flags,
4721              "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4722
4723        if (m->m_flags & M_PKTHDR) {
4724             BLOGD(sc, DBG_MBUF,
4725                   "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4726                   i, m->m_pkthdr.len, m->m_flags,
4727                   "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4728                   "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4729                   "\22M_PROMISC\23M_NOFREE",
4730                   (int)m->m_pkthdr.csum_flags,
4731                   "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4732                   "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4733                   "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4734                   "\14CSUM_PSEUDO_HDR");
4735        }
4736#endif /* #if __FreeBSD_version >= 1000000 */
4737
4738        if (m->m_flags & M_EXT) {
4739            switch (m->m_ext.ext_type) {
4740            case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4741            case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4742            case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4743            case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4744            case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4745            case EXT_PACKET:     type = "EXT_PACKET";     break;
4746            case EXT_MBUF:       type = "EXT_MBUF";       break;
4747            case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4748            case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4749            case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4750            case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4751            default:             type = "UNKNOWN";        break;
4752            }
4753
4754            BLOGD(sc, DBG_MBUF,
4755                  "%02d: - m_ext: %p ext_size=%d type=%s\n",
4756                  i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4757        }
4758
4759        if (contents) {
4760            bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4761        }
4762
4763        m = m->m_next;
4764        i++;
4765    }
4766}
4767
4768/*
4769 * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4770 * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4771 * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4772 * The headers comes in a separate bd in FreeBSD so 13-3=10.
4773 * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4774 */
4775static int
4776bxe_chktso_window(struct bxe_softc  *sc,
4777                  int               nsegs,
4778                  bus_dma_segment_t *segs,
4779                  struct mbuf       *m)
4780{
4781    uint32_t num_wnds, wnd_size, wnd_sum;
4782    int32_t frag_idx, wnd_idx;
4783    unsigned short lso_mss;
4784    int defrag;
4785
4786    defrag = 0;
4787    wnd_sum = 0;
4788    wnd_size = 10;
4789    num_wnds = nsegs - wnd_size;
4790    lso_mss = htole16(m->m_pkthdr.tso_segsz);
4791
4792    /*
4793     * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4794     * first window sum of data while skipping the first assuming it is the
4795     * header in FreeBSD.
4796     */
4797    for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4798        wnd_sum += htole16(segs[frag_idx].ds_len);
4799    }
4800
4801    /* check the first 10 bd window size */
4802    if (wnd_sum < lso_mss) {
4803        return (1);
4804    }
4805
4806    /* run through the windows */
4807    for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4808        /* subtract the first mbuf->m_len of the last wndw(-header) */
4809        wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4810        /* add the next mbuf len to the len of our new window */
4811        wnd_sum += htole16(segs[frag_idx].ds_len);
4812        if (wnd_sum < lso_mss) {
4813            return (1);
4814        }
4815    }
4816
4817    return (0);
4818}
4819
4820static uint8_t
4821bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4822                    struct mbuf         *m,
4823                    uint32_t            *parsing_data)
4824{
4825    struct ether_vlan_header *eh = NULL;
4826    struct ip *ip4 = NULL;
4827    struct ip6_hdr *ip6 = NULL;
4828    caddr_t ip = NULL;
4829    struct tcphdr *th = NULL;
4830    int e_hlen, ip_hlen, l4_off;
4831    uint16_t proto;
4832
4833    if (m->m_pkthdr.csum_flags == CSUM_IP) {
4834        /* no L4 checksum offload needed */
4835        return (0);
4836    }
4837
4838    /* get the Ethernet header */
4839    eh = mtod(m, struct ether_vlan_header *);
4840
4841    /* handle VLAN encapsulation if present */
4842    if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4843        e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4844        proto  = ntohs(eh->evl_proto);
4845    } else {
4846        e_hlen = ETHER_HDR_LEN;
4847        proto  = ntohs(eh->evl_encap_proto);
4848    }
4849
4850    switch (proto) {
4851    case ETHERTYPE_IP:
4852        /* get the IP header, if mbuf len < 20 then header in next mbuf */
4853        ip4 = (m->m_len < sizeof(struct ip)) ?
4854                  (struct ip *)m->m_next->m_data :
4855                  (struct ip *)(m->m_data + e_hlen);
4856        /* ip_hl is number of 32-bit words */
4857        ip_hlen = (ip4->ip_hl << 2);
4858        ip = (caddr_t)ip4;
4859        break;
4860    case ETHERTYPE_IPV6:
4861        /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4862        ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4863                  (struct ip6_hdr *)m->m_next->m_data :
4864                  (struct ip6_hdr *)(m->m_data + e_hlen);
4865        /* XXX cannot support offload with IPv6 extensions */
4866        ip_hlen = sizeof(struct ip6_hdr);
4867        ip = (caddr_t)ip6;
4868        break;
4869    default:
4870        /* We can't offload in this case... */
4871        /* XXX error stat ??? */
4872        return (0);
4873    }
4874
4875    /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4876    l4_off = (e_hlen + ip_hlen);
4877
4878    *parsing_data |=
4879        (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4880         ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4881
4882    if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4883                                  CSUM_TSO |
4884                                  CSUM_TCP_IPV6)) {
4885        fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4886        th = (struct tcphdr *)(ip + ip_hlen);
4887        /* th_off is number of 32-bit words */
4888        *parsing_data |= ((th->th_off <<
4889                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4890                          ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4891        return (l4_off + (th->th_off << 2)); /* entire header length */
4892    } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4893                                         CSUM_UDP_IPV6)) {
4894        fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4895        return (l4_off + sizeof(struct udphdr)); /* entire header length */
4896    } else {
4897        /* XXX error stat ??? */
4898        return (0);
4899    }
4900}
4901
4902static uint8_t
4903bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4904                 struct mbuf                *m,
4905                 struct eth_tx_parse_bd_e1x *pbd)
4906{
4907    struct ether_vlan_header *eh = NULL;
4908    struct ip *ip4 = NULL;
4909    struct ip6_hdr *ip6 = NULL;
4910    caddr_t ip = NULL;
4911    struct tcphdr *th = NULL;
4912    struct udphdr *uh = NULL;
4913    int e_hlen, ip_hlen;
4914    uint16_t proto;
4915    uint8_t hlen;
4916    uint16_t tmp_csum;
4917    uint32_t *tmp_uh;
4918
4919    /* get the Ethernet header */
4920    eh = mtod(m, struct ether_vlan_header *);
4921
4922    /* handle VLAN encapsulation if present */
4923    if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4924        e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4925        proto  = ntohs(eh->evl_proto);
4926    } else {
4927        e_hlen = ETHER_HDR_LEN;
4928        proto  = ntohs(eh->evl_encap_proto);
4929    }
4930
4931    switch (proto) {
4932    case ETHERTYPE_IP:
4933        /* get the IP header, if mbuf len < 20 then header in next mbuf */
4934        ip4 = (m->m_len < sizeof(struct ip)) ?
4935                  (struct ip *)m->m_next->m_data :
4936                  (struct ip *)(m->m_data + e_hlen);
4937        /* ip_hl is number of 32-bit words */
4938        ip_hlen = (ip4->ip_hl << 1);
4939        ip = (caddr_t)ip4;
4940        break;
4941    case ETHERTYPE_IPV6:
4942        /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4943        ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4944                  (struct ip6_hdr *)m->m_next->m_data :
4945                  (struct ip6_hdr *)(m->m_data + e_hlen);
4946        /* XXX cannot support offload with IPv6 extensions */
4947        ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4948        ip = (caddr_t)ip6;
4949        break;
4950    default:
4951        /* We can't offload in this case... */
4952        /* XXX error stat ??? */
4953        return (0);
4954    }
4955
4956    hlen = (e_hlen >> 1);
4957
4958    /* note that rest of global_data is indirectly zeroed here */
4959    if (m->m_flags & M_VLANTAG) {
4960        pbd->global_data =
4961            htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
4962    } else {
4963        pbd->global_data = htole16(hlen);
4964    }
4965
4966    pbd->ip_hlen_w = ip_hlen;
4967
4968    hlen += pbd->ip_hlen_w;
4969
4970    /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4971
4972    if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4973                                  CSUM_TSO |
4974                                  CSUM_TCP_IPV6)) {
4975        th = (struct tcphdr *)(ip + (ip_hlen << 1));
4976        /* th_off is number of 32-bit words */
4977        hlen += (uint16_t)(th->th_off << 1);
4978    } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4979                                         CSUM_UDP_IPV6)) {
4980        uh = (struct udphdr *)(ip + (ip_hlen << 1));
4981        hlen += (sizeof(struct udphdr) / 2);
4982    } else {
4983        /* valid case as only CSUM_IP was set */
4984        return (0);
4985    }
4986
4987    pbd->total_hlen_w = htole16(hlen);
4988
4989    if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4990                                  CSUM_TSO |
4991                                  CSUM_TCP_IPV6)) {
4992        fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4993        pbd->tcp_pseudo_csum = ntohs(th->th_sum);
4994    } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4995                                         CSUM_UDP_IPV6)) {
4996        fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4997
4998        /*
4999         * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5000         * checksums and does not know anything about the UDP header and where
5001         * the checksum field is located. It only knows about TCP. Therefore
5002         * we "lie" to the hardware for outgoing UDP packets w/ checksum
5003         * offload. Since the checksum field offset for TCP is 16 bytes and
5004         * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5005         * bytes less than the start of the UDP header. This allows the
5006         * hardware to write the checksum in the correct spot. But the
5007         * hardware will compute a checksum which includes the last 10 bytes
5008         * of the IP header. To correct this we tweak the stack computed
5009         * pseudo checksum by folding in the calculation of the inverse
5010         * checksum for those final 10 bytes of the IP header. This allows
5011         * the correct checksum to be computed by the hardware.
5012         */
5013
5014        /* set pointer 10 bytes before UDP header */
5015        tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5016
5017        /* calculate a pseudo header checksum over the first 10 bytes */
5018        tmp_csum = in_pseudo(*tmp_uh,
5019                             *(tmp_uh + 1),
5020                             *(uint16_t *)(tmp_uh + 2));
5021
5022        pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5023    }
5024
5025    return (hlen * 2); /* entire header length, number of bytes */
5026}
5027
5028static void
5029bxe_set_pbd_lso_e2(struct mbuf *m,
5030                   uint32_t    *parsing_data)
5031{
5032    *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5033                       ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5034                      ETH_TX_PARSE_BD_E2_LSO_MSS);
5035
5036    /* XXX test for IPv6 with extension header... */
5037}
5038
5039static void
5040bxe_set_pbd_lso(struct mbuf                *m,
5041                struct eth_tx_parse_bd_e1x *pbd)
5042{
5043    struct ether_vlan_header *eh = NULL;
5044    struct ip *ip = NULL;
5045    struct tcphdr *th = NULL;
5046    int e_hlen;
5047
5048    /* get the Ethernet header */
5049    eh = mtod(m, struct ether_vlan_header *);
5050
5051    /* handle VLAN encapsulation if present */
5052    e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5053                 (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5054
5055    /* get the IP and TCP header, with LSO entire header in first mbuf */
5056    /* XXX assuming IPv4 */
5057    ip = (struct ip *)(m->m_data + e_hlen);
5058    th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5059
5060    pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5061    pbd->tcp_send_seq = ntohl(th->th_seq);
5062    pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5063
5064#if 1
5065        /* XXX IPv4 */
5066        pbd->ip_id = ntohs(ip->ip_id);
5067        pbd->tcp_pseudo_csum =
5068            ntohs(in_pseudo(ip->ip_src.s_addr,
5069                            ip->ip_dst.s_addr,
5070                            htons(IPPROTO_TCP)));
5071#else
5072        /* XXX IPv6 */
5073        pbd->tcp_pseudo_csum =
5074            ntohs(in_pseudo(&ip6->ip6_src,
5075                            &ip6->ip6_dst,
5076                            htons(IPPROTO_TCP)));
5077#endif
5078
5079    pbd->global_data |=
5080        htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5081}
5082
5083/*
5084 * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5085 * visible to the controller.
5086 *
5087 * If an mbuf is submitted to this routine and cannot be given to the
5088 * controller (e.g. it has too many fragments) then the function may free
5089 * the mbuf and return to the caller.
5090 *
5091 * Returns:
5092 *   0 = Success, !0 = Failure
5093 *   Note the side effect that an mbuf may be freed if it causes a problem.
5094 */
5095static int
5096bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5097{
5098    bus_dma_segment_t segs[32];
5099    struct mbuf *m0;
5100    struct bxe_sw_tx_bd *tx_buf;
5101    struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5102    struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5103    /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5104    struct eth_tx_bd *tx_data_bd;
5105    struct eth_tx_bd *tx_total_pkt_size_bd;
5106    struct eth_tx_start_bd *tx_start_bd;
5107    uint16_t bd_prod, pkt_prod, total_pkt_size;
5108    uint8_t mac_type;
5109    int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5110    struct bxe_softc *sc;
5111    uint16_t tx_bd_avail;
5112    struct ether_vlan_header *eh;
5113    uint32_t pbd_e2_parsing_data = 0;
5114    uint8_t hlen = 0;
5115    int tmp_bd;
5116    int i;
5117
5118    sc = fp->sc;
5119
5120#if __FreeBSD_version >= 800000
5121    M_ASSERTPKTHDR(*m_head);
5122#endif /* #if __FreeBSD_version >= 800000 */
5123
5124    m0 = *m_head;
5125    rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5126    tx_start_bd = NULL;
5127    tx_data_bd = NULL;
5128    tx_total_pkt_size_bd = NULL;
5129
5130    /* get the H/W pointer for packets and BDs */
5131    pkt_prod = fp->tx_pkt_prod;
5132    bd_prod = fp->tx_bd_prod;
5133
5134    mac_type = UNICAST_ADDRESS;
5135
5136    /* map the mbuf into the next open DMAable memory */
5137    tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5138    error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5139                                    tx_buf->m_map, m0,
5140                                    segs, &nsegs, BUS_DMA_NOWAIT);
5141
5142    /* mapping errors */
5143    if(__predict_false(error != 0)) {
5144        fp->eth_q_stats.tx_dma_mapping_failure++;
5145        if (error == ENOMEM) {
5146            /* resource issue, try again later */
5147            rc = ENOMEM;
5148        } else if (error == EFBIG) {
5149            /* possibly recoverable with defragmentation */
5150            fp->eth_q_stats.mbuf_defrag_attempts++;
5151            m0 = m_defrag(*m_head, M_NOWAIT);
5152            if (m0 == NULL) {
5153                fp->eth_q_stats.mbuf_defrag_failures++;
5154                rc = ENOBUFS;
5155            } else {
5156                /* defrag successful, try mapping again */
5157                *m_head = m0;
5158                error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5159                                                tx_buf->m_map, m0,
5160                                                segs, &nsegs, BUS_DMA_NOWAIT);
5161                if (error) {
5162                    fp->eth_q_stats.tx_dma_mapping_failure++;
5163                    rc = error;
5164                }
5165            }
5166        } else {
5167            /* unknown, unrecoverable mapping error */
5168            BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5169            bxe_dump_mbuf(sc, m0, FALSE);
5170            rc = error;
5171        }
5172
5173        goto bxe_tx_encap_continue;
5174    }
5175
5176    tx_bd_avail = bxe_tx_avail(sc, fp);
5177
5178    /* make sure there is enough room in the send queue */
5179    if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5180        /* Recoverable, try again later. */
5181        fp->eth_q_stats.tx_hw_queue_full++;
5182        bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5183        rc = ENOMEM;
5184        goto bxe_tx_encap_continue;
5185    }
5186
5187    /* capture the current H/W TX chain high watermark */
5188    if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5189                        (TX_BD_USABLE - tx_bd_avail))) {
5190        fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5191    }
5192
5193    /* make sure it fits in the packet window */
5194    if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5195        /*
5196         * The mbuf may be to big for the controller to handle. If the frame
5197         * is a TSO frame we'll need to do an additional check.
5198         */
5199        if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5200            if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5201                goto bxe_tx_encap_continue; /* OK to send */
5202            } else {
5203                fp->eth_q_stats.tx_window_violation_tso++;
5204            }
5205        } else {
5206            fp->eth_q_stats.tx_window_violation_std++;
5207        }
5208
5209        /* lets try to defragment this mbuf and remap it */
5210        fp->eth_q_stats.mbuf_defrag_attempts++;
5211        bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5212
5213        m0 = m_defrag(*m_head, M_NOWAIT);
5214        if (m0 == NULL) {
5215            fp->eth_q_stats.mbuf_defrag_failures++;
5216            /* Ugh, just drop the frame... :( */
5217            rc = ENOBUFS;
5218        } else {
5219            /* defrag successful, try mapping again */
5220            *m_head = m0;
5221            error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5222                                            tx_buf->m_map, m0,
5223                                            segs, &nsegs, BUS_DMA_NOWAIT);
5224            if (error) {
5225                fp->eth_q_stats.tx_dma_mapping_failure++;
5226                /* No sense in trying to defrag/copy chain, drop it. :( */
5227                rc = error;
5228            }
5229            else {
5230                /* if the chain is still too long then drop it */
5231                if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5232                    bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5233                    rc = ENODEV;
5234                }
5235            }
5236        }
5237    }
5238
5239bxe_tx_encap_continue:
5240
5241    /* Check for errors */
5242    if (rc) {
5243        if (rc == ENOMEM) {
5244            /* recoverable try again later  */
5245        } else {
5246            fp->eth_q_stats.tx_soft_errors++;
5247            fp->eth_q_stats.mbuf_alloc_tx--;
5248            m_freem(*m_head);
5249            *m_head = NULL;
5250        }
5251
5252        return (rc);
5253    }
5254
5255    /* set flag according to packet type (UNICAST_ADDRESS is default) */
5256    if (m0->m_flags & M_BCAST) {
5257        mac_type = BROADCAST_ADDRESS;
5258    } else if (m0->m_flags & M_MCAST) {
5259        mac_type = MULTICAST_ADDRESS;
5260    }
5261
5262    /* store the mbuf into the mbuf ring */
5263    tx_buf->m        = m0;
5264    tx_buf->first_bd = fp->tx_bd_prod;
5265    tx_buf->flags    = 0;
5266
5267    /* prepare the first transmit (start) BD for the mbuf */
5268    tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5269
5270    BLOGD(sc, DBG_TX,
5271          "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5272          pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5273
5274    tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5275    tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5276    tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5277    total_pkt_size += tx_start_bd->nbytes;
5278    tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5279
5280    tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5281
5282    /* all frames have at least Start BD + Parsing BD */
5283    nbds = nsegs + 1;
5284    tx_start_bd->nbd = htole16(nbds);
5285
5286    if (m0->m_flags & M_VLANTAG) {
5287        tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5288        tx_start_bd->bd_flags.as_bitfield |=
5289            (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5290    } else {
5291        /* vf tx, start bd must hold the ethertype for fw to enforce it */
5292        if (IS_VF(sc)) {
5293            /* map ethernet header to find type and header length */
5294            eh = mtod(m0, struct ether_vlan_header *);
5295            tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5296        } else {
5297            /* used by FW for packet accounting */
5298            tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5299        }
5300    }
5301
5302    /*
5303     * add a parsing BD from the chain. The parsing BD is always added
5304     * though it is only used for TSO and chksum
5305     */
5306    bd_prod = TX_BD_NEXT(bd_prod);
5307
5308    if (m0->m_pkthdr.csum_flags) {
5309        if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5310            fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5311            tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5312        }
5313
5314        if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5315            tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5316                                                  ETH_TX_BD_FLAGS_L4_CSUM);
5317        } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5318            tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5319                                                  ETH_TX_BD_FLAGS_IS_UDP |
5320                                                  ETH_TX_BD_FLAGS_L4_CSUM);
5321        } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5322                   (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5323            tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5324        } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5325            tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5326                                                  ETH_TX_BD_FLAGS_IS_UDP);
5327        }
5328    }
5329
5330    if (!CHIP_IS_E1x(sc)) {
5331        pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5332        memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5333
5334        if (m0->m_pkthdr.csum_flags) {
5335            hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5336        }
5337
5338        SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5339                 mac_type);
5340    } else {
5341        uint16_t global_data = 0;
5342
5343        pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5344        memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5345
5346        if (m0->m_pkthdr.csum_flags) {
5347            hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5348        }
5349
5350        SET_FLAG(global_data,
5351                 ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5352        pbd_e1x->global_data |= htole16(global_data);
5353    }
5354
5355    /* setup the parsing BD with TSO specific info */
5356    if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5357        fp->eth_q_stats.tx_ofld_frames_lso++;
5358        tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5359
5360        if (__predict_false(tx_start_bd->nbytes > hlen)) {
5361            fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5362
5363            /* split the first BD into header/data making the fw job easy */
5364            nbds++;
5365            tx_start_bd->nbd = htole16(nbds);
5366            tx_start_bd->nbytes = htole16(hlen);
5367
5368            bd_prod = TX_BD_NEXT(bd_prod);
5369
5370            /* new transmit BD after the tx_parse_bd */
5371            tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5372            tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5373            tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5374            tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5375            if (tx_total_pkt_size_bd == NULL) {
5376                tx_total_pkt_size_bd = tx_data_bd;
5377            }
5378
5379            BLOGD(sc, DBG_TX,
5380                  "TSO split header size is %d (%x:%x) nbds %d\n",
5381                  le16toh(tx_start_bd->nbytes),
5382                  le32toh(tx_start_bd->addr_hi),
5383                  le32toh(tx_start_bd->addr_lo),
5384                  nbds);
5385        }
5386
5387        if (!CHIP_IS_E1x(sc)) {
5388            bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5389        } else {
5390            bxe_set_pbd_lso(m0, pbd_e1x);
5391        }
5392    }
5393
5394    if (pbd_e2_parsing_data) {
5395        pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5396    }
5397
5398    /* prepare remaining BDs, start tx bd contains first seg/frag */
5399    for (i = 1; i < nsegs ; i++) {
5400        bd_prod = TX_BD_NEXT(bd_prod);
5401        tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5402        tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5403        tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5404        tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5405        if (tx_total_pkt_size_bd == NULL) {
5406            tx_total_pkt_size_bd = tx_data_bd;
5407        }
5408        total_pkt_size += tx_data_bd->nbytes;
5409    }
5410
5411    BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5412
5413    if (tx_total_pkt_size_bd != NULL) {
5414        tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5415    }
5416
5417    if (__predict_false(sc->debug & DBG_TX)) {
5418        tmp_bd = tx_buf->first_bd;
5419        for (i = 0; i < nbds; i++)
5420        {
5421            if (i == 0) {
5422                BLOGD(sc, DBG_TX,
5423                      "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5424                      "bd_flags=0x%x hdr_nbds=%d\n",
5425                      tx_start_bd,
5426                      tmp_bd,
5427                      le16toh(tx_start_bd->nbd),
5428                      le16toh(tx_start_bd->vlan_or_ethertype),
5429                      tx_start_bd->bd_flags.as_bitfield,
5430                      (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5431            } else if (i == 1) {
5432                if (pbd_e1x) {
5433                    BLOGD(sc, DBG_TX,
5434                          "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5435                          "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5436                          "tcp_seq=%u total_hlen_w=%u\n",
5437                          pbd_e1x,
5438                          tmp_bd,
5439                          pbd_e1x->global_data,
5440                          pbd_e1x->ip_hlen_w,
5441                          pbd_e1x->ip_id,
5442                          pbd_e1x->lso_mss,
5443                          pbd_e1x->tcp_flags,
5444                          pbd_e1x->tcp_pseudo_csum,
5445                          pbd_e1x->tcp_send_seq,
5446                          le16toh(pbd_e1x->total_hlen_w));
5447                } else { /* if (pbd_e2) */
5448                    BLOGD(sc, DBG_TX,
5449                          "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5450                          "src=%02x:%02x:%02x parsing_data=0x%x\n",
5451                          pbd_e2,
5452                          tmp_bd,
5453                          pbd_e2->data.mac_addr.dst_hi,
5454                          pbd_e2->data.mac_addr.dst_mid,
5455                          pbd_e2->data.mac_addr.dst_lo,
5456                          pbd_e2->data.mac_addr.src_hi,
5457                          pbd_e2->data.mac_addr.src_mid,
5458                          pbd_e2->data.mac_addr.src_lo,
5459                          pbd_e2->parsing_data);
5460                }
5461            }
5462
5463            if (i != 1) { /* skip parse db as it doesn't hold data */
5464                tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5465                BLOGD(sc, DBG_TX,
5466                      "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5467                      tx_data_bd,
5468                      tmp_bd,
5469                      le16toh(tx_data_bd->nbytes),
5470                      le32toh(tx_data_bd->addr_hi),
5471                      le32toh(tx_data_bd->addr_lo));
5472            }
5473
5474            tmp_bd = TX_BD_NEXT(tmp_bd);
5475        }
5476    }
5477
5478    BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5479
5480    /* update TX BD producer index value for next TX */
5481    bd_prod = TX_BD_NEXT(bd_prod);
5482
5483    /*
5484     * If the chain of tx_bd's describing this frame is adjacent to or spans
5485     * an eth_tx_next_bd element then we need to increment the nbds value.
5486     */
5487    if (TX_BD_IDX(bd_prod) < nbds) {
5488        nbds++;
5489    }
5490
5491    /* don't allow reordering of writes for nbd and packets */
5492    mb();
5493
5494    fp->tx_db.data.prod += nbds;
5495
5496    /* producer points to the next free tx_bd at this point */
5497    fp->tx_pkt_prod++;
5498    fp->tx_bd_prod = bd_prod;
5499
5500    DOORBELL(sc, fp->index, fp->tx_db.raw);
5501
5502    fp->eth_q_stats.tx_pkts++;
5503
5504    /* Prevent speculative reads from getting ahead of the status block. */
5505    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5506                      0, 0, BUS_SPACE_BARRIER_READ);
5507
5508    /* Prevent speculative reads from getting ahead of the doorbell. */
5509    bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5510                      0, 0, BUS_SPACE_BARRIER_READ);
5511
5512    return (0);
5513}
5514
5515static void
5516bxe_tx_start_locked(struct bxe_softc *sc,
5517                    if_t ifp,
5518                    struct bxe_fastpath *fp)
5519{
5520    struct mbuf *m = NULL;
5521    int tx_count = 0;
5522    uint16_t tx_bd_avail;
5523
5524    BXE_FP_TX_LOCK_ASSERT(fp);
5525
5526    /* keep adding entries while there are frames to send */
5527    while (!if_sendq_empty(ifp)) {
5528
5529        /*
5530         * check for any frames to send
5531         * dequeue can still be NULL even if queue is not empty
5532         */
5533        m = if_dequeue(ifp);
5534        if (__predict_false(m == NULL)) {
5535            break;
5536        }
5537
5538        /* the mbuf now belongs to us */
5539        fp->eth_q_stats.mbuf_alloc_tx++;
5540
5541        /*
5542         * Put the frame into the transmit ring. If we don't have room,
5543         * place the mbuf back at the head of the TX queue, set the
5544         * OACTIVE flag, and wait for the NIC to drain the chain.
5545         */
5546        if (__predict_false(bxe_tx_encap(fp, &m))) {
5547            fp->eth_q_stats.tx_encap_failures++;
5548            if (m != NULL) {
5549                /* mark the TX queue as full and return the frame */
5550                if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5551		if_sendq_prepend(ifp, m);
5552                fp->eth_q_stats.mbuf_alloc_tx--;
5553                fp->eth_q_stats.tx_queue_xoff++;
5554            }
5555
5556            /* stop looking for more work */
5557            break;
5558        }
5559
5560        /* the frame was enqueued successfully */
5561        tx_count++;
5562
5563        /* send a copy of the frame to any BPF listeners. */
5564        if_etherbpfmtap(ifp, m);
5565
5566        tx_bd_avail = bxe_tx_avail(sc, fp);
5567
5568        /* handle any completions if we're running low */
5569        if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5570            /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5571            bxe_txeof(sc, fp);
5572            if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5573                break;
5574            }
5575        }
5576    }
5577
5578    /* all TX packets were dequeued and/or the tx ring is full */
5579    if (tx_count > 0) {
5580        /* reset the TX watchdog timeout timer */
5581        fp->watchdog_timer = BXE_TX_TIMEOUT;
5582    }
5583}
5584
5585/* Legacy (non-RSS) dispatch routine */
5586static void
5587bxe_tx_start(if_t ifp)
5588{
5589    struct bxe_softc *sc;
5590    struct bxe_fastpath *fp;
5591
5592    sc = if_getsoftc(ifp);
5593
5594    if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5595        BLOGW(sc, "Interface not running, ignoring transmit request\n");
5596        return;
5597    }
5598
5599    if (!sc->link_vars.link_up) {
5600        BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5601        return;
5602    }
5603
5604    fp = &sc->fp[0];
5605
5606    if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5607        fp->eth_q_stats.tx_queue_full_return++;
5608        return;
5609    }
5610
5611    BXE_FP_TX_LOCK(fp);
5612    bxe_tx_start_locked(sc, ifp, fp);
5613    BXE_FP_TX_UNLOCK(fp);
5614}
5615
5616#if __FreeBSD_version >= 901504
5617
5618static int
5619bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5620                       if_t                ifp,
5621                       struct bxe_fastpath *fp,
5622                       struct mbuf         *m)
5623{
5624    struct buf_ring *tx_br = fp->tx_br;
5625    struct mbuf *next;
5626    int depth, rc, tx_count;
5627    uint16_t tx_bd_avail;
5628
5629    rc = tx_count = 0;
5630
5631    BXE_FP_TX_LOCK_ASSERT(fp);
5632
5633    if (!tx_br) {
5634        BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5635        return (EINVAL);
5636    }
5637
5638    if (m != NULL) {
5639        rc = drbr_enqueue(ifp, tx_br, m);
5640        if (rc != 0) {
5641            fp->eth_q_stats.tx_soft_errors++;
5642            goto bxe_tx_mq_start_locked_exit;
5643        }
5644    }
5645
5646    if (!sc->link_vars.link_up || !(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5647        fp->eth_q_stats.tx_request_link_down_failures++;
5648        goto bxe_tx_mq_start_locked_exit;
5649    }
5650
5651    /* fetch the depth of the driver queue */
5652    depth = drbr_inuse_drv(ifp, tx_br);
5653    if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5654        fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5655    }
5656
5657    /* keep adding entries while there are frames to send */
5658    while ((next = drbr_peek(ifp, tx_br)) != NULL) {
5659        /* handle any completions if we're running low */
5660        tx_bd_avail = bxe_tx_avail(sc, fp);
5661        if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5662            /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5663            bxe_txeof(sc, fp);
5664            tx_bd_avail = bxe_tx_avail(sc, fp);
5665            if (tx_bd_avail < (BXE_TSO_MAX_SEGMENTS + 1)) {
5666                fp->eth_q_stats.bd_avail_too_less_failures++;
5667                m_freem(next);
5668                drbr_advance(ifp, tx_br);
5669                rc = ENOBUFS;
5670                break;
5671            }
5672        }
5673
5674        /* the mbuf now belongs to us */
5675        fp->eth_q_stats.mbuf_alloc_tx++;
5676
5677        /*
5678         * Put the frame into the transmit ring. If we don't have room,
5679         * place the mbuf back at the head of the TX queue, set the
5680         * OACTIVE flag, and wait for the NIC to drain the chain.
5681         */
5682        rc = bxe_tx_encap(fp, &next);
5683        if (__predict_false(rc != 0)) {
5684            fp->eth_q_stats.tx_encap_failures++;
5685            if (next != NULL) {
5686                /* mark the TX queue as full and save the frame */
5687                if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5688                drbr_putback(ifp, tx_br, next);
5689                fp->eth_q_stats.mbuf_alloc_tx--;
5690                fp->eth_q_stats.tx_frames_deferred++;
5691            } else
5692                drbr_advance(ifp, tx_br);
5693
5694            /* stop looking for more work */
5695            break;
5696        }
5697
5698        /* the transmit frame was enqueued successfully */
5699        tx_count++;
5700
5701        /* send a copy of the frame to any BPF listeners */
5702	if_etherbpfmtap(ifp, next);
5703
5704        drbr_advance(ifp, tx_br);
5705    }
5706
5707    /* all TX packets were dequeued and/or the tx ring is full */
5708    if (tx_count > 0) {
5709        /* reset the TX watchdog timeout timer */
5710        fp->watchdog_timer = BXE_TX_TIMEOUT;
5711    }
5712
5713bxe_tx_mq_start_locked_exit:
5714    /* If we didn't drain the drbr, enqueue a task in the future to do it. */
5715    if (!drbr_empty(ifp, tx_br)) {
5716        fp->eth_q_stats.tx_mq_not_empty++;
5717        taskqueue_enqueue_timeout(fp->tq, &fp->tx_timeout_task, 1);
5718    }
5719
5720    return (rc);
5721}
5722
5723static void
5724bxe_tx_mq_start_deferred(void *arg,
5725                         int pending)
5726{
5727    struct bxe_fastpath *fp = (struct bxe_fastpath *)arg;
5728    struct bxe_softc *sc = fp->sc;
5729    if_t ifp = sc->ifp;
5730
5731    BXE_FP_TX_LOCK(fp);
5732    bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
5733    BXE_FP_TX_UNLOCK(fp);
5734}
5735
5736/* Multiqueue (TSS) dispatch routine. */
5737static int
5738bxe_tx_mq_start(struct ifnet *ifp,
5739                struct mbuf  *m)
5740{
5741    struct bxe_softc *sc = if_getsoftc(ifp);
5742    struct bxe_fastpath *fp;
5743    int fp_index, rc;
5744
5745    fp_index = 0; /* default is the first queue */
5746
5747    /* check if flowid is set */
5748
5749    if (BXE_VALID_FLOWID(m))
5750        fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5751
5752    fp = &sc->fp[fp_index];
5753
5754    if (BXE_FP_TX_TRYLOCK(fp)) {
5755        rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5756        BXE_FP_TX_UNLOCK(fp);
5757    } else {
5758        rc = drbr_enqueue(ifp, fp->tx_br, m);
5759        taskqueue_enqueue(fp->tq, &fp->tx_task);
5760    }
5761
5762    return (rc);
5763}
5764
5765static void
5766bxe_mq_flush(struct ifnet *ifp)
5767{
5768    struct bxe_softc *sc = if_getsoftc(ifp);
5769    struct bxe_fastpath *fp;
5770    struct mbuf *m;
5771    int i;
5772
5773    for (i = 0; i < sc->num_queues; i++) {
5774        fp = &sc->fp[i];
5775
5776        if (fp->state != BXE_FP_STATE_OPEN) {
5777            BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5778                  fp->index, fp->state);
5779            continue;
5780        }
5781
5782        if (fp->tx_br != NULL) {
5783            BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5784            BXE_FP_TX_LOCK(fp);
5785            while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5786                m_freem(m);
5787            }
5788            BXE_FP_TX_UNLOCK(fp);
5789        }
5790    }
5791
5792    if_qflush(ifp);
5793}
5794
5795#endif /* FreeBSD_version >= 901504 */
5796
5797static uint16_t
5798bxe_cid_ilt_lines(struct bxe_softc *sc)
5799{
5800    if (IS_SRIOV(sc)) {
5801        return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5802    }
5803    return (L2_ILT_LINES(sc));
5804}
5805
5806static void
5807bxe_ilt_set_info(struct bxe_softc *sc)
5808{
5809    struct ilt_client_info *ilt_client;
5810    struct ecore_ilt *ilt = sc->ilt;
5811    uint16_t line = 0;
5812
5813    ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5814    BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5815
5816    /* CDU */
5817    ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5818    ilt_client->client_num = ILT_CLIENT_CDU;
5819    ilt_client->page_size = CDU_ILT_PAGE_SZ;
5820    ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5821    ilt_client->start = line;
5822    line += bxe_cid_ilt_lines(sc);
5823
5824    if (CNIC_SUPPORT(sc)) {
5825        line += CNIC_ILT_LINES;
5826    }
5827
5828    ilt_client->end = (line - 1);
5829
5830    BLOGD(sc, DBG_LOAD,
5831          "ilt client[CDU]: start %d, end %d, "
5832          "psz 0x%x, flags 0x%x, hw psz %d\n",
5833          ilt_client->start, ilt_client->end,
5834          ilt_client->page_size,
5835          ilt_client->flags,
5836          ilog2(ilt_client->page_size >> 12));
5837
5838    /* QM */
5839    if (QM_INIT(sc->qm_cid_count)) {
5840        ilt_client = &ilt->clients[ILT_CLIENT_QM];
5841        ilt_client->client_num = ILT_CLIENT_QM;
5842        ilt_client->page_size = QM_ILT_PAGE_SZ;
5843        ilt_client->flags = 0;
5844        ilt_client->start = line;
5845
5846        /* 4 bytes for each cid */
5847        line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5848                             QM_ILT_PAGE_SZ);
5849
5850        ilt_client->end = (line - 1);
5851
5852        BLOGD(sc, DBG_LOAD,
5853              "ilt client[QM]: start %d, end %d, "
5854              "psz 0x%x, flags 0x%x, hw psz %d\n",
5855              ilt_client->start, ilt_client->end,
5856              ilt_client->page_size, ilt_client->flags,
5857              ilog2(ilt_client->page_size >> 12));
5858    }
5859
5860    if (CNIC_SUPPORT(sc)) {
5861        /* SRC */
5862        ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5863        ilt_client->client_num = ILT_CLIENT_SRC;
5864        ilt_client->page_size = SRC_ILT_PAGE_SZ;
5865        ilt_client->flags = 0;
5866        ilt_client->start = line;
5867        line += SRC_ILT_LINES;
5868        ilt_client->end = (line - 1);
5869
5870        BLOGD(sc, DBG_LOAD,
5871              "ilt client[SRC]: start %d, end %d, "
5872              "psz 0x%x, flags 0x%x, hw psz %d\n",
5873              ilt_client->start, ilt_client->end,
5874              ilt_client->page_size, ilt_client->flags,
5875              ilog2(ilt_client->page_size >> 12));
5876
5877        /* TM */
5878        ilt_client = &ilt->clients[ILT_CLIENT_TM];
5879        ilt_client->client_num = ILT_CLIENT_TM;
5880        ilt_client->page_size = TM_ILT_PAGE_SZ;
5881        ilt_client->flags = 0;
5882        ilt_client->start = line;
5883        line += TM_ILT_LINES;
5884        ilt_client->end = (line - 1);
5885
5886        BLOGD(sc, DBG_LOAD,
5887              "ilt client[TM]: start %d, end %d, "
5888              "psz 0x%x, flags 0x%x, hw psz %d\n",
5889              ilt_client->start, ilt_client->end,
5890              ilt_client->page_size, ilt_client->flags,
5891              ilog2(ilt_client->page_size >> 12));
5892    }
5893
5894    KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5895}
5896
5897static void
5898bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5899{
5900    int i;
5901    uint32_t rx_buf_size;
5902
5903    rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5904
5905    for (i = 0; i < sc->num_queues; i++) {
5906        if(rx_buf_size <= MCLBYTES){
5907            sc->fp[i].rx_buf_size = rx_buf_size;
5908            sc->fp[i].mbuf_alloc_size = MCLBYTES;
5909        }else if (rx_buf_size <= MJUMPAGESIZE){
5910            sc->fp[i].rx_buf_size = rx_buf_size;
5911            sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5912        }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5913            sc->fp[i].rx_buf_size = MCLBYTES;
5914            sc->fp[i].mbuf_alloc_size = MCLBYTES;
5915        }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5916            sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5917            sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5918        }else {
5919            sc->fp[i].rx_buf_size = MCLBYTES;
5920            sc->fp[i].mbuf_alloc_size = MCLBYTES;
5921        }
5922    }
5923}
5924
5925static int
5926bxe_alloc_ilt_mem(struct bxe_softc *sc)
5927{
5928    int rc = 0;
5929
5930    if ((sc->ilt =
5931         (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
5932                                    M_BXE_ILT,
5933                                    (M_NOWAIT | M_ZERO))) == NULL) {
5934        rc = 1;
5935    }
5936
5937    return (rc);
5938}
5939
5940static int
5941bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
5942{
5943    int rc = 0;
5944
5945    if ((sc->ilt->lines =
5946         (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
5947                                    M_BXE_ILT,
5948                                    (M_NOWAIT | M_ZERO))) == NULL) {
5949        rc = 1;
5950    }
5951
5952    return (rc);
5953}
5954
5955static void
5956bxe_free_ilt_mem(struct bxe_softc *sc)
5957{
5958    if (sc->ilt != NULL) {
5959        free(sc->ilt, M_BXE_ILT);
5960        sc->ilt = NULL;
5961    }
5962}
5963
5964static void
5965bxe_free_ilt_lines_mem(struct bxe_softc *sc)
5966{
5967    if (sc->ilt->lines != NULL) {
5968        free(sc->ilt->lines, M_BXE_ILT);
5969        sc->ilt->lines = NULL;
5970    }
5971}
5972
5973static void
5974bxe_free_mem(struct bxe_softc *sc)
5975{
5976    int i;
5977
5978    for (i = 0; i < L2_ILT_LINES(sc); i++) {
5979        bxe_dma_free(sc, &sc->context[i].vcxt_dma);
5980        sc->context[i].vcxt = NULL;
5981        sc->context[i].size = 0;
5982    }
5983
5984    ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
5985
5986    bxe_free_ilt_lines_mem(sc);
5987
5988}
5989
5990static int
5991bxe_alloc_mem(struct bxe_softc *sc)
5992{
5993    int context_size;
5994    int allocated;
5995    int i;
5996
5997    /*
5998     * Allocate memory for CDU context:
5999     * This memory is allocated separately and not in the generic ILT
6000     * functions because CDU differs in few aspects:
6001     * 1. There can be multiple entities allocating memory for context -
6002     * regular L2, CNIC, and SRIOV drivers. Each separately controls
6003     * its own ILT lines.
6004     * 2. Since CDU page-size is not a single 4KB page (which is the case
6005     * for the other ILT clients), to be efficient we want to support
6006     * allocation of sub-page-size in the last entry.
6007     * 3. Context pointers are used by the driver to pass to FW / update
6008     * the context (for the other ILT clients the pointers are used just to
6009     * free the memory during unload).
6010     */
6011    context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6012    for (i = 0, allocated = 0; allocated < context_size; i++) {
6013        sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6014                                  (context_size - allocated));
6015
6016        if (bxe_dma_alloc(sc, sc->context[i].size,
6017                          &sc->context[i].vcxt_dma,
6018                          "cdu context") != 0) {
6019            bxe_free_mem(sc);
6020            return (-1);
6021        }
6022
6023        sc->context[i].vcxt =
6024            (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6025
6026        allocated += sc->context[i].size;
6027    }
6028
6029    bxe_alloc_ilt_lines_mem(sc);
6030
6031    BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6032          sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6033    {
6034        for (i = 0; i < 4; i++) {
6035            BLOGD(sc, DBG_LOAD,
6036                  "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6037                  i,
6038                  sc->ilt->clients[i].page_size,
6039                  sc->ilt->clients[i].start,
6040                  sc->ilt->clients[i].end,
6041                  sc->ilt->clients[i].client_num,
6042                  sc->ilt->clients[i].flags);
6043        }
6044    }
6045    if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6046        BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6047        bxe_free_mem(sc);
6048        return (-1);
6049    }
6050
6051    return (0);
6052}
6053
6054static void
6055bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6056{
6057    struct bxe_softc *sc;
6058    int i;
6059
6060    sc = fp->sc;
6061
6062    if (fp->rx_mbuf_tag == NULL) {
6063        return;
6064    }
6065
6066    /* free all mbufs and unload all maps */
6067    for (i = 0; i < RX_BD_TOTAL; i++) {
6068        if (fp->rx_mbuf_chain[i].m_map != NULL) {
6069            bus_dmamap_sync(fp->rx_mbuf_tag,
6070                            fp->rx_mbuf_chain[i].m_map,
6071                            BUS_DMASYNC_POSTREAD);
6072            bus_dmamap_unload(fp->rx_mbuf_tag,
6073                              fp->rx_mbuf_chain[i].m_map);
6074        }
6075
6076        if (fp->rx_mbuf_chain[i].m != NULL) {
6077            m_freem(fp->rx_mbuf_chain[i].m);
6078            fp->rx_mbuf_chain[i].m = NULL;
6079            fp->eth_q_stats.mbuf_alloc_rx--;
6080        }
6081    }
6082}
6083
6084static void
6085bxe_free_tpa_pool(struct bxe_fastpath *fp)
6086{
6087    struct bxe_softc *sc;
6088    int i, max_agg_queues;
6089
6090    sc = fp->sc;
6091
6092    if (fp->rx_mbuf_tag == NULL) {
6093        return;
6094    }
6095
6096    max_agg_queues = MAX_AGG_QS(sc);
6097
6098    /* release all mbufs and unload all DMA maps in the TPA pool */
6099    for (i = 0; i < max_agg_queues; i++) {
6100        if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6101            bus_dmamap_sync(fp->rx_mbuf_tag,
6102                            fp->rx_tpa_info[i].bd.m_map,
6103                            BUS_DMASYNC_POSTREAD);
6104            bus_dmamap_unload(fp->rx_mbuf_tag,
6105                              fp->rx_tpa_info[i].bd.m_map);
6106        }
6107
6108        if (fp->rx_tpa_info[i].bd.m != NULL) {
6109            m_freem(fp->rx_tpa_info[i].bd.m);
6110            fp->rx_tpa_info[i].bd.m = NULL;
6111            fp->eth_q_stats.mbuf_alloc_tpa--;
6112        }
6113    }
6114}
6115
6116static void
6117bxe_free_sge_chain(struct bxe_fastpath *fp)
6118{
6119    struct bxe_softc *sc;
6120    int i;
6121
6122    sc = fp->sc;
6123
6124    if (fp->rx_sge_mbuf_tag == NULL) {
6125        return;
6126    }
6127
6128    /* rree all mbufs and unload all maps */
6129    for (i = 0; i < RX_SGE_TOTAL; i++) {
6130        if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6131            bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6132                            fp->rx_sge_mbuf_chain[i].m_map,
6133                            BUS_DMASYNC_POSTREAD);
6134            bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6135                              fp->rx_sge_mbuf_chain[i].m_map);
6136        }
6137
6138        if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6139            m_freem(fp->rx_sge_mbuf_chain[i].m);
6140            fp->rx_sge_mbuf_chain[i].m = NULL;
6141            fp->eth_q_stats.mbuf_alloc_sge--;
6142        }
6143    }
6144}
6145
6146static void
6147bxe_free_fp_buffers(struct bxe_softc *sc)
6148{
6149    struct bxe_fastpath *fp;
6150    int i;
6151
6152    for (i = 0; i < sc->num_queues; i++) {
6153        fp = &sc->fp[i];
6154
6155#if __FreeBSD_version >= 901504
6156        if (fp->tx_br != NULL) {
6157            /* just in case bxe_mq_flush() wasn't called */
6158            if (mtx_initialized(&fp->tx_mtx)) {
6159                struct mbuf *m;
6160
6161                BXE_FP_TX_LOCK(fp);
6162                while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6163                    m_freem(m);
6164                BXE_FP_TX_UNLOCK(fp);
6165            }
6166        }
6167#endif
6168
6169        /* free all RX buffers */
6170        bxe_free_rx_bd_chain(fp);
6171        bxe_free_tpa_pool(fp);
6172        bxe_free_sge_chain(fp);
6173
6174        if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6175            BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6176                  fp->eth_q_stats.mbuf_alloc_rx);
6177        }
6178
6179        if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6180            BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6181                  fp->eth_q_stats.mbuf_alloc_sge);
6182        }
6183
6184        if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6185            BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6186                  fp->eth_q_stats.mbuf_alloc_tpa);
6187        }
6188
6189        if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6190            BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6191                  fp->eth_q_stats.mbuf_alloc_tx);
6192        }
6193
6194        /* XXX verify all mbufs were reclaimed */
6195    }
6196}
6197
6198static int
6199bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6200                     uint16_t            prev_index,
6201                     uint16_t            index)
6202{
6203    struct bxe_sw_rx_bd *rx_buf;
6204    struct eth_rx_bd *rx_bd;
6205    bus_dma_segment_t segs[1];
6206    bus_dmamap_t map;
6207    struct mbuf *m;
6208    int nsegs, rc;
6209
6210    rc = 0;
6211
6212    /* allocate the new RX BD mbuf */
6213    m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6214    if (__predict_false(m == NULL)) {
6215        fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6216        return (ENOBUFS);
6217    }
6218
6219    fp->eth_q_stats.mbuf_alloc_rx++;
6220
6221    /* initialize the mbuf buffer length */
6222    m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6223
6224    /* map the mbuf into non-paged pool */
6225    rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6226                                 fp->rx_mbuf_spare_map,
6227                                 m, segs, &nsegs, BUS_DMA_NOWAIT);
6228    if (__predict_false(rc != 0)) {
6229        fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6230        m_freem(m);
6231        fp->eth_q_stats.mbuf_alloc_rx--;
6232        return (rc);
6233    }
6234
6235    /* all mbufs must map to a single segment */
6236    KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6237
6238    /* release any existing RX BD mbuf mappings */
6239
6240    if (prev_index != index) {
6241        rx_buf = &fp->rx_mbuf_chain[prev_index];
6242
6243        if (rx_buf->m_map != NULL) {
6244            bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6245                            BUS_DMASYNC_POSTREAD);
6246            bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6247        }
6248
6249        /*
6250         * We only get here from bxe_rxeof() when the maximum number
6251         * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6252         * holds the mbuf in the prev_index so it's OK to NULL it out
6253         * here without concern of a memory leak.
6254         */
6255        fp->rx_mbuf_chain[prev_index].m = NULL;
6256    }
6257
6258    rx_buf = &fp->rx_mbuf_chain[index];
6259
6260    if (rx_buf->m_map != NULL) {
6261        bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6262                        BUS_DMASYNC_POSTREAD);
6263        bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6264    }
6265
6266    /* save the mbuf and mapping info for a future packet */
6267    map = (prev_index != index) ?
6268              fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6269    rx_buf->m_map = fp->rx_mbuf_spare_map;
6270    fp->rx_mbuf_spare_map = map;
6271    bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6272                    BUS_DMASYNC_PREREAD);
6273    rx_buf->m = m;
6274
6275    rx_bd = &fp->rx_chain[index];
6276    rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6277    rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6278
6279    return (rc);
6280}
6281
6282static int
6283bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6284                      int                 queue)
6285{
6286    struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6287    bus_dma_segment_t segs[1];
6288    bus_dmamap_t map;
6289    struct mbuf *m;
6290    int nsegs;
6291    int rc = 0;
6292
6293    /* allocate the new TPA mbuf */
6294    m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6295    if (__predict_false(m == NULL)) {
6296        fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6297        return (ENOBUFS);
6298    }
6299
6300    fp->eth_q_stats.mbuf_alloc_tpa++;
6301
6302    /* initialize the mbuf buffer length */
6303    m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6304
6305    /* map the mbuf into non-paged pool */
6306    rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6307                                 fp->rx_tpa_info_mbuf_spare_map,
6308                                 m, segs, &nsegs, BUS_DMA_NOWAIT);
6309    if (__predict_false(rc != 0)) {
6310        fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6311        m_free(m);
6312        fp->eth_q_stats.mbuf_alloc_tpa--;
6313        return (rc);
6314    }
6315
6316    /* all mbufs must map to a single segment */
6317    KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6318
6319    /* release any existing TPA mbuf mapping */
6320    if (tpa_info->bd.m_map != NULL) {
6321        bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6322                        BUS_DMASYNC_POSTREAD);
6323        bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6324    }
6325
6326    /* save the mbuf and mapping info for the TPA mbuf */
6327    map = tpa_info->bd.m_map;
6328    tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6329    fp->rx_tpa_info_mbuf_spare_map = map;
6330    bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6331                    BUS_DMASYNC_PREREAD);
6332    tpa_info->bd.m = m;
6333    tpa_info->seg = segs[0];
6334
6335    return (rc);
6336}
6337
6338/*
6339 * Allocate an mbuf and assign it to the receive scatter gather chain. The
6340 * caller must take care to save a copy of the existing mbuf in the SG mbuf
6341 * chain.
6342 */
6343static int
6344bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6345                      uint16_t            index)
6346{
6347    struct bxe_sw_rx_bd *sge_buf;
6348    struct eth_rx_sge *sge;
6349    bus_dma_segment_t segs[1];
6350    bus_dmamap_t map;
6351    struct mbuf *m;
6352    int nsegs;
6353    int rc = 0;
6354
6355    /* allocate a new SGE mbuf */
6356    m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6357    if (__predict_false(m == NULL)) {
6358        fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6359        return (ENOMEM);
6360    }
6361
6362    fp->eth_q_stats.mbuf_alloc_sge++;
6363
6364    /* initialize the mbuf buffer length */
6365    m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6366
6367    /* map the SGE mbuf into non-paged pool */
6368    rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6369                                 fp->rx_sge_mbuf_spare_map,
6370                                 m, segs, &nsegs, BUS_DMA_NOWAIT);
6371    if (__predict_false(rc != 0)) {
6372        fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6373        m_freem(m);
6374        fp->eth_q_stats.mbuf_alloc_sge--;
6375        return (rc);
6376    }
6377
6378    /* all mbufs must map to a single segment */
6379    KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6380
6381    sge_buf = &fp->rx_sge_mbuf_chain[index];
6382
6383    /* release any existing SGE mbuf mapping */
6384    if (sge_buf->m_map != NULL) {
6385        bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6386                        BUS_DMASYNC_POSTREAD);
6387        bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6388    }
6389
6390    /* save the mbuf and mapping info for a future packet */
6391    map = sge_buf->m_map;
6392    sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6393    fp->rx_sge_mbuf_spare_map = map;
6394    bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6395                    BUS_DMASYNC_PREREAD);
6396    sge_buf->m = m;
6397
6398    sge = &fp->rx_sge_chain[index];
6399    sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6400    sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6401
6402    return (rc);
6403}
6404
6405static __noinline int
6406bxe_alloc_fp_buffers(struct bxe_softc *sc)
6407{
6408    struct bxe_fastpath *fp;
6409    int i, j, rc = 0;
6410    int ring_prod, cqe_ring_prod;
6411    int max_agg_queues;
6412
6413    for (i = 0; i < sc->num_queues; i++) {
6414        fp = &sc->fp[i];
6415
6416        ring_prod = cqe_ring_prod = 0;
6417        fp->rx_bd_cons = 0;
6418        fp->rx_cq_cons = 0;
6419
6420        /* allocate buffers for the RX BDs in RX BD chain */
6421        for (j = 0; j < sc->max_rx_bufs; j++) {
6422            rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6423            if (rc != 0) {
6424                BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6425                      i, rc);
6426                goto bxe_alloc_fp_buffers_error;
6427            }
6428
6429            ring_prod     = RX_BD_NEXT(ring_prod);
6430            cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6431        }
6432
6433        fp->rx_bd_prod = ring_prod;
6434        fp->rx_cq_prod = cqe_ring_prod;
6435        fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6436
6437        max_agg_queues = MAX_AGG_QS(sc);
6438
6439        fp->tpa_enable = TRUE;
6440
6441        /* fill the TPA pool */
6442        for (j = 0; j < max_agg_queues; j++) {
6443            rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6444            if (rc != 0) {
6445                BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6446                          i, j);
6447                fp->tpa_enable = FALSE;
6448                goto bxe_alloc_fp_buffers_error;
6449            }
6450
6451            fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6452        }
6453
6454        if (fp->tpa_enable) {
6455            /* fill the RX SGE chain */
6456            ring_prod = 0;
6457            for (j = 0; j < RX_SGE_USABLE; j++) {
6458                rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6459                if (rc != 0) {
6460                    BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6461                              i, ring_prod);
6462                    fp->tpa_enable = FALSE;
6463                    ring_prod = 0;
6464                    goto bxe_alloc_fp_buffers_error;
6465                }
6466
6467                ring_prod = RX_SGE_NEXT(ring_prod);
6468            }
6469
6470            fp->rx_sge_prod = ring_prod;
6471        }
6472    }
6473
6474    return (0);
6475
6476bxe_alloc_fp_buffers_error:
6477
6478    /* unwind what was already allocated */
6479    bxe_free_rx_bd_chain(fp);
6480    bxe_free_tpa_pool(fp);
6481    bxe_free_sge_chain(fp);
6482
6483    return (ENOBUFS);
6484}
6485
6486static void
6487bxe_free_fw_stats_mem(struct bxe_softc *sc)
6488{
6489    bxe_dma_free(sc, &sc->fw_stats_dma);
6490
6491    sc->fw_stats_num = 0;
6492
6493    sc->fw_stats_req_size = 0;
6494    sc->fw_stats_req = NULL;
6495    sc->fw_stats_req_mapping = 0;
6496
6497    sc->fw_stats_data_size = 0;
6498    sc->fw_stats_data = NULL;
6499    sc->fw_stats_data_mapping = 0;
6500}
6501
6502static int
6503bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6504{
6505    uint8_t num_queue_stats;
6506    int num_groups;
6507
6508    /* number of queues for statistics is number of eth queues */
6509    num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6510
6511    /*
6512     * Total number of FW statistics requests =
6513     *   1 for port stats + 1 for PF stats + num of queues
6514     */
6515    sc->fw_stats_num = (2 + num_queue_stats);
6516
6517    /*
6518     * Request is built from stats_query_header and an array of
6519     * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6520     * rules. The real number or requests is configured in the
6521     * stats_query_header.
6522     */
6523    num_groups =
6524        ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6525         ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6526
6527    BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6528          sc->fw_stats_num, num_groups);
6529
6530    sc->fw_stats_req_size =
6531        (sizeof(struct stats_query_header) +
6532         (num_groups * sizeof(struct stats_query_cmd_group)));
6533
6534    /*
6535     * Data for statistics requests + stats_counter.
6536     * stats_counter holds per-STORM counters that are incremented when
6537     * STORM has finished with the current request. Memory for FCoE
6538     * offloaded statistics are counted anyway, even if they will not be sent.
6539     * VF stats are not accounted for here as the data of VF stats is stored
6540     * in memory allocated by the VF, not here.
6541     */
6542    sc->fw_stats_data_size =
6543        (sizeof(struct stats_counter) +
6544         sizeof(struct per_port_stats) +
6545         sizeof(struct per_pf_stats) +
6546         /* sizeof(struct fcoe_statistics_params) + */
6547         (sizeof(struct per_queue_stats) * num_queue_stats));
6548
6549    if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6550                      &sc->fw_stats_dma, "fw stats") != 0) {
6551        bxe_free_fw_stats_mem(sc);
6552        return (-1);
6553    }
6554
6555    /* set up the shortcuts */
6556
6557    sc->fw_stats_req =
6558        (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6559    sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6560
6561    sc->fw_stats_data =
6562        (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6563                                     sc->fw_stats_req_size);
6564    sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6565                                 sc->fw_stats_req_size);
6566
6567    BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6568          (uintmax_t)sc->fw_stats_req_mapping);
6569
6570    BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6571          (uintmax_t)sc->fw_stats_data_mapping);
6572
6573    return (0);
6574}
6575
6576/*
6577 * Bits map:
6578 * 0-7  - Engine0 load counter.
6579 * 8-15 - Engine1 load counter.
6580 * 16   - Engine0 RESET_IN_PROGRESS bit.
6581 * 17   - Engine1 RESET_IN_PROGRESS bit.
6582 * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6583 *        function on the engine
6584 * 19   - Engine1 ONE_IS_LOADED.
6585 * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6586 *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6587 *        for just the one belonging to its engine).
6588 */
6589#define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6590#define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6591#define BXE_PATH0_LOAD_CNT_SHIFT  0
6592#define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6593#define BXE_PATH1_LOAD_CNT_SHIFT  8
6594#define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6595#define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6596#define BXE_GLOBAL_RESET_BIT      0x00040000
6597
6598/* set the GLOBAL_RESET bit, should be run under rtnl lock */
6599static void
6600bxe_set_reset_global(struct bxe_softc *sc)
6601{
6602    uint32_t val;
6603    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6604    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6605    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6606    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6607}
6608
6609/* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6610static void
6611bxe_clear_reset_global(struct bxe_softc *sc)
6612{
6613    uint32_t val;
6614    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6615    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6616    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6617    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6618}
6619
6620/* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6621static uint8_t
6622bxe_reset_is_global(struct bxe_softc *sc)
6623{
6624    uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6625    BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6626    return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6627}
6628
6629/* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6630static void
6631bxe_set_reset_done(struct bxe_softc *sc)
6632{
6633    uint32_t val;
6634    uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6635                                 BXE_PATH0_RST_IN_PROG_BIT;
6636
6637    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6638
6639    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6640    /* Clear the bit */
6641    val &= ~bit;
6642    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6643
6644    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6645}
6646
6647/* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6648static void
6649bxe_set_reset_in_progress(struct bxe_softc *sc)
6650{
6651    uint32_t val;
6652    uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6653                                 BXE_PATH0_RST_IN_PROG_BIT;
6654
6655    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6656
6657    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6658    /* Set the bit */
6659    val |= bit;
6660    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6661
6662    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6663}
6664
6665/* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6666static uint8_t
6667bxe_reset_is_done(struct bxe_softc *sc,
6668                  int              engine)
6669{
6670    uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6671    uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6672                            BXE_PATH0_RST_IN_PROG_BIT;
6673
6674    /* return false if bit is set */
6675    return (val & bit) ? FALSE : TRUE;
6676}
6677
6678/* get the load status for an engine, should be run under rtnl lock */
6679static uint8_t
6680bxe_get_load_status(struct bxe_softc *sc,
6681                    int              engine)
6682{
6683    uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6684                             BXE_PATH0_LOAD_CNT_MASK;
6685    uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6686                              BXE_PATH0_LOAD_CNT_SHIFT;
6687    uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6688
6689    BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6690
6691    val = ((val & mask) >> shift);
6692
6693    BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6694
6695    return (val != 0);
6696}
6697
6698/* set pf load mark */
6699/* XXX needs to be under rtnl lock */
6700static void
6701bxe_set_pf_load(struct bxe_softc *sc)
6702{
6703    uint32_t val;
6704    uint32_t val1;
6705    uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6706                                  BXE_PATH0_LOAD_CNT_MASK;
6707    uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6708                                   BXE_PATH0_LOAD_CNT_SHIFT;
6709
6710    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6711
6712    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6713    BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6714
6715    /* get the current counter value */
6716    val1 = ((val & mask) >> shift);
6717
6718    /* set bit of this PF */
6719    val1 |= (1 << SC_ABS_FUNC(sc));
6720
6721    /* clear the old value */
6722    val &= ~mask;
6723
6724    /* set the new one */
6725    val |= ((val1 << shift) & mask);
6726
6727    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6728
6729    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6730}
6731
6732/* clear pf load mark */
6733/* XXX needs to be under rtnl lock */
6734static uint8_t
6735bxe_clear_pf_load(struct bxe_softc *sc)
6736{
6737    uint32_t val1, val;
6738    uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6739                                  BXE_PATH0_LOAD_CNT_MASK;
6740    uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6741                                   BXE_PATH0_LOAD_CNT_SHIFT;
6742
6743    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6744    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6745    BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6746
6747    /* get the current counter value */
6748    val1 = (val & mask) >> shift;
6749
6750    /* clear bit of that PF */
6751    val1 &= ~(1 << SC_ABS_FUNC(sc));
6752
6753    /* clear the old value */
6754    val &= ~mask;
6755
6756    /* set the new one */
6757    val |= ((val1 << shift) & mask);
6758
6759    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6760    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6761    return (val1 != 0);
6762}
6763
6764/* send load requrest to mcp and analyze response */
6765static int
6766bxe_nic_load_request(struct bxe_softc *sc,
6767                     uint32_t         *load_code)
6768{
6769    /* init fw_seq */
6770    sc->fw_seq =
6771        (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6772         DRV_MSG_SEQ_NUMBER_MASK);
6773
6774    BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6775
6776    /* get the current FW pulse sequence */
6777    sc->fw_drv_pulse_wr_seq =
6778        (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6779         DRV_PULSE_SEQ_MASK);
6780
6781    BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6782          sc->fw_drv_pulse_wr_seq);
6783
6784    /* load request */
6785    (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6786                                  DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6787
6788    /* if the MCP fails to respond we must abort */
6789    if (!(*load_code)) {
6790        BLOGE(sc, "MCP response failure!\n");
6791        return (-1);
6792    }
6793
6794    /* if MCP refused then must abort */
6795    if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6796        BLOGE(sc, "MCP refused load request\n");
6797        return (-1);
6798    }
6799
6800    return (0);
6801}
6802
6803/*
6804 * Check whether another PF has already loaded FW to chip. In virtualized
6805 * environments a pf from anoth VM may have already initialized the device
6806 * including loading FW.
6807 */
6808static int
6809bxe_nic_load_analyze_req(struct bxe_softc *sc,
6810                         uint32_t         load_code)
6811{
6812    uint32_t my_fw, loaded_fw;
6813
6814    /* is another pf loaded on this engine? */
6815    if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6816        (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6817        /* build my FW version dword */
6818        my_fw = (BCM_5710_FW_MAJOR_VERSION +
6819                 (BCM_5710_FW_MINOR_VERSION << 8 ) +
6820                 (BCM_5710_FW_REVISION_VERSION << 16) +
6821                 (BCM_5710_FW_ENGINEERING_VERSION << 24));
6822
6823        /* read loaded FW from chip */
6824        loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6825        BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6826              loaded_fw, my_fw);
6827
6828        /* abort nic load if version mismatch */
6829        if (my_fw != loaded_fw) {
6830            BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6831                  loaded_fw, my_fw);
6832            return (-1);
6833        }
6834    }
6835
6836    return (0);
6837}
6838
6839/* mark PMF if applicable */
6840static void
6841bxe_nic_load_pmf(struct bxe_softc *sc,
6842                 uint32_t         load_code)
6843{
6844    uint32_t ncsi_oem_data_addr;
6845
6846    if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6847        (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6848        (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6849        /*
6850         * Barrier here for ordering between the writing to sc->port.pmf here
6851         * and reading it from the periodic task.
6852         */
6853        sc->port.pmf = 1;
6854        mb();
6855    } else {
6856        sc->port.pmf = 0;
6857    }
6858
6859    BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6860
6861    /* XXX needed? */
6862    if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6863        if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6864            ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6865            if (ncsi_oem_data_addr) {
6866                REG_WR(sc,
6867                       (ncsi_oem_data_addr +
6868                        offsetof(struct glob_ncsi_oem_data, driver_version)),
6869                       0);
6870            }
6871        }
6872    }
6873}
6874
6875static void
6876bxe_read_mf_cfg(struct bxe_softc *sc)
6877{
6878    int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6879    int abs_func;
6880    int vn;
6881
6882    if (BXE_NOMCP(sc)) {
6883        return; /* what should be the default bvalue in this case */
6884    }
6885
6886    /*
6887     * The formula for computing the absolute function number is...
6888     * For 2 port configuration (4 functions per port):
6889     *   abs_func = 2 * vn + SC_PORT + SC_PATH
6890     * For 4 port configuration (2 functions per port):
6891     *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6892     */
6893    for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6894        abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6895        if (abs_func >= E1H_FUNC_MAX) {
6896            break;
6897        }
6898        sc->devinfo.mf_info.mf_config[vn] =
6899            MFCFG_RD(sc, func_mf_config[abs_func].config);
6900    }
6901
6902    if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6903        FUNC_MF_CFG_FUNC_DISABLED) {
6904        BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6905        sc->flags |= BXE_MF_FUNC_DIS;
6906    } else {
6907        BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6908        sc->flags &= ~BXE_MF_FUNC_DIS;
6909    }
6910}
6911
6912/* acquire split MCP access lock register */
6913static int bxe_acquire_alr(struct bxe_softc *sc)
6914{
6915    uint32_t j, val;
6916
6917    for (j = 0; j < 1000; j++) {
6918        val = (1UL << 31);
6919        REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6920        val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6921        if (val & (1L << 31))
6922            break;
6923
6924        DELAY(5000);
6925    }
6926
6927    if (!(val & (1L << 31))) {
6928        BLOGE(sc, "Cannot acquire MCP access lock register\n");
6929        return (-1);
6930    }
6931
6932    return (0);
6933}
6934
6935/* release split MCP access lock register */
6936static void bxe_release_alr(struct bxe_softc *sc)
6937{
6938    REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
6939}
6940
6941static void
6942bxe_fan_failure(struct bxe_softc *sc)
6943{
6944    int port = SC_PORT(sc);
6945    uint32_t ext_phy_config;
6946
6947    /* mark the failure */
6948    ext_phy_config =
6949        SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
6950
6951    ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
6952    ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
6953    SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
6954             ext_phy_config);
6955
6956    /* log the failure */
6957    BLOGW(sc, "Fan Failure has caused the driver to shutdown "
6958              "the card to prevent permanent damage. "
6959              "Please contact OEM Support for assistance\n");
6960
6961    /* XXX */
6962#if 1
6963    bxe_panic(sc, ("Schedule task to handle fan failure\n"));
6964#else
6965    /*
6966     * Schedule device reset (unload)
6967     * This is due to some boards consuming sufficient power when driver is
6968     * up to overheat if fan fails.
6969     */
6970    bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
6971    schedule_delayed_work(&sc->sp_rtnl_task, 0);
6972#endif
6973}
6974
6975/* this function is called upon a link interrupt */
6976static void
6977bxe_link_attn(struct bxe_softc *sc)
6978{
6979    uint32_t pause_enabled = 0;
6980    struct host_port_stats *pstats;
6981    int cmng_fns;
6982    struct bxe_fastpath *fp;
6983    int i;
6984
6985    /* Make sure that we are synced with the current statistics */
6986    bxe_stats_handle(sc, STATS_EVENT_STOP);
6987
6988    elink_link_update(&sc->link_params, &sc->link_vars);
6989
6990    if (sc->link_vars.link_up) {
6991
6992        /* dropless flow control */
6993        if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
6994            pause_enabled = 0;
6995
6996            if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
6997                pause_enabled = 1;
6998            }
6999
7000            REG_WR(sc,
7001                   (BAR_USTRORM_INTMEM +
7002                    USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7003                   pause_enabled);
7004        }
7005
7006        if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7007            pstats = BXE_SP(sc, port_stats);
7008            /* reset old mac stats */
7009            memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7010        }
7011
7012        if (sc->state == BXE_STATE_OPEN) {
7013            bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7014        }
7015
7016	/* Restart tx when the link comes back. */
7017        FOR_EACH_ETH_QUEUE(sc, i) {
7018            fp = &sc->fp[i];
7019            taskqueue_enqueue(fp->tq, &fp->tx_task);
7020	}
7021    }
7022
7023    if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7024        cmng_fns = bxe_get_cmng_fns_mode(sc);
7025
7026        if (cmng_fns != CMNG_FNS_NONE) {
7027            bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7028            storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7029        } else {
7030            /* rate shaping and fairness are disabled */
7031            BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7032        }
7033    }
7034
7035    bxe_link_report_locked(sc);
7036
7037    if (IS_MF(sc)) {
7038        ; // XXX bxe_link_sync_notify(sc);
7039    }
7040}
7041
7042static void
7043bxe_attn_int_asserted(struct bxe_softc *sc,
7044                      uint32_t         asserted)
7045{
7046    int port = SC_PORT(sc);
7047    uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7048                               MISC_REG_AEU_MASK_ATTN_FUNC_0;
7049    uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7050                                        NIG_REG_MASK_INTERRUPT_PORT0;
7051    uint32_t aeu_mask;
7052    uint32_t nig_mask = 0;
7053    uint32_t reg_addr;
7054    uint32_t igu_acked;
7055    uint32_t cnt;
7056
7057    if (sc->attn_state & asserted) {
7058        BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7059    }
7060
7061    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7062
7063    aeu_mask = REG_RD(sc, aeu_addr);
7064
7065    BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7066          aeu_mask, asserted);
7067
7068    aeu_mask &= ~(asserted & 0x3ff);
7069
7070    BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7071
7072    REG_WR(sc, aeu_addr, aeu_mask);
7073
7074    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7075
7076    BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7077    sc->attn_state |= asserted;
7078    BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7079
7080    if (asserted & ATTN_HARD_WIRED_MASK) {
7081        if (asserted & ATTN_NIG_FOR_FUNC) {
7082
7083	    bxe_acquire_phy_lock(sc);
7084            /* save nig interrupt mask */
7085            nig_mask = REG_RD(sc, nig_int_mask_addr);
7086
7087            /* If nig_mask is not set, no need to call the update function */
7088            if (nig_mask) {
7089                REG_WR(sc, nig_int_mask_addr, 0);
7090
7091                bxe_link_attn(sc);
7092            }
7093
7094            /* handle unicore attn? */
7095        }
7096
7097        if (asserted & ATTN_SW_TIMER_4_FUNC) {
7098            BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7099        }
7100
7101        if (asserted & GPIO_2_FUNC) {
7102            BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7103        }
7104
7105        if (asserted & GPIO_3_FUNC) {
7106            BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7107        }
7108
7109        if (asserted & GPIO_4_FUNC) {
7110            BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7111        }
7112
7113        if (port == 0) {
7114            if (asserted & ATTN_GENERAL_ATTN_1) {
7115                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7116                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7117            }
7118            if (asserted & ATTN_GENERAL_ATTN_2) {
7119                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7120                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7121            }
7122            if (asserted & ATTN_GENERAL_ATTN_3) {
7123                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7124                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7125            }
7126        } else {
7127            if (asserted & ATTN_GENERAL_ATTN_4) {
7128                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7129                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7130            }
7131            if (asserted & ATTN_GENERAL_ATTN_5) {
7132                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7133                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7134            }
7135            if (asserted & ATTN_GENERAL_ATTN_6) {
7136                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7137                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7138            }
7139        }
7140    } /* hardwired */
7141
7142    if (sc->devinfo.int_block == INT_BLOCK_HC) {
7143        reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7144    } else {
7145        reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7146    }
7147
7148    BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7149          asserted,
7150          (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7151    REG_WR(sc, reg_addr, asserted);
7152
7153    /* now set back the mask */
7154    if (asserted & ATTN_NIG_FOR_FUNC) {
7155        /*
7156         * Verify that IGU ack through BAR was written before restoring
7157         * NIG mask. This loop should exit after 2-3 iterations max.
7158         */
7159        if (sc->devinfo.int_block != INT_BLOCK_HC) {
7160            cnt = 0;
7161
7162            do {
7163                igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7164            } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7165                     (++cnt < MAX_IGU_ATTN_ACK_TO));
7166
7167            if (!igu_acked) {
7168                BLOGE(sc, "Failed to verify IGU ack on time\n");
7169            }
7170
7171            mb();
7172        }
7173
7174        REG_WR(sc, nig_int_mask_addr, nig_mask);
7175
7176	bxe_release_phy_lock(sc);
7177    }
7178}
7179
7180static void
7181bxe_print_next_block(struct bxe_softc *sc,
7182                     int              idx,
7183                     const char       *blk)
7184{
7185    BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7186}
7187
7188static int
7189bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7190                              uint32_t         sig,
7191                              int              par_num,
7192                              uint8_t          print)
7193{
7194    uint32_t cur_bit = 0;
7195    int i = 0;
7196
7197    for (i = 0; sig; i++) {
7198        cur_bit = ((uint32_t)0x1 << i);
7199        if (sig & cur_bit) {
7200            switch (cur_bit) {
7201            case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7202                if (print)
7203                    bxe_print_next_block(sc, par_num++, "BRB");
7204                break;
7205            case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7206                if (print)
7207                    bxe_print_next_block(sc, par_num++, "PARSER");
7208                break;
7209            case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7210                if (print)
7211                    bxe_print_next_block(sc, par_num++, "TSDM");
7212                break;
7213            case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7214                if (print)
7215                    bxe_print_next_block(sc, par_num++, "SEARCHER");
7216                break;
7217            case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7218                if (print)
7219                    bxe_print_next_block(sc, par_num++, "TCM");
7220                break;
7221            case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7222                if (print)
7223                    bxe_print_next_block(sc, par_num++, "TSEMI");
7224                break;
7225            case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7226                if (print)
7227                    bxe_print_next_block(sc, par_num++, "XPB");
7228                break;
7229            }
7230
7231            /* Clear the bit */
7232            sig &= ~cur_bit;
7233        }
7234    }
7235
7236    return (par_num);
7237}
7238
7239static int
7240bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7241                              uint32_t         sig,
7242                              int              par_num,
7243                              uint8_t          *global,
7244                              uint8_t          print)
7245{
7246    int i = 0;
7247    uint32_t cur_bit = 0;
7248    for (i = 0; sig; i++) {
7249        cur_bit = ((uint32_t)0x1 << i);
7250        if (sig & cur_bit) {
7251            switch (cur_bit) {
7252            case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7253                if (print)
7254                    bxe_print_next_block(sc, par_num++, "PBF");
7255                break;
7256            case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7257                if (print)
7258                    bxe_print_next_block(sc, par_num++, "QM");
7259                break;
7260            case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7261                if (print)
7262                    bxe_print_next_block(sc, par_num++, "TM");
7263                break;
7264            case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7265                if (print)
7266                    bxe_print_next_block(sc, par_num++, "XSDM");
7267                break;
7268            case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7269                if (print)
7270                    bxe_print_next_block(sc, par_num++, "XCM");
7271                break;
7272            case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7273                if (print)
7274                    bxe_print_next_block(sc, par_num++, "XSEMI");
7275                break;
7276            case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7277                if (print)
7278                    bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7279                break;
7280            case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7281                if (print)
7282                    bxe_print_next_block(sc, par_num++, "NIG");
7283                break;
7284            case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7285                if (print)
7286                    bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7287                *global = TRUE;
7288                break;
7289            case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7290                if (print)
7291                    bxe_print_next_block(sc, par_num++, "DEBUG");
7292                break;
7293            case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7294                if (print)
7295                    bxe_print_next_block(sc, par_num++, "USDM");
7296                break;
7297            case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7298                if (print)
7299                    bxe_print_next_block(sc, par_num++, "UCM");
7300                break;
7301            case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7302                if (print)
7303                    bxe_print_next_block(sc, par_num++, "USEMI");
7304                break;
7305            case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7306                if (print)
7307                    bxe_print_next_block(sc, par_num++, "UPB");
7308                break;
7309            case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7310                if (print)
7311                    bxe_print_next_block(sc, par_num++, "CSDM");
7312                break;
7313            case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7314                if (print)
7315                    bxe_print_next_block(sc, par_num++, "CCM");
7316                break;
7317            }
7318
7319            /* Clear the bit */
7320            sig &= ~cur_bit;
7321        }
7322    }
7323
7324    return (par_num);
7325}
7326
7327static int
7328bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7329                              uint32_t         sig,
7330                              int              par_num,
7331                              uint8_t          print)
7332{
7333    uint32_t cur_bit = 0;
7334    int i = 0;
7335
7336    for (i = 0; sig; i++) {
7337        cur_bit = ((uint32_t)0x1 << i);
7338        if (sig & cur_bit) {
7339            switch (cur_bit) {
7340            case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7341                if (print)
7342                    bxe_print_next_block(sc, par_num++, "CSEMI");
7343                break;
7344            case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7345                if (print)
7346                    bxe_print_next_block(sc, par_num++, "PXP");
7347                break;
7348            case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7349                if (print)
7350                    bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7351                break;
7352            case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7353                if (print)
7354                    bxe_print_next_block(sc, par_num++, "CFC");
7355                break;
7356            case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7357                if (print)
7358                    bxe_print_next_block(sc, par_num++, "CDU");
7359                break;
7360            case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7361                if (print)
7362                    bxe_print_next_block(sc, par_num++, "DMAE");
7363                break;
7364            case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7365                if (print)
7366                    bxe_print_next_block(sc, par_num++, "IGU");
7367                break;
7368            case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7369                if (print)
7370                    bxe_print_next_block(sc, par_num++, "MISC");
7371                break;
7372            }
7373
7374            /* Clear the bit */
7375            sig &= ~cur_bit;
7376        }
7377    }
7378
7379    return (par_num);
7380}
7381
7382static int
7383bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7384                              uint32_t         sig,
7385                              int              par_num,
7386                              uint8_t          *global,
7387                              uint8_t          print)
7388{
7389    uint32_t cur_bit = 0;
7390    int i = 0;
7391
7392    for (i = 0; sig; i++) {
7393        cur_bit = ((uint32_t)0x1 << i);
7394        if (sig & cur_bit) {
7395            switch (cur_bit) {
7396            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7397                if (print)
7398                    bxe_print_next_block(sc, par_num++, "MCP ROM");
7399                *global = TRUE;
7400                break;
7401            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7402                if (print)
7403                    bxe_print_next_block(sc, par_num++,
7404                              "MCP UMP RX");
7405                *global = TRUE;
7406                break;
7407            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7408                if (print)
7409                    bxe_print_next_block(sc, par_num++,
7410                              "MCP UMP TX");
7411                *global = TRUE;
7412                break;
7413            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7414                if (print)
7415                    bxe_print_next_block(sc, par_num++,
7416                              "MCP SCPAD");
7417                *global = TRUE;
7418                break;
7419            }
7420
7421            /* Clear the bit */
7422            sig &= ~cur_bit;
7423        }
7424    }
7425
7426    return (par_num);
7427}
7428
7429static int
7430bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7431                              uint32_t         sig,
7432                              int              par_num,
7433                              uint8_t          print)
7434{
7435    uint32_t cur_bit = 0;
7436    int i = 0;
7437
7438    for (i = 0; sig; i++) {
7439        cur_bit = ((uint32_t)0x1 << i);
7440        if (sig & cur_bit) {
7441            switch (cur_bit) {
7442            case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7443                if (print)
7444                    bxe_print_next_block(sc, par_num++, "PGLUE_B");
7445                break;
7446            case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7447                if (print)
7448                    bxe_print_next_block(sc, par_num++, "ATC");
7449                break;
7450            }
7451
7452            /* Clear the bit */
7453            sig &= ~cur_bit;
7454        }
7455    }
7456
7457    return (par_num);
7458}
7459
7460static uint8_t
7461bxe_parity_attn(struct bxe_softc *sc,
7462                uint8_t          *global,
7463                uint8_t          print,
7464                uint32_t         *sig)
7465{
7466    int par_num = 0;
7467
7468    if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7469        (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7470        (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7471        (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7472        (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7473        BLOGE(sc, "Parity error: HW block parity attention:\n"
7474                  "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7475              (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7476              (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7477              (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7478              (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7479              (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7480
7481        if (print)
7482            BLOGI(sc, "Parity errors detected in blocks: ");
7483
7484        par_num =
7485            bxe_check_blocks_with_parity0(sc, sig[0] &
7486                                          HW_PRTY_ASSERT_SET_0,
7487                                          par_num, print);
7488        par_num =
7489            bxe_check_blocks_with_parity1(sc, sig[1] &
7490                                          HW_PRTY_ASSERT_SET_1,
7491                                          par_num, global, print);
7492        par_num =
7493            bxe_check_blocks_with_parity2(sc, sig[2] &
7494                                          HW_PRTY_ASSERT_SET_2,
7495                                          par_num, print);
7496        par_num =
7497            bxe_check_blocks_with_parity3(sc, sig[3] &
7498                                          HW_PRTY_ASSERT_SET_3,
7499                                          par_num, global, print);
7500        par_num =
7501            bxe_check_blocks_with_parity4(sc, sig[4] &
7502                                          HW_PRTY_ASSERT_SET_4,
7503                                          par_num, print);
7504
7505        if (print)
7506            BLOGI(sc, "\n");
7507
7508        return (TRUE);
7509    }
7510
7511    return (FALSE);
7512}
7513
7514static uint8_t
7515bxe_chk_parity_attn(struct bxe_softc *sc,
7516                    uint8_t          *global,
7517                    uint8_t          print)
7518{
7519    struct attn_route attn = { {0} };
7520    int port = SC_PORT(sc);
7521
7522    attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7523    attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7524    attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7525    attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7526
7527    /*
7528     * Since MCP attentions can't be disabled inside the block, we need to
7529     * read AEU registers to see whether they're currently disabled
7530     */
7531    attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7532                                      : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7533                         MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7534                        ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7535
7536
7537    if (!CHIP_IS_E1x(sc))
7538        attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7539
7540    return (bxe_parity_attn(sc, global, print, attn.sig));
7541}
7542
7543static void
7544bxe_attn_int_deasserted4(struct bxe_softc *sc,
7545                         uint32_t         attn)
7546{
7547    uint32_t val;
7548
7549    if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7550        val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7551        BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7552        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7553            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7554        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7555            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7556        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7557            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7558        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7559            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7560        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7561            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7562        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7563            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7564        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7565            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7566        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7567            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7568        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7569            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7570    }
7571
7572    if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7573        val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7574        BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7575        if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7576            BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7577        if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7578            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7579        if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7580            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7581        if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7582            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7583        if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7584            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7585        if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7586            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7587    }
7588
7589    if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7590                AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7591        BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7592              (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7593                                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7594    }
7595}
7596
7597static void
7598bxe_e1h_disable(struct bxe_softc *sc)
7599{
7600    int port = SC_PORT(sc);
7601
7602    bxe_tx_disable(sc);
7603
7604    REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7605}
7606
7607static void
7608bxe_e1h_enable(struct bxe_softc *sc)
7609{
7610    int port = SC_PORT(sc);
7611
7612    REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7613
7614    // XXX bxe_tx_enable(sc);
7615}
7616
7617/*
7618 * called due to MCP event (on pmf):
7619 *   reread new bandwidth configuration
7620 *   configure FW
7621 *   notify others function about the change
7622 */
7623static void
7624bxe_config_mf_bw(struct bxe_softc *sc)
7625{
7626    if (sc->link_vars.link_up) {
7627        bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7628        // XXX bxe_link_sync_notify(sc);
7629    }
7630
7631    storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7632}
7633
7634static void
7635bxe_set_mf_bw(struct bxe_softc *sc)
7636{
7637    bxe_config_mf_bw(sc);
7638    bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7639}
7640
7641static void
7642bxe_handle_eee_event(struct bxe_softc *sc)
7643{
7644    BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7645    bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7646}
7647
7648#define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7649
7650static void
7651bxe_drv_info_ether_stat(struct bxe_softc *sc)
7652{
7653    struct eth_stats_info *ether_stat =
7654        &sc->sp->drv_info_to_mcp.ether_stat;
7655
7656    strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7657            ETH_STAT_INFO_VERSION_LEN);
7658
7659    /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7660    sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7661                                          DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7662                                          ether_stat->mac_local + MAC_PAD,
7663                                          MAC_PAD, ETH_ALEN);
7664
7665    ether_stat->mtu_size = sc->mtu;
7666
7667    ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7668    if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
7669        ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7670    }
7671
7672    // XXX ether_stat->feature_flags |= ???;
7673
7674    ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7675
7676    ether_stat->txq_size = sc->tx_ring_size;
7677    ether_stat->rxq_size = sc->rx_ring_size;
7678}
7679
7680static void
7681bxe_handle_drv_info_req(struct bxe_softc *sc)
7682{
7683    enum drv_info_opcode op_code;
7684    uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7685
7686    /* if drv_info version supported by MFW doesn't match - send NACK */
7687    if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7688        bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7689        return;
7690    }
7691
7692    op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7693               DRV_INFO_CONTROL_OP_CODE_SHIFT);
7694
7695    memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7696
7697    switch (op_code) {
7698    case ETH_STATS_OPCODE:
7699        bxe_drv_info_ether_stat(sc);
7700        break;
7701    case FCOE_STATS_OPCODE:
7702    case ISCSI_STATS_OPCODE:
7703    default:
7704        /* if op code isn't supported - send NACK */
7705        bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7706        return;
7707    }
7708
7709    /*
7710     * If we got drv_info attn from MFW then these fields are defined in
7711     * shmem2 for sure
7712     */
7713    SHMEM2_WR(sc, drv_info_host_addr_lo,
7714              U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7715    SHMEM2_WR(sc, drv_info_host_addr_hi,
7716              U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7717
7718    bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7719}
7720
7721static void
7722bxe_dcc_event(struct bxe_softc *sc,
7723              uint32_t         dcc_event)
7724{
7725    BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7726
7727    if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7728        /*
7729         * This is the only place besides the function initialization
7730         * where the sc->flags can change so it is done without any
7731         * locks
7732         */
7733        if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7734            BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7735            sc->flags |= BXE_MF_FUNC_DIS;
7736            bxe_e1h_disable(sc);
7737        } else {
7738            BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7739            sc->flags &= ~BXE_MF_FUNC_DIS;
7740            bxe_e1h_enable(sc);
7741        }
7742        dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7743    }
7744
7745    if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7746        bxe_config_mf_bw(sc);
7747        dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7748    }
7749
7750    /* Report results to MCP */
7751    if (dcc_event)
7752        bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7753    else
7754        bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7755}
7756
7757static void
7758bxe_pmf_update(struct bxe_softc *sc)
7759{
7760    int port = SC_PORT(sc);
7761    uint32_t val;
7762
7763    sc->port.pmf = 1;
7764    BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7765
7766    /*
7767     * We need the mb() to ensure the ordering between the writing to
7768     * sc->port.pmf here and reading it from the bxe_periodic_task().
7769     */
7770    mb();
7771
7772    /* queue a periodic task */
7773    // XXX schedule task...
7774
7775    // XXX bxe_dcbx_pmf_update(sc);
7776
7777    /* enable nig attention */
7778    val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7779    if (sc->devinfo.int_block == INT_BLOCK_HC) {
7780        REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7781        REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7782    } else if (!CHIP_IS_E1x(sc)) {
7783        REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7784        REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7785    }
7786
7787    bxe_stats_handle(sc, STATS_EVENT_PMF);
7788}
7789
7790static int
7791bxe_mc_assert(struct bxe_softc *sc)
7792{
7793    char last_idx;
7794    int i, rc = 0;
7795    uint32_t row0, row1, row2, row3;
7796
7797    /* XSTORM */
7798    last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7799    if (last_idx)
7800        BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7801
7802    /* print the asserts */
7803    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7804
7805        row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7806        row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7807        row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7808        row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7809
7810        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7811            BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7812                  i, row3, row2, row1, row0);
7813            rc++;
7814        } else {
7815            break;
7816        }
7817    }
7818
7819    /* TSTORM */
7820    last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7821    if (last_idx) {
7822        BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7823    }
7824
7825    /* print the asserts */
7826    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7827
7828        row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7829        row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7830        row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7831        row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7832
7833        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7834            BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7835                  i, row3, row2, row1, row0);
7836            rc++;
7837        } else {
7838            break;
7839        }
7840    }
7841
7842    /* CSTORM */
7843    last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7844    if (last_idx) {
7845        BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7846    }
7847
7848    /* print the asserts */
7849    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7850
7851        row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7852        row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7853        row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7854        row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7855
7856        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7857            BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7858                  i, row3, row2, row1, row0);
7859            rc++;
7860        } else {
7861            break;
7862        }
7863    }
7864
7865    /* USTORM */
7866    last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7867    if (last_idx) {
7868        BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7869    }
7870
7871    /* print the asserts */
7872    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7873
7874        row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7875        row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7876        row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7877        row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7878
7879        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7880            BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7881                  i, row3, row2, row1, row0);
7882            rc++;
7883        } else {
7884            break;
7885        }
7886    }
7887
7888    return (rc);
7889}
7890
7891static void
7892bxe_attn_int_deasserted3(struct bxe_softc *sc,
7893                         uint32_t         attn)
7894{
7895    int func = SC_FUNC(sc);
7896    uint32_t val;
7897
7898    if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7899
7900        if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7901
7902            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7903            bxe_read_mf_cfg(sc);
7904            sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7905                MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7906            val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7907
7908            if (val & DRV_STATUS_DCC_EVENT_MASK)
7909                bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7910
7911            if (val & DRV_STATUS_SET_MF_BW)
7912                bxe_set_mf_bw(sc);
7913
7914            if (val & DRV_STATUS_DRV_INFO_REQ)
7915                bxe_handle_drv_info_req(sc);
7916
7917            if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
7918                bxe_pmf_update(sc);
7919
7920            if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
7921                bxe_handle_eee_event(sc);
7922
7923            if (sc->link_vars.periodic_flags &
7924                ELINK_PERIODIC_FLAGS_LINK_EVENT) {
7925                /* sync with link */
7926		bxe_acquire_phy_lock(sc);
7927                sc->link_vars.periodic_flags &=
7928                    ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
7929		bxe_release_phy_lock(sc);
7930                if (IS_MF(sc))
7931                    ; // XXX bxe_link_sync_notify(sc);
7932                bxe_link_report(sc);
7933            }
7934
7935            /*
7936             * Always call it here: bxe_link_report() will
7937             * prevent the link indication duplication.
7938             */
7939            bxe_link_status_update(sc);
7940
7941        } else if (attn & BXE_MC_ASSERT_BITS) {
7942
7943            BLOGE(sc, "MC assert!\n");
7944            bxe_mc_assert(sc);
7945            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
7946            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
7947            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
7948            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
7949            bxe_panic(sc, ("MC assert!\n"));
7950
7951        } else if (attn & BXE_MCP_ASSERT) {
7952
7953            BLOGE(sc, "MCP assert!\n");
7954            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
7955            // XXX bxe_fw_dump(sc);
7956
7957        } else {
7958            BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
7959        }
7960    }
7961
7962    if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
7963        BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
7964        if (attn & BXE_GRC_TIMEOUT) {
7965            val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
7966            BLOGE(sc, "GRC time-out 0x%08x\n", val);
7967        }
7968        if (attn & BXE_GRC_RSV) {
7969            val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
7970            BLOGE(sc, "GRC reserved 0x%08x\n", val);
7971        }
7972        REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
7973    }
7974}
7975
7976static void
7977bxe_attn_int_deasserted2(struct bxe_softc *sc,
7978                         uint32_t         attn)
7979{
7980    int port = SC_PORT(sc);
7981    int reg_offset;
7982    uint32_t val0, mask0, val1, mask1;
7983    uint32_t val;
7984
7985    if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
7986        val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
7987        BLOGE(sc, "CFC hw attention 0x%08x\n", val);
7988        /* CFC error attention */
7989        if (val & 0x2) {
7990            BLOGE(sc, "FATAL error from CFC\n");
7991        }
7992    }
7993
7994    if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
7995        val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
7996        BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
7997        /* RQ_USDMDP_FIFO_OVERFLOW */
7998        if (val & 0x18000) {
7999            BLOGE(sc, "FATAL error from PXP\n");
8000        }
8001
8002        if (!CHIP_IS_E1x(sc)) {
8003            val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8004            BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8005        }
8006    }
8007
8008#define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8009#define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8010
8011    if (attn & AEU_PXP2_HW_INT_BIT) {
8012        /*  CQ47854 workaround do not panic on
8013         *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8014         */
8015        if (!CHIP_IS_E1x(sc)) {
8016            mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8017            val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8018            mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8019            val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8020            /*
8021             * If the only PXP2_EOP_ERROR_BIT is set in
8022             * STS0 and STS1 - clear it
8023             *
8024             * probably we lose additional attentions between
8025             * STS0 and STS_CLR0, in this case user will not
8026             * be notified about them
8027             */
8028            if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8029                !(val1 & mask1))
8030                val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8031
8032            /* print the register, since no one can restore it */
8033            BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8034
8035            /*
8036             * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8037             * then notify
8038             */
8039            if (val0 & PXP2_EOP_ERROR_BIT) {
8040                BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8041
8042                /*
8043                 * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8044                 * set then clear attention from PXP2 block without panic
8045                 */
8046                if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8047                    ((val1 & mask1) == 0))
8048                    attn &= ~AEU_PXP2_HW_INT_BIT;
8049            }
8050        }
8051    }
8052
8053    if (attn & HW_INTERRUT_ASSERT_SET_2) {
8054        reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8055                             MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8056
8057        val = REG_RD(sc, reg_offset);
8058        val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8059        REG_WR(sc, reg_offset, val);
8060
8061        BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8062              (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8063        bxe_panic(sc, ("HW block attention set2\n"));
8064    }
8065}
8066
8067static void
8068bxe_attn_int_deasserted1(struct bxe_softc *sc,
8069                         uint32_t         attn)
8070{
8071    int port = SC_PORT(sc);
8072    int reg_offset;
8073    uint32_t val;
8074
8075    if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8076        val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8077        BLOGE(sc, "DB hw attention 0x%08x\n", val);
8078        /* DORQ discard attention */
8079        if (val & 0x2) {
8080            BLOGE(sc, "FATAL error from DORQ\n");
8081        }
8082    }
8083
8084    if (attn & HW_INTERRUT_ASSERT_SET_1) {
8085        reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8086                             MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8087
8088        val = REG_RD(sc, reg_offset);
8089        val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8090        REG_WR(sc, reg_offset, val);
8091
8092        BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8093              (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8094        bxe_panic(sc, ("HW block attention set1\n"));
8095    }
8096}
8097
8098static void
8099bxe_attn_int_deasserted0(struct bxe_softc *sc,
8100                         uint32_t         attn)
8101{
8102    int port = SC_PORT(sc);
8103    int reg_offset;
8104    uint32_t val;
8105
8106    reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8107                          MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8108
8109    if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8110        val = REG_RD(sc, reg_offset);
8111        val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8112        REG_WR(sc, reg_offset, val);
8113
8114        BLOGW(sc, "SPIO5 hw attention\n");
8115
8116        /* Fan failure attention */
8117        elink_hw_reset_phy(&sc->link_params);
8118        bxe_fan_failure(sc);
8119    }
8120
8121    if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8122	bxe_acquire_phy_lock(sc);
8123        elink_handle_module_detect_int(&sc->link_params);
8124	bxe_release_phy_lock(sc);
8125    }
8126
8127    if (attn & HW_INTERRUT_ASSERT_SET_0) {
8128        val = REG_RD(sc, reg_offset);
8129        val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8130        REG_WR(sc, reg_offset, val);
8131
8132        bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8133                       (attn & HW_INTERRUT_ASSERT_SET_0)));
8134    }
8135}
8136
8137static void
8138bxe_attn_int_deasserted(struct bxe_softc *sc,
8139                        uint32_t         deasserted)
8140{
8141    struct attn_route attn;
8142    struct attn_route *group_mask;
8143    int port = SC_PORT(sc);
8144    int index;
8145    uint32_t reg_addr;
8146    uint32_t val;
8147    uint32_t aeu_mask;
8148    uint8_t global = FALSE;
8149
8150    /*
8151     * Need to take HW lock because MCP or other port might also
8152     * try to handle this event.
8153     */
8154    bxe_acquire_alr(sc);
8155
8156    if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8157        /* XXX
8158         * In case of parity errors don't handle attentions so that
8159         * other function would "see" parity errors.
8160         */
8161        sc->recovery_state = BXE_RECOVERY_INIT;
8162        // XXX schedule a recovery task...
8163        /* disable HW interrupts */
8164        bxe_int_disable(sc);
8165        bxe_release_alr(sc);
8166        return;
8167    }
8168
8169    attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8170    attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8171    attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8172    attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8173    if (!CHIP_IS_E1x(sc)) {
8174        attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8175    } else {
8176        attn.sig[4] = 0;
8177    }
8178
8179    BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8180          attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8181
8182    for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8183        if (deasserted & (1 << index)) {
8184            group_mask = &sc->attn_group[index];
8185
8186            BLOGD(sc, DBG_INTR,
8187                  "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8188                  group_mask->sig[0], group_mask->sig[1],
8189                  group_mask->sig[2], group_mask->sig[3],
8190                  group_mask->sig[4]);
8191
8192            bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8193            bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8194            bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8195            bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8196            bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8197        }
8198    }
8199
8200    bxe_release_alr(sc);
8201
8202    if (sc->devinfo.int_block == INT_BLOCK_HC) {
8203        reg_addr = (HC_REG_COMMAND_REG + port*32 +
8204                    COMMAND_REG_ATTN_BITS_CLR);
8205    } else {
8206        reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8207    }
8208
8209    val = ~deasserted;
8210    BLOGD(sc, DBG_INTR,
8211          "about to mask 0x%08x at %s addr 0x%08x\n", val,
8212          (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8213    REG_WR(sc, reg_addr, val);
8214
8215    if (~sc->attn_state & deasserted) {
8216        BLOGE(sc, "IGU error\n");
8217    }
8218
8219    reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8220                      MISC_REG_AEU_MASK_ATTN_FUNC_0;
8221
8222    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8223
8224    aeu_mask = REG_RD(sc, reg_addr);
8225
8226    BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8227          aeu_mask, deasserted);
8228    aeu_mask |= (deasserted & 0x3ff);
8229    BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8230
8231    REG_WR(sc, reg_addr, aeu_mask);
8232    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8233
8234    BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8235    sc->attn_state &= ~deasserted;
8236    BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8237}
8238
8239static void
8240bxe_attn_int(struct bxe_softc *sc)
8241{
8242    /* read local copy of bits */
8243    uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8244    uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8245    uint32_t attn_state = sc->attn_state;
8246
8247    /* look for changed bits */
8248    uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8249    uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8250
8251    BLOGD(sc, DBG_INTR,
8252          "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8253          attn_bits, attn_ack, asserted, deasserted);
8254
8255    if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8256        BLOGE(sc, "BAD attention state\n");
8257    }
8258
8259    /* handle bits that were raised */
8260    if (asserted) {
8261        bxe_attn_int_asserted(sc, asserted);
8262    }
8263
8264    if (deasserted) {
8265        bxe_attn_int_deasserted(sc, deasserted);
8266    }
8267}
8268
8269static uint16_t
8270bxe_update_dsb_idx(struct bxe_softc *sc)
8271{
8272    struct host_sp_status_block *def_sb = sc->def_sb;
8273    uint16_t rc = 0;
8274
8275    mb(); /* status block is written to by the chip */
8276
8277    if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8278        sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8279        rc |= BXE_DEF_SB_ATT_IDX;
8280    }
8281
8282    if (sc->def_idx != def_sb->sp_sb.running_index) {
8283        sc->def_idx = def_sb->sp_sb.running_index;
8284        rc |= BXE_DEF_SB_IDX;
8285    }
8286
8287    mb();
8288
8289    return (rc);
8290}
8291
8292static inline struct ecore_queue_sp_obj *
8293bxe_cid_to_q_obj(struct bxe_softc *sc,
8294                 uint32_t         cid)
8295{
8296    BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8297    return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8298}
8299
8300static void
8301bxe_handle_mcast_eqe(struct bxe_softc *sc)
8302{
8303    struct ecore_mcast_ramrod_params rparam;
8304    int rc;
8305
8306    memset(&rparam, 0, sizeof(rparam));
8307
8308    rparam.mcast_obj = &sc->mcast_obj;
8309
8310    BXE_MCAST_LOCK(sc);
8311
8312    /* clear pending state for the last command */
8313    sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8314
8315    /* if there are pending mcast commands - send them */
8316    if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8317        rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8318        if (rc < 0) {
8319            BLOGD(sc, DBG_SP,
8320                "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8321        }
8322    }
8323
8324    BXE_MCAST_UNLOCK(sc);
8325}
8326
8327static void
8328bxe_handle_classification_eqe(struct bxe_softc      *sc,
8329                              union event_ring_elem *elem)
8330{
8331    unsigned long ramrod_flags = 0;
8332    int rc = 0;
8333    uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8334    struct ecore_vlan_mac_obj *vlan_mac_obj;
8335
8336    /* always push next commands out, don't wait here */
8337    bit_set(&ramrod_flags, RAMROD_CONT);
8338
8339    switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8340    case ECORE_FILTER_MAC_PENDING:
8341        BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8342        vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8343        break;
8344
8345    case ECORE_FILTER_MCAST_PENDING:
8346        BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8347        /*
8348         * This is only relevant for 57710 where multicast MACs are
8349         * configured as unicast MACs using the same ramrod.
8350         */
8351        bxe_handle_mcast_eqe(sc);
8352        return;
8353
8354    default:
8355        BLOGE(sc, "Unsupported classification command: %d\n",
8356              elem->message.data.eth_event.echo);
8357        return;
8358    }
8359
8360    rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8361
8362    if (rc < 0) {
8363        BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8364    } else if (rc > 0) {
8365        BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8366    }
8367}
8368
8369static void
8370bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8371                       union event_ring_elem *elem)
8372{
8373    bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8374
8375    /* send rx_mode command again if was requested */
8376    if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8377                               &sc->sp_state)) {
8378        bxe_set_storm_rx_mode(sc);
8379    }
8380}
8381
8382static void
8383bxe_update_eq_prod(struct bxe_softc *sc,
8384                   uint16_t         prod)
8385{
8386    storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8387    wmb(); /* keep prod updates ordered */
8388}
8389
8390static void
8391bxe_eq_int(struct bxe_softc *sc)
8392{
8393    uint16_t hw_cons, sw_cons, sw_prod;
8394    union event_ring_elem *elem;
8395    uint8_t echo;
8396    uint32_t cid;
8397    uint8_t opcode;
8398    int spqe_cnt = 0;
8399    struct ecore_queue_sp_obj *q_obj;
8400    struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8401    struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8402
8403    hw_cons = le16toh(*sc->eq_cons_sb);
8404
8405    /*
8406     * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8407     * when we get to the next-page we need to adjust so the loop
8408     * condition below will be met. The next element is the size of a
8409     * regular element and hence incrementing by 1
8410     */
8411    if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8412        hw_cons++;
8413    }
8414
8415    /*
8416     * This function may never run in parallel with itself for a
8417     * specific sc and no need for a read memory barrier here.
8418     */
8419    sw_cons = sc->eq_cons;
8420    sw_prod = sc->eq_prod;
8421
8422    BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8423          hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8424
8425    for (;
8426         sw_cons != hw_cons;
8427         sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8428
8429        elem = &sc->eq[EQ_DESC(sw_cons)];
8430
8431        /* elem CID originates from FW, actually LE */
8432        cid = SW_CID(elem->message.data.cfc_del_event.cid);
8433        opcode = elem->message.opcode;
8434
8435        /* handle eq element */
8436        switch (opcode) {
8437
8438        case EVENT_RING_OPCODE_STAT_QUERY:
8439            BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8440                  sc->stats_comp++);
8441            /* nothing to do with stats comp */
8442            goto next_spqe;
8443
8444        case EVENT_RING_OPCODE_CFC_DEL:
8445            /* handle according to cid range */
8446            /* we may want to verify here that the sc state is HALTING */
8447            BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8448            q_obj = bxe_cid_to_q_obj(sc, cid);
8449            if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8450                break;
8451            }
8452            goto next_spqe;
8453
8454        case EVENT_RING_OPCODE_STOP_TRAFFIC:
8455            BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8456            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8457                break;
8458            }
8459            // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8460            goto next_spqe;
8461
8462        case EVENT_RING_OPCODE_START_TRAFFIC:
8463            BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8464            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8465                break;
8466            }
8467            // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8468            goto next_spqe;
8469
8470        case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8471            echo = elem->message.data.function_update_event.echo;
8472            if (echo == SWITCH_UPDATE) {
8473                BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8474                if (f_obj->complete_cmd(sc, f_obj,
8475                                        ECORE_F_CMD_SWITCH_UPDATE)) {
8476                    break;
8477                }
8478            }
8479            else {
8480                BLOGD(sc, DBG_SP,
8481                      "AFEX: ramrod completed FUNCTION_UPDATE\n");
8482            }
8483            goto next_spqe;
8484
8485        case EVENT_RING_OPCODE_FORWARD_SETUP:
8486            q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8487            if (q_obj->complete_cmd(sc, q_obj,
8488                                    ECORE_Q_CMD_SETUP_TX_ONLY)) {
8489                break;
8490            }
8491            goto next_spqe;
8492
8493        case EVENT_RING_OPCODE_FUNCTION_START:
8494            BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8495            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8496                break;
8497            }
8498            goto next_spqe;
8499
8500        case EVENT_RING_OPCODE_FUNCTION_STOP:
8501            BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8502            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8503                break;
8504            }
8505            goto next_spqe;
8506        }
8507
8508        switch (opcode | sc->state) {
8509        case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8510        case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8511            cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8512            BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8513            rss_raw->clear_pending(rss_raw);
8514            break;
8515
8516        case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8517        case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8518        case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8519        case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8520        case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8521        case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8522            BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8523            bxe_handle_classification_eqe(sc, elem);
8524            break;
8525
8526        case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8527        case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8528        case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8529            BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8530            bxe_handle_mcast_eqe(sc);
8531            break;
8532
8533        case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8534        case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8535        case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8536            BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8537            bxe_handle_rx_mode_eqe(sc, elem);
8538            break;
8539
8540        default:
8541            /* unknown event log error and continue */
8542            BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8543                  elem->message.opcode, sc->state);
8544        }
8545
8546next_spqe:
8547        spqe_cnt++;
8548    } /* for */
8549
8550    mb();
8551    atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8552
8553    sc->eq_cons = sw_cons;
8554    sc->eq_prod = sw_prod;
8555
8556    /* make sure that above mem writes were issued towards the memory */
8557    wmb();
8558
8559    /* update producer */
8560    bxe_update_eq_prod(sc, sc->eq_prod);
8561}
8562
8563static void
8564bxe_handle_sp_tq(void *context,
8565                 int  pending)
8566{
8567    struct bxe_softc *sc = (struct bxe_softc *)context;
8568    uint16_t status;
8569
8570    BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8571
8572    /* what work needs to be performed? */
8573    status = bxe_update_dsb_idx(sc);
8574
8575    BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8576
8577    /* HW attentions */
8578    if (status & BXE_DEF_SB_ATT_IDX) {
8579        BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8580        bxe_attn_int(sc);
8581        status &= ~BXE_DEF_SB_ATT_IDX;
8582    }
8583
8584    /* SP events: STAT_QUERY and others */
8585    if (status & BXE_DEF_SB_IDX) {
8586        /* handle EQ completions */
8587        BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8588        bxe_eq_int(sc);
8589        bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8590                   le16toh(sc->def_idx), IGU_INT_NOP, 1);
8591        status &= ~BXE_DEF_SB_IDX;
8592    }
8593
8594    /* if status is non zero then something went wrong */
8595    if (__predict_false(status)) {
8596        BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8597    }
8598
8599    /* ack status block only if something was actually handled */
8600    bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8601               le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8602
8603    /*
8604     * Must be called after the EQ processing (since eq leads to sriov
8605     * ramrod completion flows).
8606     * This flow may have been scheduled by the arrival of a ramrod
8607     * completion, or by the sriov code rescheduling itself.
8608     */
8609    // XXX bxe_iov_sp_task(sc);
8610
8611}
8612
8613static void
8614bxe_handle_fp_tq(void *context,
8615                 int  pending)
8616{
8617    struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8618    struct bxe_softc *sc = fp->sc;
8619    uint8_t more_tx = FALSE;
8620    uint8_t more_rx = FALSE;
8621
8622    BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8623
8624    /* XXX
8625     * IFF_DRV_RUNNING state can't be checked here since we process
8626     * slowpath events on a client queue during setup. Instead
8627     * we need to add a "process/continue" flag here that the driver
8628     * can use to tell the task here not to do anything.
8629     */
8630#if 0
8631    if (!(if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
8632        return;
8633    }
8634#endif
8635
8636    /* update the fastpath index */
8637    bxe_update_fp_sb_idx(fp);
8638
8639    /* XXX add loop here if ever support multiple tx CoS */
8640    /* fp->txdata[cos] */
8641    if (bxe_has_tx_work(fp)) {
8642        BXE_FP_TX_LOCK(fp);
8643        more_tx = bxe_txeof(sc, fp);
8644        BXE_FP_TX_UNLOCK(fp);
8645    }
8646
8647    if (bxe_has_rx_work(fp)) {
8648        more_rx = bxe_rxeof(sc, fp);
8649    }
8650
8651    if (more_rx /*|| more_tx*/) {
8652        /* still more work to do */
8653        taskqueue_enqueue(fp->tq, &fp->tq_task);
8654        return;
8655    }
8656
8657    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8658               le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8659}
8660
8661static void
8662bxe_task_fp(struct bxe_fastpath *fp)
8663{
8664    struct bxe_softc *sc = fp->sc;
8665    uint8_t more_tx = FALSE;
8666    uint8_t more_rx = FALSE;
8667
8668    BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8669
8670    /* update the fastpath index */
8671    bxe_update_fp_sb_idx(fp);
8672
8673    /* XXX add loop here if ever support multiple tx CoS */
8674    /* fp->txdata[cos] */
8675    if (bxe_has_tx_work(fp)) {
8676        BXE_FP_TX_LOCK(fp);
8677        more_tx = bxe_txeof(sc, fp);
8678        BXE_FP_TX_UNLOCK(fp);
8679    }
8680
8681    if (bxe_has_rx_work(fp)) {
8682        more_rx = bxe_rxeof(sc, fp);
8683    }
8684
8685    if (more_rx /*|| more_tx*/) {
8686        /* still more work to do, bail out if this ISR and process later */
8687        taskqueue_enqueue(fp->tq, &fp->tq_task);
8688        return;
8689    }
8690
8691    /*
8692     * Here we write the fastpath index taken before doing any tx or rx work.
8693     * It is very well possible other hw events occurred up to this point and
8694     * they were actually processed accordingly above. Since we're going to
8695     * write an older fastpath index, an interrupt is coming which we might
8696     * not do any work in.
8697     */
8698    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8699               le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8700}
8701
8702/*
8703 * Legacy interrupt entry point.
8704 *
8705 * Verifies that the controller generated the interrupt and
8706 * then calls a separate routine to handle the various
8707 * interrupt causes: link, RX, and TX.
8708 */
8709static void
8710bxe_intr_legacy(void *xsc)
8711{
8712    struct bxe_softc *sc = (struct bxe_softc *)xsc;
8713    struct bxe_fastpath *fp;
8714    uint16_t status, mask;
8715    int i;
8716
8717    BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8718
8719    /*
8720     * 0 for ustorm, 1 for cstorm
8721     * the bits returned from ack_int() are 0-15
8722     * bit 0 = attention status block
8723     * bit 1 = fast path status block
8724     * a mask of 0x2 or more = tx/rx event
8725     * a mask of 1 = slow path event
8726     */
8727
8728    status = bxe_ack_int(sc);
8729
8730    /* the interrupt is not for us */
8731    if (__predict_false(status == 0)) {
8732        BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8733        return;
8734    }
8735
8736    BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8737
8738    FOR_EACH_ETH_QUEUE(sc, i) {
8739        fp = &sc->fp[i];
8740        mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8741        if (status & mask) {
8742            /* acknowledge and disable further fastpath interrupts */
8743            bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8744            bxe_task_fp(fp);
8745            status &= ~mask;
8746        }
8747    }
8748
8749    if (__predict_false(status & 0x1)) {
8750        /* acknowledge and disable further slowpath interrupts */
8751        bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8752
8753        /* schedule slowpath handler */
8754        taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8755
8756        status &= ~0x1;
8757    }
8758
8759    if (__predict_false(status)) {
8760        BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8761    }
8762}
8763
8764/* slowpath interrupt entry point */
8765static void
8766bxe_intr_sp(void *xsc)
8767{
8768    struct bxe_softc *sc = (struct bxe_softc *)xsc;
8769
8770    BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8771
8772    /* acknowledge and disable further slowpath interrupts */
8773    bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8774
8775    /* schedule slowpath handler */
8776    taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8777}
8778
8779/* fastpath interrupt entry point */
8780static void
8781bxe_intr_fp(void *xfp)
8782{
8783    struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8784    struct bxe_softc *sc = fp->sc;
8785
8786    BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8787
8788    BLOGD(sc, DBG_INTR,
8789          "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8790          curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8791
8792    /* acknowledge and disable further fastpath interrupts */
8793    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8794
8795    bxe_task_fp(fp);
8796}
8797
8798/* Release all interrupts allocated by the driver. */
8799static void
8800bxe_interrupt_free(struct bxe_softc *sc)
8801{
8802    int i;
8803
8804    switch (sc->interrupt_mode) {
8805    case INTR_MODE_INTX:
8806        BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8807        if (sc->intr[0].resource != NULL) {
8808            bus_release_resource(sc->dev,
8809                                 SYS_RES_IRQ,
8810                                 sc->intr[0].rid,
8811                                 sc->intr[0].resource);
8812        }
8813        break;
8814    case INTR_MODE_MSI:
8815        for (i = 0; i < sc->intr_count; i++) {
8816            BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8817            if (sc->intr[i].resource && sc->intr[i].rid) {
8818                bus_release_resource(sc->dev,
8819                                     SYS_RES_IRQ,
8820                                     sc->intr[i].rid,
8821                                     sc->intr[i].resource);
8822            }
8823        }
8824        pci_release_msi(sc->dev);
8825        break;
8826    case INTR_MODE_MSIX:
8827        for (i = 0; i < sc->intr_count; i++) {
8828            BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8829            if (sc->intr[i].resource && sc->intr[i].rid) {
8830                bus_release_resource(sc->dev,
8831                                     SYS_RES_IRQ,
8832                                     sc->intr[i].rid,
8833                                     sc->intr[i].resource);
8834            }
8835        }
8836        pci_release_msi(sc->dev);
8837        break;
8838    default:
8839        /* nothing to do as initial allocation failed */
8840        break;
8841    }
8842}
8843
8844/*
8845 * This function determines and allocates the appropriate
8846 * interrupt based on system capabilites and user request.
8847 *
8848 * The user may force a particular interrupt mode, specify
8849 * the number of receive queues, specify the method for
8850 * distribuitng received frames to receive queues, or use
8851 * the default settings which will automatically select the
8852 * best supported combination.  In addition, the OS may or
8853 * may not support certain combinations of these settings.
8854 * This routine attempts to reconcile the settings requested
8855 * by the user with the capabilites available from the system
8856 * to select the optimal combination of features.
8857 *
8858 * Returns:
8859 *   0 = Success, !0 = Failure.
8860 */
8861static int
8862bxe_interrupt_alloc(struct bxe_softc *sc)
8863{
8864    int msix_count = 0;
8865    int msi_count = 0;
8866    int num_requested = 0;
8867    int num_allocated = 0;
8868    int rid, i, j;
8869    int rc;
8870
8871    /* get the number of available MSI/MSI-X interrupts from the OS */
8872    if (sc->interrupt_mode > 0) {
8873        if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8874            msix_count = pci_msix_count(sc->dev);
8875        }
8876
8877        if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8878            msi_count = pci_msi_count(sc->dev);
8879        }
8880
8881        BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8882              msi_count, msix_count);
8883    }
8884
8885    do { /* try allocating MSI-X interrupt resources (at least 2) */
8886        if (sc->interrupt_mode != INTR_MODE_MSIX) {
8887            break;
8888        }
8889
8890        if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
8891            (msix_count < 2)) {
8892            sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8893            break;
8894        }
8895
8896        /* ask for the necessary number of MSI-X vectors */
8897        num_requested = min((sc->num_queues + 1), msix_count);
8898
8899        BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
8900
8901        num_allocated = num_requested;
8902        if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
8903            BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
8904            sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8905            break;
8906        }
8907
8908        if (num_allocated < 2) { /* possible? */
8909            BLOGE(sc, "MSI-X allocation less than 2!\n");
8910            sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8911            pci_release_msi(sc->dev);
8912            break;
8913        }
8914
8915        BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
8916              num_requested, num_allocated);
8917
8918        /* best effort so use the number of vectors allocated to us */
8919        sc->intr_count = num_allocated;
8920        sc->num_queues = num_allocated - 1;
8921
8922        rid = 1; /* initial resource identifier */
8923
8924        /* allocate the MSI-X vectors */
8925        for (i = 0; i < num_allocated; i++) {
8926            sc->intr[i].rid = (rid + i);
8927
8928            if ((sc->intr[i].resource =
8929                 bus_alloc_resource_any(sc->dev,
8930                                        SYS_RES_IRQ,
8931                                        &sc->intr[i].rid,
8932                                        RF_ACTIVE)) == NULL) {
8933                BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
8934                      i, (rid + i));
8935
8936                for (j = (i - 1); j >= 0; j--) {
8937                    bus_release_resource(sc->dev,
8938                                         SYS_RES_IRQ,
8939                                         sc->intr[j].rid,
8940                                         sc->intr[j].resource);
8941                }
8942
8943                sc->intr_count = 0;
8944                sc->num_queues = 0;
8945                sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8946                pci_release_msi(sc->dev);
8947                break;
8948            }
8949
8950            BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
8951        }
8952    } while (0);
8953
8954    do { /* try allocating MSI vector resources (at least 2) */
8955        if (sc->interrupt_mode != INTR_MODE_MSI) {
8956            break;
8957        }
8958
8959        if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
8960            (msi_count < 1)) {
8961            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8962            break;
8963        }
8964
8965        /* ask for a single MSI vector */
8966        num_requested = 1;
8967
8968        BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
8969
8970        num_allocated = num_requested;
8971        if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
8972            BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
8973            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8974            break;
8975        }
8976
8977        if (num_allocated != 1) { /* possible? */
8978            BLOGE(sc, "MSI allocation is not 1!\n");
8979            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8980            pci_release_msi(sc->dev);
8981            break;
8982        }
8983
8984        BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
8985              num_requested, num_allocated);
8986
8987        /* best effort so use the number of vectors allocated to us */
8988        sc->intr_count = num_allocated;
8989        sc->num_queues = num_allocated;
8990
8991        rid = 1; /* initial resource identifier */
8992
8993        sc->intr[0].rid = rid;
8994
8995        if ((sc->intr[0].resource =
8996             bus_alloc_resource_any(sc->dev,
8997                                    SYS_RES_IRQ,
8998                                    &sc->intr[0].rid,
8999                                    RF_ACTIVE)) == NULL) {
9000            BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9001            sc->intr_count = 0;
9002            sc->num_queues = 0;
9003            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9004            pci_release_msi(sc->dev);
9005            break;
9006        }
9007
9008        BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9009    } while (0);
9010
9011    do { /* try allocating INTx vector resources */
9012        if (sc->interrupt_mode != INTR_MODE_INTX) {
9013            break;
9014        }
9015
9016        BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9017
9018        /* only one vector for INTx */
9019        sc->intr_count = 1;
9020        sc->num_queues = 1;
9021
9022        rid = 0; /* initial resource identifier */
9023
9024        sc->intr[0].rid = rid;
9025
9026        if ((sc->intr[0].resource =
9027             bus_alloc_resource_any(sc->dev,
9028                                    SYS_RES_IRQ,
9029                                    &sc->intr[0].rid,
9030                                    (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9031            BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9032            sc->intr_count = 0;
9033            sc->num_queues = 0;
9034            sc->interrupt_mode = -1; /* Failed! */
9035            break;
9036        }
9037
9038        BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9039    } while (0);
9040
9041    if (sc->interrupt_mode == -1) {
9042        BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9043        rc = 1;
9044    } else {
9045        BLOGD(sc, DBG_LOAD,
9046              "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9047              sc->interrupt_mode, sc->num_queues);
9048        rc = 0;
9049    }
9050
9051    return (rc);
9052}
9053
9054static void
9055bxe_interrupt_detach(struct bxe_softc *sc)
9056{
9057    struct bxe_fastpath *fp;
9058    int i;
9059
9060    /* release interrupt resources */
9061    for (i = 0; i < sc->intr_count; i++) {
9062        if (sc->intr[i].resource && sc->intr[i].tag) {
9063            BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9064            bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9065        }
9066    }
9067
9068    for (i = 0; i < sc->num_queues; i++) {
9069        fp = &sc->fp[i];
9070        if (fp->tq) {
9071            taskqueue_drain(fp->tq, &fp->tq_task);
9072            taskqueue_drain(fp->tq, &fp->tx_task);
9073            while (taskqueue_cancel_timeout(fp->tq, &fp->tx_timeout_task,
9074                NULL))
9075                taskqueue_drain_timeout(fp->tq, &fp->tx_timeout_task);
9076            taskqueue_free(fp->tq);
9077            fp->tq = NULL;
9078        }
9079    }
9080
9081
9082    if (sc->sp_tq) {
9083        taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9084        taskqueue_free(sc->sp_tq);
9085        sc->sp_tq = NULL;
9086    }
9087}
9088
9089/*
9090 * Enables interrupts and attach to the ISR.
9091 *
9092 * When using multiple MSI/MSI-X vectors the first vector
9093 * is used for slowpath operations while all remaining
9094 * vectors are used for fastpath operations.  If only a
9095 * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9096 * ISR must look for both slowpath and fastpath completions.
9097 */
9098static int
9099bxe_interrupt_attach(struct bxe_softc *sc)
9100{
9101    struct bxe_fastpath *fp;
9102    int rc = 0;
9103    int i;
9104
9105    snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9106             "bxe%d_sp_tq", sc->unit);
9107    TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9108    sc->sp_tq = taskqueue_create(sc->sp_tq_name, M_NOWAIT,
9109                                 taskqueue_thread_enqueue,
9110                                 &sc->sp_tq);
9111    taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9112                            "%s", sc->sp_tq_name);
9113
9114
9115    for (i = 0; i < sc->num_queues; i++) {
9116        fp = &sc->fp[i];
9117        snprintf(fp->tq_name, sizeof(fp->tq_name),
9118                 "bxe%d_fp%d_tq", sc->unit, i);
9119        TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9120        TASK_INIT(&fp->tx_task, 0, bxe_tx_mq_start_deferred, fp);
9121        fp->tq = taskqueue_create(fp->tq_name, M_NOWAIT,
9122                                  taskqueue_thread_enqueue,
9123                                  &fp->tq);
9124        TIMEOUT_TASK_INIT(fp->tq, &fp->tx_timeout_task, 0,
9125                          bxe_tx_mq_start_deferred, fp);
9126        taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9127                                "%s", fp->tq_name);
9128    }
9129
9130    /* setup interrupt handlers */
9131    if (sc->interrupt_mode == INTR_MODE_MSIX) {
9132        BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9133
9134        /*
9135         * Setup the interrupt handler. Note that we pass the driver instance
9136         * to the interrupt handler for the slowpath.
9137         */
9138        if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9139                                 (INTR_TYPE_NET | INTR_MPSAFE),
9140                                 NULL, bxe_intr_sp, sc,
9141                                 &sc->intr[0].tag)) != 0) {
9142            BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9143            goto bxe_interrupt_attach_exit;
9144        }
9145
9146        bus_describe_intr(sc->dev, sc->intr[0].resource,
9147                          sc->intr[0].tag, "sp");
9148
9149        /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9150
9151        /* initialize the fastpath vectors (note the first was used for sp) */
9152        for (i = 0; i < sc->num_queues; i++) {
9153            fp = &sc->fp[i];
9154            BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9155
9156            /*
9157             * Setup the interrupt handler. Note that we pass the
9158             * fastpath context to the interrupt handler in this
9159             * case.
9160             */
9161            if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9162                                     (INTR_TYPE_NET | INTR_MPSAFE),
9163                                     NULL, bxe_intr_fp, fp,
9164                                     &sc->intr[i + 1].tag)) != 0) {
9165                BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9166                      (i + 1), rc);
9167                goto bxe_interrupt_attach_exit;
9168            }
9169
9170            bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9171                              sc->intr[i + 1].tag, "fp%02d", i);
9172
9173            /* bind the fastpath instance to a cpu */
9174            if (sc->num_queues > 1) {
9175                bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9176            }
9177
9178            fp->state = BXE_FP_STATE_IRQ;
9179        }
9180    } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9181        BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9182
9183        /*
9184         * Setup the interrupt handler. Note that we pass the
9185         * driver instance to the interrupt handler which
9186         * will handle both the slowpath and fastpath.
9187         */
9188        if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9189                                 (INTR_TYPE_NET | INTR_MPSAFE),
9190                                 NULL, bxe_intr_legacy, sc,
9191                                 &sc->intr[0].tag)) != 0) {
9192            BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9193            goto bxe_interrupt_attach_exit;
9194        }
9195
9196    } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9197        BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9198
9199        /*
9200         * Setup the interrupt handler. Note that we pass the
9201         * driver instance to the interrupt handler which
9202         * will handle both the slowpath and fastpath.
9203         */
9204        if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9205                                 (INTR_TYPE_NET | INTR_MPSAFE),
9206                                 NULL, bxe_intr_legacy, sc,
9207                                 &sc->intr[0].tag)) != 0) {
9208            BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9209            goto bxe_interrupt_attach_exit;
9210        }
9211    }
9212
9213bxe_interrupt_attach_exit:
9214
9215    return (rc);
9216}
9217
9218static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9219static int  bxe_init_hw_common(struct bxe_softc *sc);
9220static int  bxe_init_hw_port(struct bxe_softc *sc);
9221static int  bxe_init_hw_func(struct bxe_softc *sc);
9222static void bxe_reset_common(struct bxe_softc *sc);
9223static void bxe_reset_port(struct bxe_softc *sc);
9224static void bxe_reset_func(struct bxe_softc *sc);
9225static int  bxe_gunzip_init(struct bxe_softc *sc);
9226static void bxe_gunzip_end(struct bxe_softc *sc);
9227static int  bxe_init_firmware(struct bxe_softc *sc);
9228static void bxe_release_firmware(struct bxe_softc *sc);
9229
9230static struct
9231ecore_func_sp_drv_ops bxe_func_sp_drv = {
9232    .init_hw_cmn_chip = bxe_init_hw_common_chip,
9233    .init_hw_cmn      = bxe_init_hw_common,
9234    .init_hw_port     = bxe_init_hw_port,
9235    .init_hw_func     = bxe_init_hw_func,
9236
9237    .reset_hw_cmn     = bxe_reset_common,
9238    .reset_hw_port    = bxe_reset_port,
9239    .reset_hw_func    = bxe_reset_func,
9240
9241    .gunzip_init      = bxe_gunzip_init,
9242    .gunzip_end       = bxe_gunzip_end,
9243
9244    .init_fw          = bxe_init_firmware,
9245    .release_fw       = bxe_release_firmware,
9246};
9247
9248static void
9249bxe_init_func_obj(struct bxe_softc *sc)
9250{
9251    sc->dmae_ready = 0;
9252
9253    ecore_init_func_obj(sc,
9254                        &sc->func_obj,
9255                        BXE_SP(sc, func_rdata),
9256                        BXE_SP_MAPPING(sc, func_rdata),
9257                        BXE_SP(sc, func_afex_rdata),
9258                        BXE_SP_MAPPING(sc, func_afex_rdata),
9259                        &bxe_func_sp_drv);
9260}
9261
9262static int
9263bxe_init_hw(struct bxe_softc *sc,
9264            uint32_t         load_code)
9265{
9266    struct ecore_func_state_params func_params = { NULL };
9267    int rc;
9268
9269    /* prepare the parameters for function state transitions */
9270    bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9271
9272    func_params.f_obj = &sc->func_obj;
9273    func_params.cmd = ECORE_F_CMD_HW_INIT;
9274
9275    func_params.params.hw_init.load_phase = load_code;
9276
9277    /*
9278     * Via a plethora of function pointers, we will eventually reach
9279     * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9280     */
9281    rc = ecore_func_state_change(sc, &func_params);
9282
9283    return (rc);
9284}
9285
9286static void
9287bxe_fill(struct bxe_softc *sc,
9288         uint32_t         addr,
9289         int              fill,
9290         uint32_t         len)
9291{
9292    uint32_t i;
9293
9294    if (!(len % 4) && !(addr % 4)) {
9295        for (i = 0; i < len; i += 4) {
9296            REG_WR(sc, (addr + i), fill);
9297        }
9298    } else {
9299        for (i = 0; i < len; i++) {
9300            REG_WR8(sc, (addr + i), fill);
9301        }
9302    }
9303}
9304
9305/* writes FP SP data to FW - data_size in dwords */
9306static void
9307bxe_wr_fp_sb_data(struct bxe_softc *sc,
9308                  int              fw_sb_id,
9309                  uint32_t         *sb_data_p,
9310                  uint32_t         data_size)
9311{
9312    int index;
9313
9314    for (index = 0; index < data_size; index++) {
9315        REG_WR(sc,
9316               (BAR_CSTRORM_INTMEM +
9317                CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9318                (sizeof(uint32_t) * index)),
9319               *(sb_data_p + index));
9320    }
9321}
9322
9323static void
9324bxe_zero_fp_sb(struct bxe_softc *sc,
9325               int              fw_sb_id)
9326{
9327    struct hc_status_block_data_e2 sb_data_e2;
9328    struct hc_status_block_data_e1x sb_data_e1x;
9329    uint32_t *sb_data_p;
9330    uint32_t data_size = 0;
9331
9332    if (!CHIP_IS_E1x(sc)) {
9333        memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9334        sb_data_e2.common.state = SB_DISABLED;
9335        sb_data_e2.common.p_func.vf_valid = FALSE;
9336        sb_data_p = (uint32_t *)&sb_data_e2;
9337        data_size = (sizeof(struct hc_status_block_data_e2) /
9338                     sizeof(uint32_t));
9339    } else {
9340        memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9341        sb_data_e1x.common.state = SB_DISABLED;
9342        sb_data_e1x.common.p_func.vf_valid = FALSE;
9343        sb_data_p = (uint32_t *)&sb_data_e1x;
9344        data_size = (sizeof(struct hc_status_block_data_e1x) /
9345                     sizeof(uint32_t));
9346    }
9347
9348    bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9349
9350    bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9351             0, CSTORM_STATUS_BLOCK_SIZE);
9352    bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9353             0, CSTORM_SYNC_BLOCK_SIZE);
9354}
9355
9356static void
9357bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9358                  struct hc_sp_status_block_data *sp_sb_data)
9359{
9360    int i;
9361
9362    for (i = 0;
9363         i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9364         i++) {
9365        REG_WR(sc,
9366               (BAR_CSTRORM_INTMEM +
9367                CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9368                (i * sizeof(uint32_t))),
9369               *((uint32_t *)sp_sb_data + i));
9370    }
9371}
9372
9373static void
9374bxe_zero_sp_sb(struct bxe_softc *sc)
9375{
9376    struct hc_sp_status_block_data sp_sb_data;
9377
9378    memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9379
9380    sp_sb_data.state           = SB_DISABLED;
9381    sp_sb_data.p_func.vf_valid = FALSE;
9382
9383    bxe_wr_sp_sb_data(sc, &sp_sb_data);
9384
9385    bxe_fill(sc,
9386             (BAR_CSTRORM_INTMEM +
9387              CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9388              0, CSTORM_SP_STATUS_BLOCK_SIZE);
9389    bxe_fill(sc,
9390             (BAR_CSTRORM_INTMEM +
9391              CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9392              0, CSTORM_SP_SYNC_BLOCK_SIZE);
9393}
9394
9395static void
9396bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9397                             int                       igu_sb_id,
9398                             int                       igu_seg_id)
9399{
9400    hc_sm->igu_sb_id      = igu_sb_id;
9401    hc_sm->igu_seg_id     = igu_seg_id;
9402    hc_sm->timer_value    = 0xFF;
9403    hc_sm->time_to_expire = 0xFFFFFFFF;
9404}
9405
9406static void
9407bxe_map_sb_state_machines(struct hc_index_data *index_data)
9408{
9409    /* zero out state machine indices */
9410
9411    /* rx indices */
9412    index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9413
9414    /* tx indices */
9415    index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9416    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9417    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9418    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9419
9420    /* map indices */
9421
9422    /* rx indices */
9423    index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9424        (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9425
9426    /* tx indices */
9427    index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9428        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9429    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9430        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9431    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9432        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9433    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9434        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9435}
9436
9437static void
9438bxe_init_sb(struct bxe_softc *sc,
9439            bus_addr_t       busaddr,
9440            int              vfid,
9441            uint8_t          vf_valid,
9442            int              fw_sb_id,
9443            int              igu_sb_id)
9444{
9445    struct hc_status_block_data_e2  sb_data_e2;
9446    struct hc_status_block_data_e1x sb_data_e1x;
9447    struct hc_status_block_sm       *hc_sm_p;
9448    uint32_t *sb_data_p;
9449    int igu_seg_id;
9450    int data_size;
9451
9452    if (CHIP_INT_MODE_IS_BC(sc)) {
9453        igu_seg_id = HC_SEG_ACCESS_NORM;
9454    } else {
9455        igu_seg_id = IGU_SEG_ACCESS_NORM;
9456    }
9457
9458    bxe_zero_fp_sb(sc, fw_sb_id);
9459
9460    if (!CHIP_IS_E1x(sc)) {
9461        memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9462        sb_data_e2.common.state = SB_ENABLED;
9463        sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9464        sb_data_e2.common.p_func.vf_id = vfid;
9465        sb_data_e2.common.p_func.vf_valid = vf_valid;
9466        sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9467        sb_data_e2.common.same_igu_sb_1b = TRUE;
9468        sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9469        sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9470        hc_sm_p = sb_data_e2.common.state_machine;
9471        sb_data_p = (uint32_t *)&sb_data_e2;
9472        data_size = (sizeof(struct hc_status_block_data_e2) /
9473                     sizeof(uint32_t));
9474        bxe_map_sb_state_machines(sb_data_e2.index_data);
9475    } else {
9476        memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9477        sb_data_e1x.common.state = SB_ENABLED;
9478        sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9479        sb_data_e1x.common.p_func.vf_id = 0xff;
9480        sb_data_e1x.common.p_func.vf_valid = FALSE;
9481        sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9482        sb_data_e1x.common.same_igu_sb_1b = TRUE;
9483        sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9484        sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9485        hc_sm_p = sb_data_e1x.common.state_machine;
9486        sb_data_p = (uint32_t *)&sb_data_e1x;
9487        data_size = (sizeof(struct hc_status_block_data_e1x) /
9488                     sizeof(uint32_t));
9489        bxe_map_sb_state_machines(sb_data_e1x.index_data);
9490    }
9491
9492    bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9493    bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9494
9495    BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9496
9497    /* write indices to HW - PCI guarantees endianity of regpairs */
9498    bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9499}
9500
9501static inline uint8_t
9502bxe_fp_qzone_id(struct bxe_fastpath *fp)
9503{
9504    if (CHIP_IS_E1x(fp->sc)) {
9505        return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9506    } else {
9507        return (fp->cl_id);
9508    }
9509}
9510
9511static inline uint32_t
9512bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9513                           struct bxe_fastpath *fp)
9514{
9515    uint32_t offset = BAR_USTRORM_INTMEM;
9516
9517    if (!CHIP_IS_E1x(sc)) {
9518        offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9519    } else {
9520        offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9521    }
9522
9523    return (offset);
9524}
9525
9526static void
9527bxe_init_eth_fp(struct bxe_softc *sc,
9528                int              idx)
9529{
9530    struct bxe_fastpath *fp = &sc->fp[idx];
9531    uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9532    unsigned long q_type = 0;
9533    int cos;
9534
9535    fp->sc    = sc;
9536    fp->index = idx;
9537
9538    fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9539    fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9540
9541    fp->cl_id = (CHIP_IS_E1x(sc)) ?
9542                    (SC_L_ID(sc) + idx) :
9543                    /* want client ID same as IGU SB ID for non-E1 */
9544                    fp->igu_sb_id;
9545    fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9546
9547    /* setup sb indices */
9548    if (!CHIP_IS_E1x(sc)) {
9549        fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9550        fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9551    } else {
9552        fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9553        fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9554    }
9555
9556    /* init shortcut */
9557    fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9558
9559    fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9560
9561    /*
9562     * XXX If multiple CoS is ever supported then each fastpath structure
9563     * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9564     */
9565    for (cos = 0; cos < sc->max_cos; cos++) {
9566        cids[cos] = idx;
9567    }
9568    fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9569
9570    /* nothing more for a VF to do */
9571    if (IS_VF(sc)) {
9572        return;
9573    }
9574
9575    bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9576                fp->fw_sb_id, fp->igu_sb_id);
9577
9578    bxe_update_fp_sb_idx(fp);
9579
9580    /* Configure Queue State object */
9581    bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9582    bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9583
9584    ecore_init_queue_obj(sc,
9585                         &sc->sp_objs[idx].q_obj,
9586                         fp->cl_id,
9587                         cids,
9588                         sc->max_cos,
9589                         SC_FUNC(sc),
9590                         BXE_SP(sc, q_rdata),
9591                         BXE_SP_MAPPING(sc, q_rdata),
9592                         q_type);
9593
9594    /* configure classification DBs */
9595    ecore_init_mac_obj(sc,
9596                       &sc->sp_objs[idx].mac_obj,
9597                       fp->cl_id,
9598                       idx,
9599                       SC_FUNC(sc),
9600                       BXE_SP(sc, mac_rdata),
9601                       BXE_SP_MAPPING(sc, mac_rdata),
9602                       ECORE_FILTER_MAC_PENDING,
9603                       &sc->sp_state,
9604                       ECORE_OBJ_TYPE_RX_TX,
9605                       &sc->macs_pool);
9606
9607    BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9608          idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9609}
9610
9611static inline void
9612bxe_update_rx_prod(struct bxe_softc    *sc,
9613                   struct bxe_fastpath *fp,
9614                   uint16_t            rx_bd_prod,
9615                   uint16_t            rx_cq_prod,
9616                   uint16_t            rx_sge_prod)
9617{
9618    struct ustorm_eth_rx_producers rx_prods = { 0 };
9619    uint32_t i;
9620
9621    /* update producers */
9622    rx_prods.bd_prod  = rx_bd_prod;
9623    rx_prods.cqe_prod = rx_cq_prod;
9624    rx_prods.sge_prod = rx_sge_prod;
9625
9626    /*
9627     * Make sure that the BD and SGE data is updated before updating the
9628     * producers since FW might read the BD/SGE right after the producer
9629     * is updated.
9630     * This is only applicable for weak-ordered memory model archs such
9631     * as IA-64. The following barrier is also mandatory since FW will
9632     * assumes BDs must have buffers.
9633     */
9634    wmb();
9635
9636    for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9637        REG_WR(sc,
9638               (fp->ustorm_rx_prods_offset + (i * 4)),
9639               ((uint32_t *)&rx_prods)[i]);
9640    }
9641
9642    wmb(); /* keep prod updates ordered */
9643
9644    BLOGD(sc, DBG_RX,
9645          "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9646          fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9647}
9648
9649static void
9650bxe_init_rx_rings(struct bxe_softc *sc)
9651{
9652    struct bxe_fastpath *fp;
9653    int i;
9654
9655    for (i = 0; i < sc->num_queues; i++) {
9656        fp = &sc->fp[i];
9657
9658        fp->rx_bd_cons = 0;
9659
9660        /*
9661         * Activate the BD ring...
9662         * Warning, this will generate an interrupt (to the TSTORM)
9663         * so this can only be done after the chip is initialized
9664         */
9665        bxe_update_rx_prod(sc, fp,
9666                           fp->rx_bd_prod,
9667                           fp->rx_cq_prod,
9668                           fp->rx_sge_prod);
9669
9670        if (i != 0) {
9671            continue;
9672        }
9673
9674        if (CHIP_IS_E1(sc)) {
9675            REG_WR(sc,
9676                   (BAR_USTRORM_INTMEM +
9677                    USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9678                   U64_LO(fp->rcq_dma.paddr));
9679            REG_WR(sc,
9680                   (BAR_USTRORM_INTMEM +
9681                    USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9682                   U64_HI(fp->rcq_dma.paddr));
9683        }
9684    }
9685}
9686
9687static void
9688bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9689{
9690    SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9691    fp->tx_db.data.zero_fill1 = 0;
9692    fp->tx_db.data.prod = 0;
9693
9694    fp->tx_pkt_prod = 0;
9695    fp->tx_pkt_cons = 0;
9696    fp->tx_bd_prod = 0;
9697    fp->tx_bd_cons = 0;
9698    fp->eth_q_stats.tx_pkts = 0;
9699}
9700
9701static inline void
9702bxe_init_tx_rings(struct bxe_softc *sc)
9703{
9704    int i;
9705
9706    for (i = 0; i < sc->num_queues; i++) {
9707        bxe_init_tx_ring_one(&sc->fp[i]);
9708    }
9709}
9710
9711static void
9712bxe_init_def_sb(struct bxe_softc *sc)
9713{
9714    struct host_sp_status_block *def_sb = sc->def_sb;
9715    bus_addr_t mapping = sc->def_sb_dma.paddr;
9716    int igu_sp_sb_index;
9717    int igu_seg_id;
9718    int port = SC_PORT(sc);
9719    int func = SC_FUNC(sc);
9720    int reg_offset, reg_offset_en5;
9721    uint64_t section;
9722    int index, sindex;
9723    struct hc_sp_status_block_data sp_sb_data;
9724
9725    memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9726
9727    if (CHIP_INT_MODE_IS_BC(sc)) {
9728        igu_sp_sb_index = DEF_SB_IGU_ID;
9729        igu_seg_id = HC_SEG_ACCESS_DEF;
9730    } else {
9731        igu_sp_sb_index = sc->igu_dsb_id;
9732        igu_seg_id = IGU_SEG_ACCESS_DEF;
9733    }
9734
9735    /* attentions */
9736    section = ((uint64_t)mapping +
9737               offsetof(struct host_sp_status_block, atten_status_block));
9738    def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9739    sc->attn_state = 0;
9740
9741    reg_offset = (port) ?
9742                     MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9743                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9744    reg_offset_en5 = (port) ?
9745                         MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9746                         MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9747
9748    for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9749        /* take care of sig[0]..sig[4] */
9750        for (sindex = 0; sindex < 4; sindex++) {
9751            sc->attn_group[index].sig[sindex] =
9752                REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9753        }
9754
9755        if (!CHIP_IS_E1x(sc)) {
9756            /*
9757             * enable5 is separate from the rest of the registers,
9758             * and the address skip is 4 and not 16 between the
9759             * different groups
9760             */
9761            sc->attn_group[index].sig[4] =
9762                REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9763        } else {
9764            sc->attn_group[index].sig[4] = 0;
9765        }
9766    }
9767
9768    if (sc->devinfo.int_block == INT_BLOCK_HC) {
9769        reg_offset = (port) ?
9770                         HC_REG_ATTN_MSG1_ADDR_L :
9771                         HC_REG_ATTN_MSG0_ADDR_L;
9772        REG_WR(sc, reg_offset, U64_LO(section));
9773        REG_WR(sc, (reg_offset + 4), U64_HI(section));
9774    } else if (!CHIP_IS_E1x(sc)) {
9775        REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9776        REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9777    }
9778
9779    section = ((uint64_t)mapping +
9780               offsetof(struct host_sp_status_block, sp_sb));
9781
9782    bxe_zero_sp_sb(sc);
9783
9784    /* PCI guarantees endianity of regpair */
9785    sp_sb_data.state           = SB_ENABLED;
9786    sp_sb_data.host_sb_addr.lo = U64_LO(section);
9787    sp_sb_data.host_sb_addr.hi = U64_HI(section);
9788    sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9789    sp_sb_data.igu_seg_id      = igu_seg_id;
9790    sp_sb_data.p_func.pf_id    = func;
9791    sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9792    sp_sb_data.p_func.vf_id    = 0xff;
9793
9794    bxe_wr_sp_sb_data(sc, &sp_sb_data);
9795
9796    bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9797}
9798
9799static void
9800bxe_init_sp_ring(struct bxe_softc *sc)
9801{
9802    atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9803    sc->spq_prod_idx = 0;
9804    sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9805    sc->spq_prod_bd = sc->spq;
9806    sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9807}
9808
9809static void
9810bxe_init_eq_ring(struct bxe_softc *sc)
9811{
9812    union event_ring_elem *elem;
9813    int i;
9814
9815    for (i = 1; i <= NUM_EQ_PAGES; i++) {
9816        elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9817
9818        elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9819                                                 BCM_PAGE_SIZE *
9820                                                 (i % NUM_EQ_PAGES)));
9821        elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9822                                                 BCM_PAGE_SIZE *
9823                                                 (i % NUM_EQ_PAGES)));
9824    }
9825
9826    sc->eq_cons    = 0;
9827    sc->eq_prod    = NUM_EQ_DESC;
9828    sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9829
9830    atomic_store_rel_long(&sc->eq_spq_left,
9831                          (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9832                               NUM_EQ_DESC) - 1));
9833}
9834
9835static void
9836bxe_init_internal_common(struct bxe_softc *sc)
9837{
9838    int i;
9839
9840    /*
9841     * Zero this manually as its initialization is currently missing
9842     * in the initTool.
9843     */
9844    for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9845        REG_WR(sc,
9846               (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9847               0);
9848    }
9849
9850    if (!CHIP_IS_E1x(sc)) {
9851        REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9852                CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9853    }
9854}
9855
9856static void
9857bxe_init_internal(struct bxe_softc *sc,
9858                  uint32_t         load_code)
9859{
9860    switch (load_code) {
9861    case FW_MSG_CODE_DRV_LOAD_COMMON:
9862    case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9863        bxe_init_internal_common(sc);
9864        /* no break */
9865
9866    case FW_MSG_CODE_DRV_LOAD_PORT:
9867        /* nothing to do */
9868        /* no break */
9869
9870    case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9871        /* internal memory per function is initialized inside bxe_pf_init */
9872        break;
9873
9874    default:
9875        BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9876        break;
9877    }
9878}
9879
9880static void
9881storm_memset_func_cfg(struct bxe_softc                         *sc,
9882                      struct tstorm_eth_function_common_config *tcfg,
9883                      uint16_t                                  abs_fid)
9884{
9885    uint32_t addr;
9886    size_t size;
9887
9888    addr = (BAR_TSTRORM_INTMEM +
9889            TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
9890    size = sizeof(struct tstorm_eth_function_common_config);
9891    ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
9892}
9893
9894static void
9895bxe_func_init(struct bxe_softc            *sc,
9896              struct bxe_func_init_params *p)
9897{
9898    struct tstorm_eth_function_common_config tcfg = { 0 };
9899
9900    if (CHIP_IS_E1x(sc)) {
9901        storm_memset_func_cfg(sc, &tcfg, p->func_id);
9902    }
9903
9904    /* Enable the function in the FW */
9905    storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
9906    storm_memset_func_en(sc, p->func_id, 1);
9907
9908    /* spq */
9909    if (p->func_flgs & FUNC_FLG_SPQ) {
9910        storm_memset_spq_addr(sc, p->spq_map, p->func_id);
9911        REG_WR(sc,
9912               (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
9913               p->spq_prod);
9914    }
9915}
9916
9917/*
9918 * Calculates the sum of vn_min_rates.
9919 * It's needed for further normalizing of the min_rates.
9920 * Returns:
9921 *   sum of vn_min_rates.
9922 *     or
9923 *   0 - if all the min_rates are 0.
9924 * In the later case fainess algorithm should be deactivated.
9925 * If all min rates are not zero then those that are zeroes will be set to 1.
9926 */
9927static void
9928bxe_calc_vn_min(struct bxe_softc       *sc,
9929                struct cmng_init_input *input)
9930{
9931    uint32_t vn_cfg;
9932    uint32_t vn_min_rate;
9933    int all_zero = 1;
9934    int vn;
9935
9936    for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
9937        vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9938        vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
9939                        FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
9940
9941        if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9942            /* skip hidden VNs */
9943            vn_min_rate = 0;
9944        } else if (!vn_min_rate) {
9945            /* If min rate is zero - set it to 100 */
9946            vn_min_rate = DEF_MIN_RATE;
9947        } else {
9948            all_zero = 0;
9949        }
9950
9951        input->vnic_min_rate[vn] = vn_min_rate;
9952    }
9953
9954    /* if ETS or all min rates are zeros - disable fairness */
9955    if (BXE_IS_ETS_ENABLED(sc)) {
9956        input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9957        BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
9958    } else if (all_zero) {
9959        input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9960        BLOGD(sc, DBG_LOAD,
9961              "Fariness disabled (all MIN values are zeroes)\n");
9962    } else {
9963        input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9964    }
9965}
9966
9967static inline uint16_t
9968bxe_extract_max_cfg(struct bxe_softc *sc,
9969                    uint32_t         mf_cfg)
9970{
9971    uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
9972                        FUNC_MF_CFG_MAX_BW_SHIFT);
9973
9974    if (!max_cfg) {
9975        BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
9976        max_cfg = 100;
9977    }
9978
9979    return (max_cfg);
9980}
9981
9982static void
9983bxe_calc_vn_max(struct bxe_softc       *sc,
9984                int                    vn,
9985                struct cmng_init_input *input)
9986{
9987    uint16_t vn_max_rate;
9988    uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9989    uint32_t max_cfg;
9990
9991    if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9992        vn_max_rate = 0;
9993    } else {
9994        max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
9995
9996        if (IS_MF_SI(sc)) {
9997            /* max_cfg in percents of linkspeed */
9998            vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
9999        } else { /* SD modes */
10000            /* max_cfg is absolute in 100Mb units */
10001            vn_max_rate = (max_cfg * 100);
10002        }
10003    }
10004
10005    BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10006
10007    input->vnic_max_rate[vn] = vn_max_rate;
10008}
10009
10010static void
10011bxe_cmng_fns_init(struct bxe_softc *sc,
10012                  uint8_t          read_cfg,
10013                  uint8_t          cmng_type)
10014{
10015    struct cmng_init_input input;
10016    int vn;
10017
10018    memset(&input, 0, sizeof(struct cmng_init_input));
10019
10020    input.port_rate = sc->link_vars.line_speed;
10021
10022    if (cmng_type == CMNG_FNS_MINMAX) {
10023        /* read mf conf from shmem */
10024        if (read_cfg) {
10025            bxe_read_mf_cfg(sc);
10026        }
10027
10028        /* get VN min rate and enable fairness if not 0 */
10029        bxe_calc_vn_min(sc, &input);
10030
10031        /* get VN max rate */
10032        if (sc->port.pmf) {
10033            for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10034                bxe_calc_vn_max(sc, vn, &input);
10035            }
10036        }
10037
10038        /* always enable rate shaping and fairness */
10039        input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10040
10041        ecore_init_cmng(&input, &sc->cmng);
10042        return;
10043    }
10044
10045    /* rate shaping and fairness are disabled */
10046    BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10047}
10048
10049static int
10050bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10051{
10052    if (CHIP_REV_IS_SLOW(sc)) {
10053        return (CMNG_FNS_NONE);
10054    }
10055
10056    if (IS_MF(sc)) {
10057        return (CMNG_FNS_MINMAX);
10058    }
10059
10060    return (CMNG_FNS_NONE);
10061}
10062
10063static void
10064storm_memset_cmng(struct bxe_softc *sc,
10065                  struct cmng_init *cmng,
10066                  uint8_t          port)
10067{
10068    int vn;
10069    int func;
10070    uint32_t addr;
10071    size_t size;
10072
10073    addr = (BAR_XSTRORM_INTMEM +
10074            XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10075    size = sizeof(struct cmng_struct_per_port);
10076    ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10077
10078    for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10079        func = func_by_vn(sc, vn);
10080
10081        addr = (BAR_XSTRORM_INTMEM +
10082                XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10083        size = sizeof(struct rate_shaping_vars_per_vn);
10084        ecore_storm_memset_struct(sc, addr, size,
10085                                  (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10086
10087        addr = (BAR_XSTRORM_INTMEM +
10088                XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10089        size = sizeof(struct fairness_vars_per_vn);
10090        ecore_storm_memset_struct(sc, addr, size,
10091                                  (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10092    }
10093}
10094
10095static void
10096bxe_pf_init(struct bxe_softc *sc)
10097{
10098    struct bxe_func_init_params func_init = { 0 };
10099    struct event_ring_data eq_data = { { 0 } };
10100    uint16_t flags;
10101
10102    if (!CHIP_IS_E1x(sc)) {
10103        /* reset IGU PF statistics: MSIX + ATTN */
10104        /* PF */
10105        REG_WR(sc,
10106               (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10107                (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10108                ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10109               0);
10110        /* ATTN */
10111        REG_WR(sc,
10112               (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10113                (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10114                (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10115                ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10116               0);
10117    }
10118
10119    /* function setup flags */
10120    flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10121
10122    /*
10123     * This flag is relevant for E1x only.
10124     * E2 doesn't have a TPA configuration in a function level.
10125     */
10126    flags |= (if_getcapenable(sc->ifp) & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10127
10128    func_init.func_flgs = flags;
10129    func_init.pf_id     = SC_FUNC(sc);
10130    func_init.func_id   = SC_FUNC(sc);
10131    func_init.spq_map   = sc->spq_dma.paddr;
10132    func_init.spq_prod  = sc->spq_prod_idx;
10133
10134    bxe_func_init(sc, &func_init);
10135
10136    memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10137
10138    /*
10139     * Congestion management values depend on the link rate.
10140     * There is no active link so initial link rate is set to 10Gbps.
10141     * When the link comes up the congestion management values are
10142     * re-calculated according to the actual link rate.
10143     */
10144    sc->link_vars.line_speed = SPEED_10000;
10145    bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10146
10147    /* Only the PMF sets the HW */
10148    if (sc->port.pmf) {
10149        storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10150    }
10151
10152    /* init Event Queue - PCI bus guarantees correct endainity */
10153    eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10154    eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10155    eq_data.producer     = sc->eq_prod;
10156    eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10157    eq_data.sb_id        = DEF_SB_ID;
10158    storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10159}
10160
10161static void
10162bxe_hc_int_enable(struct bxe_softc *sc)
10163{
10164    int port = SC_PORT(sc);
10165    uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10166    uint32_t val = REG_RD(sc, addr);
10167    uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10168    uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10169                           (sc->intr_count == 1)) ? TRUE : FALSE;
10170    uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10171
10172    if (msix) {
10173        val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10174                 HC_CONFIG_0_REG_INT_LINE_EN_0);
10175        val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10176                HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10177        if (single_msix) {
10178            val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10179        }
10180    } else if (msi) {
10181        val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10182        val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10183                HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10184                HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10185    } else {
10186        val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10187                HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10188                HC_CONFIG_0_REG_INT_LINE_EN_0 |
10189                HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10190
10191        if (!CHIP_IS_E1(sc)) {
10192            BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10193                  val, port, addr);
10194
10195            REG_WR(sc, addr, val);
10196
10197            val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10198        }
10199    }
10200
10201    if (CHIP_IS_E1(sc)) {
10202        REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10203    }
10204
10205    BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10206          val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10207
10208    REG_WR(sc, addr, val);
10209
10210    /* ensure that HC_CONFIG is written before leading/trailing edge config */
10211    mb();
10212
10213    if (!CHIP_IS_E1(sc)) {
10214        /* init leading/trailing edge */
10215        if (IS_MF(sc)) {
10216            val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10217            if (sc->port.pmf) {
10218                /* enable nig and gpio3 attention */
10219                val |= 0x1100;
10220            }
10221        } else {
10222            val = 0xffff;
10223        }
10224
10225        REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10226        REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10227    }
10228
10229    /* make sure that interrupts are indeed enabled from here on */
10230    mb();
10231}
10232
10233static void
10234bxe_igu_int_enable(struct bxe_softc *sc)
10235{
10236    uint32_t val;
10237    uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10238    uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10239                           (sc->intr_count == 1)) ? TRUE : FALSE;
10240    uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10241
10242    val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10243
10244    if (msix) {
10245        val &= ~(IGU_PF_CONF_INT_LINE_EN |
10246                 IGU_PF_CONF_SINGLE_ISR_EN);
10247        val |= (IGU_PF_CONF_MSI_MSIX_EN |
10248                IGU_PF_CONF_ATTN_BIT_EN);
10249        if (single_msix) {
10250            val |= IGU_PF_CONF_SINGLE_ISR_EN;
10251        }
10252    } else if (msi) {
10253        val &= ~IGU_PF_CONF_INT_LINE_EN;
10254        val |= (IGU_PF_CONF_MSI_MSIX_EN |
10255                IGU_PF_CONF_ATTN_BIT_EN |
10256                IGU_PF_CONF_SINGLE_ISR_EN);
10257    } else {
10258        val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10259        val |= (IGU_PF_CONF_INT_LINE_EN |
10260                IGU_PF_CONF_ATTN_BIT_EN |
10261                IGU_PF_CONF_SINGLE_ISR_EN);
10262    }
10263
10264    /* clean previous status - need to configure igu prior to ack*/
10265    if ((!msix) || single_msix) {
10266        REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10267        bxe_ack_int(sc);
10268    }
10269
10270    val |= IGU_PF_CONF_FUNC_EN;
10271
10272    BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10273          val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10274
10275    REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10276
10277    mb();
10278
10279    /* init leading/trailing edge */
10280    if (IS_MF(sc)) {
10281        val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10282        if (sc->port.pmf) {
10283            /* enable nig and gpio3 attention */
10284            val |= 0x1100;
10285        }
10286    } else {
10287        val = 0xffff;
10288    }
10289
10290    REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10291    REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10292
10293    /* make sure that interrupts are indeed enabled from here on */
10294    mb();
10295}
10296
10297static void
10298bxe_int_enable(struct bxe_softc *sc)
10299{
10300    if (sc->devinfo.int_block == INT_BLOCK_HC) {
10301        bxe_hc_int_enable(sc);
10302    } else {
10303        bxe_igu_int_enable(sc);
10304    }
10305}
10306
10307static void
10308bxe_hc_int_disable(struct bxe_softc *sc)
10309{
10310    int port = SC_PORT(sc);
10311    uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10312    uint32_t val = REG_RD(sc, addr);
10313
10314    /*
10315     * In E1 we must use only PCI configuration space to disable MSI/MSIX
10316     * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10317     * block
10318     */
10319    if (CHIP_IS_E1(sc)) {
10320        /*
10321         * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10322         * to prevent from HC sending interrupts after we exit the function
10323         */
10324        REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10325
10326        val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10327                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10328                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10329    } else {
10330        val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10331                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10332                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10333                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10334    }
10335
10336    BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10337
10338    /* flush all outstanding writes */
10339    mb();
10340
10341    REG_WR(sc, addr, val);
10342    if (REG_RD(sc, addr) != val) {
10343        BLOGE(sc, "proper val not read from HC IGU!\n");
10344    }
10345}
10346
10347static void
10348bxe_igu_int_disable(struct bxe_softc *sc)
10349{
10350    uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10351
10352    val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10353             IGU_PF_CONF_INT_LINE_EN |
10354             IGU_PF_CONF_ATTN_BIT_EN);
10355
10356    BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10357
10358    /* flush all outstanding writes */
10359    mb();
10360
10361    REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10362    if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10363        BLOGE(sc, "proper val not read from IGU!\n");
10364    }
10365}
10366
10367static void
10368bxe_int_disable(struct bxe_softc *sc)
10369{
10370    if (sc->devinfo.int_block == INT_BLOCK_HC) {
10371        bxe_hc_int_disable(sc);
10372    } else {
10373        bxe_igu_int_disable(sc);
10374    }
10375}
10376
10377static void
10378bxe_nic_init(struct bxe_softc *sc,
10379             int              load_code)
10380{
10381    int i;
10382
10383    for (i = 0; i < sc->num_queues; i++) {
10384        bxe_init_eth_fp(sc, i);
10385    }
10386
10387    rmb(); /* ensure status block indices were read */
10388
10389    bxe_init_rx_rings(sc);
10390    bxe_init_tx_rings(sc);
10391
10392    if (IS_VF(sc)) {
10393        return;
10394    }
10395
10396    /* initialize MOD_ABS interrupts */
10397    elink_init_mod_abs_int(sc, &sc->link_vars,
10398                           sc->devinfo.chip_id,
10399                           sc->devinfo.shmem_base,
10400                           sc->devinfo.shmem2_base,
10401                           SC_PORT(sc));
10402
10403    bxe_init_def_sb(sc);
10404    bxe_update_dsb_idx(sc);
10405    bxe_init_sp_ring(sc);
10406    bxe_init_eq_ring(sc);
10407    bxe_init_internal(sc, load_code);
10408    bxe_pf_init(sc);
10409    bxe_stats_init(sc);
10410
10411    /* flush all before enabling interrupts */
10412    mb();
10413
10414    bxe_int_enable(sc);
10415
10416    /* check for SPIO5 */
10417    bxe_attn_int_deasserted0(sc,
10418                             REG_RD(sc,
10419                                    (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10420                                     SC_PORT(sc)*4)) &
10421                             AEU_INPUTS_ATTN_BITS_SPIO5);
10422}
10423
10424static inline void
10425bxe_init_objs(struct bxe_softc *sc)
10426{
10427    /* mcast rules must be added to tx if tx switching is enabled */
10428    ecore_obj_type o_type =
10429        (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10430                                         ECORE_OBJ_TYPE_RX;
10431
10432    /* RX_MODE controlling object */
10433    ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10434
10435    /* multicast configuration controlling object */
10436    ecore_init_mcast_obj(sc,
10437                         &sc->mcast_obj,
10438                         sc->fp[0].cl_id,
10439                         sc->fp[0].index,
10440                         SC_FUNC(sc),
10441                         SC_FUNC(sc),
10442                         BXE_SP(sc, mcast_rdata),
10443                         BXE_SP_MAPPING(sc, mcast_rdata),
10444                         ECORE_FILTER_MCAST_PENDING,
10445                         &sc->sp_state,
10446                         o_type);
10447
10448    /* Setup CAM credit pools */
10449    ecore_init_mac_credit_pool(sc,
10450                               &sc->macs_pool,
10451                               SC_FUNC(sc),
10452                               CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10453                                                 VNICS_PER_PATH(sc));
10454
10455    ecore_init_vlan_credit_pool(sc,
10456                                &sc->vlans_pool,
10457                                SC_ABS_FUNC(sc) >> 1,
10458                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10459                                                  VNICS_PER_PATH(sc));
10460
10461    /* RSS configuration object */
10462    ecore_init_rss_config_obj(sc,
10463                              &sc->rss_conf_obj,
10464                              sc->fp[0].cl_id,
10465                              sc->fp[0].index,
10466                              SC_FUNC(sc),
10467                              SC_FUNC(sc),
10468                              BXE_SP(sc, rss_rdata),
10469                              BXE_SP_MAPPING(sc, rss_rdata),
10470                              ECORE_FILTER_RSS_CONF_PENDING,
10471                              &sc->sp_state, ECORE_OBJ_TYPE_RX);
10472}
10473
10474/*
10475 * Initialize the function. This must be called before sending CLIENT_SETUP
10476 * for the first client.
10477 */
10478static inline int
10479bxe_func_start(struct bxe_softc *sc)
10480{
10481    struct ecore_func_state_params func_params = { NULL };
10482    struct ecore_func_start_params *start_params = &func_params.params.start;
10483
10484    /* Prepare parameters for function state transitions */
10485    bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10486
10487    func_params.f_obj = &sc->func_obj;
10488    func_params.cmd = ECORE_F_CMD_START;
10489
10490    /* Function parameters */
10491    start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10492    start_params->sd_vlan_tag = OVLAN(sc);
10493
10494    if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10495        start_params->network_cos_mode = STATIC_COS;
10496    } else { /* CHIP_IS_E1X */
10497        start_params->network_cos_mode = FW_WRR;
10498    }
10499
10500    //start_params->gre_tunnel_mode = 0;
10501    //start_params->gre_tunnel_rss  = 0;
10502
10503    return (ecore_func_state_change(sc, &func_params));
10504}
10505
10506static int
10507bxe_set_power_state(struct bxe_softc *sc,
10508                    uint8_t          state)
10509{
10510    uint16_t pmcsr;
10511
10512    /* If there is no power capability, silently succeed */
10513    if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10514        BLOGW(sc, "No power capability\n");
10515        return (0);
10516    }
10517
10518    pmcsr = pci_read_config(sc->dev,
10519                            (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10520                            2);
10521
10522    switch (state) {
10523    case PCI_PM_D0:
10524        pci_write_config(sc->dev,
10525                         (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10526                         ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10527
10528        if (pmcsr & PCIM_PSTAT_DMASK) {
10529            /* delay required during transition out of D3hot */
10530            DELAY(20000);
10531        }
10532
10533        break;
10534
10535    case PCI_PM_D3hot:
10536        /* XXX if there are other clients above don't shut down the power */
10537
10538        /* don't shut down the power for emulation and FPGA */
10539        if (CHIP_REV_IS_SLOW(sc)) {
10540            return (0);
10541        }
10542
10543        pmcsr &= ~PCIM_PSTAT_DMASK;
10544        pmcsr |= PCIM_PSTAT_D3;
10545
10546        if (sc->wol) {
10547            pmcsr |= PCIM_PSTAT_PMEENABLE;
10548        }
10549
10550        pci_write_config(sc->dev,
10551                         (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10552                         pmcsr, 4);
10553
10554        /*
10555         * No more memory access after this point until device is brought back
10556         * to D0 state.
10557         */
10558        break;
10559
10560    default:
10561        BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10562            state, pmcsr);
10563        return (-1);
10564    }
10565
10566    return (0);
10567}
10568
10569
10570/* return true if succeeded to acquire the lock */
10571static uint8_t
10572bxe_trylock_hw_lock(struct bxe_softc *sc,
10573                    uint32_t         resource)
10574{
10575    uint32_t lock_status;
10576    uint32_t resource_bit = (1 << resource);
10577    int func = SC_FUNC(sc);
10578    uint32_t hw_lock_control_reg;
10579
10580    BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10581
10582    /* Validating that the resource is within range */
10583    if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10584        BLOGD(sc, DBG_LOAD,
10585              "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10586              resource, HW_LOCK_MAX_RESOURCE_VALUE);
10587        return (FALSE);
10588    }
10589
10590    if (func <= 5) {
10591        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10592    } else {
10593        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10594    }
10595
10596    /* try to acquire the lock */
10597    REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10598    lock_status = REG_RD(sc, hw_lock_control_reg);
10599    if (lock_status & resource_bit) {
10600        return (TRUE);
10601    }
10602
10603    BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10604        "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10605        lock_status, resource_bit);
10606
10607    return (FALSE);
10608}
10609
10610/*
10611 * Get the recovery leader resource id according to the engine this function
10612 * belongs to. Currently only only 2 engines is supported.
10613 */
10614static int
10615bxe_get_leader_lock_resource(struct bxe_softc *sc)
10616{
10617    if (SC_PATH(sc)) {
10618        return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10619    } else {
10620        return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10621    }
10622}
10623
10624/* try to acquire a leader lock for current engine */
10625static uint8_t
10626bxe_trylock_leader_lock(struct bxe_softc *sc)
10627{
10628    return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10629}
10630
10631static int
10632bxe_release_leader_lock(struct bxe_softc *sc)
10633{
10634    return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10635}
10636
10637/* close gates #2, #3 and #4 */
10638static void
10639bxe_set_234_gates(struct bxe_softc *sc,
10640                  uint8_t          close)
10641{
10642    uint32_t val;
10643
10644    /* gates #2 and #4a are closed/opened for "not E1" only */
10645    if (!CHIP_IS_E1(sc)) {
10646        /* #4 */
10647        REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10648        /* #2 */
10649        REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10650    }
10651
10652    /* #3 */
10653    if (CHIP_IS_E1x(sc)) {
10654        /* prevent interrupts from HC on both ports */
10655        val = REG_RD(sc, HC_REG_CONFIG_1);
10656        REG_WR(sc, HC_REG_CONFIG_1,
10657               (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10658               (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10659
10660        val = REG_RD(sc, HC_REG_CONFIG_0);
10661        REG_WR(sc, HC_REG_CONFIG_0,
10662               (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10663               (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10664    } else {
10665        /* Prevent incoming interrupts in IGU */
10666        val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10667
10668        REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10669               (!close) ?
10670               (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10671               (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10672    }
10673
10674    BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10675          close ? "closing" : "opening");
10676
10677    wmb();
10678}
10679
10680/* poll for pending writes bit, it should get cleared in no more than 1s */
10681static int
10682bxe_er_poll_igu_vq(struct bxe_softc *sc)
10683{
10684    uint32_t cnt = 1000;
10685    uint32_t pend_bits = 0;
10686
10687    do {
10688        pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10689
10690        if (pend_bits == 0) {
10691            break;
10692        }
10693
10694        DELAY(1000);
10695    } while (--cnt > 0);
10696
10697    if (cnt == 0) {
10698        BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10699        return (-1);
10700    }
10701
10702    return (0);
10703}
10704
10705#define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10706
10707static void
10708bxe_clp_reset_prep(struct bxe_softc *sc,
10709                   uint32_t         *magic_val)
10710{
10711    /* Do some magic... */
10712    uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10713    *magic_val = val & SHARED_MF_CLP_MAGIC;
10714    MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10715}
10716
10717/* restore the value of the 'magic' bit */
10718static void
10719bxe_clp_reset_done(struct bxe_softc *sc,
10720                   uint32_t         magic_val)
10721{
10722    /* Restore the 'magic' bit value... */
10723    uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10724    MFCFG_WR(sc, shared_mf_config.clp_mb,
10725              (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10726}
10727
10728/* prepare for MCP reset, takes care of CLP configurations */
10729static void
10730bxe_reset_mcp_prep(struct bxe_softc *sc,
10731                   uint32_t         *magic_val)
10732{
10733    uint32_t shmem;
10734    uint32_t validity_offset;
10735
10736    /* set `magic' bit in order to save MF config */
10737    if (!CHIP_IS_E1(sc)) {
10738        bxe_clp_reset_prep(sc, magic_val);
10739    }
10740
10741    /* get shmem offset */
10742    shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10743    validity_offset =
10744        offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10745
10746    /* Clear validity map flags */
10747    if (shmem > 0) {
10748        REG_WR(sc, shmem + validity_offset, 0);
10749    }
10750}
10751
10752#define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10753#define MCP_ONE_TIMEOUT  100    /* 100 ms */
10754
10755static void
10756bxe_mcp_wait_one(struct bxe_softc *sc)
10757{
10758    /* special handling for emulation and FPGA (10 times longer) */
10759    if (CHIP_REV_IS_SLOW(sc)) {
10760        DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10761    } else {
10762        DELAY((MCP_ONE_TIMEOUT) * 1000);
10763    }
10764}
10765
10766/* initialize shmem_base and waits for validity signature to appear */
10767static int
10768bxe_init_shmem(struct bxe_softc *sc)
10769{
10770    int cnt = 0;
10771    uint32_t val = 0;
10772
10773    do {
10774        sc->devinfo.shmem_base     =
10775        sc->link_params.shmem_base =
10776            REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10777
10778        if (sc->devinfo.shmem_base) {
10779            val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10780            if (val & SHR_MEM_VALIDITY_MB)
10781                return (0);
10782        }
10783
10784        bxe_mcp_wait_one(sc);
10785
10786    } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10787
10788    BLOGE(sc, "BAD MCP validity signature\n");
10789
10790    return (-1);
10791}
10792
10793static int
10794bxe_reset_mcp_comp(struct bxe_softc *sc,
10795                   uint32_t         magic_val)
10796{
10797    int rc = bxe_init_shmem(sc);
10798
10799    /* Restore the `magic' bit value */
10800    if (!CHIP_IS_E1(sc)) {
10801        bxe_clp_reset_done(sc, magic_val);
10802    }
10803
10804    return (rc);
10805}
10806
10807static void
10808bxe_pxp_prep(struct bxe_softc *sc)
10809{
10810    if (!CHIP_IS_E1(sc)) {
10811        REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10812        REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10813        wmb();
10814    }
10815}
10816
10817/*
10818 * Reset the whole chip except for:
10819 *      - PCIE core
10820 *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10821 *      - IGU
10822 *      - MISC (including AEU)
10823 *      - GRC
10824 *      - RBCN, RBCP
10825 */
10826static void
10827bxe_process_kill_chip_reset(struct bxe_softc *sc,
10828                            uint8_t          global)
10829{
10830    uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10831    uint32_t global_bits2, stay_reset2;
10832
10833    /*
10834     * Bits that have to be set in reset_mask2 if we want to reset 'global'
10835     * (per chip) blocks.
10836     */
10837    global_bits2 =
10838        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10839        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10840
10841    /*
10842     * Don't reset the following blocks.
10843     * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10844     *            reset, as in 4 port device they might still be owned
10845     *            by the MCP (there is only one leader per path).
10846     */
10847    not_reset_mask1 =
10848        MISC_REGISTERS_RESET_REG_1_RST_HC |
10849        MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10850        MISC_REGISTERS_RESET_REG_1_RST_PXP;
10851
10852    not_reset_mask2 =
10853        MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10854        MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10855        MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10856        MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10857        MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10858        MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10859        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10860        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10861        MISC_REGISTERS_RESET_REG_2_RST_ATC |
10862        MISC_REGISTERS_RESET_REG_2_PGLC |
10863        MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10864        MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10865        MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10866        MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10867        MISC_REGISTERS_RESET_REG_2_UMAC0 |
10868        MISC_REGISTERS_RESET_REG_2_UMAC1;
10869
10870    /*
10871     * Keep the following blocks in reset:
10872     *  - all xxMACs are handled by the elink code.
10873     */
10874    stay_reset2 =
10875        MISC_REGISTERS_RESET_REG_2_XMAC |
10876        MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10877
10878    /* Full reset masks according to the chip */
10879    reset_mask1 = 0xffffffff;
10880
10881    if (CHIP_IS_E1(sc))
10882        reset_mask2 = 0xffff;
10883    else if (CHIP_IS_E1H(sc))
10884        reset_mask2 = 0x1ffff;
10885    else if (CHIP_IS_E2(sc))
10886        reset_mask2 = 0xfffff;
10887    else /* CHIP_IS_E3 */
10888        reset_mask2 = 0x3ffffff;
10889
10890    /* Don't reset global blocks unless we need to */
10891    if (!global)
10892        reset_mask2 &= ~global_bits2;
10893
10894    /*
10895     * In case of attention in the QM, we need to reset PXP
10896     * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
10897     * because otherwise QM reset would release 'close the gates' shortly
10898     * before resetting the PXP, then the PSWRQ would send a write
10899     * request to PGLUE. Then when PXP is reset, PGLUE would try to
10900     * read the payload data from PSWWR, but PSWWR would not
10901     * respond. The write queue in PGLUE would stuck, dmae commands
10902     * would not return. Therefore it's important to reset the second
10903     * reset register (containing the
10904     * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
10905     * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
10906     * bit).
10907     */
10908    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
10909           reset_mask2 & (~not_reset_mask2));
10910
10911    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
10912           reset_mask1 & (~not_reset_mask1));
10913
10914    mb();
10915    wmb();
10916
10917    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
10918           reset_mask2 & (~stay_reset2));
10919
10920    mb();
10921    wmb();
10922
10923    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
10924    wmb();
10925}
10926
10927static int
10928bxe_process_kill(struct bxe_softc *sc,
10929                 uint8_t          global)
10930{
10931    int cnt = 1000;
10932    uint32_t val = 0;
10933    uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
10934    uint32_t tags_63_32 = 0;
10935
10936    /* Empty the Tetris buffer, wait for 1s */
10937    do {
10938        sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
10939        blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
10940        port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
10941        port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
10942        pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
10943        if (CHIP_IS_E3(sc)) {
10944            tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
10945        }
10946
10947        if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
10948            ((port_is_idle_0 & 0x1) == 0x1) &&
10949            ((port_is_idle_1 & 0x1) == 0x1) &&
10950            (pgl_exp_rom2 == 0xffffffff) &&
10951            (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
10952            break;
10953        DELAY(1000);
10954    } while (cnt-- > 0);
10955
10956    if (cnt <= 0) {
10957        BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
10958                  "are still outstanding read requests after 1s! "
10959                  "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
10960                  "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
10961              sr_cnt, blk_cnt, port_is_idle_0,
10962              port_is_idle_1, pgl_exp_rom2);
10963        return (-1);
10964    }
10965
10966    mb();
10967
10968    /* Close gates #2, #3 and #4 */
10969    bxe_set_234_gates(sc, TRUE);
10970
10971    /* Poll for IGU VQs for 57712 and newer chips */
10972    if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
10973        return (-1);
10974    }
10975
10976    /* XXX indicate that "process kill" is in progress to MCP */
10977
10978    /* clear "unprepared" bit */
10979    REG_WR(sc, MISC_REG_UNPREPARED, 0);
10980    mb();
10981
10982    /* Make sure all is written to the chip before the reset */
10983    wmb();
10984
10985    /*
10986     * Wait for 1ms to empty GLUE and PCI-E core queues,
10987     * PSWHST, GRC and PSWRD Tetris buffer.
10988     */
10989    DELAY(1000);
10990
10991    /* Prepare to chip reset: */
10992    /* MCP */
10993    if (global) {
10994        bxe_reset_mcp_prep(sc, &val);
10995    }
10996
10997    /* PXP */
10998    bxe_pxp_prep(sc);
10999    mb();
11000
11001    /* reset the chip */
11002    bxe_process_kill_chip_reset(sc, global);
11003    mb();
11004
11005    /* clear errors in PGB */
11006    if (!CHIP_IS_E1(sc))
11007        REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11008
11009    /* Recover after reset: */
11010    /* MCP */
11011    if (global && bxe_reset_mcp_comp(sc, val)) {
11012        return (-1);
11013    }
11014
11015    /* XXX add resetting the NO_MCP mode DB here */
11016
11017    /* Open the gates #2, #3 and #4 */
11018    bxe_set_234_gates(sc, FALSE);
11019
11020    /* XXX
11021     * IGU/AEU preparation bring back the AEU/IGU to a reset state
11022     * re-enable attentions
11023     */
11024
11025    return (0);
11026}
11027
11028static int
11029bxe_leader_reset(struct bxe_softc *sc)
11030{
11031    int rc = 0;
11032    uint8_t global = bxe_reset_is_global(sc);
11033    uint32_t load_code;
11034
11035    /*
11036     * If not going to reset MCP, load "fake" driver to reset HW while
11037     * driver is owner of the HW.
11038     */
11039    if (!global && !BXE_NOMCP(sc)) {
11040        load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11041                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11042        if (!load_code) {
11043            BLOGE(sc, "MCP response failure, aborting\n");
11044            rc = -1;
11045            goto exit_leader_reset;
11046        }
11047
11048        if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11049            (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11050            BLOGE(sc, "MCP unexpected response, aborting\n");
11051            rc = -1;
11052            goto exit_leader_reset2;
11053        }
11054
11055        load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11056        if (!load_code) {
11057            BLOGE(sc, "MCP response failure, aborting\n");
11058            rc = -1;
11059            goto exit_leader_reset2;
11060        }
11061    }
11062
11063    /* try to recover after the failure */
11064    if (bxe_process_kill(sc, global)) {
11065        BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11066        rc = -1;
11067        goto exit_leader_reset2;
11068    }
11069
11070    /*
11071     * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11072     * state.
11073     */
11074    bxe_set_reset_done(sc);
11075    if (global) {
11076        bxe_clear_reset_global(sc);
11077    }
11078
11079exit_leader_reset2:
11080
11081    /* unload "fake driver" if it was loaded */
11082    if (!global && !BXE_NOMCP(sc)) {
11083        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11084        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11085    }
11086
11087exit_leader_reset:
11088
11089    sc->is_leader = 0;
11090    bxe_release_leader_lock(sc);
11091
11092    mb();
11093    return (rc);
11094}
11095
11096/*
11097 * prepare INIT transition, parameters configured:
11098 *   - HC configuration
11099 *   - Queue's CDU context
11100 */
11101static void
11102bxe_pf_q_prep_init(struct bxe_softc               *sc,
11103                   struct bxe_fastpath            *fp,
11104                   struct ecore_queue_init_params *init_params)
11105{
11106    uint8_t cos;
11107    int cxt_index, cxt_offset;
11108
11109    bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11110    bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11111
11112    bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11113    bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11114
11115    /* HC rate */
11116    init_params->rx.hc_rate =
11117        sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11118    init_params->tx.hc_rate =
11119        sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11120
11121    /* FW SB ID */
11122    init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11123
11124    /* CQ index among the SB indices */
11125    init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11126    init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11127
11128    /* set maximum number of COSs supported by this queue */
11129    init_params->max_cos = sc->max_cos;
11130
11131    BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11132          fp->index, init_params->max_cos);
11133
11134    /* set the context pointers queue object */
11135    for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11136        /* XXX change index/cid here if ever support multiple tx CoS */
11137        /* fp->txdata[cos]->cid */
11138        cxt_index = fp->index / ILT_PAGE_CIDS;
11139        cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11140        init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11141    }
11142}
11143
11144/* set flags that are common for the Tx-only and not normal connections */
11145static unsigned long
11146bxe_get_common_flags(struct bxe_softc    *sc,
11147                     struct bxe_fastpath *fp,
11148                     uint8_t             zero_stats)
11149{
11150    unsigned long flags = 0;
11151
11152    /* PF driver will always initialize the Queue to an ACTIVE state */
11153    bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11154
11155    /*
11156     * tx only connections collect statistics (on the same index as the
11157     * parent connection). The statistics are zeroed when the parent
11158     * connection is initialized.
11159     */
11160
11161    bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11162    if (zero_stats) {
11163        bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11164    }
11165
11166    /*
11167     * tx only connections can support tx-switching, though their
11168     * CoS-ness doesn't survive the loopback
11169     */
11170    if (sc->flags & BXE_TX_SWITCHING) {
11171        bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11172    }
11173
11174    bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11175
11176    return (flags);
11177}
11178
11179static unsigned long
11180bxe_get_q_flags(struct bxe_softc    *sc,
11181                struct bxe_fastpath *fp,
11182                uint8_t             leading)
11183{
11184    unsigned long flags = 0;
11185
11186    if (IS_MF_SD(sc)) {
11187        bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11188    }
11189
11190    if (if_getcapenable(sc->ifp) & IFCAP_LRO) {
11191        bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11192        bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11193    }
11194
11195    if (leading) {
11196        bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11197        bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11198    }
11199
11200    bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11201
11202    /* merge with common flags */
11203    return (flags | bxe_get_common_flags(sc, fp, TRUE));
11204}
11205
11206static void
11207bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11208                      struct bxe_fastpath               *fp,
11209                      struct ecore_general_setup_params *gen_init,
11210                      uint8_t                           cos)
11211{
11212    gen_init->stat_id = bxe_stats_id(fp);
11213    gen_init->spcl_id = fp->cl_id;
11214    gen_init->mtu = sc->mtu;
11215    gen_init->cos = cos;
11216}
11217
11218static void
11219bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11220                 struct bxe_fastpath           *fp,
11221                 struct rxq_pause_params       *pause,
11222                 struct ecore_rxq_setup_params *rxq_init)
11223{
11224    uint8_t max_sge = 0;
11225    uint16_t sge_sz = 0;
11226    uint16_t tpa_agg_size = 0;
11227
11228    pause->sge_th_lo = SGE_TH_LO(sc);
11229    pause->sge_th_hi = SGE_TH_HI(sc);
11230
11231    /* validate SGE ring has enough to cross high threshold */
11232    if (sc->dropless_fc &&
11233            (pause->sge_th_hi + FW_PREFETCH_CNT) >
11234            (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11235        BLOGW(sc, "sge ring threshold limit\n");
11236    }
11237
11238    /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11239    tpa_agg_size = (2 * sc->mtu);
11240    if (tpa_agg_size < sc->max_aggregation_size) {
11241        tpa_agg_size = sc->max_aggregation_size;
11242    }
11243
11244    max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11245    max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11246                   (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11247    sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11248
11249    /* pause - not for e1 */
11250    if (!CHIP_IS_E1(sc)) {
11251        pause->bd_th_lo = BD_TH_LO(sc);
11252        pause->bd_th_hi = BD_TH_HI(sc);
11253
11254        pause->rcq_th_lo = RCQ_TH_LO(sc);
11255        pause->rcq_th_hi = RCQ_TH_HI(sc);
11256
11257        /* validate rings have enough entries to cross high thresholds */
11258        if (sc->dropless_fc &&
11259            pause->bd_th_hi + FW_PREFETCH_CNT >
11260            sc->rx_ring_size) {
11261            BLOGW(sc, "rx bd ring threshold limit\n");
11262        }
11263
11264        if (sc->dropless_fc &&
11265            pause->rcq_th_hi + FW_PREFETCH_CNT >
11266            RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11267            BLOGW(sc, "rcq ring threshold limit\n");
11268        }
11269
11270        pause->pri_map = 1;
11271    }
11272
11273    /* rxq setup */
11274    rxq_init->dscr_map   = fp->rx_dma.paddr;
11275    rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11276    rxq_init->rcq_map    = fp->rcq_dma.paddr;
11277    rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11278
11279    /*
11280     * This should be a maximum number of data bytes that may be
11281     * placed on the BD (not including paddings).
11282     */
11283    rxq_init->buf_sz = (fp->rx_buf_size -
11284                        IP_HEADER_ALIGNMENT_PADDING);
11285
11286    rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11287    rxq_init->tpa_agg_sz      = tpa_agg_size;
11288    rxq_init->sge_buf_sz      = sge_sz;
11289    rxq_init->max_sges_pkt    = max_sge;
11290    rxq_init->rss_engine_id   = SC_FUNC(sc);
11291    rxq_init->mcast_engine_id = SC_FUNC(sc);
11292
11293    /*
11294     * Maximum number or simultaneous TPA aggregation for this Queue.
11295     * For PF Clients it should be the maximum available number.
11296     * VF driver(s) may want to define it to a smaller value.
11297     */
11298    rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11299
11300    rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11301    rxq_init->fw_sb_id = fp->fw_sb_id;
11302
11303    rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11304
11305    /*
11306     * configure silent vlan removal
11307     * if multi function mode is afex, then mask default vlan
11308     */
11309    if (IS_MF_AFEX(sc)) {
11310        rxq_init->silent_removal_value =
11311            sc->devinfo.mf_info.afex_def_vlan_tag;
11312        rxq_init->silent_removal_mask = EVL_VLID_MASK;
11313    }
11314}
11315
11316static void
11317bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11318                 struct bxe_fastpath           *fp,
11319                 struct ecore_txq_setup_params *txq_init,
11320                 uint8_t                       cos)
11321{
11322    /*
11323     * XXX If multiple CoS is ever supported then each fastpath structure
11324     * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11325     * fp->txdata[cos]->tx_dma.paddr;
11326     */
11327    txq_init->dscr_map     = fp->tx_dma.paddr;
11328    txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11329    txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11330    txq_init->fw_sb_id     = fp->fw_sb_id;
11331
11332    /*
11333     * set the TSS leading client id for TX classfication to the
11334     * leading RSS client id
11335     */
11336    txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11337}
11338
11339/*
11340 * This function performs 2 steps in a queue state machine:
11341 *   1) RESET->INIT
11342 *   2) INIT->SETUP
11343 */
11344static int
11345bxe_setup_queue(struct bxe_softc    *sc,
11346                struct bxe_fastpath *fp,
11347                uint8_t             leading)
11348{
11349    struct ecore_queue_state_params q_params = { NULL };
11350    struct ecore_queue_setup_params *setup_params =
11351                        &q_params.params.setup;
11352    int rc;
11353
11354    BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11355
11356    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11357
11358    q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11359
11360    /* we want to wait for completion in this context */
11361    bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11362
11363    /* prepare the INIT parameters */
11364    bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11365
11366    /* Set the command */
11367    q_params.cmd = ECORE_Q_CMD_INIT;
11368
11369    /* Change the state to INIT */
11370    rc = ecore_queue_state_change(sc, &q_params);
11371    if (rc) {
11372        BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11373        return (rc);
11374    }
11375
11376    BLOGD(sc, DBG_LOAD, "init complete\n");
11377
11378    /* now move the Queue to the SETUP state */
11379    memset(setup_params, 0, sizeof(*setup_params));
11380
11381    /* set Queue flags */
11382    setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11383
11384    /* set general SETUP parameters */
11385    bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11386                          FIRST_TX_COS_INDEX);
11387
11388    bxe_pf_rx_q_prep(sc, fp,
11389                     &setup_params->pause_params,
11390                     &setup_params->rxq_params);
11391
11392    bxe_pf_tx_q_prep(sc, fp,
11393                     &setup_params->txq_params,
11394                     FIRST_TX_COS_INDEX);
11395
11396    /* Set the command */
11397    q_params.cmd = ECORE_Q_CMD_SETUP;
11398
11399    /* change the state to SETUP */
11400    rc = ecore_queue_state_change(sc, &q_params);
11401    if (rc) {
11402        BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11403        return (rc);
11404    }
11405
11406    return (rc);
11407}
11408
11409static int
11410bxe_setup_leading(struct bxe_softc *sc)
11411{
11412    return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11413}
11414
11415static int
11416bxe_config_rss_pf(struct bxe_softc            *sc,
11417                  struct ecore_rss_config_obj *rss_obj,
11418                  uint8_t                     config_hash)
11419{
11420    struct ecore_config_rss_params params = { NULL };
11421    int i;
11422
11423    /*
11424     * Although RSS is meaningless when there is a single HW queue we
11425     * still need it enabled in order to have HW Rx hash generated.
11426     */
11427
11428    params.rss_obj = rss_obj;
11429
11430    bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11431
11432    bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11433
11434    /* RSS configuration */
11435    bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11436    bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11437    bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11438    bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11439    if (rss_obj->udp_rss_v4) {
11440        bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11441    }
11442    if (rss_obj->udp_rss_v6) {
11443        bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11444    }
11445
11446    /* Hash bits */
11447    params.rss_result_mask = MULTI_MASK;
11448
11449    memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11450
11451    if (config_hash) {
11452        /* RSS keys */
11453        for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11454            params.rss_key[i] = arc4random();
11455        }
11456
11457        bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11458    }
11459
11460    return (ecore_config_rss(sc, &params));
11461}
11462
11463static int
11464bxe_config_rss_eth(struct bxe_softc *sc,
11465                   uint8_t          config_hash)
11466{
11467    return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11468}
11469
11470static int
11471bxe_init_rss_pf(struct bxe_softc *sc)
11472{
11473    uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11474    int i;
11475
11476    /*
11477     * Prepare the initial contents of the indirection table if
11478     * RSS is enabled
11479     */
11480    for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11481        sc->rss_conf_obj.ind_table[i] =
11482            (sc->fp->cl_id + (i % num_eth_queues));
11483    }
11484
11485    if (sc->udp_rss) {
11486        sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11487    }
11488
11489    /*
11490     * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11491     * per-port, so if explicit configuration is needed, do it only
11492     * for a PMF.
11493     *
11494     * For 57712 and newer it's a per-function configuration.
11495     */
11496    return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11497}
11498
11499static int
11500bxe_set_mac_one(struct bxe_softc          *sc,
11501                uint8_t                   *mac,
11502                struct ecore_vlan_mac_obj *obj,
11503                uint8_t                   set,
11504                int                       mac_type,
11505                unsigned long             *ramrod_flags)
11506{
11507    struct ecore_vlan_mac_ramrod_params ramrod_param;
11508    int rc;
11509
11510    memset(&ramrod_param, 0, sizeof(ramrod_param));
11511
11512    /* fill in general parameters */
11513    ramrod_param.vlan_mac_obj = obj;
11514    ramrod_param.ramrod_flags = *ramrod_flags;
11515
11516    /* fill a user request section if needed */
11517    if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11518        memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11519
11520        bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11521
11522        /* Set the command: ADD or DEL */
11523        ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11524                                            ECORE_VLAN_MAC_DEL;
11525    }
11526
11527    rc = ecore_config_vlan_mac(sc, &ramrod_param);
11528
11529    if (rc == ECORE_EXISTS) {
11530        BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11531        /* do not treat adding same MAC as error */
11532        rc = 0;
11533    } else if (rc < 0) {
11534        BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11535    }
11536
11537    return (rc);
11538}
11539
11540static int
11541bxe_set_eth_mac(struct bxe_softc *sc,
11542                uint8_t          set)
11543{
11544    unsigned long ramrod_flags = 0;
11545
11546    BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11547
11548    bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11549
11550    /* Eth MAC is set on RSS leading client (fp[0]) */
11551    return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11552                            &sc->sp_objs->mac_obj,
11553                            set, ECORE_ETH_MAC, &ramrod_flags));
11554}
11555
11556static int
11557bxe_get_cur_phy_idx(struct bxe_softc *sc)
11558{
11559    uint32_t sel_phy_idx = 0;
11560
11561    if (sc->link_params.num_phys <= 1) {
11562        return (ELINK_INT_PHY);
11563    }
11564
11565    if (sc->link_vars.link_up) {
11566        sel_phy_idx = ELINK_EXT_PHY1;
11567        /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11568        if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11569            (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11570             ELINK_SUPPORTED_FIBRE))
11571            sel_phy_idx = ELINK_EXT_PHY2;
11572    } else {
11573        switch (elink_phy_selection(&sc->link_params)) {
11574        case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11575        case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11576        case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11577               sel_phy_idx = ELINK_EXT_PHY1;
11578               break;
11579        case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11580        case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11581               sel_phy_idx = ELINK_EXT_PHY2;
11582               break;
11583        }
11584    }
11585
11586    return (sel_phy_idx);
11587}
11588
11589static int
11590bxe_get_link_cfg_idx(struct bxe_softc *sc)
11591{
11592    uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11593
11594    /*
11595     * The selected activated PHY is always after swapping (in case PHY
11596     * swapping is enabled). So when swapping is enabled, we need to reverse
11597     * the configuration
11598     */
11599
11600    if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11601        if (sel_phy_idx == ELINK_EXT_PHY1)
11602            sel_phy_idx = ELINK_EXT_PHY2;
11603        else if (sel_phy_idx == ELINK_EXT_PHY2)
11604            sel_phy_idx = ELINK_EXT_PHY1;
11605    }
11606
11607    return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11608}
11609
11610static void
11611bxe_set_requested_fc(struct bxe_softc *sc)
11612{
11613    /*
11614     * Initialize link parameters structure variables
11615     * It is recommended to turn off RX FC for jumbo frames
11616     * for better performance
11617     */
11618    if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11619        sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11620    } else {
11621        sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11622    }
11623}
11624
11625static void
11626bxe_calc_fc_adv(struct bxe_softc *sc)
11627{
11628    uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11629    switch (sc->link_vars.ieee_fc &
11630            MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11631    case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
11632    default:
11633        sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11634                                           ADVERTISED_Pause);
11635        break;
11636
11637    case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11638        sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11639                                          ADVERTISED_Pause);
11640        break;
11641
11642    case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11643        sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11644        break;
11645    }
11646}
11647
11648static uint16_t
11649bxe_get_mf_speed(struct bxe_softc *sc)
11650{
11651    uint16_t line_speed = sc->link_vars.line_speed;
11652    if (IS_MF(sc)) {
11653        uint16_t maxCfg =
11654            bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11655
11656        /* calculate the current MAX line speed limit for the MF devices */
11657        if (IS_MF_SI(sc)) {
11658            line_speed = (line_speed * maxCfg) / 100;
11659        } else { /* SD mode */
11660            uint16_t vn_max_rate = maxCfg * 100;
11661
11662            if (vn_max_rate < line_speed) {
11663                line_speed = vn_max_rate;
11664            }
11665        }
11666    }
11667
11668    return (line_speed);
11669}
11670
11671static void
11672bxe_fill_report_data(struct bxe_softc            *sc,
11673                     struct bxe_link_report_data *data)
11674{
11675    uint16_t line_speed = bxe_get_mf_speed(sc);
11676
11677    memset(data, 0, sizeof(*data));
11678
11679    /* fill the report data with the effective line speed */
11680    data->line_speed = line_speed;
11681
11682    /* Link is down */
11683    if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11684        bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11685    }
11686
11687    /* Full DUPLEX */
11688    if (sc->link_vars.duplex == DUPLEX_FULL) {
11689        bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11690    }
11691
11692    /* Rx Flow Control is ON */
11693    if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11694        bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11695    }
11696
11697    /* Tx Flow Control is ON */
11698    if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11699        bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11700    }
11701}
11702
11703/* report link status to OS, should be called under phy_lock */
11704static void
11705bxe_link_report_locked(struct bxe_softc *sc)
11706{
11707    struct bxe_link_report_data cur_data;
11708
11709    /* reread mf_cfg */
11710    if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11711        bxe_read_mf_cfg(sc);
11712    }
11713
11714    /* Read the current link report info */
11715    bxe_fill_report_data(sc, &cur_data);
11716
11717    /* Don't report link down or exactly the same link status twice */
11718    if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11719        (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11720                      &sc->last_reported_link.link_report_flags) &&
11721         bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11722                      &cur_data.link_report_flags))) {
11723        return;
11724    }
11725
11726    sc->link_cnt++;
11727
11728    /* report new link params and remember the state for the next time */
11729    memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11730
11731    if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11732                     &cur_data.link_report_flags)) {
11733        if_link_state_change(sc->ifp, LINK_STATE_DOWN);
11734        BLOGI(sc, "NIC Link is Down\n");
11735    } else {
11736        const char *duplex;
11737        const char *flow;
11738
11739        if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11740                                   &cur_data.link_report_flags)) {
11741            duplex = "full";
11742        } else {
11743            duplex = "half";
11744        }
11745
11746        /*
11747         * Handle the FC at the end so that only these flags would be
11748         * possibly set. This way we may easily check if there is no FC
11749         * enabled.
11750         */
11751        if (cur_data.link_report_flags) {
11752            if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11753                             &cur_data.link_report_flags) &&
11754                bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11755                             &cur_data.link_report_flags)) {
11756                flow = "ON - receive & transmit";
11757            } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11758                                    &cur_data.link_report_flags) &&
11759                       !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11760                                     &cur_data.link_report_flags)) {
11761                flow = "ON - receive";
11762            } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11763                                     &cur_data.link_report_flags) &&
11764                       bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11765                                    &cur_data.link_report_flags)) {
11766                flow = "ON - transmit";
11767            } else {
11768                flow = "none"; /* possible? */
11769            }
11770        } else {
11771            flow = "none";
11772        }
11773
11774        if_link_state_change(sc->ifp, LINK_STATE_UP);
11775        BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11776              cur_data.line_speed, duplex, flow);
11777    }
11778}
11779
11780static void
11781bxe_link_report(struct bxe_softc *sc)
11782{
11783    bxe_acquire_phy_lock(sc);
11784    bxe_link_report_locked(sc);
11785    bxe_release_phy_lock(sc);
11786}
11787
11788static void
11789bxe_link_status_update(struct bxe_softc *sc)
11790{
11791    if (sc->state != BXE_STATE_OPEN) {
11792        return;
11793    }
11794
11795    if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11796        elink_link_status_update(&sc->link_params, &sc->link_vars);
11797    } else {
11798        sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11799                                  ELINK_SUPPORTED_10baseT_Full |
11800                                  ELINK_SUPPORTED_100baseT_Half |
11801                                  ELINK_SUPPORTED_100baseT_Full |
11802                                  ELINK_SUPPORTED_1000baseT_Full |
11803                                  ELINK_SUPPORTED_2500baseX_Full |
11804                                  ELINK_SUPPORTED_10000baseT_Full |
11805                                  ELINK_SUPPORTED_TP |
11806                                  ELINK_SUPPORTED_FIBRE |
11807                                  ELINK_SUPPORTED_Autoneg |
11808                                  ELINK_SUPPORTED_Pause |
11809                                  ELINK_SUPPORTED_Asym_Pause);
11810        sc->port.advertising[0] = sc->port.supported[0];
11811
11812        sc->link_params.sc                = sc;
11813        sc->link_params.port              = SC_PORT(sc);
11814        sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11815        sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11816        sc->link_params.req_line_speed[0] = SPEED_10000;
11817        sc->link_params.speed_cap_mask[0] = 0x7f0000;
11818        sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11819
11820        if (CHIP_REV_IS_FPGA(sc)) {
11821            sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11822            sc->link_vars.line_speed  = ELINK_SPEED_1000;
11823            sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11824                                         LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11825        } else {
11826            sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11827            sc->link_vars.line_speed  = ELINK_SPEED_10000;
11828            sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11829                                         LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11830        }
11831
11832        sc->link_vars.link_up = 1;
11833
11834        sc->link_vars.duplex    = DUPLEX_FULL;
11835        sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11836
11837        if (IS_PF(sc)) {
11838            REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11839            bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11840            bxe_link_report(sc);
11841        }
11842    }
11843
11844    if (IS_PF(sc)) {
11845        if (sc->link_vars.link_up) {
11846            bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11847        } else {
11848            bxe_stats_handle(sc, STATS_EVENT_STOP);
11849        }
11850        bxe_link_report(sc);
11851    } else {
11852        bxe_link_report(sc);
11853        bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11854    }
11855}
11856
11857static int
11858bxe_initial_phy_init(struct bxe_softc *sc,
11859                     int              load_mode)
11860{
11861    int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11862    uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11863    struct elink_params *lp = &sc->link_params;
11864
11865    bxe_set_requested_fc(sc);
11866
11867    if (CHIP_REV_IS_SLOW(sc)) {
11868        uint32_t bond = CHIP_BOND_ID(sc);
11869        uint32_t feat = 0;
11870
11871        if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11872            feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11873        } else if (bond & 0x4) {
11874            if (CHIP_IS_E3(sc)) {
11875                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11876            } else {
11877                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11878            }
11879        } else if (bond & 0x8) {
11880            if (CHIP_IS_E3(sc)) {
11881                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11882            } else {
11883                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11884            }
11885        }
11886
11887        /* disable EMAC for E3 and above */
11888        if (bond & 0x2) {
11889            feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11890        }
11891
11892        sc->link_params.feature_config_flags |= feat;
11893    }
11894
11895    bxe_acquire_phy_lock(sc);
11896
11897    if (load_mode == LOAD_DIAG) {
11898        lp->loopback_mode = ELINK_LOOPBACK_XGXS;
11899        /* Prefer doing PHY loopback at 10G speed, if possible */
11900        if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
11901            if (lp->speed_cap_mask[cfg_idx] &
11902                PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
11903                lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
11904            } else {
11905                lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
11906            }
11907        }
11908    }
11909
11910    if (load_mode == LOAD_LOOPBACK_EXT) {
11911        lp->loopback_mode = ELINK_LOOPBACK_EXT;
11912    }
11913
11914    rc = elink_phy_init(&sc->link_params, &sc->link_vars);
11915
11916    bxe_release_phy_lock(sc);
11917
11918    bxe_calc_fc_adv(sc);
11919
11920    if (sc->link_vars.link_up) {
11921        bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11922        bxe_link_report(sc);
11923    }
11924
11925    if (!CHIP_REV_IS_SLOW(sc)) {
11926        bxe_periodic_start(sc);
11927    }
11928
11929    sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
11930    return (rc);
11931}
11932
11933/* must be called under IF_ADDR_LOCK */
11934
11935static int
11936bxe_set_mc_list(struct bxe_softc *sc)
11937{
11938    struct ecore_mcast_ramrod_params rparam = { NULL };
11939    int rc = 0;
11940    int mc_count = 0;
11941    int mcnt, i;
11942    struct ecore_mcast_list_elem *mc_mac, *mc_mac_start;
11943    unsigned char *mta;
11944    if_t ifp = sc->ifp;
11945
11946    mc_count = if_multiaddr_count(ifp, -1);/* XXX they don't have a limit */
11947    if (!mc_count)
11948        return (0);
11949
11950    mta = malloc(sizeof(unsigned char) * ETHER_ADDR_LEN *
11951            mc_count, M_DEVBUF, M_NOWAIT);
11952
11953    if(mta == NULL) {
11954        BLOGE(sc, "Failed to allocate temp mcast list\n");
11955        return (-1);
11956    }
11957    bzero(mta, (sizeof(unsigned char) * ETHER_ADDR_LEN * mc_count));
11958
11959    mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF, (M_NOWAIT | M_ZERO));
11960    mc_mac_start = mc_mac;
11961
11962    if (!mc_mac) {
11963        free(mta, M_DEVBUF);
11964        BLOGE(sc, "Failed to allocate temp mcast list\n");
11965        return (-1);
11966    }
11967    bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
11968
11969    /* mta and mcnt not expected to be  different */
11970    if_multiaddr_array(ifp, mta, &mcnt, mc_count);
11971
11972
11973    rparam.mcast_obj = &sc->mcast_obj;
11974    ECORE_LIST_INIT(&rparam.mcast_list);
11975
11976    for(i=0; i< mcnt; i++) {
11977
11978        mc_mac->mac = (uint8_t *)(mta + (i * ETHER_ADDR_LEN));
11979        ECORE_LIST_PUSH_TAIL(&mc_mac->link, &rparam.mcast_list);
11980
11981        BLOGD(sc, DBG_LOAD,
11982              "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
11983              mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
11984              mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
11985
11986        mc_mac++;
11987    }
11988    rparam.mcast_list_len = mc_count;
11989
11990    BXE_MCAST_LOCK(sc);
11991
11992    /* first, clear all configured multicast MACs */
11993    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
11994    if (rc < 0) {
11995        BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
11996        BXE_MCAST_UNLOCK(sc);
11997    	free(mc_mac_start, M_DEVBUF);
11998        free(mta, M_DEVBUF);
11999        return (rc);
12000    }
12001
12002    /* Now add the new MACs */
12003    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12004    if (rc < 0) {
12005        BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12006    }
12007
12008    BXE_MCAST_UNLOCK(sc);
12009
12010    free(mc_mac_start, M_DEVBUF);
12011    free(mta, M_DEVBUF);
12012
12013    return (rc);
12014}
12015
12016static int
12017bxe_set_uc_list(struct bxe_softc *sc)
12018{
12019    if_t ifp = sc->ifp;
12020    struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12021    struct ifaddr *ifa;
12022    unsigned long ramrod_flags = 0;
12023    int rc;
12024
12025#if __FreeBSD_version < 800000
12026    IF_ADDR_LOCK(ifp);
12027#else
12028    if_addr_rlock(ifp);
12029#endif
12030
12031    /* first schedule a cleanup up of old configuration */
12032    rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12033    if (rc < 0) {
12034        BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12035#if __FreeBSD_version < 800000
12036        IF_ADDR_UNLOCK(ifp);
12037#else
12038        if_addr_runlock(ifp);
12039#endif
12040        return (rc);
12041    }
12042
12043    ifa = if_getifaddr(ifp); /* XXX Is this structure */
12044    while (ifa) {
12045        if (ifa->ifa_addr->sa_family != AF_LINK) {
12046            ifa = TAILQ_NEXT(ifa, ifa_link);
12047            continue;
12048        }
12049
12050        rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12051                             mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12052        if (rc == -EEXIST) {
12053            BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12054            /* do not treat adding same MAC as an error */
12055            rc = 0;
12056        } else if (rc < 0) {
12057            BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12058#if __FreeBSD_version < 800000
12059            IF_ADDR_UNLOCK(ifp);
12060#else
12061            if_addr_runlock(ifp);
12062#endif
12063            return (rc);
12064        }
12065
12066        ifa = TAILQ_NEXT(ifa, ifa_link);
12067    }
12068
12069#if __FreeBSD_version < 800000
12070    IF_ADDR_UNLOCK(ifp);
12071#else
12072    if_addr_runlock(ifp);
12073#endif
12074
12075    /* Execute the pending commands */
12076    bit_set(&ramrod_flags, RAMROD_CONT);
12077    return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12078                            ECORE_UC_LIST_MAC, &ramrod_flags));
12079}
12080
12081static void
12082bxe_set_rx_mode(struct bxe_softc *sc)
12083{
12084    if_t ifp = sc->ifp;
12085    uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12086
12087    if (sc->state != BXE_STATE_OPEN) {
12088        BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12089        return;
12090    }
12091
12092    BLOGD(sc, DBG_SP, "if_flags(ifp)=0x%x\n", if_getflags(sc->ifp));
12093
12094    if (if_getflags(ifp) & IFF_PROMISC) {
12095        rx_mode = BXE_RX_MODE_PROMISC;
12096    } else if ((if_getflags(ifp) & IFF_ALLMULTI) ||
12097               ((if_getamcount(ifp) > BXE_MAX_MULTICAST) &&
12098                CHIP_IS_E1(sc))) {
12099        rx_mode = BXE_RX_MODE_ALLMULTI;
12100    } else {
12101        if (IS_PF(sc)) {
12102            /* some multicasts */
12103            if (bxe_set_mc_list(sc) < 0) {
12104                rx_mode = BXE_RX_MODE_ALLMULTI;
12105            }
12106            if (bxe_set_uc_list(sc) < 0) {
12107                rx_mode = BXE_RX_MODE_PROMISC;
12108            }
12109        }
12110    }
12111
12112    sc->rx_mode = rx_mode;
12113
12114    /* schedule the rx_mode command */
12115    if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12116        BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12117        bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12118        return;
12119    }
12120
12121    if (IS_PF(sc)) {
12122        bxe_set_storm_rx_mode(sc);
12123    }
12124}
12125
12126
12127/* update flags in shmem */
12128static void
12129bxe_update_drv_flags(struct bxe_softc *sc,
12130                     uint32_t         flags,
12131                     uint32_t         set)
12132{
12133    uint32_t drv_flags;
12134
12135    if (SHMEM2_HAS(sc, drv_flags)) {
12136        bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12137        drv_flags = SHMEM2_RD(sc, drv_flags);
12138
12139        if (set) {
12140            SET_FLAGS(drv_flags, flags);
12141        } else {
12142            RESET_FLAGS(drv_flags, flags);
12143        }
12144
12145        SHMEM2_WR(sc, drv_flags, drv_flags);
12146        BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12147
12148        bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12149    }
12150}
12151
12152/* periodic timer callout routine, only runs when the interface is up */
12153
12154static void
12155bxe_periodic_callout_func(void *xsc)
12156{
12157    struct bxe_softc *sc = (struct bxe_softc *)xsc;
12158    int i;
12159
12160    if (!BXE_CORE_TRYLOCK(sc)) {
12161        /* just bail and try again next time */
12162
12163        if ((sc->state == BXE_STATE_OPEN) &&
12164            (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12165            /* schedule the next periodic callout */
12166            callout_reset(&sc->periodic_callout, hz,
12167                          bxe_periodic_callout_func, sc);
12168        }
12169
12170        return;
12171    }
12172
12173    if ((sc->state != BXE_STATE_OPEN) ||
12174        (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12175        BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12176        BXE_CORE_UNLOCK(sc);
12177        return;
12178        }
12179
12180
12181    /* Check for TX timeouts on any fastpath. */
12182    FOR_EACH_QUEUE(sc, i) {
12183        if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12184            /* Ruh-Roh, chip was reset! */
12185            break;
12186        }
12187    }
12188
12189    if (!CHIP_REV_IS_SLOW(sc)) {
12190        /*
12191         * This barrier is needed to ensure the ordering between the writing
12192         * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12193         * the reading here.
12194         */
12195        mb();
12196        if (sc->port.pmf) {
12197	    bxe_acquire_phy_lock(sc);
12198            elink_period_func(&sc->link_params, &sc->link_vars);
12199	    bxe_release_phy_lock(sc);
12200        }
12201    }
12202
12203    if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12204        int mb_idx = SC_FW_MB_IDX(sc);
12205        uint32_t drv_pulse;
12206        uint32_t mcp_pulse;
12207
12208        ++sc->fw_drv_pulse_wr_seq;
12209        sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12210
12211        drv_pulse = sc->fw_drv_pulse_wr_seq;
12212        bxe_drv_pulse(sc);
12213
12214        mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12215                     MCP_PULSE_SEQ_MASK);
12216
12217        /*
12218         * The delta between driver pulse and mcp response should
12219         * be 1 (before mcp response) or 0 (after mcp response).
12220         */
12221        if ((drv_pulse != mcp_pulse) &&
12222            (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12223            /* someone lost a heartbeat... */
12224            BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12225                  drv_pulse, mcp_pulse);
12226        }
12227    }
12228
12229    /* state is BXE_STATE_OPEN */
12230    bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12231
12232    BXE_CORE_UNLOCK(sc);
12233
12234    if ((sc->state == BXE_STATE_OPEN) &&
12235        (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12236        /* schedule the next periodic callout */
12237        callout_reset(&sc->periodic_callout, hz,
12238                      bxe_periodic_callout_func, sc);
12239    }
12240}
12241
12242static void
12243bxe_periodic_start(struct bxe_softc *sc)
12244{
12245    atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12246    callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12247}
12248
12249static void
12250bxe_periodic_stop(struct bxe_softc *sc)
12251{
12252    atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12253    callout_drain(&sc->periodic_callout);
12254}
12255
12256/* start the controller */
12257static __noinline int
12258bxe_nic_load(struct bxe_softc *sc,
12259             int              load_mode)
12260{
12261    uint32_t val;
12262    int load_code = 0;
12263    int i, rc = 0;
12264
12265    BXE_CORE_LOCK_ASSERT(sc);
12266
12267    BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12268
12269    sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12270
12271    if (IS_PF(sc)) {
12272        /* must be called before memory allocation and HW init */
12273        bxe_ilt_set_info(sc);
12274    }
12275
12276    sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12277
12278    bxe_set_fp_rx_buf_size(sc);
12279
12280    if (bxe_alloc_fp_buffers(sc) != 0) {
12281        BLOGE(sc, "Failed to allocate fastpath memory\n");
12282        sc->state = BXE_STATE_CLOSED;
12283        rc = ENOMEM;
12284        goto bxe_nic_load_error0;
12285    }
12286
12287    if (bxe_alloc_mem(sc) != 0) {
12288        sc->state = BXE_STATE_CLOSED;
12289        rc = ENOMEM;
12290        goto bxe_nic_load_error0;
12291    }
12292
12293    if (bxe_alloc_fw_stats_mem(sc) != 0) {
12294        sc->state = BXE_STATE_CLOSED;
12295        rc = ENOMEM;
12296        goto bxe_nic_load_error0;
12297    }
12298
12299    if (IS_PF(sc)) {
12300        /* set pf load just before approaching the MCP */
12301        bxe_set_pf_load(sc);
12302
12303        /* if MCP exists send load request and analyze response */
12304        if (!BXE_NOMCP(sc)) {
12305            /* attempt to load pf */
12306            if (bxe_nic_load_request(sc, &load_code) != 0) {
12307                sc->state = BXE_STATE_CLOSED;
12308                rc = ENXIO;
12309                goto bxe_nic_load_error1;
12310            }
12311
12312            /* what did the MCP say? */
12313            if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12314                bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12315                sc->state = BXE_STATE_CLOSED;
12316                rc = ENXIO;
12317                goto bxe_nic_load_error2;
12318            }
12319        } else {
12320            BLOGI(sc, "Device has no MCP!\n");
12321            load_code = bxe_nic_load_no_mcp(sc);
12322        }
12323
12324        /* mark PMF if applicable */
12325        bxe_nic_load_pmf(sc, load_code);
12326
12327        /* Init Function state controlling object */
12328        bxe_init_func_obj(sc);
12329
12330        /* Initialize HW */
12331        if (bxe_init_hw(sc, load_code) != 0) {
12332            BLOGE(sc, "HW init failed\n");
12333            bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12334            sc->state = BXE_STATE_CLOSED;
12335            rc = ENXIO;
12336            goto bxe_nic_load_error2;
12337        }
12338    }
12339
12340    /* set ALWAYS_ALIVE bit in shmem */
12341    sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12342    bxe_drv_pulse(sc);
12343    sc->flags |= BXE_NO_PULSE;
12344
12345    /* attach interrupts */
12346    if (bxe_interrupt_attach(sc) != 0) {
12347        sc->state = BXE_STATE_CLOSED;
12348        rc = ENXIO;
12349        goto bxe_nic_load_error2;
12350    }
12351
12352    bxe_nic_init(sc, load_code);
12353
12354    /* Init per-function objects */
12355    if (IS_PF(sc)) {
12356        bxe_init_objs(sc);
12357        // XXX bxe_iov_nic_init(sc);
12358
12359        /* set AFEX default VLAN tag to an invalid value */
12360        sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12361        // XXX bxe_nic_load_afex_dcc(sc, load_code);
12362
12363        sc->state = BXE_STATE_OPENING_WAITING_PORT;
12364        rc = bxe_func_start(sc);
12365        if (rc) {
12366            BLOGE(sc, "Function start failed! rc = %d\n", rc);
12367            bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12368            sc->state = BXE_STATE_ERROR;
12369            goto bxe_nic_load_error3;
12370        }
12371
12372        /* send LOAD_DONE command to MCP */
12373        if (!BXE_NOMCP(sc)) {
12374            load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12375            if (!load_code) {
12376                BLOGE(sc, "MCP response failure, aborting\n");
12377                sc->state = BXE_STATE_ERROR;
12378                rc = ENXIO;
12379                goto bxe_nic_load_error3;
12380            }
12381        }
12382
12383        rc = bxe_setup_leading(sc);
12384        if (rc) {
12385            BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12386            sc->state = BXE_STATE_ERROR;
12387            goto bxe_nic_load_error3;
12388        }
12389
12390        FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12391            rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12392            if (rc) {
12393                BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12394                sc->state = BXE_STATE_ERROR;
12395                goto bxe_nic_load_error3;
12396            }
12397        }
12398
12399        rc = bxe_init_rss_pf(sc);
12400        if (rc) {
12401            BLOGE(sc, "PF RSS init failed\n");
12402            sc->state = BXE_STATE_ERROR;
12403            goto bxe_nic_load_error3;
12404        }
12405    }
12406    /* XXX VF */
12407
12408    /* now when Clients are configured we are ready to work */
12409    sc->state = BXE_STATE_OPEN;
12410
12411    /* Configure a ucast MAC */
12412    if (IS_PF(sc)) {
12413        rc = bxe_set_eth_mac(sc, TRUE);
12414    }
12415    if (rc) {
12416        BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12417        sc->state = BXE_STATE_ERROR;
12418        goto bxe_nic_load_error3;
12419    }
12420
12421    if (sc->port.pmf) {
12422        rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12423        if (rc) {
12424            sc->state = BXE_STATE_ERROR;
12425            goto bxe_nic_load_error3;
12426        }
12427    }
12428
12429    sc->link_params.feature_config_flags &=
12430        ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12431
12432    /* start fast path */
12433
12434    /* Initialize Rx filter */
12435    bxe_set_rx_mode(sc);
12436
12437    /* start the Tx */
12438    switch (/* XXX load_mode */LOAD_OPEN) {
12439    case LOAD_NORMAL:
12440    case LOAD_OPEN:
12441        break;
12442
12443    case LOAD_DIAG:
12444    case LOAD_LOOPBACK_EXT:
12445        sc->state = BXE_STATE_DIAG;
12446        break;
12447
12448    default:
12449        break;
12450    }
12451
12452    if (sc->port.pmf) {
12453        bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12454    } else {
12455        bxe_link_status_update(sc);
12456    }
12457
12458    /* start the periodic timer callout */
12459    bxe_periodic_start(sc);
12460
12461    if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12462        /* mark driver is loaded in shmem2 */
12463        val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12464        SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12465                  (val |
12466                   DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12467                   DRV_FLAGS_CAPABILITIES_LOADED_L2));
12468    }
12469
12470    /* wait for all pending SP commands to complete */
12471    if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12472        BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12473        bxe_periodic_stop(sc);
12474        bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12475        return (ENXIO);
12476    }
12477
12478    /* Tell the stack the driver is running! */
12479    if_setdrvflags(sc->ifp, IFF_DRV_RUNNING);
12480
12481    BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12482
12483    return (0);
12484
12485bxe_nic_load_error3:
12486
12487    if (IS_PF(sc)) {
12488        bxe_int_disable_sync(sc, 1);
12489
12490        /* clean out queued objects */
12491        bxe_squeeze_objects(sc);
12492    }
12493
12494    bxe_interrupt_detach(sc);
12495
12496bxe_nic_load_error2:
12497
12498    if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12499        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12500        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12501    }
12502
12503    sc->port.pmf = 0;
12504
12505bxe_nic_load_error1:
12506
12507    /* clear pf_load status, as it was already set */
12508    if (IS_PF(sc)) {
12509        bxe_clear_pf_load(sc);
12510    }
12511
12512bxe_nic_load_error0:
12513
12514    bxe_free_fw_stats_mem(sc);
12515    bxe_free_fp_buffers(sc);
12516    bxe_free_mem(sc);
12517
12518    return (rc);
12519}
12520
12521static int
12522bxe_init_locked(struct bxe_softc *sc)
12523{
12524    int other_engine = SC_PATH(sc) ? 0 : 1;
12525    uint8_t other_load_status, load_status;
12526    uint8_t global = FALSE;
12527    int rc;
12528
12529    BXE_CORE_LOCK_ASSERT(sc);
12530
12531    /* check if the driver is already running */
12532    if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12533        BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12534        return (0);
12535    }
12536
12537    bxe_set_power_state(sc, PCI_PM_D0);
12538
12539    /*
12540     * If parity occurred during the unload, then attentions and/or
12541     * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12542     * loaded on the current engine to complete the recovery. Parity recovery
12543     * is only relevant for PF driver.
12544     */
12545    if (IS_PF(sc)) {
12546        other_load_status = bxe_get_load_status(sc, other_engine);
12547        load_status = bxe_get_load_status(sc, SC_PATH(sc));
12548
12549        if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12550            bxe_chk_parity_attn(sc, &global, TRUE)) {
12551            do {
12552                /*
12553                 * If there are attentions and they are in global blocks, set
12554                 * the GLOBAL_RESET bit regardless whether it will be this
12555                 * function that will complete the recovery or not.
12556                 */
12557                if (global) {
12558                    bxe_set_reset_global(sc);
12559                }
12560
12561                /*
12562                 * Only the first function on the current engine should try
12563                 * to recover in open. In case of attentions in global blocks
12564                 * only the first in the chip should try to recover.
12565                 */
12566                if ((!load_status && (!global || !other_load_status)) &&
12567                    bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12568                    BLOGI(sc, "Recovered during init\n");
12569                    break;
12570                }
12571
12572                /* recovery has failed... */
12573                bxe_set_power_state(sc, PCI_PM_D3hot);
12574                sc->recovery_state = BXE_RECOVERY_FAILED;
12575
12576                BLOGE(sc, "Recovery flow hasn't properly "
12577                          "completed yet, try again later. "
12578                          "If you still see this message after a "
12579                          "few retries then power cycle is required.\n");
12580
12581                rc = ENXIO;
12582                goto bxe_init_locked_done;
12583            } while (0);
12584        }
12585    }
12586
12587    sc->recovery_state = BXE_RECOVERY_DONE;
12588
12589    rc = bxe_nic_load(sc, LOAD_OPEN);
12590
12591bxe_init_locked_done:
12592
12593    if (rc) {
12594        /* Tell the stack the driver is NOT running! */
12595        BLOGE(sc, "Initialization failed, "
12596                  "stack notified driver is NOT running!\n");
12597	if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
12598    }
12599
12600    return (rc);
12601}
12602
12603static int
12604bxe_stop_locked(struct bxe_softc *sc)
12605{
12606    BXE_CORE_LOCK_ASSERT(sc);
12607    return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12608}
12609
12610/*
12611 * Handles controller initialization when called from an unlocked routine.
12612 * ifconfig calls this function.
12613 *
12614 * Returns:
12615 *   void
12616 */
12617static void
12618bxe_init(void *xsc)
12619{
12620    struct bxe_softc *sc = (struct bxe_softc *)xsc;
12621
12622    BXE_CORE_LOCK(sc);
12623    bxe_init_locked(sc);
12624    BXE_CORE_UNLOCK(sc);
12625}
12626
12627static int
12628bxe_init_ifnet(struct bxe_softc *sc)
12629{
12630    if_t ifp;
12631    int capabilities;
12632
12633    /* ifconfig entrypoint for media type/status reporting */
12634    ifmedia_init(&sc->ifmedia, IFM_IMASK,
12635                 bxe_ifmedia_update,
12636                 bxe_ifmedia_status);
12637
12638    /* set the default interface values */
12639    ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12640    ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12641    ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12642
12643    sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12644
12645    /* allocate the ifnet structure */
12646    if ((ifp = if_gethandle(IFT_ETHER)) == NULL) {
12647        BLOGE(sc, "Interface allocation failed!\n");
12648        return (ENXIO);
12649    }
12650
12651    if_setsoftc(ifp, sc);
12652    if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12653    if_setflags(ifp, (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST));
12654    if_setioctlfn(ifp, bxe_ioctl);
12655    if_setstartfn(ifp, bxe_tx_start);
12656    if_setgetcounterfn(ifp, bxe_get_counter);
12657#if __FreeBSD_version >= 901504
12658    if_settransmitfn(ifp, bxe_tx_mq_start);
12659    if_setqflushfn(ifp, bxe_mq_flush);
12660#endif
12661#ifdef FreeBSD8_0
12662    if_settimer(ifp, 0);
12663#endif
12664    if_setinitfn(ifp, bxe_init);
12665    if_setmtu(ifp, sc->mtu);
12666    if_sethwassist(ifp, (CSUM_IP      |
12667                        CSUM_TCP      |
12668                        CSUM_UDP      |
12669                        CSUM_TSO      |
12670                        CSUM_TCP_IPV6 |
12671                        CSUM_UDP_IPV6));
12672
12673    capabilities =
12674#if __FreeBSD_version < 700000
12675        (IFCAP_VLAN_MTU       |
12676         IFCAP_VLAN_HWTAGGING |
12677         IFCAP_HWCSUM         |
12678         IFCAP_JUMBO_MTU      |
12679         IFCAP_LRO);
12680#else
12681        (IFCAP_VLAN_MTU       |
12682         IFCAP_VLAN_HWTAGGING |
12683         IFCAP_VLAN_HWTSO     |
12684         IFCAP_VLAN_HWFILTER  |
12685         IFCAP_VLAN_HWCSUM    |
12686         IFCAP_HWCSUM         |
12687         IFCAP_JUMBO_MTU      |
12688         IFCAP_LRO            |
12689         IFCAP_TSO4           |
12690         IFCAP_TSO6           |
12691         IFCAP_WOL_MAGIC);
12692#endif
12693    if_setcapabilitiesbit(ifp, capabilities, 0); /* XXX */
12694    if_setbaudrate(ifp, IF_Gbps(10));
12695/* XXX */
12696    if_setsendqlen(ifp, sc->tx_ring_size);
12697    if_setsendqready(ifp);
12698/* XXX */
12699
12700    sc->ifp = ifp;
12701
12702    /* attach to the Ethernet interface list */
12703    ether_ifattach(ifp, sc->link_params.mac_addr);
12704
12705    return (0);
12706}
12707
12708static void
12709bxe_deallocate_bars(struct bxe_softc *sc)
12710{
12711    int i;
12712
12713    for (i = 0; i < MAX_BARS; i++) {
12714        if (sc->bar[i].resource != NULL) {
12715            bus_release_resource(sc->dev,
12716                                 SYS_RES_MEMORY,
12717                                 sc->bar[i].rid,
12718                                 sc->bar[i].resource);
12719            BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12720                  i, PCIR_BAR(i));
12721        }
12722    }
12723}
12724
12725static int
12726bxe_allocate_bars(struct bxe_softc *sc)
12727{
12728    u_int flags;
12729    int i;
12730
12731    memset(sc->bar, 0, sizeof(sc->bar));
12732
12733    for (i = 0; i < MAX_BARS; i++) {
12734
12735        /* memory resources reside at BARs 0, 2, 4 */
12736        /* Run `pciconf -lb` to see mappings */
12737        if ((i != 0) && (i != 2) && (i != 4)) {
12738            continue;
12739        }
12740
12741        sc->bar[i].rid = PCIR_BAR(i);
12742
12743        flags = RF_ACTIVE;
12744        if (i == 0) {
12745            flags |= RF_SHAREABLE;
12746        }
12747
12748        if ((sc->bar[i].resource =
12749             bus_alloc_resource_any(sc->dev,
12750                                    SYS_RES_MEMORY,
12751                                    &sc->bar[i].rid,
12752                                    flags)) == NULL) {
12753            return (0);
12754        }
12755
12756        sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12757        sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12758        sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12759
12760        BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%jd) -> %p\n",
12761              i, PCIR_BAR(i),
12762              (void *)rman_get_start(sc->bar[i].resource),
12763              (void *)rman_get_end(sc->bar[i].resource),
12764              rman_get_size(sc->bar[i].resource),
12765              (void *)sc->bar[i].kva);
12766    }
12767
12768    return (0);
12769}
12770
12771static void
12772bxe_get_function_num(struct bxe_softc *sc)
12773{
12774    uint32_t val = 0;
12775
12776    /*
12777     * Read the ME register to get the function number. The ME register
12778     * holds the relative-function number and absolute-function number. The
12779     * absolute-function number appears only in E2 and above. Before that
12780     * these bits always contained zero, therefore we cannot blindly use them.
12781     */
12782
12783    val = REG_RD(sc, BAR_ME_REGISTER);
12784
12785    sc->pfunc_rel =
12786        (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12787    sc->path_id =
12788        (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12789
12790    if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12791        sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12792    } else {
12793        sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12794    }
12795
12796    BLOGD(sc, DBG_LOAD,
12797          "Relative function %d, Absolute function %d, Path %d\n",
12798          sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12799}
12800
12801static uint32_t
12802bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12803{
12804    uint32_t shmem2_size;
12805    uint32_t offset;
12806    uint32_t mf_cfg_offset_value;
12807
12808    /* Non 57712 */
12809    offset = (SHMEM_RD(sc, func_mb) +
12810              (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12811
12812    /* 57712 plus */
12813    if (sc->devinfo.shmem2_base != 0) {
12814        shmem2_size = SHMEM2_RD(sc, size);
12815        if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12816            mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12817            if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12818                offset = mf_cfg_offset_value;
12819            }
12820        }
12821    }
12822
12823    return (offset);
12824}
12825
12826static uint32_t
12827bxe_pcie_capability_read(struct bxe_softc *sc,
12828                         int    reg,
12829                         int    width)
12830{
12831    int pcie_reg;
12832
12833    /* ensure PCIe capability is enabled */
12834    if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12835        if (pcie_reg != 0) {
12836            BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12837            return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12838        }
12839    }
12840
12841    BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12842
12843    return (0);
12844}
12845
12846static uint8_t
12847bxe_is_pcie_pending(struct bxe_softc *sc)
12848{
12849    return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12850            PCIM_EXP_STA_TRANSACTION_PND);
12851}
12852
12853/*
12854 * Walk the PCI capabiites list for the device to find what features are
12855 * supported. These capabilites may be enabled/disabled by firmware so it's
12856 * best to walk the list rather than make assumptions.
12857 */
12858static void
12859bxe_probe_pci_caps(struct bxe_softc *sc)
12860{
12861    uint16_t link_status;
12862    int reg;
12863
12864    /* check if PCI Power Management is enabled */
12865    if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
12866        if (reg != 0) {
12867            BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
12868
12869            sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
12870            sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
12871        }
12872    }
12873
12874    link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
12875
12876    /* handle PCIe 2.0 workarounds for 57710 */
12877    if (CHIP_IS_E1(sc)) {
12878        /* workaround for 57710 errata E4_57710_27462 */
12879        sc->devinfo.pcie_link_speed =
12880            (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
12881
12882        /* workaround for 57710 errata E4_57710_27488 */
12883        sc->devinfo.pcie_link_width =
12884            ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12885        if (sc->devinfo.pcie_link_speed > 1) {
12886            sc->devinfo.pcie_link_width =
12887                ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
12888        }
12889    } else {
12890        sc->devinfo.pcie_link_speed =
12891            (link_status & PCIM_LINK_STA_SPEED);
12892        sc->devinfo.pcie_link_width =
12893            ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12894    }
12895
12896    BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
12897          sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
12898
12899    sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
12900    sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
12901
12902    /* check if MSI capability is enabled */
12903    if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
12904        if (reg != 0) {
12905            BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
12906
12907            sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
12908            sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
12909        }
12910    }
12911
12912    /* check if MSI-X capability is enabled */
12913    if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
12914        if (reg != 0) {
12915            BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
12916
12917            sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
12918            sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
12919        }
12920    }
12921}
12922
12923static int
12924bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
12925{
12926    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
12927    uint32_t val;
12928
12929    /* get the outer vlan if we're in switch-dependent mode */
12930
12931    val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
12932    mf_info->ext_id = (uint16_t)val;
12933
12934    mf_info->multi_vnics_mode = 1;
12935
12936    if (!VALID_OVLAN(mf_info->ext_id)) {
12937        BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
12938        return (1);
12939    }
12940
12941    /* get the capabilities */
12942    if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
12943        FUNC_MF_CFG_PROTOCOL_ISCSI) {
12944        mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
12945    } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
12946               FUNC_MF_CFG_PROTOCOL_FCOE) {
12947        mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
12948    } else {
12949        mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
12950    }
12951
12952    mf_info->vnics_per_port =
12953        (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
12954
12955    return (0);
12956}
12957
12958static uint32_t
12959bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
12960{
12961    uint32_t retval = 0;
12962    uint32_t val;
12963
12964    val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
12965
12966    if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
12967        if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
12968            retval |= MF_PROTO_SUPPORT_ETHERNET;
12969        }
12970        if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
12971            retval |= MF_PROTO_SUPPORT_ISCSI;
12972        }
12973        if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
12974            retval |= MF_PROTO_SUPPORT_FCOE;
12975        }
12976    }
12977
12978    return (retval);
12979}
12980
12981static int
12982bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
12983{
12984    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
12985    uint32_t val;
12986
12987    /*
12988     * There is no outer vlan if we're in switch-independent mode.
12989     * If the mac is valid then assume multi-function.
12990     */
12991
12992    val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
12993
12994    mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
12995
12996    mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
12997
12998    mf_info->vnics_per_port =
12999        (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13000
13001    return (0);
13002}
13003
13004static int
13005bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13006{
13007    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13008    uint32_t e1hov_tag;
13009    uint32_t func_config;
13010    uint32_t niv_config;
13011
13012    mf_info->multi_vnics_mode = 1;
13013
13014    e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13015    func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13016    niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13017
13018    mf_info->ext_id =
13019        (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13020                   FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13021
13022    mf_info->default_vlan =
13023        (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13024                   FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13025
13026    mf_info->niv_allowed_priorities =
13027        (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13028                  FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13029
13030    mf_info->niv_default_cos =
13031        (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13032                  FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13033
13034    mf_info->afex_vlan_mode =
13035        ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13036         FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13037
13038    mf_info->niv_mba_enabled =
13039        ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13040         FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13041
13042    mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13043
13044    mf_info->vnics_per_port =
13045        (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13046
13047    return (0);
13048}
13049
13050static int
13051bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13052{
13053    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13054    uint32_t mf_cfg1;
13055    uint32_t mf_cfg2;
13056    uint32_t ovlan1;
13057    uint32_t ovlan2;
13058    uint8_t i, j;
13059
13060    BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13061          SC_PORT(sc));
13062    BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13063          mf_info->mf_config[SC_VN(sc)]);
13064    BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13065          mf_info->multi_vnics_mode);
13066    BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13067          mf_info->vnics_per_port);
13068    BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13069          mf_info->ext_id);
13070    BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13071          mf_info->min_bw[0], mf_info->min_bw[1],
13072          mf_info->min_bw[2], mf_info->min_bw[3]);
13073    BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13074          mf_info->max_bw[0], mf_info->max_bw[1],
13075          mf_info->max_bw[2], mf_info->max_bw[3]);
13076    BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13077          sc->mac_addr_str);
13078
13079    /* various MF mode sanity checks... */
13080
13081    if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13082        BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13083              SC_PORT(sc));
13084        return (1);
13085    }
13086
13087    if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13088        BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13089              mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13090        return (1);
13091    }
13092
13093    if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13094        /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13095        if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13096            BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13097                  SC_VN(sc), OVLAN(sc));
13098            return (1);
13099        }
13100
13101        if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13102            BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13103                  mf_info->multi_vnics_mode, OVLAN(sc));
13104            return (1);
13105        }
13106
13107        /*
13108         * Verify all functions are either MF or SF mode. If MF, make sure
13109         * sure that all non-hidden functions have a valid ovlan. If SF,
13110         * make sure that all non-hidden functions have an invalid ovlan.
13111         */
13112        FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13113            mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13114            ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13115            if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13116                (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13117                 ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13118                BLOGE(sc, "mf_mode=SD function %d MF config "
13119                          "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13120                      i, mf_info->multi_vnics_mode, ovlan1);
13121                return (1);
13122            }
13123        }
13124
13125        /* Verify all funcs on the same port each have a different ovlan. */
13126        FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13127            mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13128            ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13129            /* iterate from the next function on the port to the max func */
13130            for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13131                mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13132                ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13133                if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13134                    VALID_OVLAN(ovlan1) &&
13135                    !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13136                    VALID_OVLAN(ovlan2) &&
13137                    (ovlan1 == ovlan2)) {
13138                    BLOGE(sc, "mf_mode=SD functions %d and %d "
13139                              "have the same ovlan (%d)\n",
13140                          i, j, ovlan1);
13141                    return (1);
13142                }
13143            }
13144        }
13145    } /* MULTI_FUNCTION_SD */
13146
13147    return (0);
13148}
13149
13150static int
13151bxe_get_mf_cfg_info(struct bxe_softc *sc)
13152{
13153    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13154    uint32_t val, mac_upper;
13155    uint8_t i, vnic;
13156
13157    /* initialize mf_info defaults */
13158    mf_info->vnics_per_port   = 1;
13159    mf_info->multi_vnics_mode = FALSE;
13160    mf_info->path_has_ovlan   = FALSE;
13161    mf_info->mf_mode          = SINGLE_FUNCTION;
13162
13163    if (!CHIP_IS_MF_CAP(sc)) {
13164        return (0);
13165    }
13166
13167    if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13168        BLOGE(sc, "Invalid mf_cfg_base!\n");
13169        return (1);
13170    }
13171
13172    /* get the MF mode (switch dependent / independent / single-function) */
13173
13174    val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13175
13176    switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13177    {
13178    case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13179
13180        mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13181
13182        /* check for legal upper mac bytes */
13183        if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13184            mf_info->mf_mode = MULTI_FUNCTION_SI;
13185        } else {
13186            BLOGE(sc, "Invalid config for Switch Independent mode\n");
13187        }
13188
13189        break;
13190
13191    case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13192    case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13193
13194        /* get outer vlan configuration */
13195        val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13196
13197        if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13198            FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13199            mf_info->mf_mode = MULTI_FUNCTION_SD;
13200        } else {
13201            BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13202        }
13203
13204        break;
13205
13206    case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13207
13208        /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13209        return (0);
13210
13211    case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13212
13213        /*
13214         * Mark MF mode as NIV if MCP version includes NPAR-SD support
13215         * and the MAC address is valid.
13216         */
13217        mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13218
13219        if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13220            (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13221            mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13222        } else {
13223            BLOGE(sc, "Invalid config for AFEX mode\n");
13224        }
13225
13226        break;
13227
13228    default:
13229
13230        BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13231              (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13232
13233        return (1);
13234    }
13235
13236    /* set path mf_mode (which could be different than function mf_mode) */
13237    if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13238        mf_info->path_has_ovlan = TRUE;
13239    } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13240        /*
13241         * Decide on path multi vnics mode. If we're not in MF mode and in
13242         * 4-port mode, this is good enough to check vnic-0 of the other port
13243         * on the same path
13244         */
13245        if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13246            uint8_t other_port = !(PORT_ID(sc) & 1);
13247            uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13248
13249            val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13250
13251            mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13252        }
13253    }
13254
13255    if (mf_info->mf_mode == SINGLE_FUNCTION) {
13256        /* invalid MF config */
13257        if (SC_VN(sc) >= 1) {
13258            BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13259            return (1);
13260        }
13261
13262        return (0);
13263    }
13264
13265    /* get the MF configuration */
13266    mf_info->mf_config[SC_VN(sc)] =
13267        MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13268
13269    switch(mf_info->mf_mode)
13270    {
13271    case MULTI_FUNCTION_SD:
13272
13273        bxe_get_shmem_mf_cfg_info_sd(sc);
13274        break;
13275
13276    case MULTI_FUNCTION_SI:
13277
13278        bxe_get_shmem_mf_cfg_info_si(sc);
13279        break;
13280
13281    case MULTI_FUNCTION_AFEX:
13282
13283        bxe_get_shmem_mf_cfg_info_niv(sc);
13284        break;
13285
13286    default:
13287
13288        BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13289              mf_info->mf_mode);
13290        return (1);
13291    }
13292
13293    /* get the congestion management parameters */
13294
13295    vnic = 0;
13296    FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13297        /* get min/max bw */
13298        val = MFCFG_RD(sc, func_mf_config[i].config);
13299        mf_info->min_bw[vnic] =
13300            ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13301        mf_info->max_bw[vnic] =
13302            ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13303        vnic++;
13304    }
13305
13306    return (bxe_check_valid_mf_cfg(sc));
13307}
13308
13309static int
13310bxe_get_shmem_info(struct bxe_softc *sc)
13311{
13312    int port;
13313    uint32_t mac_hi, mac_lo, val;
13314
13315    port = SC_PORT(sc);
13316    mac_hi = mac_lo = 0;
13317
13318    sc->link_params.sc   = sc;
13319    sc->link_params.port = port;
13320
13321    /* get the hardware config info */
13322    sc->devinfo.hw_config =
13323        SHMEM_RD(sc, dev_info.shared_hw_config.config);
13324    sc->devinfo.hw_config2 =
13325        SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13326
13327    sc->link_params.hw_led_mode =
13328        ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13329         SHARED_HW_CFG_LED_MODE_SHIFT);
13330
13331    /* get the port feature config */
13332    sc->port.config =
13333        SHMEM_RD(sc, dev_info.port_feature_config[port].config);
13334
13335    /* get the link params */
13336    sc->link_params.speed_cap_mask[0] =
13337        SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13338    sc->link_params.speed_cap_mask[1] =
13339        SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13340
13341    /* get the lane config */
13342    sc->link_params.lane_config =
13343        SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13344
13345    /* get the link config */
13346    val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13347    sc->port.link_config[ELINK_INT_PHY] = val;
13348    sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13349    sc->port.link_config[ELINK_EXT_PHY1] =
13350        SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13351
13352    /* get the override preemphasis flag and enable it or turn it off */
13353    val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13354    if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13355        sc->link_params.feature_config_flags |=
13356            ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13357    } else {
13358        sc->link_params.feature_config_flags &=
13359            ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13360    }
13361
13362    /* get the initial value of the link params */
13363    sc->link_params.multi_phy_config =
13364        SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13365
13366    /* get external phy info */
13367    sc->port.ext_phy_config =
13368        SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13369
13370    /* get the multifunction configuration */
13371    bxe_get_mf_cfg_info(sc);
13372
13373    /* get the mac address */
13374    if (IS_MF(sc)) {
13375        mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13376        mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13377    } else {
13378        mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13379        mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13380    }
13381
13382    if ((mac_lo == 0) && (mac_hi == 0)) {
13383        *sc->mac_addr_str = 0;
13384        BLOGE(sc, "No Ethernet address programmed!\n");
13385    } else {
13386        sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13387        sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13388        sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13389        sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13390        sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13391        sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13392        snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13393                 "%02x:%02x:%02x:%02x:%02x:%02x",
13394                 sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13395                 sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13396                 sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13397        BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13398    }
13399
13400    return (0);
13401}
13402
13403static void
13404bxe_get_tunable_params(struct bxe_softc *sc)
13405{
13406    /* sanity checks */
13407
13408    if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13409        (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13410        (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13411        BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13412        bxe_interrupt_mode = INTR_MODE_MSIX;
13413    }
13414
13415    if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13416        BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13417        bxe_queue_count = 0;
13418    }
13419
13420    if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13421        if (bxe_max_rx_bufs == 0) {
13422            bxe_max_rx_bufs = RX_BD_USABLE;
13423        } else {
13424            BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13425            bxe_max_rx_bufs = 2048;
13426        }
13427    }
13428
13429    if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13430        BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13431        bxe_hc_rx_ticks = 25;
13432    }
13433
13434    if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13435        BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13436        bxe_hc_tx_ticks = 50;
13437    }
13438
13439    if (bxe_max_aggregation_size == 0) {
13440        bxe_max_aggregation_size = TPA_AGG_SIZE;
13441    }
13442
13443    if (bxe_max_aggregation_size > 0xffff) {
13444        BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13445              bxe_max_aggregation_size);
13446        bxe_max_aggregation_size = TPA_AGG_SIZE;
13447    }
13448
13449    if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13450        BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13451        bxe_mrrs = -1;
13452    }
13453
13454    if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13455        BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13456        bxe_autogreeen = 0;
13457    }
13458
13459    if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13460        BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13461        bxe_udp_rss = 0;
13462    }
13463
13464    /* pull in user settings */
13465
13466    sc->interrupt_mode       = bxe_interrupt_mode;
13467    sc->max_rx_bufs          = bxe_max_rx_bufs;
13468    sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13469    sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13470    sc->max_aggregation_size = bxe_max_aggregation_size;
13471    sc->mrrs                 = bxe_mrrs;
13472    sc->autogreeen           = bxe_autogreeen;
13473    sc->udp_rss              = bxe_udp_rss;
13474
13475    if (bxe_interrupt_mode == INTR_MODE_INTX) {
13476        sc->num_queues = 1;
13477    } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13478        sc->num_queues =
13479            min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13480                MAX_RSS_CHAINS);
13481        if (sc->num_queues > mp_ncpus) {
13482            sc->num_queues = mp_ncpus;
13483        }
13484    }
13485
13486    BLOGD(sc, DBG_LOAD,
13487          "User Config: "
13488          "debug=0x%lx "
13489          "interrupt_mode=%d "
13490          "queue_count=%d "
13491          "hc_rx_ticks=%d "
13492          "hc_tx_ticks=%d "
13493          "rx_budget=%d "
13494          "max_aggregation_size=%d "
13495          "mrrs=%d "
13496          "autogreeen=%d "
13497          "udp_rss=%d\n",
13498          bxe_debug,
13499          sc->interrupt_mode,
13500          sc->num_queues,
13501          sc->hc_rx_ticks,
13502          sc->hc_tx_ticks,
13503          bxe_rx_budget,
13504          sc->max_aggregation_size,
13505          sc->mrrs,
13506          sc->autogreeen,
13507          sc->udp_rss);
13508}
13509
13510static int
13511bxe_media_detect(struct bxe_softc *sc)
13512{
13513    int port_type;
13514    uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13515
13516    switch (sc->link_params.phy[phy_idx].media_type) {
13517    case ELINK_ETH_PHY_SFPP_10G_FIBER:
13518    case ELINK_ETH_PHY_XFP_FIBER:
13519        BLOGI(sc, "Found 10Gb Fiber media.\n");
13520        sc->media = IFM_10G_SR;
13521        port_type = PORT_FIBRE;
13522        break;
13523    case ELINK_ETH_PHY_SFP_1G_FIBER:
13524        BLOGI(sc, "Found 1Gb Fiber media.\n");
13525        sc->media = IFM_1000_SX;
13526        port_type = PORT_FIBRE;
13527        break;
13528    case ELINK_ETH_PHY_KR:
13529    case ELINK_ETH_PHY_CX4:
13530        BLOGI(sc, "Found 10GBase-CX4 media.\n");
13531        sc->media = IFM_10G_CX4;
13532        port_type = PORT_FIBRE;
13533        break;
13534    case ELINK_ETH_PHY_DA_TWINAX:
13535        BLOGI(sc, "Found 10Gb Twinax media.\n");
13536        sc->media = IFM_10G_TWINAX;
13537        port_type = PORT_DA;
13538        break;
13539    case ELINK_ETH_PHY_BASE_T:
13540        if (sc->link_params.speed_cap_mask[0] &
13541            PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13542            BLOGI(sc, "Found 10GBase-T media.\n");
13543            sc->media = IFM_10G_T;
13544            port_type = PORT_TP;
13545        } else {
13546            BLOGI(sc, "Found 1000Base-T media.\n");
13547            sc->media = IFM_1000_T;
13548            port_type = PORT_TP;
13549        }
13550        break;
13551    case ELINK_ETH_PHY_NOT_PRESENT:
13552        BLOGI(sc, "Media not present.\n");
13553        sc->media = 0;
13554        port_type = PORT_OTHER;
13555        break;
13556    case ELINK_ETH_PHY_UNSPECIFIED:
13557    default:
13558        BLOGI(sc, "Unknown media!\n");
13559        sc->media = 0;
13560        port_type = PORT_OTHER;
13561        break;
13562    }
13563    return port_type;
13564}
13565
13566#define GET_FIELD(value, fname)                     \
13567    (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13568#define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13569#define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13570
13571static int
13572bxe_get_igu_cam_info(struct bxe_softc *sc)
13573{
13574    int pfid = SC_FUNC(sc);
13575    int igu_sb_id;
13576    uint32_t val;
13577    uint8_t fid, igu_sb_cnt = 0;
13578
13579    sc->igu_base_sb = 0xff;
13580
13581    if (CHIP_INT_MODE_IS_BC(sc)) {
13582        int vn = SC_VN(sc);
13583        igu_sb_cnt = sc->igu_sb_cnt;
13584        sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13585                           FP_SB_MAX_E1x);
13586        sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13587                          (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13588        return (0);
13589    }
13590
13591    /* IGU in normal mode - read CAM */
13592    for (igu_sb_id = 0;
13593         igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13594         igu_sb_id++) {
13595        val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13596        if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13597            continue;
13598        }
13599        fid = IGU_FID(val);
13600        if ((fid & IGU_FID_ENCODE_IS_PF)) {
13601            if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13602                continue;
13603            }
13604            if (IGU_VEC(val) == 0) {
13605                /* default status block */
13606                sc->igu_dsb_id = igu_sb_id;
13607            } else {
13608                if (sc->igu_base_sb == 0xff) {
13609                    sc->igu_base_sb = igu_sb_id;
13610                }
13611                igu_sb_cnt++;
13612            }
13613        }
13614    }
13615
13616    /*
13617     * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13618     * that number of CAM entries will not be equal to the value advertised in
13619     * PCI. Driver should use the minimal value of both as the actual status
13620     * block count
13621     */
13622    sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13623
13624    if (igu_sb_cnt == 0) {
13625        BLOGE(sc, "CAM configuration error\n");
13626        return (-1);
13627    }
13628
13629    return (0);
13630}
13631
13632/*
13633 * Gather various information from the device config space, the device itself,
13634 * shmem, and the user input.
13635 */
13636static int
13637bxe_get_device_info(struct bxe_softc *sc)
13638{
13639    uint32_t val;
13640    int rc;
13641
13642    /* Get the data for the device */
13643    sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13644    sc->devinfo.device_id    = pci_get_device(sc->dev);
13645    sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13646    sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13647
13648    /* get the chip revision (chip metal comes from pci config space) */
13649    sc->devinfo.chip_id     =
13650    sc->link_params.chip_id =
13651        (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13652         ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13653         (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13654         ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13655
13656    /* force 57811 according to MISC register */
13657    if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13658        if (CHIP_IS_57810(sc)) {
13659            sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13660                                   (sc->devinfo.chip_id & 0x0000ffff));
13661        } else if (CHIP_IS_57810_MF(sc)) {
13662            sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13663                                   (sc->devinfo.chip_id & 0x0000ffff));
13664        }
13665        sc->devinfo.chip_id |= 0x1;
13666    }
13667
13668    BLOGD(sc, DBG_LOAD,
13669          "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13670          sc->devinfo.chip_id,
13671          ((sc->devinfo.chip_id >> 16) & 0xffff),
13672          ((sc->devinfo.chip_id >> 12) & 0xf),
13673          ((sc->devinfo.chip_id >>  4) & 0xff),
13674          ((sc->devinfo.chip_id >>  0) & 0xf));
13675
13676    val = (REG_RD(sc, 0x2874) & 0x55);
13677    if ((sc->devinfo.chip_id & 0x1) ||
13678        (CHIP_IS_E1(sc) && val) ||
13679        (CHIP_IS_E1H(sc) && (val == 0x55))) {
13680        sc->flags |= BXE_ONE_PORT_FLAG;
13681        BLOGD(sc, DBG_LOAD, "single port device\n");
13682    }
13683
13684    /* set the doorbell size */
13685    sc->doorbell_size = (1 << BXE_DB_SHIFT);
13686
13687    /* determine whether the device is in 2 port or 4 port mode */
13688    sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13689    if (CHIP_IS_E2E3(sc)) {
13690        /*
13691         * Read port4mode_en_ovwr[0]:
13692         *   If 1, four port mode is in port4mode_en_ovwr[1].
13693         *   If 0, four port mode is in port4mode_en[0].
13694         */
13695        val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13696        if (val & 1) {
13697            val = ((val >> 1) & 1);
13698        } else {
13699            val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13700        }
13701
13702        sc->devinfo.chip_port_mode =
13703            (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13704
13705        BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13706    }
13707
13708    /* get the function and path info for the device */
13709    bxe_get_function_num(sc);
13710
13711    /* get the shared memory base address */
13712    sc->devinfo.shmem_base     =
13713    sc->link_params.shmem_base =
13714        REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13715    sc->devinfo.shmem2_base =
13716        REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13717                                  MISC_REG_GENERIC_CR_0));
13718
13719    BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13720          sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13721
13722    if (!sc->devinfo.shmem_base) {
13723        /* this should ONLY prevent upcoming shmem reads */
13724        BLOGI(sc, "MCP not active\n");
13725        sc->flags |= BXE_NO_MCP_FLAG;
13726        return (0);
13727    }
13728
13729    /* make sure the shared memory contents are valid */
13730    val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13731    if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13732        (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13733        BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13734        return (0);
13735    }
13736    BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13737
13738    /* get the bootcode version */
13739    sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13740    snprintf(sc->devinfo.bc_ver_str,
13741             sizeof(sc->devinfo.bc_ver_str),
13742             "%d.%d.%d",
13743             ((sc->devinfo.bc_ver >> 24) & 0xff),
13744             ((sc->devinfo.bc_ver >> 16) & 0xff),
13745             ((sc->devinfo.bc_ver >>  8) & 0xff));
13746    BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13747
13748    /* get the bootcode shmem address */
13749    sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13750    BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13751
13752    /* clean indirect addresses as they're not used */
13753    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13754    if (IS_PF(sc)) {
13755        REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13756        REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13757        REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13758        REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13759        if (CHIP_IS_E1x(sc)) {
13760            REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13761            REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13762            REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13763            REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13764        }
13765
13766        /*
13767         * Enable internal target-read (in case we are probed after PF
13768         * FLR). Must be done prior to any BAR read access. Only for
13769         * 57712 and up
13770         */
13771        if (!CHIP_IS_E1x(sc)) {
13772            REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13773        }
13774    }
13775
13776    /* get the nvram size */
13777    val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13778    sc->devinfo.flash_size =
13779        (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13780    BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13781
13782    /* get PCI capabilites */
13783    bxe_probe_pci_caps(sc);
13784
13785    bxe_set_power_state(sc, PCI_PM_D0);
13786
13787    /* get various configuration parameters from shmem */
13788    bxe_get_shmem_info(sc);
13789
13790    if (sc->devinfo.pcie_msix_cap_reg != 0) {
13791        val = pci_read_config(sc->dev,
13792                              (sc->devinfo.pcie_msix_cap_reg +
13793                               PCIR_MSIX_CTRL),
13794                              2);
13795        sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13796    } else {
13797        sc->igu_sb_cnt = 1;
13798    }
13799
13800    sc->igu_base_addr = BAR_IGU_INTMEM;
13801
13802    /* initialize IGU parameters */
13803    if (CHIP_IS_E1x(sc)) {
13804        sc->devinfo.int_block = INT_BLOCK_HC;
13805        sc->igu_dsb_id = DEF_SB_IGU_ID;
13806        sc->igu_base_sb = 0;
13807    } else {
13808        sc->devinfo.int_block = INT_BLOCK_IGU;
13809
13810        /* do not allow device reset during IGU info preocessing */
13811        bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13812
13813        val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13814
13815        if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13816            int tout = 5000;
13817
13818            BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13819
13820            val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13821            REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13822            REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13823
13824            while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13825                tout--;
13826                DELAY(1000);
13827            }
13828
13829            if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13830                BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13831                bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13832                return (-1);
13833            }
13834        }
13835
13836        if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13837            BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13838            sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13839        } else {
13840            BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13841        }
13842
13843        rc = bxe_get_igu_cam_info(sc);
13844
13845        bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13846
13847        if (rc) {
13848            return (rc);
13849        }
13850    }
13851
13852    /*
13853     * Get base FW non-default (fast path) status block ID. This value is
13854     * used to initialize the fw_sb_id saved on the fp/queue structure to
13855     * determine the id used by the FW.
13856     */
13857    if (CHIP_IS_E1x(sc)) {
13858        sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
13859    } else {
13860        /*
13861         * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
13862         * the same queue are indicated on the same IGU SB). So we prefer
13863         * FW and IGU SBs to be the same value.
13864         */
13865        sc->base_fw_ndsb = sc->igu_base_sb;
13866    }
13867
13868    BLOGD(sc, DBG_LOAD,
13869          "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
13870          sc->igu_dsb_id, sc->igu_base_sb,
13871          sc->igu_sb_cnt, sc->base_fw_ndsb);
13872
13873    elink_phy_probe(&sc->link_params);
13874
13875    return (0);
13876}
13877
13878static void
13879bxe_link_settings_supported(struct bxe_softc *sc,
13880                            uint32_t         switch_cfg)
13881{
13882    uint32_t cfg_size = 0;
13883    uint32_t idx;
13884    uint8_t port = SC_PORT(sc);
13885
13886    /* aggregation of supported attributes of all external phys */
13887    sc->port.supported[0] = 0;
13888    sc->port.supported[1] = 0;
13889
13890    switch (sc->link_params.num_phys) {
13891    case 1:
13892        sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
13893        cfg_size = 1;
13894        break;
13895    case 2:
13896        sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
13897        cfg_size = 1;
13898        break;
13899    case 3:
13900        if (sc->link_params.multi_phy_config &
13901            PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
13902            sc->port.supported[1] =
13903                sc->link_params.phy[ELINK_EXT_PHY1].supported;
13904            sc->port.supported[0] =
13905                sc->link_params.phy[ELINK_EXT_PHY2].supported;
13906        } else {
13907            sc->port.supported[0] =
13908                sc->link_params.phy[ELINK_EXT_PHY1].supported;
13909            sc->port.supported[1] =
13910                sc->link_params.phy[ELINK_EXT_PHY2].supported;
13911        }
13912        cfg_size = 2;
13913        break;
13914    }
13915
13916    if (!(sc->port.supported[0] || sc->port.supported[1])) {
13917        BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
13918              SHMEM_RD(sc,
13919                       dev_info.port_hw_config[port].external_phy_config),
13920              SHMEM_RD(sc,
13921                       dev_info.port_hw_config[port].external_phy_config2));
13922        return;
13923    }
13924
13925    if (CHIP_IS_E3(sc))
13926        sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
13927    else {
13928        switch (switch_cfg) {
13929        case ELINK_SWITCH_CFG_1G:
13930            sc->port.phy_addr =
13931                REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
13932            break;
13933        case ELINK_SWITCH_CFG_10G:
13934            sc->port.phy_addr =
13935                REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
13936            break;
13937        default:
13938            BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
13939                  sc->port.link_config[0]);
13940            return;
13941        }
13942    }
13943
13944    BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
13945
13946    /* mask what we support according to speed_cap_mask per configuration */
13947    for (idx = 0; idx < cfg_size; idx++) {
13948        if (!(sc->link_params.speed_cap_mask[idx] &
13949              PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
13950            sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
13951        }
13952
13953        if (!(sc->link_params.speed_cap_mask[idx] &
13954              PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
13955            sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
13956        }
13957
13958        if (!(sc->link_params.speed_cap_mask[idx] &
13959              PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
13960            sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
13961        }
13962
13963        if (!(sc->link_params.speed_cap_mask[idx] &
13964              PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
13965            sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
13966        }
13967
13968        if (!(sc->link_params.speed_cap_mask[idx] &
13969              PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
13970            sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
13971        }
13972
13973        if (!(sc->link_params.speed_cap_mask[idx] &
13974              PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
13975            sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
13976        }
13977
13978        if (!(sc->link_params.speed_cap_mask[idx] &
13979              PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
13980            sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
13981        }
13982
13983        if (!(sc->link_params.speed_cap_mask[idx] &
13984              PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
13985            sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
13986        }
13987    }
13988
13989    BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
13990          sc->port.supported[0], sc->port.supported[1]);
13991}
13992
13993static void
13994bxe_link_settings_requested(struct bxe_softc *sc)
13995{
13996    uint32_t link_config;
13997    uint32_t idx;
13998    uint32_t cfg_size = 0;
13999
14000    sc->port.advertising[0] = 0;
14001    sc->port.advertising[1] = 0;
14002
14003    switch (sc->link_params.num_phys) {
14004    case 1:
14005    case 2:
14006        cfg_size = 1;
14007        break;
14008    case 3:
14009        cfg_size = 2;
14010        break;
14011    }
14012
14013    for (idx = 0; idx < cfg_size; idx++) {
14014        sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14015        link_config = sc->port.link_config[idx];
14016
14017        switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14018        case PORT_FEATURE_LINK_SPEED_AUTO:
14019            if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14020                sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14021                sc->port.advertising[idx] |= sc->port.supported[idx];
14022                if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14023                    PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14024                    sc->port.advertising[idx] |=
14025                        (ELINK_SUPPORTED_100baseT_Half |
14026                         ELINK_SUPPORTED_100baseT_Full);
14027            } else {
14028                /* force 10G, no AN */
14029                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14030                sc->port.advertising[idx] |=
14031                    (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14032                continue;
14033            }
14034            break;
14035
14036        case PORT_FEATURE_LINK_SPEED_10M_FULL:
14037            if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14038                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14039                sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14040                                              ADVERTISED_TP);
14041            } else {
14042                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14043                          "speed_cap_mask=0x%08x\n",
14044                      link_config, sc->link_params.speed_cap_mask[idx]);
14045                return;
14046            }
14047            break;
14048
14049        case PORT_FEATURE_LINK_SPEED_10M_HALF:
14050            if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14051                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14052                sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14053                sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14054                                              ADVERTISED_TP);
14055            } else {
14056                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14057                          "speed_cap_mask=0x%08x\n",
14058                      link_config, sc->link_params.speed_cap_mask[idx]);
14059                return;
14060            }
14061            break;
14062
14063        case PORT_FEATURE_LINK_SPEED_100M_FULL:
14064            if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14065                sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14066                sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14067                                              ADVERTISED_TP);
14068            } else {
14069                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14070                          "speed_cap_mask=0x%08x\n",
14071                      link_config, sc->link_params.speed_cap_mask[idx]);
14072                return;
14073            }
14074            break;
14075
14076        case PORT_FEATURE_LINK_SPEED_100M_HALF:
14077            if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14078                sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14079                sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14080                sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14081                                              ADVERTISED_TP);
14082            } else {
14083                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14084                          "speed_cap_mask=0x%08x\n",
14085                      link_config, sc->link_params.speed_cap_mask[idx]);
14086                return;
14087            }
14088            break;
14089
14090        case PORT_FEATURE_LINK_SPEED_1G:
14091            if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14092                sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14093                sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14094                                              ADVERTISED_TP);
14095            } else {
14096                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14097                          "speed_cap_mask=0x%08x\n",
14098                      link_config, sc->link_params.speed_cap_mask[idx]);
14099                return;
14100            }
14101            break;
14102
14103        case PORT_FEATURE_LINK_SPEED_2_5G:
14104            if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14105                sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14106                sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14107                                              ADVERTISED_TP);
14108            } else {
14109                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14110                          "speed_cap_mask=0x%08x\n",
14111                      link_config, sc->link_params.speed_cap_mask[idx]);
14112                return;
14113            }
14114            break;
14115
14116        case PORT_FEATURE_LINK_SPEED_10G_CX4:
14117            if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14118                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14119                sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14120                                              ADVERTISED_FIBRE);
14121            } else {
14122                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14123                          "speed_cap_mask=0x%08x\n",
14124                      link_config, sc->link_params.speed_cap_mask[idx]);
14125                return;
14126            }
14127            break;
14128
14129        case PORT_FEATURE_LINK_SPEED_20G:
14130            sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14131            break;
14132
14133        default:
14134            BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14135                      "speed_cap_mask=0x%08x\n",
14136                  link_config, sc->link_params.speed_cap_mask[idx]);
14137            sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14138            sc->port.advertising[idx] = sc->port.supported[idx];
14139            break;
14140        }
14141
14142        sc->link_params.req_flow_ctrl[idx] =
14143            (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14144
14145        if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14146            if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14147                sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14148            } else {
14149                bxe_set_requested_fc(sc);
14150            }
14151        }
14152
14153        BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14154                            "req_flow_ctrl=0x%x advertising=0x%x\n",
14155              sc->link_params.req_line_speed[idx],
14156              sc->link_params.req_duplex[idx],
14157              sc->link_params.req_flow_ctrl[idx],
14158              sc->port.advertising[idx]);
14159    }
14160}
14161
14162static void
14163bxe_get_phy_info(struct bxe_softc *sc)
14164{
14165    uint8_t port = SC_PORT(sc);
14166    uint32_t config = sc->port.config;
14167    uint32_t eee_mode;
14168
14169    /* shmem data already read in bxe_get_shmem_info() */
14170
14171    BLOGD(sc, DBG_LOAD, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14172                        "link_config0=0x%08x\n",
14173               sc->link_params.lane_config,
14174               sc->link_params.speed_cap_mask[0],
14175               sc->port.link_config[0]);
14176
14177    bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14178    bxe_link_settings_requested(sc);
14179
14180    if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14181        sc->link_params.feature_config_flags |=
14182            ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14183    } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14184        sc->link_params.feature_config_flags &=
14185            ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14186    } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14187        sc->link_params.feature_config_flags |=
14188            ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14189    }
14190
14191    /* configure link feature according to nvram value */
14192    eee_mode =
14193        (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14194          PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14195         PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14196    if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14197        sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14198                                    ELINK_EEE_MODE_ENABLE_LPI |
14199                                    ELINK_EEE_MODE_OUTPUT_TIME);
14200    } else {
14201        sc->link_params.eee_mode = 0;
14202    }
14203
14204    /* get the media type */
14205    bxe_media_detect(sc);
14206}
14207
14208static void
14209bxe_get_params(struct bxe_softc *sc)
14210{
14211    /* get user tunable params */
14212    bxe_get_tunable_params(sc);
14213
14214    /* select the RX and TX ring sizes */
14215    sc->tx_ring_size = TX_BD_USABLE;
14216    sc->rx_ring_size = RX_BD_USABLE;
14217
14218    /* XXX disable WoL */
14219    sc->wol = 0;
14220}
14221
14222static void
14223bxe_set_modes_bitmap(struct bxe_softc *sc)
14224{
14225    uint32_t flags = 0;
14226
14227    if (CHIP_REV_IS_FPGA(sc)) {
14228        SET_FLAGS(flags, MODE_FPGA);
14229    } else if (CHIP_REV_IS_EMUL(sc)) {
14230        SET_FLAGS(flags, MODE_EMUL);
14231    } else {
14232        SET_FLAGS(flags, MODE_ASIC);
14233    }
14234
14235    if (CHIP_IS_MODE_4_PORT(sc)) {
14236        SET_FLAGS(flags, MODE_PORT4);
14237    } else {
14238        SET_FLAGS(flags, MODE_PORT2);
14239    }
14240
14241    if (CHIP_IS_E2(sc)) {
14242        SET_FLAGS(flags, MODE_E2);
14243    } else if (CHIP_IS_E3(sc)) {
14244        SET_FLAGS(flags, MODE_E3);
14245        if (CHIP_REV(sc) == CHIP_REV_Ax) {
14246            SET_FLAGS(flags, MODE_E3_A0);
14247        } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14248            SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14249        }
14250    }
14251
14252    if (IS_MF(sc)) {
14253        SET_FLAGS(flags, MODE_MF);
14254        switch (sc->devinfo.mf_info.mf_mode) {
14255        case MULTI_FUNCTION_SD:
14256            SET_FLAGS(flags, MODE_MF_SD);
14257            break;
14258        case MULTI_FUNCTION_SI:
14259            SET_FLAGS(flags, MODE_MF_SI);
14260            break;
14261        case MULTI_FUNCTION_AFEX:
14262            SET_FLAGS(flags, MODE_MF_AFEX);
14263            break;
14264        }
14265    } else {
14266        SET_FLAGS(flags, MODE_SF);
14267    }
14268
14269#if defined(__LITTLE_ENDIAN)
14270    SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14271#else /* __BIG_ENDIAN */
14272    SET_FLAGS(flags, MODE_BIG_ENDIAN);
14273#endif
14274
14275    INIT_MODE_FLAGS(sc) = flags;
14276}
14277
14278static int
14279bxe_alloc_hsi_mem(struct bxe_softc *sc)
14280{
14281    struct bxe_fastpath *fp;
14282    bus_addr_t busaddr;
14283    int max_agg_queues;
14284    int max_segments;
14285    bus_size_t max_size;
14286    bus_size_t max_seg_size;
14287    char buf[32];
14288    int rc;
14289    int i, j;
14290
14291    /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14292
14293    /* allocate the parent bus DMA tag */
14294    rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14295                            1,                        /* alignment */
14296                            0,                        /* boundary limit */
14297                            BUS_SPACE_MAXADDR,        /* restricted low */
14298                            BUS_SPACE_MAXADDR,        /* restricted hi */
14299                            NULL,                     /* addr filter() */
14300                            NULL,                     /* addr filter() arg */
14301                            BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14302                            BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14303                            BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14304                            0,                        /* flags */
14305                            NULL,                     /* lock() */
14306                            NULL,                     /* lock() arg */
14307                            &sc->parent_dma_tag);     /* returned dma tag */
14308    if (rc != 0) {
14309        BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14310        return (1);
14311    }
14312
14313    /************************/
14314    /* DEFAULT STATUS BLOCK */
14315    /************************/
14316
14317    if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14318                      &sc->def_sb_dma, "default status block") != 0) {
14319        /* XXX */
14320        bus_dma_tag_destroy(sc->parent_dma_tag);
14321        return (1);
14322    }
14323
14324    sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14325
14326    /***************/
14327    /* EVENT QUEUE */
14328    /***************/
14329
14330    if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14331                      &sc->eq_dma, "event queue") != 0) {
14332        /* XXX */
14333        bxe_dma_free(sc, &sc->def_sb_dma);
14334        sc->def_sb = NULL;
14335        bus_dma_tag_destroy(sc->parent_dma_tag);
14336        return (1);
14337    }
14338
14339    sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14340
14341    /*************/
14342    /* SLOW PATH */
14343    /*************/
14344
14345    if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14346                      &sc->sp_dma, "slow path") != 0) {
14347        /* XXX */
14348        bxe_dma_free(sc, &sc->eq_dma);
14349        sc->eq = NULL;
14350        bxe_dma_free(sc, &sc->def_sb_dma);
14351        sc->def_sb = NULL;
14352        bus_dma_tag_destroy(sc->parent_dma_tag);
14353        return (1);
14354    }
14355
14356    sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14357
14358    /*******************/
14359    /* SLOW PATH QUEUE */
14360    /*******************/
14361
14362    if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14363                      &sc->spq_dma, "slow path queue") != 0) {
14364        /* XXX */
14365        bxe_dma_free(sc, &sc->sp_dma);
14366        sc->sp = NULL;
14367        bxe_dma_free(sc, &sc->eq_dma);
14368        sc->eq = NULL;
14369        bxe_dma_free(sc, &sc->def_sb_dma);
14370        sc->def_sb = NULL;
14371        bus_dma_tag_destroy(sc->parent_dma_tag);
14372        return (1);
14373    }
14374
14375    sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14376
14377    /***************************/
14378    /* FW DECOMPRESSION BUFFER */
14379    /***************************/
14380
14381    if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14382                      "fw decompression buffer") != 0) {
14383        /* XXX */
14384        bxe_dma_free(sc, &sc->spq_dma);
14385        sc->spq = NULL;
14386        bxe_dma_free(sc, &sc->sp_dma);
14387        sc->sp = NULL;
14388        bxe_dma_free(sc, &sc->eq_dma);
14389        sc->eq = NULL;
14390        bxe_dma_free(sc, &sc->def_sb_dma);
14391        sc->def_sb = NULL;
14392        bus_dma_tag_destroy(sc->parent_dma_tag);
14393        return (1);
14394    }
14395
14396    sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14397
14398    if ((sc->gz_strm =
14399         malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14400        /* XXX */
14401        bxe_dma_free(sc, &sc->gz_buf_dma);
14402        sc->gz_buf = NULL;
14403        bxe_dma_free(sc, &sc->spq_dma);
14404        sc->spq = NULL;
14405        bxe_dma_free(sc, &sc->sp_dma);
14406        sc->sp = NULL;
14407        bxe_dma_free(sc, &sc->eq_dma);
14408        sc->eq = NULL;
14409        bxe_dma_free(sc, &sc->def_sb_dma);
14410        sc->def_sb = NULL;
14411        bus_dma_tag_destroy(sc->parent_dma_tag);
14412        return (1);
14413    }
14414
14415    /*************/
14416    /* FASTPATHS */
14417    /*************/
14418
14419    /* allocate DMA memory for each fastpath structure */
14420    for (i = 0; i < sc->num_queues; i++) {
14421        fp = &sc->fp[i];
14422        fp->sc    = sc;
14423        fp->index = i;
14424
14425        /*******************/
14426        /* FP STATUS BLOCK */
14427        /*******************/
14428
14429        snprintf(buf, sizeof(buf), "fp %d status block", i);
14430        if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14431                          &fp->sb_dma, buf) != 0) {
14432            /* XXX unwind and free previous fastpath allocations */
14433            BLOGE(sc, "Failed to alloc %s\n", buf);
14434            return (1);
14435        } else {
14436            if (CHIP_IS_E2E3(sc)) {
14437                fp->status_block.e2_sb =
14438                    (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14439            } else {
14440                fp->status_block.e1x_sb =
14441                    (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14442            }
14443        }
14444
14445        /******************/
14446        /* FP TX BD CHAIN */
14447        /******************/
14448
14449        snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14450        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14451                          &fp->tx_dma, buf) != 0) {
14452            /* XXX unwind and free previous fastpath allocations */
14453            BLOGE(sc, "Failed to alloc %s\n", buf);
14454            return (1);
14455        } else {
14456            fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14457        }
14458
14459        /* link together the tx bd chain pages */
14460        for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14461            /* index into the tx bd chain array to last entry per page */
14462            struct eth_tx_next_bd *tx_next_bd =
14463                &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14464            /* point to the next page and wrap from last page */
14465            busaddr = (fp->tx_dma.paddr +
14466                       (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14467            tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14468            tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14469        }
14470
14471        /******************/
14472        /* FP RX BD CHAIN */
14473        /******************/
14474
14475        snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14476        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14477                          &fp->rx_dma, buf) != 0) {
14478            /* XXX unwind and free previous fastpath allocations */
14479            BLOGE(sc, "Failed to alloc %s\n", buf);
14480            return (1);
14481        } else {
14482            fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14483        }
14484
14485        /* link together the rx bd chain pages */
14486        for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14487            /* index into the rx bd chain array to last entry per page */
14488            struct eth_rx_bd *rx_bd =
14489                &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14490            /* point to the next page and wrap from last page */
14491            busaddr = (fp->rx_dma.paddr +
14492                       (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14493            rx_bd->addr_hi = htole32(U64_HI(busaddr));
14494            rx_bd->addr_lo = htole32(U64_LO(busaddr));
14495        }
14496
14497        /*******************/
14498        /* FP RX RCQ CHAIN */
14499        /*******************/
14500
14501        snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14502        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14503                          &fp->rcq_dma, buf) != 0) {
14504            /* XXX unwind and free previous fastpath allocations */
14505            BLOGE(sc, "Failed to alloc %s\n", buf);
14506            return (1);
14507        } else {
14508            fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14509        }
14510
14511        /* link together the rcq chain pages */
14512        for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14513            /* index into the rcq chain array to last entry per page */
14514            struct eth_rx_cqe_next_page *rx_cqe_next =
14515                (struct eth_rx_cqe_next_page *)
14516                &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14517            /* point to the next page and wrap from last page */
14518            busaddr = (fp->rcq_dma.paddr +
14519                       (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14520            rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14521            rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14522        }
14523
14524        /*******************/
14525        /* FP RX SGE CHAIN */
14526        /*******************/
14527
14528        snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14529        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14530                          &fp->rx_sge_dma, buf) != 0) {
14531            /* XXX unwind and free previous fastpath allocations */
14532            BLOGE(sc, "Failed to alloc %s\n", buf);
14533            return (1);
14534        } else {
14535            fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14536        }
14537
14538        /* link together the sge chain pages */
14539        for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14540            /* index into the rcq chain array to last entry per page */
14541            struct eth_rx_sge *rx_sge =
14542                &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14543            /* point to the next page and wrap from last page */
14544            busaddr = (fp->rx_sge_dma.paddr +
14545                       (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14546            rx_sge->addr_hi = htole32(U64_HI(busaddr));
14547            rx_sge->addr_lo = htole32(U64_LO(busaddr));
14548        }
14549
14550        /***********************/
14551        /* FP TX MBUF DMA MAPS */
14552        /***********************/
14553
14554        /* set required sizes before mapping to conserve resources */
14555        if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
14556            max_size     = BXE_TSO_MAX_SIZE;
14557            max_segments = BXE_TSO_MAX_SEGMENTS;
14558            max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14559        } else {
14560            max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14561            max_segments = BXE_MAX_SEGMENTS;
14562            max_seg_size = MCLBYTES;
14563        }
14564
14565        /* create a dma tag for the tx mbufs */
14566        rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14567                                1,                  /* alignment */
14568                                0,                  /* boundary limit */
14569                                BUS_SPACE_MAXADDR,  /* restricted low */
14570                                BUS_SPACE_MAXADDR,  /* restricted hi */
14571                                NULL,               /* addr filter() */
14572                                NULL,               /* addr filter() arg */
14573                                max_size,           /* max map size */
14574                                max_segments,       /* num discontinuous */
14575                                max_seg_size,       /* max seg size */
14576                                0,                  /* flags */
14577                                NULL,               /* lock() */
14578                                NULL,               /* lock() arg */
14579                                &fp->tx_mbuf_tag);  /* returned dma tag */
14580        if (rc != 0) {
14581            /* XXX unwind and free previous fastpath allocations */
14582            BLOGE(sc, "Failed to create dma tag for "
14583                      "'fp %d tx mbufs' (%d)\n", i, rc);
14584            return (1);
14585        }
14586
14587        /* create dma maps for each of the tx mbuf clusters */
14588        for (j = 0; j < TX_BD_TOTAL; j++) {
14589            if (bus_dmamap_create(fp->tx_mbuf_tag,
14590                                  BUS_DMA_NOWAIT,
14591                                  &fp->tx_mbuf_chain[j].m_map)) {
14592                /* XXX unwind and free previous fastpath allocations */
14593                BLOGE(sc, "Failed to create dma map for "
14594                          "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14595                return (1);
14596            }
14597        }
14598
14599        /***********************/
14600        /* FP RX MBUF DMA MAPS */
14601        /***********************/
14602
14603        /* create a dma tag for the rx mbufs */
14604        rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14605                                1,                  /* alignment */
14606                                0,                  /* boundary limit */
14607                                BUS_SPACE_MAXADDR,  /* restricted low */
14608                                BUS_SPACE_MAXADDR,  /* restricted hi */
14609                                NULL,               /* addr filter() */
14610                                NULL,               /* addr filter() arg */
14611                                MJUM9BYTES,         /* max map size */
14612                                1,                  /* num discontinuous */
14613                                MJUM9BYTES,         /* max seg size */
14614                                0,                  /* flags */
14615                                NULL,               /* lock() */
14616                                NULL,               /* lock() arg */
14617                                &fp->rx_mbuf_tag);  /* returned dma tag */
14618        if (rc != 0) {
14619            /* XXX unwind and free previous fastpath allocations */
14620            BLOGE(sc, "Failed to create dma tag for "
14621                      "'fp %d rx mbufs' (%d)\n", i, rc);
14622            return (1);
14623        }
14624
14625        /* create dma maps for each of the rx mbuf clusters */
14626        for (j = 0; j < RX_BD_TOTAL; j++) {
14627            if (bus_dmamap_create(fp->rx_mbuf_tag,
14628                                  BUS_DMA_NOWAIT,
14629                                  &fp->rx_mbuf_chain[j].m_map)) {
14630                /* XXX unwind and free previous fastpath allocations */
14631                BLOGE(sc, "Failed to create dma map for "
14632                          "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14633                return (1);
14634            }
14635        }
14636
14637        /* create dma map for the spare rx mbuf cluster */
14638        if (bus_dmamap_create(fp->rx_mbuf_tag,
14639                              BUS_DMA_NOWAIT,
14640                              &fp->rx_mbuf_spare_map)) {
14641            /* XXX unwind and free previous fastpath allocations */
14642            BLOGE(sc, "Failed to create dma map for "
14643                      "'fp %d spare rx mbuf' (%d)\n", i, rc);
14644            return (1);
14645        }
14646
14647        /***************************/
14648        /* FP RX SGE MBUF DMA MAPS */
14649        /***************************/
14650
14651        /* create a dma tag for the rx sge mbufs */
14652        rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14653                                1,                  /* alignment */
14654                                0,                  /* boundary limit */
14655                                BUS_SPACE_MAXADDR,  /* restricted low */
14656                                BUS_SPACE_MAXADDR,  /* restricted hi */
14657                                NULL,               /* addr filter() */
14658                                NULL,               /* addr filter() arg */
14659                                BCM_PAGE_SIZE,      /* max map size */
14660                                1,                  /* num discontinuous */
14661                                BCM_PAGE_SIZE,      /* max seg size */
14662                                0,                  /* flags */
14663                                NULL,               /* lock() */
14664                                NULL,               /* lock() arg */
14665                                &fp->rx_sge_mbuf_tag); /* returned dma tag */
14666        if (rc != 0) {
14667            /* XXX unwind and free previous fastpath allocations */
14668            BLOGE(sc, "Failed to create dma tag for "
14669                      "'fp %d rx sge mbufs' (%d)\n", i, rc);
14670            return (1);
14671        }
14672
14673        /* create dma maps for the rx sge mbuf clusters */
14674        for (j = 0; j < RX_SGE_TOTAL; j++) {
14675            if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14676                                  BUS_DMA_NOWAIT,
14677                                  &fp->rx_sge_mbuf_chain[j].m_map)) {
14678                /* XXX unwind and free previous fastpath allocations */
14679                BLOGE(sc, "Failed to create dma map for "
14680                          "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14681                return (1);
14682            }
14683        }
14684
14685        /* create dma map for the spare rx sge mbuf cluster */
14686        if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14687                              BUS_DMA_NOWAIT,
14688                              &fp->rx_sge_mbuf_spare_map)) {
14689            /* XXX unwind and free previous fastpath allocations */
14690            BLOGE(sc, "Failed to create dma map for "
14691                      "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14692            return (1);
14693        }
14694
14695        /***************************/
14696        /* FP RX TPA MBUF DMA MAPS */
14697        /***************************/
14698
14699        /* create dma maps for the rx tpa mbuf clusters */
14700        max_agg_queues = MAX_AGG_QS(sc);
14701
14702        for (j = 0; j < max_agg_queues; j++) {
14703            if (bus_dmamap_create(fp->rx_mbuf_tag,
14704                                  BUS_DMA_NOWAIT,
14705                                  &fp->rx_tpa_info[j].bd.m_map)) {
14706                /* XXX unwind and free previous fastpath allocations */
14707                BLOGE(sc, "Failed to create dma map for "
14708                          "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14709                return (1);
14710            }
14711        }
14712
14713        /* create dma map for the spare rx tpa mbuf cluster */
14714        if (bus_dmamap_create(fp->rx_mbuf_tag,
14715                              BUS_DMA_NOWAIT,
14716                              &fp->rx_tpa_info_mbuf_spare_map)) {
14717            /* XXX unwind and free previous fastpath allocations */
14718            BLOGE(sc, "Failed to create dma map for "
14719                      "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14720            return (1);
14721        }
14722
14723        bxe_init_sge_ring_bit_mask(fp);
14724    }
14725
14726    return (0);
14727}
14728
14729static void
14730bxe_free_hsi_mem(struct bxe_softc *sc)
14731{
14732    struct bxe_fastpath *fp;
14733    int max_agg_queues;
14734    int i, j;
14735
14736    if (sc->parent_dma_tag == NULL) {
14737        return; /* assume nothing was allocated */
14738    }
14739
14740    for (i = 0; i < sc->num_queues; i++) {
14741        fp = &sc->fp[i];
14742
14743        /*******************/
14744        /* FP STATUS BLOCK */
14745        /*******************/
14746
14747        bxe_dma_free(sc, &fp->sb_dma);
14748        memset(&fp->status_block, 0, sizeof(fp->status_block));
14749
14750        /******************/
14751        /* FP TX BD CHAIN */
14752        /******************/
14753
14754        bxe_dma_free(sc, &fp->tx_dma);
14755        fp->tx_chain = NULL;
14756
14757        /******************/
14758        /* FP RX BD CHAIN */
14759        /******************/
14760
14761        bxe_dma_free(sc, &fp->rx_dma);
14762        fp->rx_chain = NULL;
14763
14764        /*******************/
14765        /* FP RX RCQ CHAIN */
14766        /*******************/
14767
14768        bxe_dma_free(sc, &fp->rcq_dma);
14769        fp->rcq_chain = NULL;
14770
14771        /*******************/
14772        /* FP RX SGE CHAIN */
14773        /*******************/
14774
14775        bxe_dma_free(sc, &fp->rx_sge_dma);
14776        fp->rx_sge_chain = NULL;
14777
14778        /***********************/
14779        /* FP TX MBUF DMA MAPS */
14780        /***********************/
14781
14782        if (fp->tx_mbuf_tag != NULL) {
14783            for (j = 0; j < TX_BD_TOTAL; j++) {
14784                if (fp->tx_mbuf_chain[j].m_map != NULL) {
14785                    bus_dmamap_unload(fp->tx_mbuf_tag,
14786                                      fp->tx_mbuf_chain[j].m_map);
14787                    bus_dmamap_destroy(fp->tx_mbuf_tag,
14788                                       fp->tx_mbuf_chain[j].m_map);
14789                }
14790            }
14791
14792            bus_dma_tag_destroy(fp->tx_mbuf_tag);
14793            fp->tx_mbuf_tag = NULL;
14794        }
14795
14796        /***********************/
14797        /* FP RX MBUF DMA MAPS */
14798        /***********************/
14799
14800        if (fp->rx_mbuf_tag != NULL) {
14801            for (j = 0; j < RX_BD_TOTAL; j++) {
14802                if (fp->rx_mbuf_chain[j].m_map != NULL) {
14803                    bus_dmamap_unload(fp->rx_mbuf_tag,
14804                                      fp->rx_mbuf_chain[j].m_map);
14805                    bus_dmamap_destroy(fp->rx_mbuf_tag,
14806                                       fp->rx_mbuf_chain[j].m_map);
14807                }
14808            }
14809
14810            if (fp->rx_mbuf_spare_map != NULL) {
14811                bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14812                bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14813            }
14814
14815            /***************************/
14816            /* FP RX TPA MBUF DMA MAPS */
14817            /***************************/
14818
14819            max_agg_queues = MAX_AGG_QS(sc);
14820
14821            for (j = 0; j < max_agg_queues; j++) {
14822                if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14823                    bus_dmamap_unload(fp->rx_mbuf_tag,
14824                                      fp->rx_tpa_info[j].bd.m_map);
14825                    bus_dmamap_destroy(fp->rx_mbuf_tag,
14826                                       fp->rx_tpa_info[j].bd.m_map);
14827                }
14828            }
14829
14830            if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14831                bus_dmamap_unload(fp->rx_mbuf_tag,
14832                                  fp->rx_tpa_info_mbuf_spare_map);
14833                bus_dmamap_destroy(fp->rx_mbuf_tag,
14834                                   fp->rx_tpa_info_mbuf_spare_map);
14835            }
14836
14837            bus_dma_tag_destroy(fp->rx_mbuf_tag);
14838            fp->rx_mbuf_tag = NULL;
14839        }
14840
14841        /***************************/
14842        /* FP RX SGE MBUF DMA MAPS */
14843        /***************************/
14844
14845        if (fp->rx_sge_mbuf_tag != NULL) {
14846            for (j = 0; j < RX_SGE_TOTAL; j++) {
14847                if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14848                    bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14849                                      fp->rx_sge_mbuf_chain[j].m_map);
14850                    bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14851                                       fp->rx_sge_mbuf_chain[j].m_map);
14852                }
14853            }
14854
14855            if (fp->rx_sge_mbuf_spare_map != NULL) {
14856                bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14857                                  fp->rx_sge_mbuf_spare_map);
14858                bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14859                                   fp->rx_sge_mbuf_spare_map);
14860            }
14861
14862            bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
14863            fp->rx_sge_mbuf_tag = NULL;
14864        }
14865    }
14866
14867    /***************************/
14868    /* FW DECOMPRESSION BUFFER */
14869    /***************************/
14870
14871    bxe_dma_free(sc, &sc->gz_buf_dma);
14872    sc->gz_buf = NULL;
14873    free(sc->gz_strm, M_DEVBUF);
14874    sc->gz_strm = NULL;
14875
14876    /*******************/
14877    /* SLOW PATH QUEUE */
14878    /*******************/
14879
14880    bxe_dma_free(sc, &sc->spq_dma);
14881    sc->spq = NULL;
14882
14883    /*************/
14884    /* SLOW PATH */
14885    /*************/
14886
14887    bxe_dma_free(sc, &sc->sp_dma);
14888    sc->sp = NULL;
14889
14890    /***************/
14891    /* EVENT QUEUE */
14892    /***************/
14893
14894    bxe_dma_free(sc, &sc->eq_dma);
14895    sc->eq = NULL;
14896
14897    /************************/
14898    /* DEFAULT STATUS BLOCK */
14899    /************************/
14900
14901    bxe_dma_free(sc, &sc->def_sb_dma);
14902    sc->def_sb = NULL;
14903
14904    bus_dma_tag_destroy(sc->parent_dma_tag);
14905    sc->parent_dma_tag = NULL;
14906}
14907
14908/*
14909 * Previous driver DMAE transaction may have occurred when pre-boot stage
14910 * ended and boot began. This would invalidate the addresses of the
14911 * transaction, resulting in was-error bit set in the PCI causing all
14912 * hw-to-host PCIe transactions to timeout. If this happened we want to clear
14913 * the interrupt which detected this from the pglueb and the was-done bit
14914 */
14915static void
14916bxe_prev_interrupted_dmae(struct bxe_softc *sc)
14917{
14918    uint32_t val;
14919
14920    if (!CHIP_IS_E1x(sc)) {
14921        val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
14922        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
14923            BLOGD(sc, DBG_LOAD,
14924                  "Clearing 'was-error' bit that was set in pglueb");
14925            REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
14926        }
14927    }
14928}
14929
14930static int
14931bxe_prev_mcp_done(struct bxe_softc *sc)
14932{
14933    uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
14934                                 DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
14935    if (!rc) {
14936        BLOGE(sc, "MCP response failure, aborting\n");
14937        return (-1);
14938    }
14939
14940    return (0);
14941}
14942
14943static struct bxe_prev_list_node *
14944bxe_prev_path_get_entry(struct bxe_softc *sc)
14945{
14946    struct bxe_prev_list_node *tmp;
14947
14948    LIST_FOREACH(tmp, &bxe_prev_list, node) {
14949        if ((sc->pcie_bus == tmp->bus) &&
14950            (sc->pcie_device == tmp->slot) &&
14951            (SC_PATH(sc) == tmp->path)) {
14952            return (tmp);
14953        }
14954    }
14955
14956    return (NULL);
14957}
14958
14959static uint8_t
14960bxe_prev_is_path_marked(struct bxe_softc *sc)
14961{
14962    struct bxe_prev_list_node *tmp;
14963    int rc = FALSE;
14964
14965    mtx_lock(&bxe_prev_mtx);
14966
14967    tmp = bxe_prev_path_get_entry(sc);
14968    if (tmp) {
14969        if (tmp->aer) {
14970            BLOGD(sc, DBG_LOAD,
14971                  "Path %d/%d/%d was marked by AER\n",
14972                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
14973        } else {
14974            rc = TRUE;
14975            BLOGD(sc, DBG_LOAD,
14976                  "Path %d/%d/%d was already cleaned from previous drivers\n",
14977                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
14978        }
14979    }
14980
14981    mtx_unlock(&bxe_prev_mtx);
14982
14983    return (rc);
14984}
14985
14986static int
14987bxe_prev_mark_path(struct bxe_softc *sc,
14988                   uint8_t          after_undi)
14989{
14990    struct bxe_prev_list_node *tmp;
14991
14992    mtx_lock(&bxe_prev_mtx);
14993
14994    /* Check whether the entry for this path already exists */
14995    tmp = bxe_prev_path_get_entry(sc);
14996    if (tmp) {
14997        if (!tmp->aer) {
14998            BLOGD(sc, DBG_LOAD,
14999                  "Re-marking AER in path %d/%d/%d\n",
15000                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15001        } else {
15002            BLOGD(sc, DBG_LOAD,
15003                  "Removing AER indication from path %d/%d/%d\n",
15004                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15005            tmp->aer = 0;
15006        }
15007
15008        mtx_unlock(&bxe_prev_mtx);
15009        return (0);
15010    }
15011
15012    mtx_unlock(&bxe_prev_mtx);
15013
15014    /* Create an entry for this path and add it */
15015    tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15016                 (M_NOWAIT | M_ZERO));
15017    if (!tmp) {
15018        BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15019        return (-1);
15020    }
15021
15022    tmp->bus  = sc->pcie_bus;
15023    tmp->slot = sc->pcie_device;
15024    tmp->path = SC_PATH(sc);
15025    tmp->aer  = 0;
15026    tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15027
15028    mtx_lock(&bxe_prev_mtx);
15029
15030    BLOGD(sc, DBG_LOAD,
15031          "Marked path %d/%d/%d - finished previous unload\n",
15032          sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15033    LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15034
15035    mtx_unlock(&bxe_prev_mtx);
15036
15037    return (0);
15038}
15039
15040static int
15041bxe_do_flr(struct bxe_softc *sc)
15042{
15043    int i;
15044
15045    /* only E2 and onwards support FLR */
15046    if (CHIP_IS_E1x(sc)) {
15047        BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15048        return (-1);
15049    }
15050
15051    /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15052    if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15053        BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15054              sc->devinfo.bc_ver);
15055        return (-1);
15056    }
15057
15058    /* Wait for Transaction Pending bit clean */
15059    for (i = 0; i < 4; i++) {
15060        if (i) {
15061            DELAY(((1 << (i - 1)) * 100) * 1000);
15062        }
15063
15064        if (!bxe_is_pcie_pending(sc)) {
15065            goto clear;
15066        }
15067    }
15068
15069    BLOGE(sc, "PCIE transaction is not cleared, "
15070              "proceeding with reset anyway\n");
15071
15072clear:
15073
15074    BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15075    bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15076
15077    return (0);
15078}
15079
15080struct bxe_mac_vals {
15081    uint32_t xmac_addr;
15082    uint32_t xmac_val;
15083    uint32_t emac_addr;
15084    uint32_t emac_val;
15085    uint32_t umac_addr;
15086    uint32_t umac_val;
15087    uint32_t bmac_addr;
15088    uint32_t bmac_val[2];
15089};
15090
15091static void
15092bxe_prev_unload_close_mac(struct bxe_softc *sc,
15093                          struct bxe_mac_vals *vals)
15094{
15095    uint32_t val, base_addr, offset, mask, reset_reg;
15096    uint8_t mac_stopped = FALSE;
15097    uint8_t port = SC_PORT(sc);
15098    uint32_t wb_data[2];
15099
15100    /* reset addresses as they also mark which values were changed */
15101    vals->bmac_addr = 0;
15102    vals->umac_addr = 0;
15103    vals->xmac_addr = 0;
15104    vals->emac_addr = 0;
15105
15106    reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15107
15108    if (!CHIP_IS_E3(sc)) {
15109        val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15110        mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15111        if ((mask & reset_reg) && val) {
15112            BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15113            base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15114                                    : NIG_REG_INGRESS_BMAC0_MEM;
15115            offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15116                                    : BIGMAC_REGISTER_BMAC_CONTROL;
15117
15118            /*
15119             * use rd/wr since we cannot use dmae. This is safe
15120             * since MCP won't access the bus due to the request
15121             * to unload, and no function on the path can be
15122             * loaded at this time.
15123             */
15124            wb_data[0] = REG_RD(sc, base_addr + offset);
15125            wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15126            vals->bmac_addr = base_addr + offset;
15127            vals->bmac_val[0] = wb_data[0];
15128            vals->bmac_val[1] = wb_data[1];
15129            wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15130            REG_WR(sc, vals->bmac_addr, wb_data[0]);
15131            REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15132        }
15133
15134        BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15135        vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15136        vals->emac_val = REG_RD(sc, vals->emac_addr);
15137        REG_WR(sc, vals->emac_addr, 0);
15138        mac_stopped = TRUE;
15139    } else {
15140        if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15141            BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15142            base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15143            val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15144            REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15145            REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15146            vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15147            vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15148            REG_WR(sc, vals->xmac_addr, 0);
15149            mac_stopped = TRUE;
15150        }
15151
15152        mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15153        if (mask & reset_reg) {
15154            BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15155            base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15156            vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15157            vals->umac_val = REG_RD(sc, vals->umac_addr);
15158            REG_WR(sc, vals->umac_addr, 0);
15159            mac_stopped = TRUE;
15160        }
15161    }
15162
15163    if (mac_stopped) {
15164        DELAY(20000);
15165    }
15166}
15167
15168#define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15169#define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15170#define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15171#define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15172
15173static void
15174bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15175                         uint8_t          port,
15176                         uint8_t          inc)
15177{
15178    uint16_t rcq, bd;
15179    uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15180
15181    rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15182    bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15183
15184    tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15185    REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15186
15187    BLOGD(sc, DBG_LOAD,
15188          "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15189          port, bd, rcq);
15190}
15191
15192static int
15193bxe_prev_unload_common(struct bxe_softc *sc)
15194{
15195    uint32_t reset_reg, tmp_reg = 0, rc;
15196    uint8_t prev_undi = FALSE;
15197    struct bxe_mac_vals mac_vals;
15198    uint32_t timer_count = 1000;
15199    uint32_t prev_brb;
15200
15201    /*
15202     * It is possible a previous function received 'common' answer,
15203     * but hasn't loaded yet, therefore creating a scenario of
15204     * multiple functions receiving 'common' on the same path.
15205     */
15206    BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15207
15208    memset(&mac_vals, 0, sizeof(mac_vals));
15209
15210    if (bxe_prev_is_path_marked(sc)) {
15211        return (bxe_prev_mcp_done(sc));
15212    }
15213
15214    reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15215
15216    /* Reset should be performed after BRB is emptied */
15217    if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15218        /* Close the MAC Rx to prevent BRB from filling up */
15219        bxe_prev_unload_close_mac(sc, &mac_vals);
15220
15221        /* close LLH filters towards the BRB */
15222        elink_set_rx_filter(&sc->link_params, 0);
15223
15224        /*
15225         * Check if the UNDI driver was previously loaded.
15226         * UNDI driver initializes CID offset for normal bell to 0x7
15227         */
15228        if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15229            tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15230            if (tmp_reg == 0x7) {
15231                BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15232                prev_undi = TRUE;
15233                /* clear the UNDI indication */
15234                REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15235                /* clear possible idle check errors */
15236                REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15237            }
15238        }
15239
15240        /* wait until BRB is empty */
15241        tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15242        while (timer_count) {
15243            prev_brb = tmp_reg;
15244
15245            tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15246            if (!tmp_reg) {
15247                break;
15248            }
15249
15250            BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15251
15252            /* reset timer as long as BRB actually gets emptied */
15253            if (prev_brb > tmp_reg) {
15254                timer_count = 1000;
15255            } else {
15256                timer_count--;
15257            }
15258
15259            /* If UNDI resides in memory, manually increment it */
15260            if (prev_undi) {
15261                bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15262            }
15263
15264            DELAY(10);
15265        }
15266
15267        if (!timer_count) {
15268            BLOGE(sc, "Failed to empty BRB\n");
15269        }
15270    }
15271
15272    /* No packets are in the pipeline, path is ready for reset */
15273    bxe_reset_common(sc);
15274
15275    if (mac_vals.xmac_addr) {
15276        REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15277    }
15278    if (mac_vals.umac_addr) {
15279        REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15280    }
15281    if (mac_vals.emac_addr) {
15282        REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15283    }
15284    if (mac_vals.bmac_addr) {
15285        REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15286        REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15287    }
15288
15289    rc = bxe_prev_mark_path(sc, prev_undi);
15290    if (rc) {
15291        bxe_prev_mcp_done(sc);
15292        return (rc);
15293    }
15294
15295    return (bxe_prev_mcp_done(sc));
15296}
15297
15298static int
15299bxe_prev_unload_uncommon(struct bxe_softc *sc)
15300{
15301    int rc;
15302
15303    BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15304
15305    /* Test if previous unload process was already finished for this path */
15306    if (bxe_prev_is_path_marked(sc)) {
15307        return (bxe_prev_mcp_done(sc));
15308    }
15309
15310    BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15311
15312    /*
15313     * If function has FLR capabilities, and existing FW version matches
15314     * the one required, then FLR will be sufficient to clean any residue
15315     * left by previous driver
15316     */
15317    rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15318    if (!rc) {
15319        /* fw version is good */
15320        BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15321        rc = bxe_do_flr(sc);
15322    }
15323
15324    if (!rc) {
15325        /* FLR was performed */
15326        BLOGD(sc, DBG_LOAD, "FLR successful\n");
15327        return (0);
15328    }
15329
15330    BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15331
15332    /* Close the MCP request, return failure*/
15333    rc = bxe_prev_mcp_done(sc);
15334    if (!rc) {
15335        rc = BXE_PREV_WAIT_NEEDED;
15336    }
15337
15338    return (rc);
15339}
15340
15341static int
15342bxe_prev_unload(struct bxe_softc *sc)
15343{
15344    int time_counter = 10;
15345    uint32_t fw, hw_lock_reg, hw_lock_val;
15346    uint32_t rc = 0;
15347
15348    /*
15349     * Clear HW from errors which may have resulted from an interrupted
15350     * DMAE transaction.
15351     */
15352    bxe_prev_interrupted_dmae(sc);
15353
15354    /* Release previously held locks */
15355    hw_lock_reg =
15356        (SC_FUNC(sc) <= 5) ?
15357            (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15358            (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15359
15360    hw_lock_val = (REG_RD(sc, hw_lock_reg));
15361    if (hw_lock_val) {
15362        if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15363            BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15364            REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15365                   (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15366        }
15367        BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15368        REG_WR(sc, hw_lock_reg, 0xffffffff);
15369    } else {
15370        BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15371    }
15372
15373    if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15374        BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15375        REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15376    }
15377
15378    do {
15379        /* Lock MCP using an unload request */
15380        fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15381        if (!fw) {
15382            BLOGE(sc, "MCP response failure, aborting\n");
15383            rc = -1;
15384            break;
15385        }
15386
15387        if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15388            rc = bxe_prev_unload_common(sc);
15389            break;
15390        }
15391
15392        /* non-common reply from MCP night require looping */
15393        rc = bxe_prev_unload_uncommon(sc);
15394        if (rc != BXE_PREV_WAIT_NEEDED) {
15395            break;
15396        }
15397
15398        DELAY(20000);
15399    } while (--time_counter);
15400
15401    if (!time_counter || rc) {
15402        BLOGE(sc, "Failed to unload previous driver!"
15403            " time_counter %d rc %d\n", time_counter, rc);
15404        rc = -1;
15405    }
15406
15407    return (rc);
15408}
15409
15410void
15411bxe_dcbx_set_state(struct bxe_softc *sc,
15412                   uint8_t          dcb_on,
15413                   uint32_t         dcbx_enabled)
15414{
15415    if (!CHIP_IS_E1x(sc)) {
15416        sc->dcb_state = dcb_on;
15417        sc->dcbx_enabled = dcbx_enabled;
15418    } else {
15419        sc->dcb_state = FALSE;
15420        sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15421    }
15422    BLOGD(sc, DBG_LOAD,
15423          "DCB state [%s:%s]\n",
15424          dcb_on ? "ON" : "OFF",
15425          (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15426          (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15427          (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15428          "on-chip with negotiation" : "invalid");
15429}
15430
15431/* must be called after sriov-enable */
15432static int
15433bxe_set_qm_cid_count(struct bxe_softc *sc)
15434{
15435    int cid_count = BXE_L2_MAX_CID(sc);
15436
15437    if (IS_SRIOV(sc)) {
15438        cid_count += BXE_VF_CIDS;
15439    }
15440
15441    if (CNIC_SUPPORT(sc)) {
15442        cid_count += CNIC_CID_MAX;
15443    }
15444
15445    return (roundup(cid_count, QM_CID_ROUND));
15446}
15447
15448static void
15449bxe_init_multi_cos(struct bxe_softc *sc)
15450{
15451    int pri, cos;
15452
15453    uint32_t pri_map = 0; /* XXX change to user config */
15454
15455    for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15456        cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15457        if (cos < sc->max_cos) {
15458            sc->prio_to_cos[pri] = cos;
15459        } else {
15460            BLOGW(sc, "Invalid COS %d for priority %d "
15461                      "(max COS is %d), setting to 0\n",
15462                  cos, pri, (sc->max_cos - 1));
15463            sc->prio_to_cos[pri] = 0;
15464        }
15465    }
15466}
15467
15468static int
15469bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15470{
15471    struct bxe_softc *sc;
15472    int error, result;
15473
15474    result = 0;
15475    error = sysctl_handle_int(oidp, &result, 0, req);
15476
15477    if (error || !req->newptr) {
15478        return (error);
15479    }
15480
15481    if (result == 1) {
15482        uint32_t  temp;
15483        sc = (struct bxe_softc *)arg1;
15484
15485        BLOGI(sc, "... dumping driver state ...\n");
15486        temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15487        BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15488    }
15489
15490    return (error);
15491}
15492
15493static int
15494bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15495{
15496    struct bxe_softc *sc = (struct bxe_softc *)arg1;
15497    uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15498    uint32_t *offset;
15499    uint64_t value = 0;
15500    int index = (int)arg2;
15501
15502    if (index >= BXE_NUM_ETH_STATS) {
15503        BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15504        return (-1);
15505    }
15506
15507    offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15508
15509    switch (bxe_eth_stats_arr[index].size) {
15510    case 4:
15511        value = (uint64_t)*offset;
15512        break;
15513    case 8:
15514        value = HILO_U64(*offset, *(offset + 1));
15515        break;
15516    default:
15517        BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15518              index, bxe_eth_stats_arr[index].size);
15519        return (-1);
15520    }
15521
15522    return (sysctl_handle_64(oidp, &value, 0, req));
15523}
15524
15525static int
15526bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15527{
15528    struct bxe_softc *sc = (struct bxe_softc *)arg1;
15529    uint32_t *eth_stats;
15530    uint32_t *offset;
15531    uint64_t value = 0;
15532    uint32_t q_stat = (uint32_t)arg2;
15533    uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15534    uint32_t index = (q_stat & 0xffff);
15535
15536    eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15537
15538    if (index >= BXE_NUM_ETH_Q_STATS) {
15539        BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15540        return (-1);
15541    }
15542
15543    offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15544
15545    switch (bxe_eth_q_stats_arr[index].size) {
15546    case 4:
15547        value = (uint64_t)*offset;
15548        break;
15549    case 8:
15550        value = HILO_U64(*offset, *(offset + 1));
15551        break;
15552    default:
15553        BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15554              index, bxe_eth_q_stats_arr[index].size);
15555        return (-1);
15556    }
15557
15558    return (sysctl_handle_64(oidp, &value, 0, req));
15559}
15560
15561static void
15562bxe_add_sysctls(struct bxe_softc *sc)
15563{
15564    struct sysctl_ctx_list *ctx;
15565    struct sysctl_oid_list *children;
15566    struct sysctl_oid *queue_top, *queue;
15567    struct sysctl_oid_list *queue_top_children, *queue_children;
15568    char queue_num_buf[32];
15569    uint32_t q_stat;
15570    int i, j;
15571
15572    ctx = device_get_sysctl_ctx(sc->dev);
15573    children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15574
15575    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15576                      CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15577                      "version");
15578
15579    snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15580             BCM_5710_FW_MAJOR_VERSION,
15581             BCM_5710_FW_MINOR_VERSION,
15582             BCM_5710_FW_REVISION_VERSION,
15583             BCM_5710_FW_ENGINEERING_VERSION);
15584
15585    snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15586        ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15587         (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15588         (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15589         (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15590                                                                "Unknown"));
15591    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15592                    CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15593                    "multifunction vnics per port");
15594
15595    snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15596        ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15597         (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15598         (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15599                                              "???GT/s"),
15600        sc->devinfo.pcie_link_width);
15601
15602    sc->debug = bxe_debug;
15603
15604#if __FreeBSD_version >= 900000
15605    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15606                      CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15607                      "bootcode version");
15608    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15609                      CTLFLAG_RD, sc->fw_ver_str, 0,
15610                      "firmware version");
15611    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15612                      CTLFLAG_RD, sc->mf_mode_str, 0,
15613                      "multifunction mode");
15614    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15615                      CTLFLAG_RD, sc->mac_addr_str, 0,
15616                      "mac address");
15617    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15618                      CTLFLAG_RD, sc->pci_link_str, 0,
15619                      "pci link status");
15620    SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
15621                    CTLFLAG_RW, &sc->debug,
15622                    "debug logging mode");
15623#else
15624    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15625                      CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15626                      "bootcode version");
15627    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15628                      CTLFLAG_RD, &sc->fw_ver_str, 0,
15629                      "firmware version");
15630    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15631                      CTLFLAG_RD, &sc->mf_mode_str, 0,
15632                      "multifunction mode");
15633    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15634                      CTLFLAG_RD, &sc->mac_addr_str, 0,
15635                      "mac address");
15636    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15637                      CTLFLAG_RD, &sc->pci_link_str, 0,
15638                      "pci link status");
15639    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15640                    CTLFLAG_RW, &sc->debug, 0,
15641                    "debug logging mode");
15642#endif /* #if __FreeBSD_version >= 900000 */
15643
15644    sc->trigger_grcdump = 0;
15645    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
15646                   CTLFLAG_RW, &sc->trigger_grcdump, 0,
15647                   "trigger grcdump should be invoked"
15648                   "  before collecting grcdump");
15649
15650    sc->grcdump_started = 0;
15651    sc->grcdump_done = 0;
15652    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15653                   CTLFLAG_RD, &sc->grcdump_done, 0,
15654                   "set by driver when grcdump is done");
15655
15656    sc->rx_budget = bxe_rx_budget;
15657    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15658                    CTLFLAG_RW, &sc->rx_budget, 0,
15659                    "rx processing budget");
15660
15661    SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15662                    CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15663                    bxe_sysctl_state, "IU", "dump driver state");
15664
15665    for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15666        SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15667                        bxe_eth_stats_arr[i].string,
15668                        CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15669                        bxe_sysctl_eth_stat, "LU",
15670                        bxe_eth_stats_arr[i].string);
15671    }
15672
15673    /* add a new parent node for all queues "dev.bxe.#.queue" */
15674    queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15675                                CTLFLAG_RD, NULL, "queue");
15676    queue_top_children = SYSCTL_CHILDREN(queue_top);
15677
15678    for (i = 0; i < sc->num_queues; i++) {
15679        /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15680        snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15681        queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15682                                queue_num_buf, CTLFLAG_RD, NULL,
15683                                "single queue");
15684        queue_children = SYSCTL_CHILDREN(queue);
15685
15686        for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15687            q_stat = ((i << 16) | j);
15688            SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15689                            bxe_eth_q_stats_arr[j].string,
15690                            CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15691                            bxe_sysctl_eth_q_stat, "LU",
15692                            bxe_eth_q_stats_arr[j].string);
15693        }
15694    }
15695}
15696
15697static int
15698bxe_alloc_buf_rings(struct bxe_softc *sc)
15699{
15700#if __FreeBSD_version >= 901504
15701
15702    int i;
15703    struct bxe_fastpath *fp;
15704
15705    for (i = 0; i < sc->num_queues; i++) {
15706
15707        fp = &sc->fp[i];
15708
15709        fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15710                                   M_NOWAIT, &fp->tx_mtx);
15711        if (fp->tx_br == NULL)
15712            return (-1);
15713    }
15714#endif
15715    return (0);
15716}
15717
15718static void
15719bxe_free_buf_rings(struct bxe_softc *sc)
15720{
15721#if __FreeBSD_version >= 901504
15722
15723    int i;
15724    struct bxe_fastpath *fp;
15725
15726    for (i = 0; i < sc->num_queues; i++) {
15727
15728        fp = &sc->fp[i];
15729
15730        if (fp->tx_br) {
15731            buf_ring_free(fp->tx_br, M_DEVBUF);
15732            fp->tx_br = NULL;
15733        }
15734    }
15735
15736#endif
15737}
15738
15739static void
15740bxe_init_fp_mutexs(struct bxe_softc *sc)
15741{
15742    int i;
15743    struct bxe_fastpath *fp;
15744
15745    for (i = 0; i < sc->num_queues; i++) {
15746
15747        fp = &sc->fp[i];
15748
15749        snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15750            "bxe%d_fp%d_tx_lock", sc->unit, i);
15751        mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15752
15753        snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15754            "bxe%d_fp%d_rx_lock", sc->unit, i);
15755        mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15756    }
15757}
15758
15759static void
15760bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15761{
15762    int i;
15763    struct bxe_fastpath *fp;
15764
15765    for (i = 0; i < sc->num_queues; i++) {
15766
15767        fp = &sc->fp[i];
15768
15769        if (mtx_initialized(&fp->tx_mtx)) {
15770            mtx_destroy(&fp->tx_mtx);
15771        }
15772
15773        if (mtx_initialized(&fp->rx_mtx)) {
15774            mtx_destroy(&fp->rx_mtx);
15775        }
15776    }
15777}
15778
15779
15780/*
15781 * Device attach function.
15782 *
15783 * Allocates device resources, performs secondary chip identification, and
15784 * initializes driver instance variables. This function is called from driver
15785 * load after a successful probe.
15786 *
15787 * Returns:
15788 *   0 = Success, >0 = Failure
15789 */
15790static int
15791bxe_attach(device_t dev)
15792{
15793    struct bxe_softc *sc;
15794
15795    sc = device_get_softc(dev);
15796
15797    BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15798
15799    sc->state = BXE_STATE_CLOSED;
15800
15801    sc->dev  = dev;
15802    sc->unit = device_get_unit(dev);
15803
15804    BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
15805
15806    sc->pcie_bus    = pci_get_bus(dev);
15807    sc->pcie_device = pci_get_slot(dev);
15808    sc->pcie_func   = pci_get_function(dev);
15809
15810    /* enable bus master capability */
15811    pci_enable_busmaster(dev);
15812
15813    /* get the BARs */
15814    if (bxe_allocate_bars(sc) != 0) {
15815        return (ENXIO);
15816    }
15817
15818    /* initialize the mutexes */
15819    bxe_init_mutexes(sc);
15820
15821    /* prepare the periodic callout */
15822    callout_init(&sc->periodic_callout, 0);
15823
15824    /* prepare the chip taskqueue */
15825    sc->chip_tq_flags = CHIP_TQ_NONE;
15826    snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
15827             "bxe%d_chip_tq", sc->unit);
15828    TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
15829    sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
15830                                   taskqueue_thread_enqueue,
15831                                   &sc->chip_tq);
15832    taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
15833                            "%s", sc->chip_tq_name);
15834
15835    /* get device info and set params */
15836    if (bxe_get_device_info(sc) != 0) {
15837        BLOGE(sc, "getting device info\n");
15838        bxe_deallocate_bars(sc);
15839        pci_disable_busmaster(dev);
15840        return (ENXIO);
15841    }
15842
15843    /* get final misc params */
15844    bxe_get_params(sc);
15845
15846    /* set the default MTU (changed via ifconfig) */
15847    sc->mtu = ETHERMTU;
15848
15849    bxe_set_modes_bitmap(sc);
15850
15851    /* XXX
15852     * If in AFEX mode and the function is configured for FCoE
15853     * then bail... no L2 allowed.
15854     */
15855
15856    /* get phy settings from shmem and 'and' against admin settings */
15857    bxe_get_phy_info(sc);
15858
15859    /* initialize the FreeBSD ifnet interface */
15860    if (bxe_init_ifnet(sc) != 0) {
15861        bxe_release_mutexes(sc);
15862        bxe_deallocate_bars(sc);
15863        pci_disable_busmaster(dev);
15864        return (ENXIO);
15865    }
15866
15867    if (bxe_add_cdev(sc) != 0) {
15868        if (sc->ifp != NULL) {
15869            ether_ifdetach(sc->ifp);
15870        }
15871        ifmedia_removeall(&sc->ifmedia);
15872        bxe_release_mutexes(sc);
15873        bxe_deallocate_bars(sc);
15874        pci_disable_busmaster(dev);
15875        return (ENXIO);
15876    }
15877
15878    /* allocate device interrupts */
15879    if (bxe_interrupt_alloc(sc) != 0) {
15880        bxe_del_cdev(sc);
15881        if (sc->ifp != NULL) {
15882            ether_ifdetach(sc->ifp);
15883        }
15884        ifmedia_removeall(&sc->ifmedia);
15885        bxe_release_mutexes(sc);
15886        bxe_deallocate_bars(sc);
15887        pci_disable_busmaster(dev);
15888        return (ENXIO);
15889    }
15890
15891    bxe_init_fp_mutexs(sc);
15892
15893    if (bxe_alloc_buf_rings(sc) != 0) {
15894	bxe_free_buf_rings(sc);
15895        bxe_interrupt_free(sc);
15896        bxe_del_cdev(sc);
15897        if (sc->ifp != NULL) {
15898            ether_ifdetach(sc->ifp);
15899        }
15900        ifmedia_removeall(&sc->ifmedia);
15901        bxe_release_mutexes(sc);
15902        bxe_deallocate_bars(sc);
15903        pci_disable_busmaster(dev);
15904        return (ENXIO);
15905    }
15906
15907    /* allocate ilt */
15908    if (bxe_alloc_ilt_mem(sc) != 0) {
15909	bxe_free_buf_rings(sc);
15910        bxe_interrupt_free(sc);
15911        bxe_del_cdev(sc);
15912        if (sc->ifp != NULL) {
15913            ether_ifdetach(sc->ifp);
15914        }
15915        ifmedia_removeall(&sc->ifmedia);
15916        bxe_release_mutexes(sc);
15917        bxe_deallocate_bars(sc);
15918        pci_disable_busmaster(dev);
15919        return (ENXIO);
15920    }
15921
15922    /* allocate the host hardware/software hsi structures */
15923    if (bxe_alloc_hsi_mem(sc) != 0) {
15924        bxe_free_ilt_mem(sc);
15925	bxe_free_buf_rings(sc);
15926        bxe_interrupt_free(sc);
15927        bxe_del_cdev(sc);
15928        if (sc->ifp != NULL) {
15929            ether_ifdetach(sc->ifp);
15930        }
15931        ifmedia_removeall(&sc->ifmedia);
15932        bxe_release_mutexes(sc);
15933        bxe_deallocate_bars(sc);
15934        pci_disable_busmaster(dev);
15935        return (ENXIO);
15936    }
15937
15938    /* need to reset chip if UNDI was active */
15939    if (IS_PF(sc) && !BXE_NOMCP(sc)) {
15940        /* init fw_seq */
15941        sc->fw_seq =
15942            (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
15943             DRV_MSG_SEQ_NUMBER_MASK);
15944        BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
15945        bxe_prev_unload(sc);
15946    }
15947
15948#if 1
15949    /* XXX */
15950    bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
15951#else
15952    if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
15953        SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
15954        SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
15955        SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
15956        bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
15957        bxe_dcbx_init_params(sc);
15958    } else {
15959        bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
15960    }
15961#endif
15962
15963    /* calculate qm_cid_count */
15964    sc->qm_cid_count = bxe_set_qm_cid_count(sc);
15965    BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
15966
15967    sc->max_cos = 1;
15968    bxe_init_multi_cos(sc);
15969
15970    bxe_add_sysctls(sc);
15971
15972    return (0);
15973}
15974
15975/*
15976 * Device detach function.
15977 *
15978 * Stops the controller, resets the controller, and releases resources.
15979 *
15980 * Returns:
15981 *   0 = Success, >0 = Failure
15982 */
15983static int
15984bxe_detach(device_t dev)
15985{
15986    struct bxe_softc *sc;
15987    if_t ifp;
15988
15989    sc = device_get_softc(dev);
15990
15991    BLOGD(sc, DBG_LOAD, "Starting detach...\n");
15992
15993    ifp = sc->ifp;
15994    if (ifp != NULL && if_vlantrunkinuse(ifp)) {
15995        BLOGE(sc, "Cannot detach while VLANs are in use.\n");
15996        return(EBUSY);
15997    }
15998
15999    bxe_del_cdev(sc);
16000
16001    /* stop the periodic callout */
16002    bxe_periodic_stop(sc);
16003
16004    /* stop the chip taskqueue */
16005    atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16006    if (sc->chip_tq) {
16007        taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16008        taskqueue_free(sc->chip_tq);
16009        sc->chip_tq = NULL;
16010    }
16011
16012    /* stop and reset the controller if it was open */
16013    if (sc->state != BXE_STATE_CLOSED) {
16014        BXE_CORE_LOCK(sc);
16015        bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16016        sc->state = BXE_STATE_DISABLED;
16017        BXE_CORE_UNLOCK(sc);
16018    }
16019
16020    /* release the network interface */
16021    if (ifp != NULL) {
16022        ether_ifdetach(ifp);
16023    }
16024    ifmedia_removeall(&sc->ifmedia);
16025
16026    /* XXX do the following based on driver state... */
16027
16028    /* free the host hardware/software hsi structures */
16029    bxe_free_hsi_mem(sc);
16030
16031    /* free ilt */
16032    bxe_free_ilt_mem(sc);
16033
16034    bxe_free_buf_rings(sc);
16035
16036    /* release the interrupts */
16037    bxe_interrupt_free(sc);
16038
16039    /* Release the mutexes*/
16040    bxe_destroy_fp_mutexs(sc);
16041    bxe_release_mutexes(sc);
16042
16043
16044    /* Release the PCIe BAR mapped memory */
16045    bxe_deallocate_bars(sc);
16046
16047    /* Release the FreeBSD interface. */
16048    if (sc->ifp != NULL) {
16049        if_free(sc->ifp);
16050    }
16051
16052    pci_disable_busmaster(dev);
16053
16054    return (0);
16055}
16056
16057/*
16058 * Device shutdown function.
16059 *
16060 * Stops and resets the controller.
16061 *
16062 * Returns:
16063 *   Nothing
16064 */
16065static int
16066bxe_shutdown(device_t dev)
16067{
16068    struct bxe_softc *sc;
16069
16070    sc = device_get_softc(dev);
16071
16072    BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16073
16074    /* stop the periodic callout */
16075    bxe_periodic_stop(sc);
16076
16077    BXE_CORE_LOCK(sc);
16078    bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16079    BXE_CORE_UNLOCK(sc);
16080
16081    return (0);
16082}
16083
16084void
16085bxe_igu_ack_sb(struct bxe_softc *sc,
16086               uint8_t          igu_sb_id,
16087               uint8_t          segment,
16088               uint16_t         index,
16089               uint8_t          op,
16090               uint8_t          update)
16091{
16092    uint32_t igu_addr = sc->igu_base_addr;
16093    igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16094    bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16095}
16096
16097static void
16098bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16099                     uint8_t          func,
16100                     uint8_t          idu_sb_id,
16101                     uint8_t          is_pf)
16102{
16103    uint32_t data, ctl, cnt = 100;
16104    uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16105    uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16106    uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16107    uint32_t sb_bit =  1 << (idu_sb_id%32);
16108    uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16109    uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16110
16111    /* Not supported in BC mode */
16112    if (CHIP_INT_MODE_IS_BC(sc)) {
16113        return;
16114    }
16115
16116    data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16117             IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16118            IGU_REGULAR_CLEANUP_SET |
16119            IGU_REGULAR_BCLEANUP);
16120
16121    ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16122           (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16123           (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16124
16125    BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16126            data, igu_addr_data);
16127    REG_WR(sc, igu_addr_data, data);
16128
16129    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16130                      BUS_SPACE_BARRIER_WRITE);
16131    mb();
16132
16133    BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16134            ctl, igu_addr_ctl);
16135    REG_WR(sc, igu_addr_ctl, ctl);
16136
16137    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16138                      BUS_SPACE_BARRIER_WRITE);
16139    mb();
16140
16141    /* wait for clean up to finish */
16142    while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16143        DELAY(20000);
16144    }
16145
16146    if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16147        BLOGD(sc, DBG_LOAD,
16148              "Unable to finish IGU cleanup: "
16149              "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16150              idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16151    }
16152}
16153
16154static void
16155bxe_igu_clear_sb(struct bxe_softc *sc,
16156                 uint8_t          idu_sb_id)
16157{
16158    bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16159}
16160
16161
16162
16163
16164
16165
16166
16167/*******************/
16168/* ECORE CALLBACKS */
16169/*******************/
16170
16171static void
16172bxe_reset_common(struct bxe_softc *sc)
16173{
16174    uint32_t val = 0x1400;
16175
16176    /* reset_common */
16177    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16178
16179    if (CHIP_IS_E3(sc)) {
16180        val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16181        val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16182    }
16183
16184    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16185}
16186
16187static void
16188bxe_common_init_phy(struct bxe_softc *sc)
16189{
16190    uint32_t shmem_base[2];
16191    uint32_t shmem2_base[2];
16192
16193    /* Avoid common init in case MFW supports LFA */
16194    if (SHMEM2_RD(sc, size) >
16195        (uint32_t)offsetof(struct shmem2_region,
16196                           lfa_host_addr[SC_PORT(sc)])) {
16197        return;
16198    }
16199
16200    shmem_base[0]  = sc->devinfo.shmem_base;
16201    shmem2_base[0] = sc->devinfo.shmem2_base;
16202
16203    if (!CHIP_IS_E1x(sc)) {
16204        shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16205        shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16206    }
16207
16208    bxe_acquire_phy_lock(sc);
16209    elink_common_init_phy(sc, shmem_base, shmem2_base,
16210                          sc->devinfo.chip_id, 0);
16211    bxe_release_phy_lock(sc);
16212}
16213
16214static void
16215bxe_pf_disable(struct bxe_softc *sc)
16216{
16217    uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16218
16219    val &= ~IGU_PF_CONF_FUNC_EN;
16220
16221    REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16222    REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16223    REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16224}
16225
16226static void
16227bxe_init_pxp(struct bxe_softc *sc)
16228{
16229    uint16_t devctl;
16230    int r_order, w_order;
16231
16232    devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16233
16234    BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16235
16236    w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16237
16238    if (sc->mrrs == -1) {
16239        r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16240    } else {
16241        BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16242        r_order = sc->mrrs;
16243    }
16244
16245    ecore_init_pxp_arb(sc, r_order, w_order);
16246}
16247
16248static uint32_t
16249bxe_get_pretend_reg(struct bxe_softc *sc)
16250{
16251    uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16252    uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16253    return (base + (SC_ABS_FUNC(sc)) * stride);
16254}
16255
16256/*
16257 * Called only on E1H or E2.
16258 * When pretending to be PF, the pretend value is the function number 0..7.
16259 * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16260 * combination.
16261 */
16262static int
16263bxe_pretend_func(struct bxe_softc *sc,
16264                 uint16_t         pretend_func_val)
16265{
16266    uint32_t pretend_reg;
16267
16268    if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16269        return (-1);
16270    }
16271
16272    /* get my own pretend register */
16273    pretend_reg = bxe_get_pretend_reg(sc);
16274    REG_WR(sc, pretend_reg, pretend_func_val);
16275    REG_RD(sc, pretend_reg);
16276    return (0);
16277}
16278
16279static void
16280bxe_iov_init_dmae(struct bxe_softc *sc)
16281{
16282    return;
16283}
16284
16285static void
16286bxe_iov_init_dq(struct bxe_softc *sc)
16287{
16288    return;
16289}
16290
16291/* send a NIG loopback debug packet */
16292static void
16293bxe_lb_pckt(struct bxe_softc *sc)
16294{
16295    uint32_t wb_write[3];
16296
16297    /* Ethernet source and destination addresses */
16298    wb_write[0] = 0x55555555;
16299    wb_write[1] = 0x55555555;
16300    wb_write[2] = 0x20;     /* SOP */
16301    REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16302
16303    /* NON-IP protocol */
16304    wb_write[0] = 0x09000000;
16305    wb_write[1] = 0x55555555;
16306    wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16307    REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16308}
16309
16310/*
16311 * Some of the internal memories are not directly readable from the driver.
16312 * To test them we send debug packets.
16313 */
16314static int
16315bxe_int_mem_test(struct bxe_softc *sc)
16316{
16317    int factor;
16318    int count, i;
16319    uint32_t val = 0;
16320
16321    if (CHIP_REV_IS_FPGA(sc)) {
16322        factor = 120;
16323    } else if (CHIP_REV_IS_EMUL(sc)) {
16324        factor = 200;
16325    } else {
16326        factor = 1;
16327    }
16328
16329    /* disable inputs of parser neighbor blocks */
16330    REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16331    REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16332    REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16333    REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16334
16335    /*  write 0 to parser credits for CFC search request */
16336    REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16337
16338    /* send Ethernet packet */
16339    bxe_lb_pckt(sc);
16340
16341    /* TODO do i reset NIG statistic? */
16342    /* Wait until NIG register shows 1 packet of size 0x10 */
16343    count = 1000 * factor;
16344    while (count) {
16345        bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16346        val = *BXE_SP(sc, wb_data[0]);
16347        if (val == 0x10) {
16348            break;
16349        }
16350
16351        DELAY(10000);
16352        count--;
16353    }
16354
16355    if (val != 0x10) {
16356        BLOGE(sc, "NIG timeout val=0x%x\n", val);
16357        return (-1);
16358    }
16359
16360    /* wait until PRS register shows 1 packet */
16361    count = (1000 * factor);
16362    while (count) {
16363        val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16364        if (val == 1) {
16365            break;
16366        }
16367
16368        DELAY(10000);
16369        count--;
16370    }
16371
16372    if (val != 0x1) {
16373        BLOGE(sc, "PRS timeout val=0x%x\n", val);
16374        return (-2);
16375    }
16376
16377    /* Reset and init BRB, PRS */
16378    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16379    DELAY(50000);
16380    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16381    DELAY(50000);
16382    ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16383    ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16384
16385    /* Disable inputs of parser neighbor blocks */
16386    REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16387    REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16388    REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16389    REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16390
16391    /* Write 0 to parser credits for CFC search request */
16392    REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16393
16394    /* send 10 Ethernet packets */
16395    for (i = 0; i < 10; i++) {
16396        bxe_lb_pckt(sc);
16397    }
16398
16399    /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16400    count = (1000 * factor);
16401    while (count) {
16402        bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16403        val = *BXE_SP(sc, wb_data[0]);
16404        if (val == 0xb0) {
16405            break;
16406        }
16407
16408        DELAY(10000);
16409        count--;
16410    }
16411
16412    if (val != 0xb0) {
16413        BLOGE(sc, "NIG timeout val=0x%x\n", val);
16414        return (-3);
16415    }
16416
16417    /* Wait until PRS register shows 2 packets */
16418    val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16419    if (val != 2) {
16420        BLOGE(sc, "PRS timeout val=0x%x\n", val);
16421    }
16422
16423    /* Write 1 to parser credits for CFC search request */
16424    REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16425
16426    /* Wait until PRS register shows 3 packets */
16427    DELAY(10000 * factor);
16428
16429    /* Wait until NIG register shows 1 packet of size 0x10 */
16430    val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16431    if (val != 3) {
16432        BLOGE(sc, "PRS timeout val=0x%x\n", val);
16433    }
16434
16435    /* clear NIG EOP FIFO */
16436    for (i = 0; i < 11; i++) {
16437        REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16438    }
16439
16440    val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16441    if (val != 1) {
16442        BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16443        return (-4);
16444    }
16445
16446    /* Reset and init BRB, PRS, NIG */
16447    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16448    DELAY(50000);
16449    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16450    DELAY(50000);
16451    ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16452    ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16453    if (!CNIC_SUPPORT(sc)) {
16454        /* set NIC mode */
16455        REG_WR(sc, PRS_REG_NIC_MODE, 1);
16456    }
16457
16458    /* Enable inputs of parser neighbor blocks */
16459    REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16460    REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16461    REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16462    REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16463
16464    return (0);
16465}
16466
16467static void
16468bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16469{
16470    int is_required;
16471    uint32_t val;
16472    int port;
16473
16474    is_required = 0;
16475    val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16476           SHARED_HW_CFG_FAN_FAILURE_MASK);
16477
16478    if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16479        is_required = 1;
16480    }
16481    /*
16482     * The fan failure mechanism is usually related to the PHY type since
16483     * the power consumption of the board is affected by the PHY. Currently,
16484     * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16485     */
16486    else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16487        for (port = PORT_0; port < PORT_MAX; port++) {
16488            is_required |= elink_fan_failure_det_req(sc,
16489                                                     sc->devinfo.shmem_base,
16490                                                     sc->devinfo.shmem2_base,
16491                                                     port);
16492        }
16493    }
16494
16495    BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16496
16497    if (is_required == 0) {
16498        return;
16499    }
16500
16501    /* Fan failure is indicated by SPIO 5 */
16502    bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16503
16504    /* set to active low mode */
16505    val = REG_RD(sc, MISC_REG_SPIO_INT);
16506    val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16507    REG_WR(sc, MISC_REG_SPIO_INT, val);
16508
16509    /* enable interrupt to signal the IGU */
16510    val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16511    val |= MISC_SPIO_SPIO5;
16512    REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16513}
16514
16515static void
16516bxe_enable_blocks_attention(struct bxe_softc *sc)
16517{
16518    uint32_t val;
16519
16520    REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16521    if (!CHIP_IS_E1x(sc)) {
16522        REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16523    } else {
16524        REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16525    }
16526    REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16527    REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16528    /*
16529     * mask read length error interrupts in brb for parser
16530     * (parsing unit and 'checksum and crc' unit)
16531     * these errors are legal (PU reads fixed length and CAC can cause
16532     * read length error on truncated packets)
16533     */
16534    REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16535    REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16536    REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16537    REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16538    REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16539    REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16540/*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16541/*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16542    REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16543    REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16544    REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16545/*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16546/*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16547    REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16548    REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16549    REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16550    REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16551/*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16552/*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16553
16554    val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16555           PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16556           PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16557    if (!CHIP_IS_E1x(sc)) {
16558        val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16559                PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16560    }
16561    REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16562
16563    REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16564    REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16565    REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16566/*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16567
16568    if (!CHIP_IS_E1x(sc)) {
16569        /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16570        REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16571    }
16572
16573    REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16574    REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16575/*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16576    REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16577}
16578
16579/**
16580 * bxe_init_hw_common - initialize the HW at the COMMON phase.
16581 *
16582 * @sc:     driver handle
16583 */
16584static int
16585bxe_init_hw_common(struct bxe_softc *sc)
16586{
16587    uint8_t abs_func_id;
16588    uint32_t val;
16589
16590    BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16591          SC_ABS_FUNC(sc));
16592
16593    /*
16594     * take the RESET lock to protect undi_unload flow from accessing
16595     * registers while we are resetting the chip
16596     */
16597    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16598
16599    bxe_reset_common(sc);
16600
16601    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16602
16603    val = 0xfffc;
16604    if (CHIP_IS_E3(sc)) {
16605        val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16606        val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16607    }
16608
16609    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16610
16611    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16612
16613    ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16614    BLOGD(sc, DBG_LOAD, "after misc block init\n");
16615
16616    if (!CHIP_IS_E1x(sc)) {
16617        /*
16618         * 4-port mode or 2-port mode we need to turn off master-enable for
16619         * everyone. After that we turn it back on for self. So, we disregard
16620         * multi-function, and always disable all functions on the given path,
16621         * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16622         */
16623        for (abs_func_id = SC_PATH(sc);
16624             abs_func_id < (E2_FUNC_MAX * 2);
16625             abs_func_id += 2) {
16626            if (abs_func_id == SC_ABS_FUNC(sc)) {
16627                REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16628                continue;
16629            }
16630
16631            bxe_pretend_func(sc, abs_func_id);
16632
16633            /* clear pf enable */
16634            bxe_pf_disable(sc);
16635
16636            bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16637        }
16638    }
16639
16640    BLOGD(sc, DBG_LOAD, "after pf disable\n");
16641
16642    ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16643
16644    if (CHIP_IS_E1(sc)) {
16645        /*
16646         * enable HW interrupt from PXP on USDM overflow
16647         * bit 16 on INT_MASK_0
16648         */
16649        REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16650    }
16651
16652    ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16653    bxe_init_pxp(sc);
16654
16655#ifdef __BIG_ENDIAN
16656    REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16657    REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16658    REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16659    REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16660    REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16661    /* make sure this value is 0 */
16662    REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16663
16664    //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16665    REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16666    REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16667    REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16668    REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16669#endif
16670
16671    ecore_ilt_init_page_size(sc, INITOP_SET);
16672
16673    if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16674        REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16675    }
16676
16677    /* let the HW do it's magic... */
16678    DELAY(100000);
16679
16680    /* finish PXP init */
16681    val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16682    if (val != 1) {
16683        BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16684            val);
16685        return (-1);
16686    }
16687    val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16688    if (val != 1) {
16689        BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16690        return (-1);
16691    }
16692
16693    BLOGD(sc, DBG_LOAD, "after pxp init\n");
16694
16695    /*
16696     * Timer bug workaround for E2 only. We need to set the entire ILT to have
16697     * entries with value "0" and valid bit on. This needs to be done by the
16698     * first PF that is loaded in a path (i.e. common phase)
16699     */
16700    if (!CHIP_IS_E1x(sc)) {
16701/*
16702 * In E2 there is a bug in the timers block that can cause function 6 / 7
16703 * (i.e. vnic3) to start even if it is marked as "scan-off".
16704 * This occurs when a different function (func2,3) is being marked
16705 * as "scan-off". Real-life scenario for example: if a driver is being
16706 * load-unloaded while func6,7 are down. This will cause the timer to access
16707 * the ilt, translate to a logical address and send a request to read/write.
16708 * Since the ilt for the function that is down is not valid, this will cause
16709 * a translation error which is unrecoverable.
16710 * The Workaround is intended to make sure that when this happens nothing
16711 * fatal will occur. The workaround:
16712 *  1.  First PF driver which loads on a path will:
16713 *      a.  After taking the chip out of reset, by using pretend,
16714 *          it will write "0" to the following registers of
16715 *          the other vnics.
16716 *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16717 *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16718 *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16719 *          And for itself it will write '1' to
16720 *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16721 *          dmae-operations (writing to pram for example.)
16722 *          note: can be done for only function 6,7 but cleaner this
16723 *            way.
16724 *      b.  Write zero+valid to the entire ILT.
16725 *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16726 *          VNIC3 (of that port). The range allocated will be the
16727 *          entire ILT. This is needed to prevent  ILT range error.
16728 *  2.  Any PF driver load flow:
16729 *      a.  ILT update with the physical addresses of the allocated
16730 *          logical pages.
16731 *      b.  Wait 20msec. - note that this timeout is needed to make
16732 *          sure there are no requests in one of the PXP internal
16733 *          queues with "old" ILT addresses.
16734 *      c.  PF enable in the PGLC.
16735 *      d.  Clear the was_error of the PF in the PGLC. (could have
16736 *          occurred while driver was down)
16737 *      e.  PF enable in the CFC (WEAK + STRONG)
16738 *      f.  Timers scan enable
16739 *  3.  PF driver unload flow:
16740 *      a.  Clear the Timers scan_en.
16741 *      b.  Polling for scan_on=0 for that PF.
16742 *      c.  Clear the PF enable bit in the PXP.
16743 *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16744 *      e.  Write zero+valid to all ILT entries (The valid bit must
16745 *          stay set)
16746 *      f.  If this is VNIC 3 of a port then also init
16747 *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16748 *          to the last enrty in the ILT.
16749 *
16750 *      Notes:
16751 *      Currently the PF error in the PGLC is non recoverable.
16752 *      In the future the there will be a recovery routine for this error.
16753 *      Currently attention is masked.
16754 *      Having an MCP lock on the load/unload process does not guarantee that
16755 *      there is no Timer disable during Func6/7 enable. This is because the
16756 *      Timers scan is currently being cleared by the MCP on FLR.
16757 *      Step 2.d can be done only for PF6/7 and the driver can also check if
16758 *      there is error before clearing it. But the flow above is simpler and
16759 *      more general.
16760 *      All ILT entries are written by zero+valid and not just PF6/7
16761 *      ILT entries since in the future the ILT entries allocation for
16762 *      PF-s might be dynamic.
16763 */
16764        struct ilt_client_info ilt_cli;
16765        struct ecore_ilt ilt;
16766
16767        memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16768        memset(&ilt, 0, sizeof(struct ecore_ilt));
16769
16770        /* initialize dummy TM client */
16771        ilt_cli.start      = 0;
16772        ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16773        ilt_cli.client_num = ILT_CLIENT_TM;
16774
16775        /*
16776         * Step 1: set zeroes to all ilt page entries with valid bit on
16777         * Step 2: set the timers first/last ilt entry to point
16778         * to the entire range to prevent ILT range error for 3rd/4th
16779         * vnic (this code assumes existence of the vnic)
16780         *
16781         * both steps performed by call to ecore_ilt_client_init_op()
16782         * with dummy TM client
16783         *
16784         * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16785         * and his brother are split registers
16786         */
16787
16788        bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16789        ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16790        bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16791
16792        REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16793        REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16794        REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16795    }
16796
16797    REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16798    REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16799
16800    if (!CHIP_IS_E1x(sc)) {
16801        int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16802                     (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
16803
16804        ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
16805        ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
16806
16807        /* let the HW do it's magic... */
16808        do {
16809            DELAY(200000);
16810            val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
16811        } while (factor-- && (val != 1));
16812
16813        if (val != 1) {
16814            BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
16815            return (-1);
16816        }
16817    }
16818
16819    BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
16820
16821    ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
16822
16823    bxe_iov_init_dmae(sc);
16824
16825    /* clean the DMAE memory */
16826    sc->dmae_ready = 1;
16827    ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
16828
16829    ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
16830
16831    ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
16832
16833    ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
16834
16835    ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
16836
16837    bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
16838    bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
16839    bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
16840    bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
16841
16842    ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
16843
16844    /* QM queues pointers table */
16845    ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
16846
16847    /* soft reset pulse */
16848    REG_WR(sc, QM_REG_SOFT_RESET, 1);
16849    REG_WR(sc, QM_REG_SOFT_RESET, 0);
16850
16851    if (CNIC_SUPPORT(sc))
16852        ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
16853
16854    ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
16855    REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
16856    if (!CHIP_REV_IS_SLOW(sc)) {
16857        /* enable hw interrupt from doorbell Q */
16858        REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16859    }
16860
16861    ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16862
16863    ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16864    REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
16865
16866    if (!CHIP_IS_E1(sc)) {
16867        REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
16868    }
16869
16870    if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
16871        if (IS_MF_AFEX(sc)) {
16872            /*
16873             * configure that AFEX and VLAN headers must be
16874             * received in AFEX mode
16875             */
16876            REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
16877            REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
16878            REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
16879            REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
16880            REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
16881        } else {
16882            /*
16883             * Bit-map indicating which L2 hdrs may appear
16884             * after the basic Ethernet header
16885             */
16886            REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
16887                   sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
16888        }
16889    }
16890
16891    ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
16892    ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
16893    ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
16894    ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
16895
16896    if (!CHIP_IS_E1x(sc)) {
16897        /* reset VFC memories */
16898        REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
16899               VFC_MEMORIES_RST_REG_CAM_RST |
16900               VFC_MEMORIES_RST_REG_RAM_RST);
16901        REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
16902               VFC_MEMORIES_RST_REG_CAM_RST |
16903               VFC_MEMORIES_RST_REG_RAM_RST);
16904
16905        DELAY(20000);
16906    }
16907
16908    ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
16909    ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
16910    ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
16911    ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
16912
16913    /* sync semi rtc */
16914    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
16915           0x80000000);
16916    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
16917           0x80000000);
16918
16919    ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
16920    ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
16921    ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
16922
16923    if (!CHIP_IS_E1x(sc)) {
16924        if (IS_MF_AFEX(sc)) {
16925            /*
16926             * configure that AFEX and VLAN headers must be
16927             * sent in AFEX mode
16928             */
16929            REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
16930            REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
16931            REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
16932            REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
16933            REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
16934        } else {
16935            REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
16936                   sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
16937        }
16938    }
16939
16940    REG_WR(sc, SRC_REG_SOFT_RST, 1);
16941
16942    ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
16943
16944    if (CNIC_SUPPORT(sc)) {
16945        REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
16946        REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
16947        REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
16948        REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
16949        REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
16950        REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
16951        REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
16952        REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
16953        REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
16954        REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
16955    }
16956    REG_WR(sc, SRC_REG_SOFT_RST, 0);
16957
16958    if (sizeof(union cdu_context) != 1024) {
16959        /* we currently assume that a context is 1024 bytes */
16960        BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
16961              (long)sizeof(union cdu_context));
16962    }
16963
16964    ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
16965    val = (4 << 24) + (0 << 12) + 1024;
16966    REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
16967
16968    ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
16969
16970    REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
16971    /* enable context validation interrupt from CFC */
16972    REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16973
16974    /* set the thresholds to prevent CFC/CDU race */
16975    REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
16976    ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
16977
16978    if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
16979        REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
16980    }
16981
16982    ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
16983    ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
16984
16985    /* Reset PCIE errors for debug */
16986    REG_WR(sc, 0x2814, 0xffffffff);
16987    REG_WR(sc, 0x3820, 0xffffffff);
16988
16989    if (!CHIP_IS_E1x(sc)) {
16990        REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
16991               (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
16992                PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
16993        REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
16994               (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
16995                PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
16996                PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
16997        REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
16998               (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
16999                PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17000                PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17001    }
17002
17003    ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17004
17005    if (!CHIP_IS_E1(sc)) {
17006        /* in E3 this done in per-port section */
17007        if (!CHIP_IS_E3(sc))
17008            REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17009    }
17010
17011    if (CHIP_IS_E1H(sc)) {
17012        /* not applicable for E2 (and above ...) */
17013        REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17014    }
17015
17016    if (CHIP_REV_IS_SLOW(sc)) {
17017        DELAY(200000);
17018    }
17019
17020    /* finish CFC init */
17021    val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17022    if (val != 1) {
17023        BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17024        return (-1);
17025    }
17026    val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17027    if (val != 1) {
17028        BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17029        return (-1);
17030    }
17031    val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17032    if (val != 1) {
17033        BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17034        return (-1);
17035    }
17036    REG_WR(sc, CFC_REG_DEBUG0, 0);
17037
17038    if (CHIP_IS_E1(sc)) {
17039        /* read NIG statistic to see if this is our first up since powerup */
17040        bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17041        val = *BXE_SP(sc, wb_data[0]);
17042
17043        /* do internal memory self test */
17044        if ((val == 0) && bxe_int_mem_test(sc)) {
17045            BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17046            return (-1);
17047        }
17048    }
17049
17050    bxe_setup_fan_failure_detection(sc);
17051
17052    /* clear PXP2 attentions */
17053    REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17054
17055    bxe_enable_blocks_attention(sc);
17056
17057    if (!CHIP_REV_IS_SLOW(sc)) {
17058        ecore_enable_blocks_parity(sc);
17059    }
17060
17061    if (!BXE_NOMCP(sc)) {
17062        if (CHIP_IS_E1x(sc)) {
17063            bxe_common_init_phy(sc);
17064        }
17065    }
17066
17067    return (0);
17068}
17069
17070/**
17071 * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17072 *
17073 * @sc:     driver handle
17074 */
17075static int
17076bxe_init_hw_common_chip(struct bxe_softc *sc)
17077{
17078    int rc = bxe_init_hw_common(sc);
17079
17080    if (rc) {
17081        BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17082        return (rc);
17083    }
17084
17085    /* In E2 2-PORT mode, same ext phy is used for the two paths */
17086    if (!BXE_NOMCP(sc)) {
17087        bxe_common_init_phy(sc);
17088    }
17089
17090    return (0);
17091}
17092
17093static int
17094bxe_init_hw_port(struct bxe_softc *sc)
17095{
17096    int port = SC_PORT(sc);
17097    int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17098    uint32_t low, high;
17099    uint32_t val;
17100
17101    BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17102
17103    REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17104
17105    ecore_init_block(sc, BLOCK_MISC, init_phase);
17106    ecore_init_block(sc, BLOCK_PXP, init_phase);
17107    ecore_init_block(sc, BLOCK_PXP2, init_phase);
17108
17109    /*
17110     * Timers bug workaround: disables the pf_master bit in pglue at
17111     * common phase, we need to enable it here before any dmae access are
17112     * attempted. Therefore we manually added the enable-master to the
17113     * port phase (it also happens in the function phase)
17114     */
17115    if (!CHIP_IS_E1x(sc)) {
17116        REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17117    }
17118
17119    ecore_init_block(sc, BLOCK_ATC, init_phase);
17120    ecore_init_block(sc, BLOCK_DMAE, init_phase);
17121    ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17122    ecore_init_block(sc, BLOCK_QM, init_phase);
17123
17124    ecore_init_block(sc, BLOCK_TCM, init_phase);
17125    ecore_init_block(sc, BLOCK_UCM, init_phase);
17126    ecore_init_block(sc, BLOCK_CCM, init_phase);
17127    ecore_init_block(sc, BLOCK_XCM, init_phase);
17128
17129    /* QM cid (connection) count */
17130    ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17131
17132    if (CNIC_SUPPORT(sc)) {
17133        ecore_init_block(sc, BLOCK_TM, init_phase);
17134        REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17135        REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17136    }
17137
17138    ecore_init_block(sc, BLOCK_DORQ, init_phase);
17139
17140    ecore_init_block(sc, BLOCK_BRB1, init_phase);
17141
17142    if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17143        if (IS_MF(sc)) {
17144            low = (BXE_ONE_PORT(sc) ? 160 : 246);
17145        } else if (sc->mtu > 4096) {
17146            if (BXE_ONE_PORT(sc)) {
17147                low = 160;
17148            } else {
17149                val = sc->mtu;
17150                /* (24*1024 + val*4)/256 */
17151                low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17152            }
17153        } else {
17154            low = (BXE_ONE_PORT(sc) ? 80 : 160);
17155        }
17156        high = (low + 56); /* 14*1024/256 */
17157        REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17158        REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17159    }
17160
17161    if (CHIP_IS_MODE_4_PORT(sc)) {
17162        REG_WR(sc, SC_PORT(sc) ?
17163               BRB1_REG_MAC_GUARANTIED_1 :
17164               BRB1_REG_MAC_GUARANTIED_0, 40);
17165    }
17166
17167    ecore_init_block(sc, BLOCK_PRS, init_phase);
17168    if (CHIP_IS_E3B0(sc)) {
17169        if (IS_MF_AFEX(sc)) {
17170            /* configure headers for AFEX mode */
17171            REG_WR(sc, SC_PORT(sc) ?
17172                   PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17173                   PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17174            REG_WR(sc, SC_PORT(sc) ?
17175                   PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17176                   PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17177            REG_WR(sc, SC_PORT(sc) ?
17178                   PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17179                   PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17180        } else {
17181            /* Ovlan exists only if we are in multi-function +
17182             * switch-dependent mode, in switch-independent there
17183             * is no ovlan headers
17184             */
17185            REG_WR(sc, SC_PORT(sc) ?
17186                   PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17187                   PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17188                   (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17189        }
17190    }
17191
17192    ecore_init_block(sc, BLOCK_TSDM, init_phase);
17193    ecore_init_block(sc, BLOCK_CSDM, init_phase);
17194    ecore_init_block(sc, BLOCK_USDM, init_phase);
17195    ecore_init_block(sc, BLOCK_XSDM, init_phase);
17196
17197    ecore_init_block(sc, BLOCK_TSEM, init_phase);
17198    ecore_init_block(sc, BLOCK_USEM, init_phase);
17199    ecore_init_block(sc, BLOCK_CSEM, init_phase);
17200    ecore_init_block(sc, BLOCK_XSEM, init_phase);
17201
17202    ecore_init_block(sc, BLOCK_UPB, init_phase);
17203    ecore_init_block(sc, BLOCK_XPB, init_phase);
17204
17205    ecore_init_block(sc, BLOCK_PBF, init_phase);
17206
17207    if (CHIP_IS_E1x(sc)) {
17208        /* configure PBF to work without PAUSE mtu 9000 */
17209        REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17210
17211        /* update threshold */
17212        REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17213        /* update init credit */
17214        REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17215
17216        /* probe changes */
17217        REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17218        DELAY(50);
17219        REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17220    }
17221
17222    if (CNIC_SUPPORT(sc)) {
17223        ecore_init_block(sc, BLOCK_SRC, init_phase);
17224    }
17225
17226    ecore_init_block(sc, BLOCK_CDU, init_phase);
17227    ecore_init_block(sc, BLOCK_CFC, init_phase);
17228
17229    if (CHIP_IS_E1(sc)) {
17230        REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17231        REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17232    }
17233    ecore_init_block(sc, BLOCK_HC, init_phase);
17234
17235    ecore_init_block(sc, BLOCK_IGU, init_phase);
17236
17237    ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17238    /* init aeu_mask_attn_func_0/1:
17239     *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17240     *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17241     *             bits 4-7 are used for "per vn group attention" */
17242    val = IS_MF(sc) ? 0xF7 : 0x7;
17243    /* Enable DCBX attention for all but E1 */
17244    val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17245    REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17246
17247    ecore_init_block(sc, BLOCK_NIG, init_phase);
17248
17249    if (!CHIP_IS_E1x(sc)) {
17250        /* Bit-map indicating which L2 hdrs may appear after the
17251         * basic Ethernet header
17252         */
17253        if (IS_MF_AFEX(sc)) {
17254            REG_WR(sc, SC_PORT(sc) ?
17255                   NIG_REG_P1_HDRS_AFTER_BASIC :
17256                   NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17257        } else {
17258            REG_WR(sc, SC_PORT(sc) ?
17259                   NIG_REG_P1_HDRS_AFTER_BASIC :
17260                   NIG_REG_P0_HDRS_AFTER_BASIC,
17261                   IS_MF_SD(sc) ? 7 : 6);
17262        }
17263
17264        if (CHIP_IS_E3(sc)) {
17265            REG_WR(sc, SC_PORT(sc) ?
17266                   NIG_REG_LLH1_MF_MODE :
17267                   NIG_REG_LLH_MF_MODE, IS_MF(sc));
17268        }
17269    }
17270    if (!CHIP_IS_E3(sc)) {
17271        REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17272    }
17273
17274    if (!CHIP_IS_E1(sc)) {
17275        /* 0x2 disable mf_ov, 0x1 enable */
17276        REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17277               (IS_MF_SD(sc) ? 0x1 : 0x2));
17278
17279        if (!CHIP_IS_E1x(sc)) {
17280            val = 0;
17281            switch (sc->devinfo.mf_info.mf_mode) {
17282            case MULTI_FUNCTION_SD:
17283                val = 1;
17284                break;
17285            case MULTI_FUNCTION_SI:
17286            case MULTI_FUNCTION_AFEX:
17287                val = 2;
17288                break;
17289            }
17290
17291            REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17292                        NIG_REG_LLH0_CLS_TYPE), val);
17293        }
17294        REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17295        REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17296        REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17297    }
17298
17299    /* If SPIO5 is set to generate interrupts, enable it for this port */
17300    val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17301    if (val & MISC_SPIO_SPIO5) {
17302        uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17303                                    MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17304        val = REG_RD(sc, reg_addr);
17305        val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17306        REG_WR(sc, reg_addr, val);
17307    }
17308
17309    return (0);
17310}
17311
17312static uint32_t
17313bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17314                       uint32_t         reg,
17315                       uint32_t         expected,
17316                       uint32_t         poll_count)
17317{
17318    uint32_t cur_cnt = poll_count;
17319    uint32_t val;
17320
17321    while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17322        DELAY(FLR_WAIT_INTERVAL);
17323    }
17324
17325    return (val);
17326}
17327
17328static int
17329bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17330                              uint32_t         reg,
17331                              char             *msg,
17332                              uint32_t         poll_cnt)
17333{
17334    uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17335
17336    if (val != 0) {
17337        BLOGE(sc, "%s usage count=%d\n", msg, val);
17338        return (1);
17339    }
17340
17341    return (0);
17342}
17343
17344/* Common routines with VF FLR cleanup */
17345static uint32_t
17346bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17347{
17348    /* adjust polling timeout */
17349    if (CHIP_REV_IS_EMUL(sc)) {
17350        return (FLR_POLL_CNT * 2000);
17351    }
17352
17353    if (CHIP_REV_IS_FPGA(sc)) {
17354        return (FLR_POLL_CNT * 120);
17355    }
17356
17357    return (FLR_POLL_CNT);
17358}
17359
17360static int
17361bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17362                           uint32_t         poll_cnt)
17363{
17364    /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17365    if (bxe_flr_clnup_poll_hw_counter(sc,
17366                                      CFC_REG_NUM_LCIDS_INSIDE_PF,
17367                                      "CFC PF usage counter timed out",
17368                                      poll_cnt)) {
17369        return (1);
17370    }
17371
17372    /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17373    if (bxe_flr_clnup_poll_hw_counter(sc,
17374                                      DORQ_REG_PF_USAGE_CNT,
17375                                      "DQ PF usage counter timed out",
17376                                      poll_cnt)) {
17377        return (1);
17378    }
17379
17380    /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17381    if (bxe_flr_clnup_poll_hw_counter(sc,
17382                                      QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17383                                      "QM PF usage counter timed out",
17384                                      poll_cnt)) {
17385        return (1);
17386    }
17387
17388    /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17389    if (bxe_flr_clnup_poll_hw_counter(sc,
17390                                      TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17391                                      "Timers VNIC usage counter timed out",
17392                                      poll_cnt)) {
17393        return (1);
17394    }
17395
17396    if (bxe_flr_clnup_poll_hw_counter(sc,
17397                                      TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17398                                      "Timers NUM_SCANS usage counter timed out",
17399                                      poll_cnt)) {
17400        return (1);
17401    }
17402
17403    /* Wait DMAE PF usage counter to zero */
17404    if (bxe_flr_clnup_poll_hw_counter(sc,
17405                                      dmae_reg_go_c[INIT_DMAE_C(sc)],
17406                                      "DMAE dommand register timed out",
17407                                      poll_cnt)) {
17408        return (1);
17409    }
17410
17411    return (0);
17412}
17413
17414#define OP_GEN_PARAM(param)                                            \
17415    (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17416#define OP_GEN_TYPE(type)                                           \
17417    (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17418#define OP_GEN_AGG_VECT(index)                                             \
17419    (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17420
17421static int
17422bxe_send_final_clnup(struct bxe_softc *sc,
17423                     uint8_t          clnup_func,
17424                     uint32_t         poll_cnt)
17425{
17426    uint32_t op_gen_command = 0;
17427    uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17428                          CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17429    int ret = 0;
17430
17431    if (REG_RD(sc, comp_addr)) {
17432        BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17433        return (1);
17434    }
17435
17436    op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17437    op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17438    op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17439    op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17440
17441    BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17442    REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17443
17444    if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17445        BLOGE(sc, "FW final cleanup did not succeed\n");
17446        BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17447              (REG_RD(sc, comp_addr)));
17448        bxe_panic(sc, ("FLR cleanup failed\n"));
17449        return (1);
17450    }
17451
17452    /* Zero completion for nxt FLR */
17453    REG_WR(sc, comp_addr, 0);
17454
17455    return (ret);
17456}
17457
17458static void
17459bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17460                       struct pbf_pN_buf_regs *regs,
17461                       uint32_t               poll_count)
17462{
17463    uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17464    uint32_t cur_cnt = poll_count;
17465
17466    crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17467    crd = crd_start = REG_RD(sc, regs->crd);
17468    init_crd = REG_RD(sc, regs->init_crd);
17469
17470    BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17471    BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17472    BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17473
17474    while ((crd != init_crd) &&
17475           ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17476            (init_crd - crd_start))) {
17477        if (cur_cnt--) {
17478            DELAY(FLR_WAIT_INTERVAL);
17479            crd = REG_RD(sc, regs->crd);
17480            crd_freed = REG_RD(sc, regs->crd_freed);
17481        } else {
17482            BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17483            BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17484            BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17485            break;
17486        }
17487    }
17488
17489    BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17490          poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17491}
17492
17493static void
17494bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17495                       struct pbf_pN_cmd_regs *regs,
17496                       uint32_t               poll_count)
17497{
17498    uint32_t occup, to_free, freed, freed_start;
17499    uint32_t cur_cnt = poll_count;
17500
17501    occup = to_free = REG_RD(sc, regs->lines_occup);
17502    freed = freed_start = REG_RD(sc, regs->lines_freed);
17503
17504    BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17505    BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17506
17507    while (occup &&
17508           ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17509        if (cur_cnt--) {
17510            DELAY(FLR_WAIT_INTERVAL);
17511            occup = REG_RD(sc, regs->lines_occup);
17512            freed = REG_RD(sc, regs->lines_freed);
17513        } else {
17514            BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17515            BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17516            BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17517            break;
17518        }
17519    }
17520
17521    BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17522          poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17523}
17524
17525static void
17526bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17527{
17528    struct pbf_pN_cmd_regs cmd_regs[] = {
17529        {0, (CHIP_IS_E3B0(sc)) ?
17530            PBF_REG_TQ_OCCUPANCY_Q0 :
17531            PBF_REG_P0_TQ_OCCUPANCY,
17532            (CHIP_IS_E3B0(sc)) ?
17533            PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17534            PBF_REG_P0_TQ_LINES_FREED_CNT},
17535        {1, (CHIP_IS_E3B0(sc)) ?
17536            PBF_REG_TQ_OCCUPANCY_Q1 :
17537            PBF_REG_P1_TQ_OCCUPANCY,
17538            (CHIP_IS_E3B0(sc)) ?
17539            PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17540            PBF_REG_P1_TQ_LINES_FREED_CNT},
17541        {4, (CHIP_IS_E3B0(sc)) ?
17542            PBF_REG_TQ_OCCUPANCY_LB_Q :
17543            PBF_REG_P4_TQ_OCCUPANCY,
17544            (CHIP_IS_E3B0(sc)) ?
17545            PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17546            PBF_REG_P4_TQ_LINES_FREED_CNT}
17547    };
17548
17549    struct pbf_pN_buf_regs buf_regs[] = {
17550        {0, (CHIP_IS_E3B0(sc)) ?
17551            PBF_REG_INIT_CRD_Q0 :
17552            PBF_REG_P0_INIT_CRD ,
17553            (CHIP_IS_E3B0(sc)) ?
17554            PBF_REG_CREDIT_Q0 :
17555            PBF_REG_P0_CREDIT,
17556            (CHIP_IS_E3B0(sc)) ?
17557            PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17558            PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17559        {1, (CHIP_IS_E3B0(sc)) ?
17560            PBF_REG_INIT_CRD_Q1 :
17561            PBF_REG_P1_INIT_CRD,
17562            (CHIP_IS_E3B0(sc)) ?
17563            PBF_REG_CREDIT_Q1 :
17564            PBF_REG_P1_CREDIT,
17565            (CHIP_IS_E3B0(sc)) ?
17566            PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17567            PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17568        {4, (CHIP_IS_E3B0(sc)) ?
17569            PBF_REG_INIT_CRD_LB_Q :
17570            PBF_REG_P4_INIT_CRD,
17571            (CHIP_IS_E3B0(sc)) ?
17572            PBF_REG_CREDIT_LB_Q :
17573            PBF_REG_P4_CREDIT,
17574            (CHIP_IS_E3B0(sc)) ?
17575            PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17576            PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17577    };
17578
17579    int i;
17580
17581    /* Verify the command queues are flushed P0, P1, P4 */
17582    for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17583        bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17584    }
17585
17586    /* Verify the transmission buffers are flushed P0, P1, P4 */
17587    for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17588        bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17589    }
17590}
17591
17592static void
17593bxe_hw_enable_status(struct bxe_softc *sc)
17594{
17595    uint32_t val;
17596
17597    val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17598    BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17599
17600    val = REG_RD(sc, PBF_REG_DISABLE_PF);
17601    BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17602
17603    val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17604    BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17605
17606    val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17607    BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17608
17609    val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17610    BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17611
17612    val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17613    BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17614
17615    val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17616    BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17617
17618    val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17619    BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17620}
17621
17622static int
17623bxe_pf_flr_clnup(struct bxe_softc *sc)
17624{
17625    uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17626
17627    BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17628
17629    /* Re-enable PF target read access */
17630    REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17631
17632    /* Poll HW usage counters */
17633    BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17634    if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17635        return (-1);
17636    }
17637
17638    /* Zero the igu 'trailing edge' and 'leading edge' */
17639
17640    /* Send the FW cleanup command */
17641    if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17642        return (-1);
17643    }
17644
17645    /* ATC cleanup */
17646
17647    /* Verify TX hw is flushed */
17648    bxe_tx_hw_flushed(sc, poll_cnt);
17649
17650    /* Wait 100ms (not adjusted according to platform) */
17651    DELAY(100000);
17652
17653    /* Verify no pending pci transactions */
17654    if (bxe_is_pcie_pending(sc)) {
17655        BLOGE(sc, "PCIE Transactions still pending\n");
17656    }
17657
17658    /* Debug */
17659    bxe_hw_enable_status(sc);
17660
17661    /*
17662     * Master enable - Due to WB DMAE writes performed before this
17663     * register is re-initialized as part of the regular function init
17664     */
17665    REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17666
17667    return (0);
17668}
17669
17670static int
17671bxe_init_hw_func(struct bxe_softc *sc)
17672{
17673    int port = SC_PORT(sc);
17674    int func = SC_FUNC(sc);
17675    int init_phase = PHASE_PF0 + func;
17676    struct ecore_ilt *ilt = sc->ilt;
17677    uint16_t cdu_ilt_start;
17678    uint32_t addr, val;
17679    uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17680    int i, main_mem_width, rc;
17681
17682    BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17683
17684    /* FLR cleanup */
17685    if (!CHIP_IS_E1x(sc)) {
17686        rc = bxe_pf_flr_clnup(sc);
17687        if (rc) {
17688            BLOGE(sc, "FLR cleanup failed!\n");
17689            // XXX bxe_fw_dump(sc);
17690            // XXX bxe_idle_chk(sc);
17691            return (rc);
17692        }
17693    }
17694
17695    /* set MSI reconfigure capability */
17696    if (sc->devinfo.int_block == INT_BLOCK_HC) {
17697        addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17698        val = REG_RD(sc, addr);
17699        val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17700        REG_WR(sc, addr, val);
17701    }
17702
17703    ecore_init_block(sc, BLOCK_PXP, init_phase);
17704    ecore_init_block(sc, BLOCK_PXP2, init_phase);
17705
17706    ilt = sc->ilt;
17707    cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17708
17709    for (i = 0; i < L2_ILT_LINES(sc); i++) {
17710        ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17711        ilt->lines[cdu_ilt_start + i].page_mapping =
17712            sc->context[i].vcxt_dma.paddr;
17713        ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17714    }
17715    ecore_ilt_init_op(sc, INITOP_SET);
17716
17717    /* Set NIC mode */
17718    REG_WR(sc, PRS_REG_NIC_MODE, 1);
17719    BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17720
17721    if (!CHIP_IS_E1x(sc)) {
17722        uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17723
17724        /* Turn on a single ISR mode in IGU if driver is going to use
17725         * INT#x or MSI
17726         */
17727        if (sc->interrupt_mode != INTR_MODE_MSIX) {
17728            pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17729        }
17730
17731        /*
17732         * Timers workaround bug: function init part.
17733         * Need to wait 20msec after initializing ILT,
17734         * needed to make sure there are no requests in
17735         * one of the PXP internal queues with "old" ILT addresses
17736         */
17737        DELAY(20000);
17738
17739        /*
17740         * Master enable - Due to WB DMAE writes performed before this
17741         * register is re-initialized as part of the regular function
17742         * init
17743         */
17744        REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17745        /* Enable the function in IGU */
17746        REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17747    }
17748
17749    sc->dmae_ready = 1;
17750
17751    ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17752
17753    if (!CHIP_IS_E1x(sc))
17754        REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17755
17756    ecore_init_block(sc, BLOCK_ATC, init_phase);
17757    ecore_init_block(sc, BLOCK_DMAE, init_phase);
17758    ecore_init_block(sc, BLOCK_NIG, init_phase);
17759    ecore_init_block(sc, BLOCK_SRC, init_phase);
17760    ecore_init_block(sc, BLOCK_MISC, init_phase);
17761    ecore_init_block(sc, BLOCK_TCM, init_phase);
17762    ecore_init_block(sc, BLOCK_UCM, init_phase);
17763    ecore_init_block(sc, BLOCK_CCM, init_phase);
17764    ecore_init_block(sc, BLOCK_XCM, init_phase);
17765    ecore_init_block(sc, BLOCK_TSEM, init_phase);
17766    ecore_init_block(sc, BLOCK_USEM, init_phase);
17767    ecore_init_block(sc, BLOCK_CSEM, init_phase);
17768    ecore_init_block(sc, BLOCK_XSEM, init_phase);
17769
17770    if (!CHIP_IS_E1x(sc))
17771        REG_WR(sc, QM_REG_PF_EN, 1);
17772
17773    if (!CHIP_IS_E1x(sc)) {
17774        REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17775        REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17776        REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17777        REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17778    }
17779    ecore_init_block(sc, BLOCK_QM, init_phase);
17780
17781    ecore_init_block(sc, BLOCK_TM, init_phase);
17782    ecore_init_block(sc, BLOCK_DORQ, init_phase);
17783
17784    bxe_iov_init_dq(sc);
17785
17786    ecore_init_block(sc, BLOCK_BRB1, init_phase);
17787    ecore_init_block(sc, BLOCK_PRS, init_phase);
17788    ecore_init_block(sc, BLOCK_TSDM, init_phase);
17789    ecore_init_block(sc, BLOCK_CSDM, init_phase);
17790    ecore_init_block(sc, BLOCK_USDM, init_phase);
17791    ecore_init_block(sc, BLOCK_XSDM, init_phase);
17792    ecore_init_block(sc, BLOCK_UPB, init_phase);
17793    ecore_init_block(sc, BLOCK_XPB, init_phase);
17794    ecore_init_block(sc, BLOCK_PBF, init_phase);
17795    if (!CHIP_IS_E1x(sc))
17796        REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17797
17798    ecore_init_block(sc, BLOCK_CDU, init_phase);
17799
17800    ecore_init_block(sc, BLOCK_CFC, init_phase);
17801
17802    if (!CHIP_IS_E1x(sc))
17803        REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
17804
17805    if (IS_MF(sc)) {
17806        REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
17807        REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
17808    }
17809
17810    ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17811
17812    /* HC init per function */
17813    if (sc->devinfo.int_block == INT_BLOCK_HC) {
17814        if (CHIP_IS_E1H(sc)) {
17815            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17816
17817            REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17818            REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17819        }
17820        ecore_init_block(sc, BLOCK_HC, init_phase);
17821
17822    } else {
17823        int num_segs, sb_idx, prod_offset;
17824
17825        REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17826
17827        if (!CHIP_IS_E1x(sc)) {
17828            REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
17829            REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
17830        }
17831
17832        ecore_init_block(sc, BLOCK_IGU, init_phase);
17833
17834        if (!CHIP_IS_E1x(sc)) {
17835            int dsb_idx = 0;
17836            /**
17837             * Producer memory:
17838             * E2 mode: address 0-135 match to the mapping memory;
17839             * 136 - PF0 default prod; 137 - PF1 default prod;
17840             * 138 - PF2 default prod; 139 - PF3 default prod;
17841             * 140 - PF0 attn prod;    141 - PF1 attn prod;
17842             * 142 - PF2 attn prod;    143 - PF3 attn prod;
17843             * 144-147 reserved.
17844             *
17845             * E1.5 mode - In backward compatible mode;
17846             * for non default SB; each even line in the memory
17847             * holds the U producer and each odd line hold
17848             * the C producer. The first 128 producers are for
17849             * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
17850             * producers are for the DSB for each PF.
17851             * Each PF has five segments: (the order inside each
17852             * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
17853             * 132-135 C prods; 136-139 X prods; 140-143 T prods;
17854             * 144-147 attn prods;
17855             */
17856            /* non-default-status-blocks */
17857            num_segs = CHIP_INT_MODE_IS_BC(sc) ?
17858                IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
17859            for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
17860                prod_offset = (sc->igu_base_sb + sb_idx) *
17861                    num_segs;
17862
17863                for (i = 0; i < num_segs; i++) {
17864                    addr = IGU_REG_PROD_CONS_MEMORY +
17865                            (prod_offset + i) * 4;
17866                    REG_WR(sc, addr, 0);
17867                }
17868                /* send consumer update with value 0 */
17869                bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
17870                           USTORM_ID, 0, IGU_INT_NOP, 1);
17871                bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
17872            }
17873
17874            /* default-status-blocks */
17875            num_segs = CHIP_INT_MODE_IS_BC(sc) ?
17876                IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
17877
17878            if (CHIP_IS_MODE_4_PORT(sc))
17879                dsb_idx = SC_FUNC(sc);
17880            else
17881                dsb_idx = SC_VN(sc);
17882
17883            prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
17884                       IGU_BC_BASE_DSB_PROD + dsb_idx :
17885                       IGU_NORM_BASE_DSB_PROD + dsb_idx);
17886
17887            /*
17888             * igu prods come in chunks of E1HVN_MAX (4) -
17889             * does not matters what is the current chip mode
17890             */
17891            for (i = 0; i < (num_segs * E1HVN_MAX);
17892                 i += E1HVN_MAX) {
17893                addr = IGU_REG_PROD_CONS_MEMORY +
17894                            (prod_offset + i)*4;
17895                REG_WR(sc, addr, 0);
17896            }
17897            /* send consumer update with 0 */
17898            if (CHIP_INT_MODE_IS_BC(sc)) {
17899                bxe_ack_sb(sc, sc->igu_dsb_id,
17900                           USTORM_ID, 0, IGU_INT_NOP, 1);
17901                bxe_ack_sb(sc, sc->igu_dsb_id,
17902                           CSTORM_ID, 0, IGU_INT_NOP, 1);
17903                bxe_ack_sb(sc, sc->igu_dsb_id,
17904                           XSTORM_ID, 0, IGU_INT_NOP, 1);
17905                bxe_ack_sb(sc, sc->igu_dsb_id,
17906                           TSTORM_ID, 0, IGU_INT_NOP, 1);
17907                bxe_ack_sb(sc, sc->igu_dsb_id,
17908                           ATTENTION_ID, 0, IGU_INT_NOP, 1);
17909            } else {
17910                bxe_ack_sb(sc, sc->igu_dsb_id,
17911                           USTORM_ID, 0, IGU_INT_NOP, 1);
17912                bxe_ack_sb(sc, sc->igu_dsb_id,
17913                           ATTENTION_ID, 0, IGU_INT_NOP, 1);
17914            }
17915            bxe_igu_clear_sb(sc, sc->igu_dsb_id);
17916
17917            /* !!! these should become driver const once
17918               rf-tool supports split-68 const */
17919            REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
17920            REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
17921            REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
17922            REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
17923            REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
17924            REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
17925        }
17926    }
17927
17928    /* Reset PCIE errors for debug */
17929    REG_WR(sc, 0x2114, 0xffffffff);
17930    REG_WR(sc, 0x2120, 0xffffffff);
17931
17932    if (CHIP_IS_E1x(sc)) {
17933        main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
17934        main_mem_base = HC_REG_MAIN_MEMORY +
17935                SC_PORT(sc) * (main_mem_size * 4);
17936        main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
17937        main_mem_width = 8;
17938
17939        val = REG_RD(sc, main_mem_prty_clr);
17940        if (val) {
17941            BLOGD(sc, DBG_LOAD,
17942                  "Parity errors in HC block during function init (0x%x)!\n",
17943                  val);
17944        }
17945
17946        /* Clear "false" parity errors in MSI-X table */
17947        for (i = main_mem_base;
17948             i < main_mem_base + main_mem_size * 4;
17949             i += main_mem_width) {
17950            bxe_read_dmae(sc, i, main_mem_width / 4);
17951            bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
17952                           i, main_mem_width / 4);
17953        }
17954        /* Clear HC parity attention */
17955        REG_RD(sc, main_mem_prty_clr);
17956    }
17957
17958#if 1
17959    /* Enable STORMs SP logging */
17960    REG_WR8(sc, BAR_USTRORM_INTMEM +
17961           USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17962    REG_WR8(sc, BAR_TSTRORM_INTMEM +
17963           TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17964    REG_WR8(sc, BAR_CSTRORM_INTMEM +
17965           CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17966    REG_WR8(sc, BAR_XSTRORM_INTMEM +
17967           XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17968#endif
17969
17970    elink_phy_probe(&sc->link_params);
17971
17972    return (0);
17973}
17974
17975static void
17976bxe_link_reset(struct bxe_softc *sc)
17977{
17978    if (!BXE_NOMCP(sc)) {
17979	bxe_acquire_phy_lock(sc);
17980        elink_lfa_reset(&sc->link_params, &sc->link_vars);
17981	bxe_release_phy_lock(sc);
17982    } else {
17983        if (!CHIP_REV_IS_SLOW(sc)) {
17984            BLOGW(sc, "Bootcode is missing - cannot reset link\n");
17985        }
17986    }
17987}
17988
17989static void
17990bxe_reset_port(struct bxe_softc *sc)
17991{
17992    int port = SC_PORT(sc);
17993    uint32_t val;
17994
17995    /* reset physical Link */
17996    bxe_link_reset(sc);
17997
17998    REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17999
18000    /* Do not rcv packets to BRB */
18001    REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18002    /* Do not direct rcv packets that are not for MCP to the BRB */
18003    REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18004               NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18005
18006    /* Configure AEU */
18007    REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18008
18009    DELAY(100000);
18010
18011    /* Check for BRB port occupancy */
18012    val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18013    if (val) {
18014        BLOGD(sc, DBG_LOAD,
18015              "BRB1 is not empty, %d blocks are occupied\n", val);
18016    }
18017
18018    /* TODO: Close Doorbell port? */
18019}
18020
18021static void
18022bxe_ilt_wr(struct bxe_softc *sc,
18023           uint32_t         index,
18024           bus_addr_t       addr)
18025{
18026    int reg;
18027    uint32_t wb_write[2];
18028
18029    if (CHIP_IS_E1(sc)) {
18030        reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18031    } else {
18032        reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18033    }
18034
18035    wb_write[0] = ONCHIP_ADDR1(addr);
18036    wb_write[1] = ONCHIP_ADDR2(addr);
18037    REG_WR_DMAE(sc, reg, wb_write, 2);
18038}
18039
18040static void
18041bxe_clear_func_ilt(struct bxe_softc *sc,
18042                   uint32_t         func)
18043{
18044    uint32_t i, base = FUNC_ILT_BASE(func);
18045    for (i = base; i < base + ILT_PER_FUNC; i++) {
18046        bxe_ilt_wr(sc, i, 0);
18047    }
18048}
18049
18050static void
18051bxe_reset_func(struct bxe_softc *sc)
18052{
18053    struct bxe_fastpath *fp;
18054    int port = SC_PORT(sc);
18055    int func = SC_FUNC(sc);
18056    int i;
18057
18058    /* Disable the function in the FW */
18059    REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18060    REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18061    REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18062    REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18063
18064    /* FP SBs */
18065    FOR_EACH_ETH_QUEUE(sc, i) {
18066        fp = &sc->fp[i];
18067        REG_WR8(sc, BAR_CSTRORM_INTMEM +
18068                CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18069                SB_DISABLED);
18070    }
18071
18072    /* SP SB */
18073    REG_WR8(sc, BAR_CSTRORM_INTMEM +
18074            CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18075            SB_DISABLED);
18076
18077    for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18078        REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18079    }
18080
18081    /* Configure IGU */
18082    if (sc->devinfo.int_block == INT_BLOCK_HC) {
18083        REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18084        REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18085    } else {
18086        REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18087        REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18088    }
18089
18090    if (CNIC_LOADED(sc)) {
18091        /* Disable Timer scan */
18092        REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18093        /*
18094         * Wait for at least 10ms and up to 2 second for the timers
18095         * scan to complete
18096         */
18097        for (i = 0; i < 200; i++) {
18098            DELAY(10000);
18099            if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18100                break;
18101        }
18102    }
18103
18104    /* Clear ILT */
18105    bxe_clear_func_ilt(sc, func);
18106
18107    /*
18108     * Timers workaround bug for E2: if this is vnic-3,
18109     * we need to set the entire ilt range for this timers.
18110     */
18111    if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18112        struct ilt_client_info ilt_cli;
18113        /* use dummy TM client */
18114        memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18115        ilt_cli.start = 0;
18116        ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18117        ilt_cli.client_num = ILT_CLIENT_TM;
18118
18119        ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18120    }
18121
18122    /* this assumes that reset_port() called before reset_func()*/
18123    if (!CHIP_IS_E1x(sc)) {
18124        bxe_pf_disable(sc);
18125    }
18126
18127    sc->dmae_ready = 0;
18128}
18129
18130static int
18131bxe_gunzip_init(struct bxe_softc *sc)
18132{
18133    return (0);
18134}
18135
18136static void
18137bxe_gunzip_end(struct bxe_softc *sc)
18138{
18139    return;
18140}
18141
18142static int
18143bxe_init_firmware(struct bxe_softc *sc)
18144{
18145    if (CHIP_IS_E1(sc)) {
18146        ecore_init_e1_firmware(sc);
18147        sc->iro_array = e1_iro_arr;
18148    } else if (CHIP_IS_E1H(sc)) {
18149        ecore_init_e1h_firmware(sc);
18150        sc->iro_array = e1h_iro_arr;
18151    } else if (!CHIP_IS_E1x(sc)) {
18152        ecore_init_e2_firmware(sc);
18153        sc->iro_array = e2_iro_arr;
18154    } else {
18155        BLOGE(sc, "Unsupported chip revision\n");
18156        return (-1);
18157    }
18158
18159    return (0);
18160}
18161
18162static void
18163bxe_release_firmware(struct bxe_softc *sc)
18164{
18165    /* Do nothing */
18166    return;
18167}
18168
18169static int
18170ecore_gunzip(struct bxe_softc *sc,
18171             const uint8_t    *zbuf,
18172             int              len)
18173{
18174    /* XXX : Implement... */
18175    BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18176    return (FALSE);
18177}
18178
18179static void
18180ecore_reg_wr_ind(struct bxe_softc *sc,
18181                 uint32_t         addr,
18182                 uint32_t         val)
18183{
18184    bxe_reg_wr_ind(sc, addr, val);
18185}
18186
18187static void
18188ecore_write_dmae_phys_len(struct bxe_softc *sc,
18189                          bus_addr_t       phys_addr,
18190                          uint32_t         addr,
18191                          uint32_t         len)
18192{
18193    bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18194}
18195
18196void
18197ecore_storm_memset_struct(struct bxe_softc *sc,
18198                          uint32_t         addr,
18199                          size_t           size,
18200                          uint32_t         *data)
18201{
18202    uint8_t i;
18203    for (i = 0; i < size/4; i++) {
18204        REG_WR(sc, addr + (i * 4), data[i]);
18205    }
18206}
18207
18208
18209/*
18210 * character device - ioctl interface definitions
18211 */
18212
18213
18214#include "bxe_dump.h"
18215#include "bxe_ioctl.h"
18216#include <sys/conf.h>
18217
18218static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18219                struct thread *td);
18220
18221static struct cdevsw bxe_cdevsw = {
18222    .d_version = D_VERSION,
18223    .d_ioctl = bxe_eioctl,
18224    .d_name = "bxecnic",
18225};
18226
18227#define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18228
18229
18230#define DUMP_ALL_PRESETS        0x1FFF
18231#define DUMP_MAX_PRESETS        13
18232#define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18233#define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18234#define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18235#define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18236#define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18237
18238#define IS_REG_IN_PRESET(presets, idx)  \
18239                ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18240
18241
18242static int
18243bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18244{
18245    if (CHIP_IS_E1(sc))
18246        return dump_num_registers[0][preset-1];
18247    else if (CHIP_IS_E1H(sc))
18248        return dump_num_registers[1][preset-1];
18249    else if (CHIP_IS_E2(sc))
18250        return dump_num_registers[2][preset-1];
18251    else if (CHIP_IS_E3A0(sc))
18252        return dump_num_registers[3][preset-1];
18253    else if (CHIP_IS_E3B0(sc))
18254        return dump_num_registers[4][preset-1];
18255    else
18256        return 0;
18257}
18258
18259static int
18260bxe_get_total_regs_len32(struct bxe_softc *sc)
18261{
18262    uint32_t preset_idx;
18263    int regdump_len32 = 0;
18264
18265
18266    /* Calculate the total preset regs length */
18267    for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18268        regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18269    }
18270
18271    return regdump_len32;
18272}
18273
18274static const uint32_t *
18275__bxe_get_page_addr_ar(struct bxe_softc *sc)
18276{
18277    if (CHIP_IS_E2(sc))
18278        return page_vals_e2;
18279    else if (CHIP_IS_E3(sc))
18280        return page_vals_e3;
18281    else
18282        return NULL;
18283}
18284
18285static uint32_t
18286__bxe_get_page_reg_num(struct bxe_softc *sc)
18287{
18288    if (CHIP_IS_E2(sc))
18289        return PAGE_MODE_VALUES_E2;
18290    else if (CHIP_IS_E3(sc))
18291        return PAGE_MODE_VALUES_E3;
18292    else
18293        return 0;
18294}
18295
18296static const uint32_t *
18297__bxe_get_page_write_ar(struct bxe_softc *sc)
18298{
18299    if (CHIP_IS_E2(sc))
18300        return page_write_regs_e2;
18301    else if (CHIP_IS_E3(sc))
18302        return page_write_regs_e3;
18303    else
18304        return NULL;
18305}
18306
18307static uint32_t
18308__bxe_get_page_write_num(struct bxe_softc *sc)
18309{
18310    if (CHIP_IS_E2(sc))
18311        return PAGE_WRITE_REGS_E2;
18312    else if (CHIP_IS_E3(sc))
18313        return PAGE_WRITE_REGS_E3;
18314    else
18315        return 0;
18316}
18317
18318static const struct reg_addr *
18319__bxe_get_page_read_ar(struct bxe_softc *sc)
18320{
18321    if (CHIP_IS_E2(sc))
18322        return page_read_regs_e2;
18323    else if (CHIP_IS_E3(sc))
18324        return page_read_regs_e3;
18325    else
18326        return NULL;
18327}
18328
18329static uint32_t
18330__bxe_get_page_read_num(struct bxe_softc *sc)
18331{
18332    if (CHIP_IS_E2(sc))
18333        return PAGE_READ_REGS_E2;
18334    else if (CHIP_IS_E3(sc))
18335        return PAGE_READ_REGS_E3;
18336    else
18337        return 0;
18338}
18339
18340static bool
18341bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18342{
18343    if (CHIP_IS_E1(sc))
18344        return IS_E1_REG(reg_info->chips);
18345    else if (CHIP_IS_E1H(sc))
18346        return IS_E1H_REG(reg_info->chips);
18347    else if (CHIP_IS_E2(sc))
18348        return IS_E2_REG(reg_info->chips);
18349    else if (CHIP_IS_E3A0(sc))
18350        return IS_E3A0_REG(reg_info->chips);
18351    else if (CHIP_IS_E3B0(sc))
18352        return IS_E3B0_REG(reg_info->chips);
18353    else
18354        return 0;
18355}
18356
18357static bool
18358bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18359{
18360    if (CHIP_IS_E1(sc))
18361        return IS_E1_REG(wreg_info->chips);
18362    else if (CHIP_IS_E1H(sc))
18363        return IS_E1H_REG(wreg_info->chips);
18364    else if (CHIP_IS_E2(sc))
18365        return IS_E2_REG(wreg_info->chips);
18366    else if (CHIP_IS_E3A0(sc))
18367        return IS_E3A0_REG(wreg_info->chips);
18368    else if (CHIP_IS_E3B0(sc))
18369        return IS_E3B0_REG(wreg_info->chips);
18370    else
18371        return 0;
18372}
18373
18374/**
18375 * bxe_read_pages_regs - read "paged" registers
18376 *
18377 * @bp          device handle
18378 * @p           output buffer
18379 *
18380 * Reads "paged" memories: memories that may only be read by first writing to a
18381 * specific address ("write address") and then reading from a specific address
18382 * ("read address"). There may be more than one write address per "page" and
18383 * more than one read address per write address.
18384 */
18385static void
18386bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18387{
18388    uint32_t i, j, k, n;
18389
18390    /* addresses of the paged registers */
18391    const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18392    /* number of paged registers */
18393    int num_pages = __bxe_get_page_reg_num(sc);
18394    /* write addresses */
18395    const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18396    /* number of write addresses */
18397    int write_num = __bxe_get_page_write_num(sc);
18398    /* read addresses info */
18399    const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18400    /* number of read addresses */
18401    int read_num = __bxe_get_page_read_num(sc);
18402    uint32_t addr, size;
18403
18404    for (i = 0; i < num_pages; i++) {
18405        for (j = 0; j < write_num; j++) {
18406            REG_WR(sc, write_addr[j], page_addr[i]);
18407
18408            for (k = 0; k < read_num; k++) {
18409                if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18410                    size = read_addr[k].size;
18411                    for (n = 0; n < size; n++) {
18412                        addr = read_addr[k].addr + n*4;
18413                        *p++ = REG_RD(sc, addr);
18414                    }
18415                }
18416            }
18417        }
18418    }
18419    return;
18420}
18421
18422
18423static int
18424bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18425{
18426    uint32_t i, j, addr;
18427    const struct wreg_addr *wreg_addr_p = NULL;
18428
18429    if (CHIP_IS_E1(sc))
18430        wreg_addr_p = &wreg_addr_e1;
18431    else if (CHIP_IS_E1H(sc))
18432        wreg_addr_p = &wreg_addr_e1h;
18433    else if (CHIP_IS_E2(sc))
18434        wreg_addr_p = &wreg_addr_e2;
18435    else if (CHIP_IS_E3A0(sc))
18436        wreg_addr_p = &wreg_addr_e3;
18437    else if (CHIP_IS_E3B0(sc))
18438        wreg_addr_p = &wreg_addr_e3b0;
18439    else
18440        return (-1);
18441
18442    /* Read the idle_chk registers */
18443    for (i = 0; i < IDLE_REGS_COUNT; i++) {
18444        if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18445            IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18446            for (j = 0; j < idle_reg_addrs[i].size; j++)
18447                *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18448        }
18449    }
18450
18451    /* Read the regular registers */
18452    for (i = 0; i < REGS_COUNT; i++) {
18453        if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18454            IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18455            for (j = 0; j < reg_addrs[i].size; j++)
18456                *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18457        }
18458    }
18459
18460    /* Read the CAM registers */
18461    if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18462        IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18463        for (i = 0; i < wreg_addr_p->size; i++) {
18464            *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18465
18466            /* In case of wreg_addr register, read additional
18467               registers from read_regs array
18468             */
18469            for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18470                addr = *(wreg_addr_p->read_regs);
18471                *p++ = REG_RD(sc, addr + j*4);
18472            }
18473        }
18474    }
18475
18476    /* Paged registers are supported in E2 & E3 only */
18477    if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18478        /* Read "paged" registers */
18479        bxe_read_pages_regs(sc, p, preset);
18480    }
18481
18482    return 0;
18483}
18484
18485int
18486bxe_grc_dump(struct bxe_softc *sc)
18487{
18488    int rval = 0;
18489    uint32_t preset_idx;
18490    uint8_t *buf;
18491    uint32_t size;
18492    struct  dump_header *d_hdr;
18493    uint32_t i;
18494    uint32_t reg_val;
18495    uint32_t reg_addr;
18496    uint32_t cmd_offset;
18497    int context_size;
18498    int allocated;
18499    struct ecore_ilt *ilt = SC_ILT(sc);
18500    struct bxe_fastpath *fp;
18501    struct ilt_client_info *ilt_cli;
18502    int grc_dump_size;
18503
18504
18505    if (sc->grcdump_done || sc->grcdump_started)
18506	return (rval);
18507
18508    sc->grcdump_started = 1;
18509    BLOGI(sc, "Started collecting grcdump\n");
18510
18511    grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18512                sizeof(struct  dump_header);
18513
18514    sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18515
18516    if (sc->grc_dump == NULL) {
18517        BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
18518        return(ENOMEM);
18519    }
18520
18521
18522
18523    /* Disable parity attentions as long as following dump may
18524     * cause false alarms by reading never written registers. We
18525     * will re-enable parity attentions right after the dump.
18526     */
18527
18528    /* Disable parity on path 0 */
18529    bxe_pretend_func(sc, 0);
18530
18531    ecore_disable_blocks_parity(sc);
18532
18533    /* Disable parity on path 1 */
18534    bxe_pretend_func(sc, 1);
18535    ecore_disable_blocks_parity(sc);
18536
18537    /* Return to current function */
18538    bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18539
18540    buf = sc->grc_dump;
18541    d_hdr = sc->grc_dump;
18542
18543    d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18544    d_hdr->version = BNX2X_DUMP_VERSION;
18545    d_hdr->preset = DUMP_ALL_PRESETS;
18546
18547    if (CHIP_IS_E1(sc)) {
18548        d_hdr->dump_meta_data = DUMP_CHIP_E1;
18549    } else if (CHIP_IS_E1H(sc)) {
18550        d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18551    } else if (CHIP_IS_E2(sc)) {
18552        d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18553                (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18554    } else if (CHIP_IS_E3A0(sc)) {
18555        d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18556                (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18557    } else if (CHIP_IS_E3B0(sc)) {
18558        d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18559                (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18560    }
18561
18562    buf += sizeof(struct  dump_header);
18563
18564    for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18565
18566        /* Skip presets with IOR */
18567        if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18568            (preset_idx == 11))
18569            continue;
18570
18571        rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
18572
18573	if (rval)
18574            break;
18575
18576        size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18577
18578        buf += size;
18579    }
18580
18581    bxe_pretend_func(sc, 0);
18582    ecore_clear_blocks_parity(sc);
18583    ecore_enable_blocks_parity(sc);
18584
18585    bxe_pretend_func(sc, 1);
18586    ecore_clear_blocks_parity(sc);
18587    ecore_enable_blocks_parity(sc);
18588
18589    /* Return to current function */
18590    bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18591
18592
18593    context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
18594    for (i = 0, allocated = 0; allocated < context_size; i++) {
18595
18596        BLOGI(sc, "cdu_context i %d paddr %#jx vaddr %p size 0x%zx\n", i,
18597            (uintmax_t)sc->context[i].vcxt_dma.paddr,
18598            sc->context[i].vcxt_dma.vaddr,
18599            sc->context[i].size);
18600        allocated += sc->context[i].size;
18601    }
18602    BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
18603        (uintmax_t)sc->fw_stats_req_mapping,
18604        (uintmax_t)sc->fw_stats_data_mapping,
18605        sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
18606    BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
18607        (void *)sc->def_sb_dma.paddr, sc->def_sb,
18608        sizeof(struct host_sp_status_block));
18609    BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
18610        (uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
18611    BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
18612        (uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
18613        sizeof(struct bxe_slowpath));
18614    BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
18615        (uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
18616    BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
18617        (uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
18618        FW_BUF_SIZE);
18619    for (i = 0; i < sc->num_queues; i++) {
18620        fp = &sc->fp[i];
18621        BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18622            (uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
18623            sizeof(union bxe_host_hc_status_block));
18624        BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18625            (uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
18626            (BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
18627        BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18628            (uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
18629            (BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
18630        BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18631            (uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
18632            (BCM_PAGE_SIZE * RCQ_NUM_PAGES));
18633        BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18634            (uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
18635            (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
18636    }
18637
18638    ilt_cli = &ilt->clients[1];
18639    for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
18640        BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
18641            (uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
18642            ((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
18643    }
18644
18645
18646    cmd_offset = DMAE_REG_CMD_MEM;
18647    for (i = 0; i < 224; i++) {
18648        reg_addr = (cmd_offset +(i * 4));
18649        reg_val = REG_RD(sc, reg_addr);
18650        BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
18651            reg_addr, reg_val);
18652    }
18653
18654
18655    BLOGI(sc, "Collection of grcdump done\n");
18656    sc->grcdump_done = 1;
18657    return(rval);
18658}
18659
18660static int
18661bxe_add_cdev(struct bxe_softc *sc)
18662{
18663    sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
18664
18665    if (sc->eeprom == NULL) {
18666        BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
18667        return (-1);
18668    }
18669
18670    sc->ioctl_dev = make_dev(&bxe_cdevsw,
18671                            sc->ifp->if_dunit,
18672                            UID_ROOT,
18673                            GID_WHEEL,
18674                            0600,
18675                            "%s",
18676                            if_name(sc->ifp));
18677
18678    if (sc->ioctl_dev == NULL) {
18679        free(sc->eeprom, M_DEVBUF);
18680        sc->eeprom = NULL;
18681        return (-1);
18682    }
18683
18684    sc->ioctl_dev->si_drv1 = sc;
18685
18686    return (0);
18687}
18688
18689static void
18690bxe_del_cdev(struct bxe_softc *sc)
18691{
18692    if (sc->ioctl_dev != NULL)
18693        destroy_dev(sc->ioctl_dev);
18694
18695    if (sc->eeprom != NULL) {
18696        free(sc->eeprom, M_DEVBUF);
18697        sc->eeprom = NULL;
18698    }
18699    sc->ioctl_dev = NULL;
18700
18701    return;
18702}
18703
18704static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
18705{
18706
18707    if ((if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) == 0)
18708        return FALSE;
18709
18710    return TRUE;
18711}
18712
18713
18714static int
18715bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18716{
18717    int rval = 0;
18718
18719    if(!bxe_is_nvram_accessible(sc)) {
18720        BLOGW(sc, "Cannot access eeprom when interface is down\n");
18721        return (-EAGAIN);
18722    }
18723    rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
18724
18725
18726   return (rval);
18727}
18728
18729static int
18730bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18731{
18732    int rval = 0;
18733
18734    if(!bxe_is_nvram_accessible(sc)) {
18735        BLOGW(sc, "Cannot access eeprom when interface is down\n");
18736        return (-EAGAIN);
18737    }
18738    rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
18739
18740   return (rval);
18741}
18742
18743static int
18744bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
18745{
18746    int rval = 0;
18747
18748    switch (eeprom->eeprom_cmd) {
18749
18750    case BXE_EEPROM_CMD_SET_EEPROM:
18751
18752        rval = copyin(eeprom->eeprom_data, sc->eeprom,
18753                       eeprom->eeprom_data_len);
18754
18755        if (rval)
18756            break;
18757
18758        rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18759                       eeprom->eeprom_data_len);
18760        break;
18761
18762    case BXE_EEPROM_CMD_GET_EEPROM:
18763
18764        rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18765                       eeprom->eeprom_data_len);
18766
18767        if (rval) {
18768            break;
18769        }
18770
18771        rval = copyout(sc->eeprom, eeprom->eeprom_data,
18772                       eeprom->eeprom_data_len);
18773        break;
18774
18775    default:
18776            rval = EINVAL;
18777            break;
18778    }
18779
18780    if (rval) {
18781        BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
18782    }
18783
18784    return (rval);
18785}
18786
18787static int
18788bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
18789{
18790    uint32_t ext_phy_config;
18791    int port = SC_PORT(sc);
18792    int cfg_idx = bxe_get_link_cfg_idx(sc);
18793
18794    dev_p->supported = sc->port.supported[cfg_idx] |
18795            (sc->port.supported[cfg_idx ^ 1] &
18796            (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
18797    dev_p->advertising = sc->port.advertising[cfg_idx];
18798    if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
18799        ELINK_ETH_PHY_SFP_1G_FIBER) {
18800        dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
18801        dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
18802    }
18803    if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
18804        !(sc->flags & BXE_MF_FUNC_DIS)) {
18805        dev_p->duplex = sc->link_vars.duplex;
18806        if (IS_MF(sc) && !BXE_NOMCP(sc))
18807            dev_p->speed = bxe_get_mf_speed(sc);
18808        else
18809            dev_p->speed = sc->link_vars.line_speed;
18810    } else {
18811        dev_p->duplex = DUPLEX_UNKNOWN;
18812        dev_p->speed = SPEED_UNKNOWN;
18813    }
18814
18815    dev_p->port = bxe_media_detect(sc);
18816
18817    ext_phy_config = SHMEM_RD(sc,
18818                         dev_info.port_hw_config[port].external_phy_config);
18819    if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
18820        PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
18821        dev_p->phy_address =  sc->port.phy_addr;
18822    else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18823            PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
18824        ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18825            PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
18826        dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
18827    else
18828        dev_p->phy_address = 0;
18829
18830    if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
18831        dev_p->autoneg = AUTONEG_ENABLE;
18832    else
18833       dev_p->autoneg = AUTONEG_DISABLE;
18834
18835
18836    return 0;
18837}
18838
18839static int
18840bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18841        struct thread *td)
18842{
18843    struct bxe_softc    *sc;
18844    int                 rval = 0;
18845    device_t            pci_dev;
18846    bxe_grcdump_t       *dump = NULL;
18847    int grc_dump_size;
18848    bxe_drvinfo_t   *drv_infop = NULL;
18849    bxe_dev_setting_t  *dev_p;
18850    bxe_dev_setting_t  dev_set;
18851    bxe_get_regs_t  *reg_p;
18852    bxe_reg_rdw_t *reg_rdw_p;
18853    bxe_pcicfg_rdw_t *cfg_rdw_p;
18854    bxe_perm_mac_addr_t *mac_addr_p;
18855
18856
18857    if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
18858        return ENXIO;
18859
18860    pci_dev= sc->dev;
18861
18862    dump = (bxe_grcdump_t *)data;
18863
18864    switch(cmd) {
18865
18866        case BXE_GRC_DUMP_SIZE:
18867            dump->pci_func = sc->pcie_func;
18868            dump->grcdump_size =
18869                (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18870                     sizeof(struct  dump_header);
18871            break;
18872
18873        case BXE_GRC_DUMP:
18874
18875            grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18876                                sizeof(struct  dump_header);
18877            if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
18878                (dump->grcdump_size < grc_dump_size)) {
18879                rval = EINVAL;
18880                break;
18881            }
18882
18883            if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
18884                (!sc->grcdump_started)) {
18885                rval =  bxe_grc_dump(sc);
18886            }
18887
18888            if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
18889                (sc->grc_dump != NULL))  {
18890                dump->grcdump_dwords = grc_dump_size >> 2;
18891                rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
18892                free(sc->grc_dump, M_DEVBUF);
18893                sc->grc_dump = NULL;
18894                sc->grcdump_started = 0;
18895                sc->grcdump_done = 0;
18896            }
18897
18898            break;
18899
18900        case BXE_DRV_INFO:
18901            drv_infop = (bxe_drvinfo_t *)data;
18902            snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
18903            snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
18904                BXE_DRIVER_VERSION);
18905            snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
18906                sc->devinfo.bc_ver_str);
18907            snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
18908                "%s", sc->fw_ver_str);
18909            drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
18910            drv_infop->reg_dump_len =
18911                (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
18912                    + sizeof(struct  dump_header);
18913            snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
18914                sc->pcie_bus, sc->pcie_device, sc->pcie_func);
18915            break;
18916
18917        case BXE_DEV_SETTING:
18918            dev_p = (bxe_dev_setting_t *)data;
18919            bxe_get_settings(sc, &dev_set);
18920            dev_p->supported = dev_set.supported;
18921            dev_p->advertising = dev_set.advertising;
18922            dev_p->speed = dev_set.speed;
18923            dev_p->duplex = dev_set.duplex;
18924            dev_p->port = dev_set.port;
18925            dev_p->phy_address = dev_set.phy_address;
18926            dev_p->autoneg = dev_set.autoneg;
18927
18928            break;
18929
18930        case BXE_GET_REGS:
18931
18932            reg_p = (bxe_get_regs_t *)data;
18933            grc_dump_size = reg_p->reg_buf_len;
18934
18935            if((!sc->grcdump_done) && (!sc->grcdump_started)) {
18936                bxe_grc_dump(sc);
18937            }
18938            if((sc->grcdump_done) && (sc->grcdump_started) &&
18939                (sc->grc_dump != NULL))  {
18940                rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
18941                free(sc->grc_dump, M_DEVBUF);
18942                sc->grc_dump = NULL;
18943                sc->grcdump_started = 0;
18944                sc->grcdump_done = 0;
18945            }
18946
18947            break;
18948
18949        case BXE_RDW_REG:
18950            reg_rdw_p = (bxe_reg_rdw_t *)data;
18951            if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
18952                (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
18953                reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
18954
18955            if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
18956                (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
18957                REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
18958
18959            break;
18960
18961        case BXE_RDW_PCICFG:
18962            cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
18963            if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
18964
18965                cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
18966                                         cfg_rdw_p->cfg_width);
18967
18968            } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
18969                pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
18970                            cfg_rdw_p->cfg_width);
18971            } else {
18972                BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
18973            }
18974            break;
18975
18976        case BXE_MAC_ADDR:
18977            mac_addr_p = (bxe_perm_mac_addr_t *)data;
18978            snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
18979                sc->mac_addr_str);
18980            break;
18981
18982        case BXE_EEPROM:
18983            rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
18984            break;
18985
18986
18987        default:
18988            break;
18989    }
18990
18991    return (rval);
18992}
18993