bxe.c revision 298955
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: head/sys/dev/bxe/bxe.c 298955 2016-05-03 03:41:25Z pfg $");
29
30#define BXE_DRIVER_VERSION "1.78.81"
31
32#include "bxe.h"
33#include "ecore_sp.h"
34#include "ecore_init.h"
35#include "ecore_init_ops.h"
36
37#include "57710_int_offsets.h"
38#include "57711_int_offsets.h"
39#include "57712_int_offsets.h"
40
41/*
42 * CTLTYPE_U64 and sysctl_handle_64 were added in r217616. Define these
43 * explicitly here for older kernels that don't include this changeset.
44 */
45#ifndef CTLTYPE_U64
46#define CTLTYPE_U64      CTLTYPE_QUAD
47#define sysctl_handle_64 sysctl_handle_quad
48#endif
49
50/*
51 * CSUM_TCP_IPV6 and CSUM_UDP_IPV6 were added in r236170. Define these
52 * here as zero(0) for older kernels that don't include this changeset
53 * thereby masking the functionality.
54 */
55#ifndef CSUM_TCP_IPV6
56#define CSUM_TCP_IPV6 0
57#define CSUM_UDP_IPV6 0
58#endif
59
60/*
61 * pci_find_cap was added in r219865. Re-define this at pci_find_extcap
62 * for older kernels that don't include this changeset.
63 */
64#if __FreeBSD_version < 900035
65#define pci_find_cap pci_find_extcap
66#endif
67
68#define BXE_DEF_SB_ATT_IDX 0x0001
69#define BXE_DEF_SB_IDX     0x0002
70
71/*
72 * FLR Support - bxe_pf_flr_clnup() is called during nic_load in the per
73 * function HW initialization.
74 */
75#define FLR_WAIT_USEC     10000 /* 10 msecs */
76#define FLR_WAIT_INTERVAL 50    /* usecs */
77#define FLR_POLL_CNT      (FLR_WAIT_USEC / FLR_WAIT_INTERVAL) /* 200 */
78
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};
494
495static const struct {
496    uint32_t offset;
497    uint32_t size;
498    char string[STAT_NAME_LEN];
499} bxe_eth_q_stats_arr[] = {
500    { Q_STATS_OFFSET32(total_bytes_received_hi),
501                8, "rx_bytes" },
502    { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
503                8, "rx_ucast_packets" },
504    { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
505                8, "rx_mcast_packets" },
506    { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
507                8, "rx_bcast_packets" },
508    { Q_STATS_OFFSET32(no_buff_discard_hi),
509                8, "rx_discards" },
510    { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
511                8, "tx_bytes" },
512    { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
513                8, "tx_ucast_packets" },
514    { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
515                8, "tx_mcast_packets" },
516    { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
517                8, "tx_bcast_packets" },
518    { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
519                8, "tpa_aggregations" },
520    { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
521                8, "tpa_aggregated_frames"},
522    { Q_STATS_OFFSET32(total_tpa_bytes_hi),
523                8, "tpa_bytes"},
524    { Q_STATS_OFFSET32(rx_calls),
525                4, "rx_calls"},
526    { Q_STATS_OFFSET32(rx_pkts),
527                4, "rx_pkts"},
528    { Q_STATS_OFFSET32(rx_tpa_pkts),
529                4, "rx_tpa_pkts"},
530    { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
531                4, "rx_erroneous_jumbo_sge_pkts"},
532    { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
533                4, "rx_bxe_service_rxsgl"},
534    { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
535                4, "rx_jumbo_sge_pkts"},
536    { Q_STATS_OFFSET32(rx_soft_errors),
537                4, "rx_soft_errors"},
538    { Q_STATS_OFFSET32(rx_hw_csum_errors),
539                4, "rx_hw_csum_errors"},
540    { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
541                4, "rx_ofld_frames_csum_ip"},
542    { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
543                4, "rx_ofld_frames_csum_tcp_udp"},
544    { Q_STATS_OFFSET32(rx_budget_reached),
545                4, "rx_budget_reached"},
546    { Q_STATS_OFFSET32(tx_pkts),
547                4, "tx_pkts"},
548    { Q_STATS_OFFSET32(tx_soft_errors),
549                4, "tx_soft_errors"},
550    { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
551                4, "tx_ofld_frames_csum_ip"},
552    { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
553                4, "tx_ofld_frames_csum_tcp"},
554    { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
555                4, "tx_ofld_frames_csum_udp"},
556    { Q_STATS_OFFSET32(tx_ofld_frames_lso),
557                4, "tx_ofld_frames_lso"},
558    { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
559                4, "tx_ofld_frames_lso_hdr_splits"},
560    { Q_STATS_OFFSET32(tx_encap_failures),
561                4, "tx_encap_failures"},
562    { Q_STATS_OFFSET32(tx_hw_queue_full),
563                4, "tx_hw_queue_full"},
564    { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
565                4, "tx_hw_max_queue_depth"},
566    { Q_STATS_OFFSET32(tx_dma_mapping_failure),
567                4, "tx_dma_mapping_failure"},
568    { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
569                4, "tx_max_drbr_queue_depth"},
570    { Q_STATS_OFFSET32(tx_window_violation_std),
571                4, "tx_window_violation_std"},
572    { Q_STATS_OFFSET32(tx_window_violation_tso),
573                4, "tx_window_violation_tso"},
574    { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
575                4, "tx_chain_lost_mbuf"},
576    { Q_STATS_OFFSET32(tx_frames_deferred),
577                4, "tx_frames_deferred"},
578    { Q_STATS_OFFSET32(tx_queue_xoff),
579                4, "tx_queue_xoff"},
580    { Q_STATS_OFFSET32(mbuf_defrag_attempts),
581                4, "mbuf_defrag_attempts"},
582    { Q_STATS_OFFSET32(mbuf_defrag_failures),
583                4, "mbuf_defrag_failures"},
584    { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
585                4, "mbuf_rx_bd_alloc_failed"},
586    { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
587                4, "mbuf_rx_bd_mapping_failed"},
588    { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
589                4, "mbuf_rx_tpa_alloc_failed"},
590    { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
591                4, "mbuf_rx_tpa_mapping_failed"},
592    { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
593                4, "mbuf_rx_sge_alloc_failed"},
594    { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
595                4, "mbuf_rx_sge_mapping_failed"},
596    { Q_STATS_OFFSET32(mbuf_alloc_tx),
597                4, "mbuf_alloc_tx"},
598    { Q_STATS_OFFSET32(mbuf_alloc_rx),
599                4, "mbuf_alloc_rx"},
600    { Q_STATS_OFFSET32(mbuf_alloc_sge),
601                4, "mbuf_alloc_sge"},
602    { Q_STATS_OFFSET32(mbuf_alloc_tpa),
603                4, "mbuf_alloc_tpa"},
604    { Q_STATS_OFFSET32(tx_queue_full_return),
605                4, "tx_queue_full_return"}
606};
607
608#define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
609#define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
610
611
612static void    bxe_cmng_fns_init(struct bxe_softc *sc,
613                                 uint8_t          read_cfg,
614                                 uint8_t          cmng_type);
615static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
616static void    storm_memset_cmng(struct bxe_softc *sc,
617                                 struct cmng_init *cmng,
618                                 uint8_t          port);
619static void    bxe_set_reset_global(struct bxe_softc *sc);
620static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
621static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
622                                 int              engine);
623static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
624static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
625                                   uint8_t          *global,
626                                   uint8_t          print);
627static void    bxe_int_disable(struct bxe_softc *sc);
628static int     bxe_release_leader_lock(struct bxe_softc *sc);
629static void    bxe_pf_disable(struct bxe_softc *sc);
630static void    bxe_free_fp_buffers(struct bxe_softc *sc);
631static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
632                                      struct bxe_fastpath *fp,
633                                      uint16_t            rx_bd_prod,
634                                      uint16_t            rx_cq_prod,
635                                      uint16_t            rx_sge_prod);
636static void    bxe_link_report_locked(struct bxe_softc *sc);
637static void    bxe_link_report(struct bxe_softc *sc);
638static void    bxe_link_status_update(struct bxe_softc *sc);
639static void    bxe_periodic_callout_func(void *xsc);
640static void    bxe_periodic_start(struct bxe_softc *sc);
641static void    bxe_periodic_stop(struct bxe_softc *sc);
642static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
643                                    uint16_t prev_index,
644                                    uint16_t index);
645static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
646                                     int                 queue);
647static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
648                                     uint16_t            index);
649static uint8_t bxe_txeof(struct bxe_softc *sc,
650                         struct bxe_fastpath *fp);
651static void    bxe_task_fp(struct bxe_fastpath *fp);
652static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
653                                     struct mbuf      *m,
654                                     uint8_t          contents);
655static int     bxe_alloc_mem(struct bxe_softc *sc);
656static void    bxe_free_mem(struct bxe_softc *sc);
657static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
658static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
659static int     bxe_interrupt_attach(struct bxe_softc *sc);
660static void    bxe_interrupt_detach(struct bxe_softc *sc);
661static void    bxe_set_rx_mode(struct bxe_softc *sc);
662static int     bxe_init_locked(struct bxe_softc *sc);
663static int     bxe_stop_locked(struct bxe_softc *sc);
664static __noinline int bxe_nic_load(struct bxe_softc *sc,
665                                   int              load_mode);
666static __noinline int bxe_nic_unload(struct bxe_softc *sc,
667                                     uint32_t         unload_mode,
668                                     uint8_t          keep_link);
669
670static void bxe_handle_sp_tq(void *context, int pending);
671static void bxe_handle_fp_tq(void *context, int pending);
672
673static int bxe_add_cdev(struct bxe_softc *sc);
674static void bxe_del_cdev(struct bxe_softc *sc);
675static int bxe_alloc_buf_rings(struct bxe_softc *sc);
676static void bxe_free_buf_rings(struct bxe_softc *sc);
677
678/* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
679uint32_t
680calc_crc32(uint8_t  *crc32_packet,
681           uint32_t crc32_length,
682           uint32_t crc32_seed,
683           uint8_t  complement)
684{
685   uint32_t byte         = 0;
686   uint32_t bit          = 0;
687   uint8_t  msb          = 0;
688   uint32_t temp         = 0;
689   uint32_t shft         = 0;
690   uint8_t  current_byte = 0;
691   uint32_t crc32_result = crc32_seed;
692   const uint32_t CRC32_POLY = 0x1edc6f41;
693
694   if ((crc32_packet == NULL) ||
695       (crc32_length == 0) ||
696       ((crc32_length % 8) != 0))
697    {
698        return (crc32_result);
699    }
700
701    for (byte = 0; byte < crc32_length; byte = byte + 1)
702    {
703        current_byte = crc32_packet[byte];
704        for (bit = 0; bit < 8; bit = bit + 1)
705        {
706            /* msb = crc32_result[31]; */
707            msb = (uint8_t)(crc32_result >> 31);
708
709            crc32_result = crc32_result << 1;
710
711            /* it (msb != current_byte[bit]) */
712            if (msb != (0x1 & (current_byte >> bit)))
713            {
714                crc32_result = crc32_result ^ CRC32_POLY;
715                /* crc32_result[0] = 1 */
716                crc32_result |= 1;
717            }
718        }
719    }
720
721    /* Last step is to:
722     * 1. "mirror" every bit
723     * 2. swap the 4 bytes
724     * 3. complement each bit
725     */
726
727    /* Mirror */
728    temp = crc32_result;
729    shft = sizeof(crc32_result) * 8 - 1;
730
731    for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
732    {
733        temp <<= 1;
734        temp |= crc32_result & 1;
735        shft-- ;
736    }
737
738    /* temp[31-bit] = crc32_result[bit] */
739    temp <<= shft;
740
741    /* Swap */
742    /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
743    {
744        uint32_t t0, t1, t2, t3;
745        t0 = (0x000000ff & (temp >> 24));
746        t1 = (0x0000ff00 & (temp >> 8));
747        t2 = (0x00ff0000 & (temp << 8));
748        t3 = (0xff000000 & (temp << 24));
749        crc32_result = t0 | t1 | t2 | t3;
750    }
751
752    /* Complement */
753    if (complement)
754    {
755        crc32_result = ~crc32_result;
756    }
757
758    return (crc32_result);
759}
760
761int
762bxe_test_bit(int                    nr,
763             volatile unsigned long *addr)
764{
765    return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
766}
767
768void
769bxe_set_bit(unsigned int           nr,
770            volatile unsigned long *addr)
771{
772    atomic_set_acq_long(addr, (1 << nr));
773}
774
775void
776bxe_clear_bit(int                    nr,
777              volatile unsigned long *addr)
778{
779    atomic_clear_acq_long(addr, (1 << nr));
780}
781
782int
783bxe_test_and_set_bit(int                    nr,
784                       volatile unsigned long *addr)
785{
786    unsigned long x;
787    nr = (1 << nr);
788    do {
789        x = *addr;
790    } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
791    // if (x & nr) bit_was_set; else bit_was_not_set;
792    return (x & nr);
793}
794
795int
796bxe_test_and_clear_bit(int                    nr,
797                       volatile unsigned long *addr)
798{
799    unsigned long x;
800    nr = (1 << nr);
801    do {
802        x = *addr;
803    } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
804    // if (x & nr) bit_was_set; else bit_was_not_set;
805    return (x & nr);
806}
807
808int
809bxe_cmpxchg(volatile int *addr,
810            int          old,
811            int          new)
812{
813    int x;
814    do {
815        x = *addr;
816    } while (atomic_cmpset_acq_int(addr, old, new) == 0);
817    return (x);
818}
819
820/*
821 * Get DMA memory from the OS.
822 *
823 * Validates that the OS has provided DMA buffers in response to a
824 * bus_dmamap_load call and saves the physical address of those buffers.
825 * When the callback is used the OS will return 0 for the mapping function
826 * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
827 * failures back to the caller.
828 *
829 * Returns:
830 *   Nothing.
831 */
832static void
833bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
834{
835    struct bxe_dma *dma = arg;
836
837    if (error) {
838        dma->paddr = 0;
839        dma->nseg  = 0;
840        BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
841    } else {
842        dma->paddr = segs->ds_addr;
843        dma->nseg  = nseg;
844    }
845}
846
847/*
848 * Allocate a block of memory and map it for DMA. No partial completions
849 * allowed and release any resources acquired if we can't acquire all
850 * resources.
851 *
852 * Returns:
853 *   0 = Success, !0 = Failure
854 */
855int
856bxe_dma_alloc(struct bxe_softc *sc,
857              bus_size_t       size,
858              struct bxe_dma   *dma,
859              const char       *msg)
860{
861    int rc;
862
863    if (dma->size > 0) {
864        BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
865              (unsigned long)dma->size);
866        return (1);
867    }
868
869    memset(dma, 0, sizeof(*dma)); /* sanity */
870    dma->sc   = sc;
871    dma->size = size;
872    snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
873
874    rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
875                            BCM_PAGE_SIZE,      /* alignment */
876                            0,                  /* boundary limit */
877                            BUS_SPACE_MAXADDR,  /* restricted low */
878                            BUS_SPACE_MAXADDR,  /* restricted hi */
879                            NULL,               /* addr filter() */
880                            NULL,               /* addr filter() arg */
881                            size,               /* max map size */
882                            1,                  /* num discontinuous */
883                            size,               /* max seg size */
884                            BUS_DMA_ALLOCNOW,   /* flags */
885                            NULL,               /* lock() */
886                            NULL,               /* lock() arg */
887                            &dma->tag);         /* returned dma tag */
888    if (rc != 0) {
889        BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
890        memset(dma, 0, sizeof(*dma));
891        return (1);
892    }
893
894    rc = bus_dmamem_alloc(dma->tag,
895                          (void **)&dma->vaddr,
896                          (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
897                          &dma->map);
898    if (rc != 0) {
899        BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
900        bus_dma_tag_destroy(dma->tag);
901        memset(dma, 0, sizeof(*dma));
902        return (1);
903    }
904
905    rc = bus_dmamap_load(dma->tag,
906                         dma->map,
907                         dma->vaddr,
908                         size,
909                         bxe_dma_map_addr, /* BLOGD in here */
910                         dma,
911                         BUS_DMA_NOWAIT);
912    if (rc != 0) {
913        BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
914        bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
915        bus_dma_tag_destroy(dma->tag);
916        memset(dma, 0, sizeof(*dma));
917        return (1);
918    }
919
920    return (0);
921}
922
923void
924bxe_dma_free(struct bxe_softc *sc,
925             struct bxe_dma   *dma)
926{
927    if (dma->size > 0) {
928        DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
929
930        bus_dmamap_sync(dma->tag, dma->map,
931                        (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
932        bus_dmamap_unload(dma->tag, dma->map);
933        bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
934        bus_dma_tag_destroy(dma->tag);
935    }
936
937    memset(dma, 0, sizeof(*dma));
938}
939
940/*
941 * These indirect read and write routines are only during init.
942 * The locking is handled by the MCP.
943 */
944
945void
946bxe_reg_wr_ind(struct bxe_softc *sc,
947               uint32_t         addr,
948               uint32_t         val)
949{
950    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
951    pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
952    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
953}
954
955uint32_t
956bxe_reg_rd_ind(struct bxe_softc *sc,
957               uint32_t         addr)
958{
959    uint32_t val;
960
961    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
962    val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
963    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
964
965    return (val);
966}
967
968static int
969bxe_acquire_hw_lock(struct bxe_softc *sc,
970                    uint32_t         resource)
971{
972    uint32_t lock_status;
973    uint32_t resource_bit = (1 << resource);
974    int func = SC_FUNC(sc);
975    uint32_t hw_lock_control_reg;
976    int cnt;
977
978    /* validate the resource is within range */
979    if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
980        BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
981            " resource_bit 0x%x\n", resource, resource_bit);
982        return (-1);
983    }
984
985    if (func <= 5) {
986        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
987    } else {
988        hw_lock_control_reg =
989                (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
990    }
991
992    /* validate the resource is not already taken */
993    lock_status = REG_RD(sc, hw_lock_control_reg);
994    if (lock_status & resource_bit) {
995        BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
996              resource, lock_status, resource_bit);
997        return (-1);
998    }
999
1000    /* try every 5ms for 5 seconds */
1001    for (cnt = 0; cnt < 1000; cnt++) {
1002        REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1003        lock_status = REG_RD(sc, hw_lock_control_reg);
1004        if (lock_status & resource_bit) {
1005            return (0);
1006        }
1007        DELAY(5000);
1008    }
1009
1010    BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1011        resource, resource_bit);
1012    return (-1);
1013}
1014
1015static int
1016bxe_release_hw_lock(struct bxe_softc *sc,
1017                    uint32_t         resource)
1018{
1019    uint32_t lock_status;
1020    uint32_t resource_bit = (1 << resource);
1021    int func = SC_FUNC(sc);
1022    uint32_t hw_lock_control_reg;
1023
1024    /* validate the resource is within range */
1025    if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1026        BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1027            " resource_bit 0x%x\n", resource, resource_bit);
1028        return (-1);
1029    }
1030
1031    if (func <= 5) {
1032        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1033    } else {
1034        hw_lock_control_reg =
1035                (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1036    }
1037
1038    /* validate the resource is currently taken */
1039    lock_status = REG_RD(sc, hw_lock_control_reg);
1040    if (!(lock_status & resource_bit)) {
1041        BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1042              resource, lock_status, resource_bit);
1043        return (-1);
1044    }
1045
1046    REG_WR(sc, hw_lock_control_reg, resource_bit);
1047    return (0);
1048}
1049static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1050{
1051	BXE_PHY_LOCK(sc);
1052	bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1053}
1054
1055static void bxe_release_phy_lock(struct bxe_softc *sc)
1056{
1057	bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1058	BXE_PHY_UNLOCK(sc);
1059}
1060/*
1061 * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1062 * had we done things the other way around, if two pfs from the same port
1063 * would attempt to access nvram at the same time, we could run into a
1064 * scenario such as:
1065 * pf A takes the port lock.
1066 * pf B succeeds in taking the same lock since they are from the same port.
1067 * pf A takes the per pf misc lock. Performs eeprom access.
1068 * pf A finishes. Unlocks the per pf misc lock.
1069 * Pf B takes the lock and proceeds to perform it's own access.
1070 * pf A unlocks the per port lock, while pf B is still working (!).
1071 * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1072 * access corrupted by pf B).*
1073 */
1074static int
1075bxe_acquire_nvram_lock(struct bxe_softc *sc)
1076{
1077    int port = SC_PORT(sc);
1078    int count, i;
1079    uint32_t val = 0;
1080
1081    /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1082    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1083
1084    /* adjust timeout for emulation/FPGA */
1085    count = NVRAM_TIMEOUT_COUNT;
1086    if (CHIP_REV_IS_SLOW(sc)) {
1087        count *= 100;
1088    }
1089
1090    /* request access to nvram interface */
1091    REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1092           (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1093
1094    for (i = 0; i < count*10; i++) {
1095        val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1096        if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1097            break;
1098        }
1099
1100        DELAY(5);
1101    }
1102
1103    if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1104        BLOGE(sc, "Cannot get access to nvram interface "
1105            "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1106            port, val);
1107        return (-1);
1108    }
1109
1110    return (0);
1111}
1112
1113static int
1114bxe_release_nvram_lock(struct bxe_softc *sc)
1115{
1116    int port = SC_PORT(sc);
1117    int count, i;
1118    uint32_t val = 0;
1119
1120    /* adjust timeout for emulation/FPGA */
1121    count = NVRAM_TIMEOUT_COUNT;
1122    if (CHIP_REV_IS_SLOW(sc)) {
1123        count *= 100;
1124    }
1125
1126    /* relinquish nvram interface */
1127    REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1128           (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1129
1130    for (i = 0; i < count*10; i++) {
1131        val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1132        if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1133            break;
1134        }
1135
1136        DELAY(5);
1137    }
1138
1139    if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1140        BLOGE(sc, "Cannot free access to nvram interface "
1141            "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1142            port, val);
1143        return (-1);
1144    }
1145
1146    /* release HW lock: protect against other PFs in PF Direct Assignment */
1147    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1148
1149    return (0);
1150}
1151
1152static void
1153bxe_enable_nvram_access(struct bxe_softc *sc)
1154{
1155    uint32_t val;
1156
1157    val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1158
1159    /* enable both bits, even on read */
1160    REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1161           (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1162}
1163
1164static void
1165bxe_disable_nvram_access(struct bxe_softc *sc)
1166{
1167    uint32_t val;
1168
1169    val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1170
1171    /* disable both bits, even after read */
1172    REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1173           (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1174                    MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1175}
1176
1177static int
1178bxe_nvram_read_dword(struct bxe_softc *sc,
1179                     uint32_t         offset,
1180                     uint32_t         *ret_val,
1181                     uint32_t         cmd_flags)
1182{
1183    int count, i, rc;
1184    uint32_t val;
1185
1186    /* build the command word */
1187    cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1188
1189    /* need to clear DONE bit separately */
1190    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1191
1192    /* address of the NVRAM to read from */
1193    REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1194           (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1195
1196    /* issue a read command */
1197    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1198
1199    /* adjust timeout for emulation/FPGA */
1200    count = NVRAM_TIMEOUT_COUNT;
1201    if (CHIP_REV_IS_SLOW(sc)) {
1202        count *= 100;
1203    }
1204
1205    /* wait for completion */
1206    *ret_val = 0;
1207    rc = -1;
1208    for (i = 0; i < count; i++) {
1209        DELAY(5);
1210        val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1211
1212        if (val & MCPR_NVM_COMMAND_DONE) {
1213            val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1214            /* we read nvram data in cpu order
1215             * but ethtool sees it as an array of bytes
1216             * converting to big-endian will do the work
1217             */
1218            *ret_val = htobe32(val);
1219            rc = 0;
1220            break;
1221        }
1222    }
1223
1224    if (rc == -1) {
1225        BLOGE(sc, "nvram read timeout expired "
1226            "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1227            offset, cmd_flags, val);
1228    }
1229
1230    return (rc);
1231}
1232
1233static int
1234bxe_nvram_read(struct bxe_softc *sc,
1235               uint32_t         offset,
1236               uint8_t          *ret_buf,
1237               int              buf_size)
1238{
1239    uint32_t cmd_flags;
1240    uint32_t val;
1241    int rc;
1242
1243    if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1244        BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1245              offset, buf_size);
1246        return (-1);
1247    }
1248
1249    if ((offset + buf_size) > sc->devinfo.flash_size) {
1250        BLOGE(sc, "Invalid parameter, "
1251                  "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1252              offset, buf_size, sc->devinfo.flash_size);
1253        return (-1);
1254    }
1255
1256    /* request access to nvram interface */
1257    rc = bxe_acquire_nvram_lock(sc);
1258    if (rc) {
1259        return (rc);
1260    }
1261
1262    /* enable access to nvram interface */
1263    bxe_enable_nvram_access(sc);
1264
1265    /* read the first word(s) */
1266    cmd_flags = MCPR_NVM_COMMAND_FIRST;
1267    while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1268        rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1269        memcpy(ret_buf, &val, 4);
1270
1271        /* advance to the next dword */
1272        offset += sizeof(uint32_t);
1273        ret_buf += sizeof(uint32_t);
1274        buf_size -= sizeof(uint32_t);
1275        cmd_flags = 0;
1276    }
1277
1278    if (rc == 0) {
1279        cmd_flags |= MCPR_NVM_COMMAND_LAST;
1280        rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1281        memcpy(ret_buf, &val, 4);
1282    }
1283
1284    /* disable access to nvram interface */
1285    bxe_disable_nvram_access(sc);
1286    bxe_release_nvram_lock(sc);
1287
1288    return (rc);
1289}
1290
1291static int
1292bxe_nvram_write_dword(struct bxe_softc *sc,
1293                      uint32_t         offset,
1294                      uint32_t         val,
1295                      uint32_t         cmd_flags)
1296{
1297    int count, i, rc;
1298
1299    /* build the command word */
1300    cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1301
1302    /* need to clear DONE bit separately */
1303    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1304
1305    /* write the data */
1306    REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1307
1308    /* address of the NVRAM to write to */
1309    REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1310           (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1311
1312    /* issue the write command */
1313    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1314
1315    /* adjust timeout for emulation/FPGA */
1316    count = NVRAM_TIMEOUT_COUNT;
1317    if (CHIP_REV_IS_SLOW(sc)) {
1318        count *= 100;
1319    }
1320
1321    /* wait for completion */
1322    rc = -1;
1323    for (i = 0; i < count; i++) {
1324        DELAY(5);
1325        val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1326        if (val & MCPR_NVM_COMMAND_DONE) {
1327            rc = 0;
1328            break;
1329        }
1330    }
1331
1332    if (rc == -1) {
1333        BLOGE(sc, "nvram write timeout expired "
1334            "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1335            offset, cmd_flags, val);
1336    }
1337
1338    return (rc);
1339}
1340
1341#define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1342
1343static int
1344bxe_nvram_write1(struct bxe_softc *sc,
1345                 uint32_t         offset,
1346                 uint8_t          *data_buf,
1347                 int              buf_size)
1348{
1349    uint32_t cmd_flags;
1350    uint32_t align_offset;
1351    uint32_t val;
1352    int rc;
1353
1354    if ((offset + buf_size) > sc->devinfo.flash_size) {
1355        BLOGE(sc, "Invalid parameter, "
1356                  "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1357              offset, buf_size, sc->devinfo.flash_size);
1358        return (-1);
1359    }
1360
1361    /* request access to nvram interface */
1362    rc = bxe_acquire_nvram_lock(sc);
1363    if (rc) {
1364        return (rc);
1365    }
1366
1367    /* enable access to nvram interface */
1368    bxe_enable_nvram_access(sc);
1369
1370    cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1371    align_offset = (offset & ~0x03);
1372    rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1373
1374    if (rc == 0) {
1375        val &= ~(0xff << BYTE_OFFSET(offset));
1376        val |= (*data_buf << BYTE_OFFSET(offset));
1377
1378        /* nvram data is returned as an array of bytes
1379         * convert it back to cpu order
1380         */
1381        val = be32toh(val);
1382
1383        rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1384    }
1385
1386    /* disable access to nvram interface */
1387    bxe_disable_nvram_access(sc);
1388    bxe_release_nvram_lock(sc);
1389
1390    return (rc);
1391}
1392
1393static int
1394bxe_nvram_write(struct bxe_softc *sc,
1395                uint32_t         offset,
1396                uint8_t          *data_buf,
1397                int              buf_size)
1398{
1399    uint32_t cmd_flags;
1400    uint32_t val;
1401    uint32_t written_so_far;
1402    int rc;
1403
1404    if (buf_size == 1) {
1405        return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1406    }
1407
1408    if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1409        BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1410              offset, buf_size);
1411        return (-1);
1412    }
1413
1414    if (buf_size == 0) {
1415        return (0); /* nothing to do */
1416    }
1417
1418    if ((offset + buf_size) > sc->devinfo.flash_size) {
1419        BLOGE(sc, "Invalid parameter, "
1420                  "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1421              offset, buf_size, sc->devinfo.flash_size);
1422        return (-1);
1423    }
1424
1425    /* request access to nvram interface */
1426    rc = bxe_acquire_nvram_lock(sc);
1427    if (rc) {
1428        return (rc);
1429    }
1430
1431    /* enable access to nvram interface */
1432    bxe_enable_nvram_access(sc);
1433
1434    written_so_far = 0;
1435    cmd_flags = MCPR_NVM_COMMAND_FIRST;
1436    while ((written_so_far < buf_size) && (rc == 0)) {
1437        if (written_so_far == (buf_size - sizeof(uint32_t))) {
1438            cmd_flags |= MCPR_NVM_COMMAND_LAST;
1439        } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1440            cmd_flags |= MCPR_NVM_COMMAND_LAST;
1441        } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1442            cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1443        }
1444
1445        memcpy(&val, data_buf, 4);
1446
1447        rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1448
1449        /* advance to the next dword */
1450        offset += sizeof(uint32_t);
1451        data_buf += sizeof(uint32_t);
1452        written_so_far += sizeof(uint32_t);
1453        cmd_flags = 0;
1454    }
1455
1456    /* disable access to nvram interface */
1457    bxe_disable_nvram_access(sc);
1458    bxe_release_nvram_lock(sc);
1459
1460    return (rc);
1461}
1462
1463/* copy command into DMAE command memory and set DMAE command Go */
1464void
1465bxe_post_dmae(struct bxe_softc    *sc,
1466              struct dmae_cmd *dmae,
1467              int                 idx)
1468{
1469    uint32_t cmd_offset;
1470    int i;
1471
1472    cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1473    for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1474        REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1475    }
1476
1477    REG_WR(sc, dmae_reg_go_c[idx], 1);
1478}
1479
1480uint32_t
1481bxe_dmae_opcode_add_comp(uint32_t opcode,
1482                         uint8_t  comp_type)
1483{
1484    return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1485                      DMAE_CMD_C_TYPE_ENABLE));
1486}
1487
1488uint32_t
1489bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1490{
1491    return (opcode & ~DMAE_CMD_SRC_RESET);
1492}
1493
1494uint32_t
1495bxe_dmae_opcode(struct bxe_softc *sc,
1496                uint8_t          src_type,
1497                uint8_t          dst_type,
1498                uint8_t          with_comp,
1499                uint8_t          comp_type)
1500{
1501    uint32_t opcode = 0;
1502
1503    opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1504               (dst_type << DMAE_CMD_DST_SHIFT));
1505
1506    opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1507
1508    opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1509
1510    opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1511               (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1512
1513    opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1514
1515#ifdef __BIG_ENDIAN
1516    opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1517#else
1518    opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1519#endif
1520
1521    if (with_comp) {
1522        opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1523    }
1524
1525    return (opcode);
1526}
1527
1528static void
1529bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1530                        struct dmae_cmd *dmae,
1531                        uint8_t             src_type,
1532                        uint8_t             dst_type)
1533{
1534    memset(dmae, 0, sizeof(struct dmae_cmd));
1535
1536    /* set the opcode */
1537    dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1538                                   TRUE, DMAE_COMP_PCI);
1539
1540    /* fill in the completion parameters */
1541    dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1542    dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1543    dmae->comp_val     = DMAE_COMP_VAL;
1544}
1545
1546/* issue a DMAE command over the init channel and wait for completion */
1547static int
1548bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1549                         struct dmae_cmd *dmae)
1550{
1551    uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1552    int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1553
1554    BXE_DMAE_LOCK(sc);
1555
1556    /* reset completion */
1557    *wb_comp = 0;
1558
1559    /* post the command on the channel used for initializations */
1560    bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1561
1562    /* wait for completion */
1563    DELAY(5);
1564
1565    while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1566        if (!timeout ||
1567            (sc->recovery_state != BXE_RECOVERY_DONE &&
1568             sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1569            BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1570                *wb_comp, sc->recovery_state);
1571            BXE_DMAE_UNLOCK(sc);
1572            return (DMAE_TIMEOUT);
1573        }
1574
1575        timeout--;
1576        DELAY(50);
1577    }
1578
1579    if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1580        BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1581                *wb_comp, sc->recovery_state);
1582        BXE_DMAE_UNLOCK(sc);
1583        return (DMAE_PCI_ERROR);
1584    }
1585
1586    BXE_DMAE_UNLOCK(sc);
1587    return (0);
1588}
1589
1590void
1591bxe_read_dmae(struct bxe_softc *sc,
1592              uint32_t         src_addr,
1593              uint32_t         len32)
1594{
1595    struct dmae_cmd dmae;
1596    uint32_t *data;
1597    int i, rc;
1598
1599    DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1600
1601    if (!sc->dmae_ready) {
1602        data = BXE_SP(sc, wb_data[0]);
1603
1604        for (i = 0; i < len32; i++) {
1605            data[i] = (CHIP_IS_E1(sc)) ?
1606                          bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1607                          REG_RD(sc, (src_addr + (i * 4)));
1608        }
1609
1610        return;
1611    }
1612
1613    /* set opcode and fixed command fields */
1614    bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1615
1616    /* fill in addresses and len */
1617    dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1618    dmae.src_addr_hi = 0;
1619    dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1620    dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1621    dmae.len         = len32;
1622
1623    /* issue the command and wait for completion */
1624    if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1625        bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1626    }
1627}
1628
1629void
1630bxe_write_dmae(struct bxe_softc *sc,
1631               bus_addr_t       dma_addr,
1632               uint32_t         dst_addr,
1633               uint32_t         len32)
1634{
1635    struct dmae_cmd dmae;
1636    int rc;
1637
1638    if (!sc->dmae_ready) {
1639        DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1640
1641        if (CHIP_IS_E1(sc)) {
1642            ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1643        } else {
1644            ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1645        }
1646
1647        return;
1648    }
1649
1650    /* set opcode and fixed command fields */
1651    bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1652
1653    /* fill in addresses and len */
1654    dmae.src_addr_lo = U64_LO(dma_addr);
1655    dmae.src_addr_hi = U64_HI(dma_addr);
1656    dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1657    dmae.dst_addr_hi = 0;
1658    dmae.len         = len32;
1659
1660    /* issue the command and wait for completion */
1661    if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1662        bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1663    }
1664}
1665
1666void
1667bxe_write_dmae_phys_len(struct bxe_softc *sc,
1668                        bus_addr_t       phys_addr,
1669                        uint32_t         addr,
1670                        uint32_t         len)
1671{
1672    int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1673    int offset = 0;
1674
1675    while (len > dmae_wr_max) {
1676        bxe_write_dmae(sc,
1677                       (phys_addr + offset), /* src DMA address */
1678                       (addr + offset),      /* dst GRC address */
1679                       dmae_wr_max);
1680        offset += (dmae_wr_max * 4);
1681        len -= dmae_wr_max;
1682    }
1683
1684    bxe_write_dmae(sc,
1685                   (phys_addr + offset), /* src DMA address */
1686                   (addr + offset),      /* dst GRC address */
1687                   len);
1688}
1689
1690void
1691bxe_set_ctx_validation(struct bxe_softc   *sc,
1692                       struct eth_context *cxt,
1693                       uint32_t           cid)
1694{
1695    /* ustorm cxt validation */
1696    cxt->ustorm_ag_context.cdu_usage =
1697        CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1698            CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1699    /* xcontext validation */
1700    cxt->xstorm_ag_context.cdu_reserved =
1701        CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1702            CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1703}
1704
1705static void
1706bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1707                            uint8_t          port,
1708                            uint8_t          fw_sb_id,
1709                            uint8_t          sb_index,
1710                            uint8_t          ticks)
1711{
1712    uint32_t addr =
1713        (BAR_CSTRORM_INTMEM +
1714         CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1715
1716    REG_WR8(sc, addr, ticks);
1717
1718    BLOGD(sc, DBG_LOAD,
1719          "port %d fw_sb_id %d sb_index %d ticks %d\n",
1720          port, fw_sb_id, sb_index, ticks);
1721}
1722
1723static void
1724bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1725                            uint8_t          port,
1726                            uint16_t         fw_sb_id,
1727                            uint8_t          sb_index,
1728                            uint8_t          disable)
1729{
1730    uint32_t enable_flag =
1731        (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1732    uint32_t addr =
1733        (BAR_CSTRORM_INTMEM +
1734         CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1735    uint8_t flags;
1736
1737    /* clear and set */
1738    flags = REG_RD8(sc, addr);
1739    flags &= ~HC_INDEX_DATA_HC_ENABLED;
1740    flags |= enable_flag;
1741    REG_WR8(sc, addr, flags);
1742
1743    BLOGD(sc, DBG_LOAD,
1744          "port %d fw_sb_id %d sb_index %d disable %d\n",
1745          port, fw_sb_id, sb_index, disable);
1746}
1747
1748void
1749bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1750                             uint8_t          fw_sb_id,
1751                             uint8_t          sb_index,
1752                             uint8_t          disable,
1753                             uint16_t         usec)
1754{
1755    int port = SC_PORT(sc);
1756    uint8_t ticks = (usec / 4); /* XXX ??? */
1757
1758    bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1759
1760    disable = (disable) ? 1 : ((usec) ? 0 : 1);
1761    bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1762}
1763
1764void
1765elink_cb_udelay(struct bxe_softc *sc,
1766                uint32_t         usecs)
1767{
1768    DELAY(usecs);
1769}
1770
1771uint32_t
1772elink_cb_reg_read(struct bxe_softc *sc,
1773                  uint32_t         reg_addr)
1774{
1775    return (REG_RD(sc, reg_addr));
1776}
1777
1778void
1779elink_cb_reg_write(struct bxe_softc *sc,
1780                   uint32_t         reg_addr,
1781                   uint32_t         val)
1782{
1783    REG_WR(sc, reg_addr, val);
1784}
1785
1786void
1787elink_cb_reg_wb_write(struct bxe_softc *sc,
1788                      uint32_t         offset,
1789                      uint32_t         *wb_write,
1790                      uint16_t         len)
1791{
1792    REG_WR_DMAE(sc, offset, wb_write, len);
1793}
1794
1795void
1796elink_cb_reg_wb_read(struct bxe_softc *sc,
1797                     uint32_t         offset,
1798                     uint32_t         *wb_write,
1799                     uint16_t         len)
1800{
1801    REG_RD_DMAE(sc, offset, wb_write, len);
1802}
1803
1804uint8_t
1805elink_cb_path_id(struct bxe_softc *sc)
1806{
1807    return (SC_PATH(sc));
1808}
1809
1810void
1811elink_cb_event_log(struct bxe_softc     *sc,
1812                   const elink_log_id_t elink_log_id,
1813                   ...)
1814{
1815    /* XXX */
1816    BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1817}
1818
1819static int
1820bxe_set_spio(struct bxe_softc *sc,
1821             int              spio,
1822             uint32_t         mode)
1823{
1824    uint32_t spio_reg;
1825
1826    /* Only 2 SPIOs are configurable */
1827    if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1828        BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1829        return (-1);
1830    }
1831
1832    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1833
1834    /* read SPIO and mask except the float bits */
1835    spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1836
1837    switch (mode) {
1838    case MISC_SPIO_OUTPUT_LOW:
1839        BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1840        /* clear FLOAT and set CLR */
1841        spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1842        spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1843        break;
1844
1845    case MISC_SPIO_OUTPUT_HIGH:
1846        BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1847        /* clear FLOAT and set SET */
1848        spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1849        spio_reg |=  (spio << MISC_SPIO_SET_POS);
1850        break;
1851
1852    case MISC_SPIO_INPUT_HI_Z:
1853        BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1854        /* set FLOAT */
1855        spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1856        break;
1857
1858    default:
1859        break;
1860    }
1861
1862    REG_WR(sc, MISC_REG_SPIO, spio_reg);
1863    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1864
1865    return (0);
1866}
1867
1868static int
1869bxe_gpio_read(struct bxe_softc *sc,
1870              int              gpio_num,
1871              uint8_t          port)
1872{
1873    /* The GPIO should be swapped if swap register is set and active */
1874    int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1875                      REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1876    int gpio_shift = (gpio_num +
1877                      (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1878    uint32_t gpio_mask = (1 << gpio_shift);
1879    uint32_t gpio_reg;
1880
1881    if (gpio_num > MISC_REGISTERS_GPIO_3) {
1882        BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1883            " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1884            gpio_mask);
1885        return (-1);
1886    }
1887
1888    /* read GPIO value */
1889    gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1890
1891    /* get the requested pin value */
1892    return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1893}
1894
1895static int
1896bxe_gpio_write(struct bxe_softc *sc,
1897               int              gpio_num,
1898               uint32_t         mode,
1899               uint8_t          port)
1900{
1901    /* The GPIO should be swapped if swap register is set and active */
1902    int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1903                      REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1904    int gpio_shift = (gpio_num +
1905                      (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1906    uint32_t gpio_mask = (1 << gpio_shift);
1907    uint32_t gpio_reg;
1908
1909    if (gpio_num > MISC_REGISTERS_GPIO_3) {
1910        BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1911            " gpio_shift %d gpio_mask 0x%x\n",
1912            gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1913        return (-1);
1914    }
1915
1916    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1917
1918    /* read GPIO and mask except the float bits */
1919    gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1920
1921    switch (mode) {
1922    case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1923        BLOGD(sc, DBG_PHY,
1924              "Set GPIO %d (shift %d) -> output low\n",
1925              gpio_num, gpio_shift);
1926        /* clear FLOAT and set CLR */
1927        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1928        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1929        break;
1930
1931    case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1932        BLOGD(sc, DBG_PHY,
1933              "Set GPIO %d (shift %d) -> output high\n",
1934              gpio_num, gpio_shift);
1935        /* clear FLOAT and set SET */
1936        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1937        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1938        break;
1939
1940    case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1941        BLOGD(sc, DBG_PHY,
1942              "Set GPIO %d (shift %d) -> input\n",
1943              gpio_num, gpio_shift);
1944        /* set FLOAT */
1945        gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1946        break;
1947
1948    default:
1949        break;
1950    }
1951
1952    REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1953    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1954
1955    return (0);
1956}
1957
1958static int
1959bxe_gpio_mult_write(struct bxe_softc *sc,
1960                    uint8_t          pins,
1961                    uint32_t         mode)
1962{
1963    uint32_t gpio_reg;
1964
1965    /* any port swapping should be handled by caller */
1966
1967    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1968
1969    /* read GPIO and mask except the float bits */
1970    gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1971    gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1972    gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
1973    gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
1974
1975    switch (mode) {
1976    case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1977        BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
1978        /* set CLR */
1979        gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
1980        break;
1981
1982    case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1983        BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
1984        /* set SET */
1985        gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
1986        break;
1987
1988    case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1989        BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
1990        /* set FLOAT */
1991        gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1992        break;
1993
1994    default:
1995        BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
1996            " gpio_reg 0x%x\n", pins, mode, gpio_reg);
1997        bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1998        return (-1);
1999    }
2000
2001    REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2002    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2003
2004    return (0);
2005}
2006
2007static int
2008bxe_gpio_int_write(struct bxe_softc *sc,
2009                   int              gpio_num,
2010                   uint32_t         mode,
2011                   uint8_t          port)
2012{
2013    /* The GPIO should be swapped if swap register is set and active */
2014    int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2015                      REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2016    int gpio_shift = (gpio_num +
2017                      (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2018    uint32_t gpio_mask = (1 << gpio_shift);
2019    uint32_t gpio_reg;
2020
2021    if (gpio_num > MISC_REGISTERS_GPIO_3) {
2022        BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2023            " gpio_shift %d gpio_mask 0x%x\n",
2024            gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2025        return (-1);
2026    }
2027
2028    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2029
2030    /* read GPIO int */
2031    gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2032
2033    switch (mode) {
2034    case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2035        BLOGD(sc, DBG_PHY,
2036              "Clear GPIO INT %d (shift %d) -> output low\n",
2037              gpio_num, gpio_shift);
2038        /* clear SET and set CLR */
2039        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2040        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2041        break;
2042
2043    case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2044        BLOGD(sc, DBG_PHY,
2045              "Set GPIO INT %d (shift %d) -> output high\n",
2046              gpio_num, gpio_shift);
2047        /* clear CLR and set SET */
2048        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2049        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2050        break;
2051
2052    default:
2053        break;
2054    }
2055
2056    REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2057    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2058
2059    return (0);
2060}
2061
2062uint32_t
2063elink_cb_gpio_read(struct bxe_softc *sc,
2064                   uint16_t         gpio_num,
2065                   uint8_t          port)
2066{
2067    return (bxe_gpio_read(sc, gpio_num, port));
2068}
2069
2070uint8_t
2071elink_cb_gpio_write(struct bxe_softc *sc,
2072                    uint16_t         gpio_num,
2073                    uint8_t          mode, /* 0=low 1=high */
2074                    uint8_t          port)
2075{
2076    return (bxe_gpio_write(sc, gpio_num, mode, port));
2077}
2078
2079uint8_t
2080elink_cb_gpio_mult_write(struct bxe_softc *sc,
2081                         uint8_t          pins,
2082                         uint8_t          mode) /* 0=low 1=high */
2083{
2084    return (bxe_gpio_mult_write(sc, pins, mode));
2085}
2086
2087uint8_t
2088elink_cb_gpio_int_write(struct bxe_softc *sc,
2089                        uint16_t         gpio_num,
2090                        uint8_t          mode, /* 0=low 1=high */
2091                        uint8_t          port)
2092{
2093    return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2094}
2095
2096void
2097elink_cb_notify_link_changed(struct bxe_softc *sc)
2098{
2099    REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2100                (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2101}
2102
2103/* send the MCP a request, block until there is a reply */
2104uint32_t
2105elink_cb_fw_command(struct bxe_softc *sc,
2106                    uint32_t         command,
2107                    uint32_t         param)
2108{
2109    int mb_idx = SC_FW_MB_IDX(sc);
2110    uint32_t seq;
2111    uint32_t rc = 0;
2112    uint32_t cnt = 1;
2113    uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2114
2115    BXE_FWMB_LOCK(sc);
2116
2117    seq = ++sc->fw_seq;
2118    SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2119    SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2120
2121    BLOGD(sc, DBG_PHY,
2122          "wrote command 0x%08x to FW MB param 0x%08x\n",
2123          (command | seq), param);
2124
2125    /* Let the FW do it's magic. GIve it up to 5 seconds... */
2126    do {
2127        DELAY(delay * 1000);
2128        rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2129    } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2130
2131    BLOGD(sc, DBG_PHY,
2132          "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2133          cnt*delay, rc, seq);
2134
2135    /* is this a reply to our command? */
2136    if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2137        rc &= FW_MSG_CODE_MASK;
2138    } else {
2139        /* Ruh-roh! */
2140        BLOGE(sc, "FW failed to respond!\n");
2141        // XXX bxe_fw_dump(sc);
2142        rc = 0;
2143    }
2144
2145    BXE_FWMB_UNLOCK(sc);
2146    return (rc);
2147}
2148
2149static uint32_t
2150bxe_fw_command(struct bxe_softc *sc,
2151               uint32_t         command,
2152               uint32_t         param)
2153{
2154    return (elink_cb_fw_command(sc, command, param));
2155}
2156
2157static void
2158__storm_memset_dma_mapping(struct bxe_softc *sc,
2159                           uint32_t         addr,
2160                           bus_addr_t       mapping)
2161{
2162    REG_WR(sc, addr, U64_LO(mapping));
2163    REG_WR(sc, (addr + 4), U64_HI(mapping));
2164}
2165
2166static void
2167storm_memset_spq_addr(struct bxe_softc *sc,
2168                      bus_addr_t       mapping,
2169                      uint16_t         abs_fid)
2170{
2171    uint32_t addr = (XSEM_REG_FAST_MEMORY +
2172                     XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2173    __storm_memset_dma_mapping(sc, addr, mapping);
2174}
2175
2176static void
2177storm_memset_vf_to_pf(struct bxe_softc *sc,
2178                      uint16_t         abs_fid,
2179                      uint16_t         pf_id)
2180{
2181    REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2182    REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2183    REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2184    REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2185}
2186
2187static void
2188storm_memset_func_en(struct bxe_softc *sc,
2189                     uint16_t         abs_fid,
2190                     uint8_t          enable)
2191{
2192    REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2193    REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2194    REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2195    REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2196}
2197
2198static void
2199storm_memset_eq_data(struct bxe_softc       *sc,
2200                     struct event_ring_data *eq_data,
2201                     uint16_t               pfid)
2202{
2203    uint32_t addr;
2204    size_t size;
2205
2206    addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2207    size = sizeof(struct event_ring_data);
2208    ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2209}
2210
2211static void
2212storm_memset_eq_prod(struct bxe_softc *sc,
2213                     uint16_t         eq_prod,
2214                     uint16_t         pfid)
2215{
2216    uint32_t addr = (BAR_CSTRORM_INTMEM +
2217                     CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2218    REG_WR16(sc, addr, eq_prod);
2219}
2220
2221/*
2222 * Post a slowpath command.
2223 *
2224 * A slowpath command is used to propagate a configuration change through
2225 * the controller in a controlled manner, allowing each STORM processor and
2226 * other H/W blocks to phase in the change.  The commands sent on the
2227 * slowpath are referred to as ramrods.  Depending on the ramrod used the
2228 * completion of the ramrod will occur in different ways.  Here's a
2229 * breakdown of ramrods and how they complete:
2230 *
2231 * RAMROD_CMD_ID_ETH_PORT_SETUP
2232 *   Used to setup the leading connection on a port.  Completes on the
2233 *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2234 *
2235 * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2236 *   Used to setup an additional connection on a port.  Completes on the
2237 *   RCQ of the multi-queue/RSS connection being initialized.
2238 *
2239 * RAMROD_CMD_ID_ETH_STAT_QUERY
2240 *   Used to force the storm processors to update the statistics database
2241 *   in host memory.  This ramrod is send on the leading connection CID and
2242 *   completes as an index increment of the CSTORM on the default status
2243 *   block.
2244 *
2245 * RAMROD_CMD_ID_ETH_UPDATE
2246 *   Used to update the state of the leading connection, usually to udpate
2247 *   the RSS indirection table.  Completes on the RCQ of the leading
2248 *   connection. (Not currently used under FreeBSD until OS support becomes
2249 *   available.)
2250 *
2251 * RAMROD_CMD_ID_ETH_HALT
2252 *   Used when tearing down a connection prior to driver unload.  Completes
2253 *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2254 *   use this on the leading connection.
2255 *
2256 * RAMROD_CMD_ID_ETH_SET_MAC
2257 *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2258 *   the RCQ of the leading connection.
2259 *
2260 * RAMROD_CMD_ID_ETH_CFC_DEL
2261 *   Used when tearing down a conneciton prior to driver unload.  Completes
2262 *   on the RCQ of the leading connection (since the current connection
2263 *   has been completely removed from controller memory).
2264 *
2265 * RAMROD_CMD_ID_ETH_PORT_DEL
2266 *   Used to tear down the leading connection prior to driver unload,
2267 *   typically fp[0].  Completes as an index increment of the CSTORM on the
2268 *   default status block.
2269 *
2270 * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2271 *   Used for connection offload.  Completes on the RCQ of the multi-queue
2272 *   RSS connection that is being offloaded.  (Not currently used under
2273 *   FreeBSD.)
2274 *
2275 * There can only be one command pending per function.
2276 *
2277 * Returns:
2278 *   0 = Success, !0 = Failure.
2279 */
2280
2281/* must be called under the spq lock */
2282static inline
2283struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2284{
2285    struct eth_spe *next_spe = sc->spq_prod_bd;
2286
2287    if (sc->spq_prod_bd == sc->spq_last_bd) {
2288        /* wrap back to the first eth_spq */
2289        sc->spq_prod_bd = sc->spq;
2290        sc->spq_prod_idx = 0;
2291    } else {
2292        sc->spq_prod_bd++;
2293        sc->spq_prod_idx++;
2294    }
2295
2296    return (next_spe);
2297}
2298
2299/* must be called under the spq lock */
2300static inline
2301void bxe_sp_prod_update(struct bxe_softc *sc)
2302{
2303    int func = SC_FUNC(sc);
2304
2305    /*
2306     * Make sure that BD data is updated before writing the producer.
2307     * BD data is written to the memory, the producer is read from the
2308     * memory, thus we need a full memory barrier to ensure the ordering.
2309     */
2310    mb();
2311
2312    REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2313             sc->spq_prod_idx);
2314
2315    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2316                      BUS_SPACE_BARRIER_WRITE);
2317}
2318
2319/**
2320 * bxe_is_contextless_ramrod - check if the current command ends on EQ
2321 *
2322 * @cmd:      command to check
2323 * @cmd_type: command type
2324 */
2325static inline
2326int bxe_is_contextless_ramrod(int cmd,
2327                              int cmd_type)
2328{
2329    if ((cmd_type == NONE_CONNECTION_TYPE) ||
2330        (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2331        (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2332        (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2333        (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2334        (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2335        (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2336        return (TRUE);
2337    } else {
2338        return (FALSE);
2339    }
2340}
2341
2342/**
2343 * bxe_sp_post - place a single command on an SP ring
2344 *
2345 * @sc:         driver handle
2346 * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2347 * @cid:        SW CID the command is related to
2348 * @data_hi:    command private data address (high 32 bits)
2349 * @data_lo:    command private data address (low 32 bits)
2350 * @cmd_type:   command type (e.g. NONE, ETH)
2351 *
2352 * SP data is handled as if it's always an address pair, thus data fields are
2353 * not swapped to little endian in upper functions. Instead this function swaps
2354 * data as if it's two uint32 fields.
2355 */
2356int
2357bxe_sp_post(struct bxe_softc *sc,
2358            int              command,
2359            int              cid,
2360            uint32_t         data_hi,
2361            uint32_t         data_lo,
2362            int              cmd_type)
2363{
2364    struct eth_spe *spe;
2365    uint16_t type;
2366    int common;
2367
2368    common = bxe_is_contextless_ramrod(command, cmd_type);
2369
2370    BXE_SP_LOCK(sc);
2371
2372    if (common) {
2373        if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2374            BLOGE(sc, "EQ ring is full!\n");
2375            BXE_SP_UNLOCK(sc);
2376            return (-1);
2377        }
2378    } else {
2379        if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2380            BLOGE(sc, "SPQ ring is full!\n");
2381            BXE_SP_UNLOCK(sc);
2382            return (-1);
2383        }
2384    }
2385
2386    spe = bxe_sp_get_next(sc);
2387
2388    /* CID needs port number to be encoded int it */
2389    spe->hdr.conn_and_cmd_data =
2390        htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2391
2392    type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2393
2394    /* TBD: Check if it works for VFs */
2395    type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2396             SPE_HDR_T_FUNCTION_ID);
2397
2398    spe->hdr.type = htole16(type);
2399
2400    spe->data.update_data_addr.hi = htole32(data_hi);
2401    spe->data.update_data_addr.lo = htole32(data_lo);
2402
2403    /*
2404     * It's ok if the actual decrement is issued towards the memory
2405     * somewhere between the lock and unlock. Thus no more explict
2406     * memory barrier is needed.
2407     */
2408    if (common) {
2409        atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2410    } else {
2411        atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2412    }
2413
2414    BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2415    BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2416          BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2417    BLOGD(sc, DBG_SP,
2418          "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2419          sc->spq_prod_idx,
2420          (uint32_t)U64_HI(sc->spq_dma.paddr),
2421          (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2422          command,
2423          common,
2424          HW_CID(sc, cid),
2425          data_hi,
2426          data_lo,
2427          type,
2428          atomic_load_acq_long(&sc->cq_spq_left),
2429          atomic_load_acq_long(&sc->eq_spq_left));
2430
2431    bxe_sp_prod_update(sc);
2432
2433    BXE_SP_UNLOCK(sc);
2434    return (0);
2435}
2436
2437/**
2438 * bxe_debug_print_ind_table - prints the indirection table configuration.
2439 *
2440 * @sc: driver hanlde
2441 * @p:  pointer to rss configuration
2442 */
2443
2444/*
2445 * FreeBSD Device probe function.
2446 *
2447 * Compares the device found to the driver's list of supported devices and
2448 * reports back to the bsd loader whether this is the right driver for the device.
2449 * This is the driver entry function called from the "kldload" command.
2450 *
2451 * Returns:
2452 *   BUS_PROBE_DEFAULT on success, positive value on failure.
2453 */
2454static int
2455bxe_probe(device_t dev)
2456{
2457    struct bxe_softc *sc;
2458    struct bxe_device_type *t;
2459    char *descbuf;
2460    uint16_t did, sdid, svid, vid;
2461
2462    /* Find our device structure */
2463    sc = device_get_softc(dev);
2464    sc->dev = dev;
2465    t = bxe_devs;
2466
2467    /* Get the data for the device to be probed. */
2468    vid  = pci_get_vendor(dev);
2469    did  = pci_get_device(dev);
2470    svid = pci_get_subvendor(dev);
2471    sdid = pci_get_subdevice(dev);
2472
2473    BLOGD(sc, DBG_LOAD,
2474          "%s(); VID = 0x%04X, DID = 0x%04X, SVID = 0x%04X, "
2475          "SDID = 0x%04X\n", __FUNCTION__, vid, did, svid, sdid);
2476
2477    /* Look through the list of known devices for a match. */
2478    while (t->bxe_name != NULL) {
2479        if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2480            ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2481            ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2482            descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2483            if (descbuf == NULL)
2484                return (ENOMEM);
2485
2486            /* Print out the device identity. */
2487            snprintf(descbuf, BXE_DEVDESC_MAX,
2488                     "%s (%c%d) BXE v:%s\n", t->bxe_name,
2489                     (((pci_read_config(dev, PCIR_REVID, 4) &
2490                        0xf0) >> 4) + 'A'),
2491                     (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2492                     BXE_DRIVER_VERSION);
2493
2494            device_set_desc_copy(dev, descbuf);
2495            free(descbuf, M_TEMP);
2496            return (BUS_PROBE_DEFAULT);
2497        }
2498        t++;
2499    }
2500
2501    return (ENXIO);
2502}
2503
2504static void
2505bxe_init_mutexes(struct bxe_softc *sc)
2506{
2507#ifdef BXE_CORE_LOCK_SX
2508    snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2509             "bxe%d_core_lock", sc->unit);
2510    sx_init(&sc->core_sx, sc->core_sx_name);
2511#else
2512    snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2513             "bxe%d_core_lock", sc->unit);
2514    mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2515#endif
2516
2517    snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2518             "bxe%d_sp_lock", sc->unit);
2519    mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2520
2521    snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2522             "bxe%d_dmae_lock", sc->unit);
2523    mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2524
2525    snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2526             "bxe%d_phy_lock", sc->unit);
2527    mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2528
2529    snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2530             "bxe%d_fwmb_lock", sc->unit);
2531    mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2532
2533    snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2534             "bxe%d_print_lock", sc->unit);
2535    mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2536
2537    snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2538             "bxe%d_stats_lock", sc->unit);
2539    mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2540
2541    snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2542             "bxe%d_mcast_lock", sc->unit);
2543    mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2544}
2545
2546static void
2547bxe_release_mutexes(struct bxe_softc *sc)
2548{
2549#ifdef BXE_CORE_LOCK_SX
2550    sx_destroy(&sc->core_sx);
2551#else
2552    if (mtx_initialized(&sc->core_mtx)) {
2553        mtx_destroy(&sc->core_mtx);
2554    }
2555#endif
2556
2557    if (mtx_initialized(&sc->sp_mtx)) {
2558        mtx_destroy(&sc->sp_mtx);
2559    }
2560
2561    if (mtx_initialized(&sc->dmae_mtx)) {
2562        mtx_destroy(&sc->dmae_mtx);
2563    }
2564
2565    if (mtx_initialized(&sc->port.phy_mtx)) {
2566        mtx_destroy(&sc->port.phy_mtx);
2567    }
2568
2569    if (mtx_initialized(&sc->fwmb_mtx)) {
2570        mtx_destroy(&sc->fwmb_mtx);
2571    }
2572
2573    if (mtx_initialized(&sc->print_mtx)) {
2574        mtx_destroy(&sc->print_mtx);
2575    }
2576
2577    if (mtx_initialized(&sc->stats_mtx)) {
2578        mtx_destroy(&sc->stats_mtx);
2579    }
2580
2581    if (mtx_initialized(&sc->mcast_mtx)) {
2582        mtx_destroy(&sc->mcast_mtx);
2583    }
2584}
2585
2586static void
2587bxe_tx_disable(struct bxe_softc* sc)
2588{
2589    if_t ifp = sc->ifp;
2590
2591    /* tell the stack the driver is stopped and TX queue is full */
2592    if (ifp !=  NULL) {
2593        if_setdrvflags(ifp, 0);
2594    }
2595}
2596
2597static void
2598bxe_drv_pulse(struct bxe_softc *sc)
2599{
2600    SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2601             sc->fw_drv_pulse_wr_seq);
2602}
2603
2604static inline uint16_t
2605bxe_tx_avail(struct bxe_softc *sc,
2606             struct bxe_fastpath *fp)
2607{
2608    int16_t  used;
2609    uint16_t prod;
2610    uint16_t cons;
2611
2612    prod = fp->tx_bd_prod;
2613    cons = fp->tx_bd_cons;
2614
2615    used = SUB_S16(prod, cons);
2616
2617    return (int16_t)(sc->tx_ring_size) - used;
2618}
2619
2620static inline int
2621bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2622{
2623    uint16_t hw_cons;
2624
2625    mb(); /* status block fields can change */
2626    hw_cons = le16toh(*fp->tx_cons_sb);
2627    return (hw_cons != fp->tx_pkt_cons);
2628}
2629
2630static inline uint8_t
2631bxe_has_tx_work(struct bxe_fastpath *fp)
2632{
2633    /* expand this for multi-cos if ever supported */
2634    return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2635}
2636
2637static inline int
2638bxe_has_rx_work(struct bxe_fastpath *fp)
2639{
2640    uint16_t rx_cq_cons_sb;
2641
2642    mb(); /* status block fields can change */
2643    rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2644    if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2645        rx_cq_cons_sb++;
2646    return (fp->rx_cq_cons != rx_cq_cons_sb);
2647}
2648
2649static void
2650bxe_sp_event(struct bxe_softc    *sc,
2651             struct bxe_fastpath *fp,
2652             union eth_rx_cqe    *rr_cqe)
2653{
2654    int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2655    int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2656    enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2657    struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2658
2659    BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2660          fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2661
2662    switch (command) {
2663    case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2664        BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2665        drv_cmd = ECORE_Q_CMD_UPDATE;
2666        break;
2667
2668    case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2669        BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2670        drv_cmd = ECORE_Q_CMD_SETUP;
2671        break;
2672
2673    case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2674        BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2675        drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2676        break;
2677
2678    case (RAMROD_CMD_ID_ETH_HALT):
2679        BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2680        drv_cmd = ECORE_Q_CMD_HALT;
2681        break;
2682
2683    case (RAMROD_CMD_ID_ETH_TERMINATE):
2684        BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2685        drv_cmd = ECORE_Q_CMD_TERMINATE;
2686        break;
2687
2688    case (RAMROD_CMD_ID_ETH_EMPTY):
2689        BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2690        drv_cmd = ECORE_Q_CMD_EMPTY;
2691        break;
2692
2693    default:
2694        BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2695              command, fp->index);
2696        return;
2697    }
2698
2699    if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2700        q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2701        /*
2702         * q_obj->complete_cmd() failure means that this was
2703         * an unexpected completion.
2704         *
2705         * In this case we don't want to increase the sc->spq_left
2706         * because apparently we haven't sent this command the first
2707         * place.
2708         */
2709        // bxe_panic(sc, ("Unexpected SP completion\n"));
2710        return;
2711    }
2712
2713    atomic_add_acq_long(&sc->cq_spq_left, 1);
2714
2715    BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2716          atomic_load_acq_long(&sc->cq_spq_left));
2717}
2718
2719/*
2720 * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2721 * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2722 * the current aggregation queue as in-progress.
2723 */
2724static void
2725bxe_tpa_start(struct bxe_softc            *sc,
2726              struct bxe_fastpath         *fp,
2727              uint16_t                    queue,
2728              uint16_t                    cons,
2729              uint16_t                    prod,
2730              struct eth_fast_path_rx_cqe *cqe)
2731{
2732    struct bxe_sw_rx_bd tmp_bd;
2733    struct bxe_sw_rx_bd *rx_buf;
2734    struct eth_rx_bd *rx_bd;
2735    int max_agg_queues;
2736    struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2737    uint16_t index;
2738
2739    BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2740                       "cons=%d prod=%d\n",
2741          fp->index, queue, cons, prod);
2742
2743    max_agg_queues = MAX_AGG_QS(sc);
2744
2745    KASSERT((queue < max_agg_queues),
2746            ("fp[%02d] invalid aggr queue (%d >= %d)!",
2747             fp->index, queue, max_agg_queues));
2748
2749    KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2750            ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2751             fp->index, queue));
2752
2753    /* copy the existing mbuf and mapping from the TPA pool */
2754    tmp_bd = tpa_info->bd;
2755
2756    if (tmp_bd.m == NULL) {
2757        uint32_t *tmp;
2758
2759        tmp = (uint32_t *)cqe;
2760
2761        BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2762              fp->index, queue, cons, prod);
2763        BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2764            *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2765
2766        /* XXX Error handling? */
2767        return;
2768    }
2769
2770    /* change the TPA queue to the start state */
2771    tpa_info->state            = BXE_TPA_STATE_START;
2772    tpa_info->placement_offset = cqe->placement_offset;
2773    tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2774    tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2775    tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2776
2777    fp->rx_tpa_queue_used |= (1 << queue);
2778
2779    /*
2780     * If all the buffer descriptors are filled with mbufs then fill in
2781     * the current consumer index with a new BD. Else if a maximum Rx
2782     * buffer limit is imposed then fill in the next producer index.
2783     */
2784    index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2785                prod : cons;
2786
2787    /* move the received mbuf and mapping to TPA pool */
2788    tpa_info->bd = fp->rx_mbuf_chain[cons];
2789
2790    /* release any existing RX BD mbuf mappings */
2791    if (cons != index) {
2792        rx_buf = &fp->rx_mbuf_chain[cons];
2793
2794        if (rx_buf->m_map != NULL) {
2795            bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2796                            BUS_DMASYNC_POSTREAD);
2797            bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2798        }
2799
2800        /*
2801         * We get here when the maximum number of rx buffers is less than
2802         * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2803         * it out here without concern of a memory leak.
2804         */
2805        fp->rx_mbuf_chain[cons].m = NULL;
2806    }
2807
2808    /* update the Rx SW BD with the mbuf info from the TPA pool */
2809    fp->rx_mbuf_chain[index] = tmp_bd;
2810
2811    /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2812    rx_bd = &fp->rx_chain[index];
2813    rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2814    rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2815}
2816
2817/*
2818 * When a TPA aggregation is completed, loop through the individual mbufs
2819 * of the aggregation, combining them into a single mbuf which will be sent
2820 * up the stack. Refill all freed SGEs with mbufs as we go along.
2821 */
2822static int
2823bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2824                   struct bxe_fastpath       *fp,
2825                   struct bxe_sw_tpa_info    *tpa_info,
2826                   uint16_t                  queue,
2827                   uint16_t                  pages,
2828                   struct mbuf               *m,
2829			       struct eth_end_agg_rx_cqe *cqe,
2830                   uint16_t                  cqe_idx)
2831{
2832    struct mbuf *m_frag;
2833    uint32_t frag_len, frag_size, i;
2834    uint16_t sge_idx;
2835    int rc = 0;
2836    int j;
2837
2838    frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2839
2840    BLOGD(sc, DBG_LRO,
2841          "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2842          fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2843
2844    /* make sure the aggregated frame is not too big to handle */
2845    if (pages > 8 * PAGES_PER_SGE) {
2846
2847        uint32_t *tmp = (uint32_t *)cqe;
2848
2849        BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2850                  "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2851              fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2852              tpa_info->len_on_bd, frag_size);
2853
2854        BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2855            *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2856
2857        bxe_panic(sc, ("sge page count error\n"));
2858        return (EINVAL);
2859    }
2860
2861    /*
2862     * Scan through the scatter gather list pulling individual mbufs into a
2863     * single mbuf for the host stack.
2864     */
2865    for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2866        sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2867
2868        /*
2869         * Firmware gives the indices of the SGE as if the ring is an array
2870         * (meaning that the "next" element will consume 2 indices).
2871         */
2872        frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2873
2874        BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2875                           "sge_idx=%d frag_size=%d frag_len=%d\n",
2876              fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2877
2878        m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2879
2880        /* allocate a new mbuf for the SGE */
2881        rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2882        if (rc) {
2883            /* Leave all remaining SGEs in the ring! */
2884            return (rc);
2885        }
2886
2887        /* update the fragment length */
2888        m_frag->m_len = frag_len;
2889
2890        /* concatenate the fragment to the head mbuf */
2891        m_cat(m, m_frag);
2892        fp->eth_q_stats.mbuf_alloc_sge--;
2893
2894        /* update the TPA mbuf size and remaining fragment size */
2895        m->m_pkthdr.len += frag_len;
2896        frag_size -= frag_len;
2897    }
2898
2899    BLOGD(sc, DBG_LRO,
2900          "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2901          fp->index, queue, frag_size);
2902
2903    return (rc);
2904}
2905
2906static inline void
2907bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2908{
2909    int i, j;
2910
2911    for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2912        int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2913
2914        for (j = 0; j < 2; j++) {
2915            BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2916            idx--;
2917        }
2918    }
2919}
2920
2921static inline void
2922bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2923{
2924    /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2925    memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2926
2927    /*
2928     * Clear the two last indices in the page to 1. These are the indices that
2929     * correspond to the "next" element, hence will never be indicated and
2930     * should be removed from the calculations.
2931     */
2932    bxe_clear_sge_mask_next_elems(fp);
2933}
2934
2935static inline void
2936bxe_update_last_max_sge(struct bxe_fastpath *fp,
2937                        uint16_t            idx)
2938{
2939    uint16_t last_max = fp->last_max_sge;
2940
2941    if (SUB_S16(idx, last_max) > 0) {
2942        fp->last_max_sge = idx;
2943    }
2944}
2945
2946static inline void
2947bxe_update_sge_prod(struct bxe_softc          *sc,
2948                    struct bxe_fastpath       *fp,
2949                    uint16_t                  sge_len,
2950                    union eth_sgl_or_raw_data *cqe)
2951{
2952    uint16_t last_max, last_elem, first_elem;
2953    uint16_t delta = 0;
2954    uint16_t i;
2955
2956    if (!sge_len) {
2957        return;
2958    }
2959
2960    /* first mark all used pages */
2961    for (i = 0; i < sge_len; i++) {
2962        BIT_VEC64_CLEAR_BIT(fp->sge_mask,
2963                            RX_SGE(le16toh(cqe->sgl[i])));
2964    }
2965
2966    BLOGD(sc, DBG_LRO,
2967          "fp[%02d] fp_cqe->sgl[%d] = %d\n",
2968          fp->index, sge_len - 1,
2969          le16toh(cqe->sgl[sge_len - 1]));
2970
2971    /* assume that the last SGE index is the biggest */
2972    bxe_update_last_max_sge(fp,
2973                            le16toh(cqe->sgl[sge_len - 1]));
2974
2975    last_max = RX_SGE(fp->last_max_sge);
2976    last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
2977    first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
2978
2979    /* if ring is not full */
2980    if (last_elem + 1 != first_elem) {
2981        last_elem++;
2982    }
2983
2984    /* now update the prod */
2985    for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
2986        if (__predict_true(fp->sge_mask[i])) {
2987            break;
2988        }
2989
2990        fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
2991        delta += BIT_VEC64_ELEM_SZ;
2992    }
2993
2994    if (delta > 0) {
2995        fp->rx_sge_prod += delta;
2996        /* clear page-end entries */
2997        bxe_clear_sge_mask_next_elems(fp);
2998    }
2999
3000    BLOGD(sc, DBG_LRO,
3001          "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3002          fp->index, fp->last_max_sge, fp->rx_sge_prod);
3003}
3004
3005/*
3006 * The aggregation on the current TPA queue has completed. Pull the individual
3007 * mbuf fragments together into a single mbuf, perform all necessary checksum
3008 * calculations, and send the resuting mbuf to the stack.
3009 */
3010static void
3011bxe_tpa_stop(struct bxe_softc          *sc,
3012             struct bxe_fastpath       *fp,
3013             struct bxe_sw_tpa_info    *tpa_info,
3014             uint16_t                  queue,
3015             uint16_t                  pages,
3016			 struct eth_end_agg_rx_cqe *cqe,
3017             uint16_t                  cqe_idx)
3018{
3019    if_t ifp = sc->ifp;
3020    struct mbuf *m;
3021    int rc = 0;
3022
3023    BLOGD(sc, DBG_LRO,
3024          "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3025          fp->index, queue, tpa_info->placement_offset,
3026          le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3027
3028    m = tpa_info->bd.m;
3029
3030    /* allocate a replacement before modifying existing mbuf */
3031    rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3032    if (rc) {
3033        /* drop the frame and log an error */
3034        fp->eth_q_stats.rx_soft_errors++;
3035        goto bxe_tpa_stop_exit;
3036    }
3037
3038    /* we have a replacement, fixup the current mbuf */
3039    m_adj(m, tpa_info->placement_offset);
3040    m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3041
3042    /* mark the checksums valid (taken care of by the firmware) */
3043    fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3044    fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3045    m->m_pkthdr.csum_data = 0xffff;
3046    m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3047                               CSUM_IP_VALID   |
3048                               CSUM_DATA_VALID |
3049                               CSUM_PSEUDO_HDR);
3050
3051    /* aggregate all of the SGEs into a single mbuf */
3052    rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3053    if (rc) {
3054        /* drop the packet and log an error */
3055        fp->eth_q_stats.rx_soft_errors++;
3056        m_freem(m);
3057    } else {
3058        if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3059            m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3060            m->m_flags |= M_VLANTAG;
3061        }
3062
3063        /* assign packet to this interface interface */
3064        if_setrcvif(m, ifp);
3065
3066#if __FreeBSD_version >= 800000
3067        /* specify what RSS queue was used for this flow */
3068        m->m_pkthdr.flowid = fp->index;
3069        BXE_SET_FLOWID(m);
3070#endif
3071
3072        if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3073        fp->eth_q_stats.rx_tpa_pkts++;
3074
3075        /* pass the frame to the stack */
3076        if_input(ifp, m);
3077    }
3078
3079    /* we passed an mbuf up the stack or dropped the frame */
3080    fp->eth_q_stats.mbuf_alloc_tpa--;
3081
3082bxe_tpa_stop_exit:
3083
3084    fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3085    fp->rx_tpa_queue_used &= ~(1 << queue);
3086}
3087
3088static uint8_t
3089bxe_service_rxsgl(
3090                 struct bxe_fastpath *fp,
3091                 uint16_t len,
3092                 uint16_t lenonbd,
3093                 struct mbuf *m,
3094                 struct eth_fast_path_rx_cqe *cqe_fp)
3095{
3096    struct mbuf *m_frag;
3097    uint16_t frags, frag_len;
3098    uint16_t sge_idx = 0;
3099    uint16_t j;
3100    uint8_t i, rc = 0;
3101    uint32_t frag_size;
3102
3103    /* adjust the mbuf */
3104    m->m_len = lenonbd;
3105
3106    frag_size =  len - lenonbd;
3107    frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3108
3109    for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3110        sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3111
3112        m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3113        frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3114        m_frag->m_len = frag_len;
3115
3116       /* allocate a new mbuf for the SGE */
3117        rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3118        if (rc) {
3119            /* Leave all remaining SGEs in the ring! */
3120            return (rc);
3121        }
3122        fp->eth_q_stats.mbuf_alloc_sge--;
3123
3124        /* concatenate the fragment to the head mbuf */
3125        m_cat(m, m_frag);
3126
3127        frag_size -= frag_len;
3128    }
3129
3130    bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3131
3132    return rc;
3133}
3134
3135static uint8_t
3136bxe_rxeof(struct bxe_softc    *sc,
3137          struct bxe_fastpath *fp)
3138{
3139    if_t ifp = sc->ifp;
3140    uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3141    uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3142    int rx_pkts = 0;
3143    int rc = 0;
3144
3145    BXE_FP_RX_LOCK(fp);
3146
3147    /* CQ "next element" is of the size of the regular element */
3148    hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3149    if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3150        hw_cq_cons++;
3151    }
3152
3153    bd_cons = fp->rx_bd_cons;
3154    bd_prod = fp->rx_bd_prod;
3155    bd_prod_fw = bd_prod;
3156    sw_cq_cons = fp->rx_cq_cons;
3157    sw_cq_prod = fp->rx_cq_prod;
3158
3159    /*
3160     * Memory barrier necessary as speculative reads of the rx
3161     * buffer can be ahead of the index in the status block
3162     */
3163    rmb();
3164
3165    BLOGD(sc, DBG_RX,
3166          "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3167          fp->index, hw_cq_cons, sw_cq_cons);
3168
3169    while (sw_cq_cons != hw_cq_cons) {
3170        struct bxe_sw_rx_bd *rx_buf = NULL;
3171        union eth_rx_cqe *cqe;
3172        struct eth_fast_path_rx_cqe *cqe_fp;
3173        uint8_t cqe_fp_flags;
3174        enum eth_rx_cqe_type cqe_fp_type;
3175        uint16_t len, lenonbd,  pad;
3176        struct mbuf *m = NULL;
3177
3178        comp_ring_cons = RCQ(sw_cq_cons);
3179        bd_prod = RX_BD(bd_prod);
3180        bd_cons = RX_BD(bd_cons);
3181
3182        cqe          = &fp->rcq_chain[comp_ring_cons];
3183        cqe_fp       = &cqe->fast_path_cqe;
3184        cqe_fp_flags = cqe_fp->type_error_flags;
3185        cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3186
3187        BLOGD(sc, DBG_RX,
3188              "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3189              "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3190              "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3191              fp->index,
3192              hw_cq_cons,
3193              sw_cq_cons,
3194              bd_prod,
3195              bd_cons,
3196              CQE_TYPE(cqe_fp_flags),
3197              cqe_fp_flags,
3198              cqe_fp->status_flags,
3199              le32toh(cqe_fp->rss_hash_result),
3200              le16toh(cqe_fp->vlan_tag),
3201              le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3202              le16toh(cqe_fp->len_on_bd));
3203
3204        /* is this a slowpath msg? */
3205        if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3206            bxe_sp_event(sc, fp, cqe);
3207            goto next_cqe;
3208        }
3209
3210        rx_buf = &fp->rx_mbuf_chain[bd_cons];
3211
3212        if (!CQE_TYPE_FAST(cqe_fp_type)) {
3213            struct bxe_sw_tpa_info *tpa_info;
3214            uint16_t frag_size, pages;
3215            uint8_t queue;
3216
3217            if (CQE_TYPE_START(cqe_fp_type)) {
3218                bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3219                              bd_cons, bd_prod, cqe_fp);
3220                m = NULL; /* packet not ready yet */
3221                goto next_rx;
3222            }
3223
3224            KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3225                    ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3226
3227            queue = cqe->end_agg_cqe.queue_index;
3228            tpa_info = &fp->rx_tpa_info[queue];
3229
3230            BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3231                  fp->index, queue);
3232
3233            frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3234                         tpa_info->len_on_bd);
3235            pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3236
3237            bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3238                         &cqe->end_agg_cqe, comp_ring_cons);
3239
3240            bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3241
3242            goto next_cqe;
3243        }
3244
3245        /* non TPA */
3246
3247        /* is this an error packet? */
3248        if (__predict_false(cqe_fp_flags &
3249                            ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3250            BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3251            fp->eth_q_stats.rx_soft_errors++;
3252            goto next_rx;
3253        }
3254
3255        len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3256        lenonbd = le16toh(cqe_fp->len_on_bd);
3257        pad = cqe_fp->placement_offset;
3258
3259        m = rx_buf->m;
3260
3261        if (__predict_false(m == NULL)) {
3262            BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3263                  bd_cons, fp->index);
3264            goto next_rx;
3265        }
3266
3267        /* XXX double copy if packet length under a threshold */
3268
3269        /*
3270         * If all the buffer descriptors are filled with mbufs then fill in
3271         * the current consumer index with a new BD. Else if a maximum Rx
3272         * buffer limit is imposed then fill in the next producer index.
3273         */
3274        rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3275                                  (sc->max_rx_bufs != RX_BD_USABLE) ?
3276                                      bd_prod : bd_cons);
3277        if (rc != 0) {
3278
3279            /* we simply reuse the received mbuf and don't post it to the stack */
3280            m = NULL;
3281
3282            BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3283                  fp->index, rc);
3284            fp->eth_q_stats.rx_soft_errors++;
3285
3286            if (sc->max_rx_bufs != RX_BD_USABLE) {
3287                /* copy this consumer index to the producer index */
3288                memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3289                       sizeof(struct bxe_sw_rx_bd));
3290                memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3291            }
3292
3293            goto next_rx;
3294        }
3295
3296        /* current mbuf was detached from the bd */
3297        fp->eth_q_stats.mbuf_alloc_rx--;
3298
3299        /* we allocated a replacement mbuf, fixup the current one */
3300        m_adj(m, pad);
3301        m->m_pkthdr.len = m->m_len = len;
3302
3303        if ((len > 60) && (len > lenonbd)) {
3304            fp->eth_q_stats.rx_bxe_service_rxsgl++;
3305            rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3306            if (rc)
3307                break;
3308            fp->eth_q_stats.rx_jumbo_sge_pkts++;
3309        } else if (lenonbd < len) {
3310            fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3311        }
3312
3313        /* assign packet to this interface interface */
3314	if_setrcvif(m, ifp);
3315
3316        /* assume no hardware checksum has complated */
3317        m->m_pkthdr.csum_flags = 0;
3318
3319        /* validate checksum if offload enabled */
3320        if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
3321            /* check for a valid IP frame */
3322            if (!(cqe->fast_path_cqe.status_flags &
3323                  ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3324                m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3325                if (__predict_false(cqe_fp_flags &
3326                                    ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3327                    fp->eth_q_stats.rx_hw_csum_errors++;
3328                } else {
3329                    fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3330                    m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3331                }
3332            }
3333
3334            /* check for a valid TCP/UDP frame */
3335            if (!(cqe->fast_path_cqe.status_flags &
3336                  ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3337                if (__predict_false(cqe_fp_flags &
3338                                    ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3339                    fp->eth_q_stats.rx_hw_csum_errors++;
3340                } else {
3341                    fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3342                    m->m_pkthdr.csum_data = 0xFFFF;
3343                    m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3344                                               CSUM_PSEUDO_HDR);
3345                }
3346            }
3347        }
3348
3349        /* if there is a VLAN tag then flag that info */
3350        if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3351            m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3352            m->m_flags |= M_VLANTAG;
3353        }
3354
3355#if __FreeBSD_version >= 800000
3356        /* specify what RSS queue was used for this flow */
3357        m->m_pkthdr.flowid = fp->index;
3358        BXE_SET_FLOWID(m);
3359#endif
3360
3361next_rx:
3362
3363        bd_cons    = RX_BD_NEXT(bd_cons);
3364        bd_prod    = RX_BD_NEXT(bd_prod);
3365        bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3366
3367        /* pass the frame to the stack */
3368        if (__predict_true(m != NULL)) {
3369            if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3370            rx_pkts++;
3371            if_input(ifp, m);
3372        }
3373
3374next_cqe:
3375
3376        sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3377        sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3378
3379        /* limit spinning on the queue */
3380        if (rc != 0)
3381            break;
3382
3383        if (rx_pkts == sc->rx_budget) {
3384            fp->eth_q_stats.rx_budget_reached++;
3385            break;
3386        }
3387    } /* while work to do */
3388
3389    fp->rx_bd_cons = bd_cons;
3390    fp->rx_bd_prod = bd_prod_fw;
3391    fp->rx_cq_cons = sw_cq_cons;
3392    fp->rx_cq_prod = sw_cq_prod;
3393
3394    /* Update producers */
3395    bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3396
3397    fp->eth_q_stats.rx_pkts += rx_pkts;
3398    fp->eth_q_stats.rx_calls++;
3399
3400    BXE_FP_RX_UNLOCK(fp);
3401
3402    return (sw_cq_cons != hw_cq_cons);
3403}
3404
3405static uint16_t
3406bxe_free_tx_pkt(struct bxe_softc    *sc,
3407                struct bxe_fastpath *fp,
3408                uint16_t            idx)
3409{
3410    struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3411    struct eth_tx_start_bd *tx_start_bd;
3412    uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3413    uint16_t new_cons;
3414    int nbd;
3415
3416    /* unmap the mbuf from non-paged memory */
3417    bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3418
3419    tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3420    nbd = le16toh(tx_start_bd->nbd) - 1;
3421
3422    new_cons = (tx_buf->first_bd + nbd);
3423
3424    /* free the mbuf */
3425    if (__predict_true(tx_buf->m != NULL)) {
3426        m_freem(tx_buf->m);
3427        fp->eth_q_stats.mbuf_alloc_tx--;
3428    } else {
3429        fp->eth_q_stats.tx_chain_lost_mbuf++;
3430    }
3431
3432    tx_buf->m = NULL;
3433    tx_buf->first_bd = 0;
3434
3435    return (new_cons);
3436}
3437
3438/* transmit timeout watchdog */
3439static int
3440bxe_watchdog(struct bxe_softc    *sc,
3441             struct bxe_fastpath *fp)
3442{
3443    BXE_FP_TX_LOCK(fp);
3444
3445    if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3446        BXE_FP_TX_UNLOCK(fp);
3447        return (0);
3448    }
3449
3450    BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3451    if(sc->trigger_grcdump) {
3452         /* taking grcdump */
3453         bxe_grc_dump(sc);
3454    }
3455
3456    BXE_FP_TX_UNLOCK(fp);
3457
3458    atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3459    taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3460
3461    return (-1);
3462}
3463
3464/* processes transmit completions */
3465static uint8_t
3466bxe_txeof(struct bxe_softc    *sc,
3467          struct bxe_fastpath *fp)
3468{
3469    if_t ifp = sc->ifp;
3470    uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3471    uint16_t tx_bd_avail;
3472
3473    BXE_FP_TX_LOCK_ASSERT(fp);
3474
3475    bd_cons = fp->tx_bd_cons;
3476    hw_cons = le16toh(*fp->tx_cons_sb);
3477    sw_cons = fp->tx_pkt_cons;
3478
3479    while (sw_cons != hw_cons) {
3480        pkt_cons = TX_BD(sw_cons);
3481
3482        BLOGD(sc, DBG_TX,
3483              "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3484              fp->index, hw_cons, sw_cons, pkt_cons);
3485
3486        bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3487
3488        sw_cons++;
3489    }
3490
3491    fp->tx_pkt_cons = sw_cons;
3492    fp->tx_bd_cons  = bd_cons;
3493
3494    BLOGD(sc, DBG_TX,
3495          "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3496          fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3497
3498    mb();
3499
3500    tx_bd_avail = bxe_tx_avail(sc, fp);
3501
3502    if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3503        if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
3504    } else {
3505        if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
3506    }
3507
3508    if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3509        /* reset the watchdog timer if there are pending transmits */
3510        fp->watchdog_timer = BXE_TX_TIMEOUT;
3511        return (TRUE);
3512    } else {
3513        /* clear watchdog when there are no pending transmits */
3514        fp->watchdog_timer = 0;
3515        return (FALSE);
3516    }
3517}
3518
3519static void
3520bxe_drain_tx_queues(struct bxe_softc *sc)
3521{
3522    struct bxe_fastpath *fp;
3523    int i, count;
3524
3525    /* wait until all TX fastpath tasks have completed */
3526    for (i = 0; i < sc->num_queues; i++) {
3527        fp = &sc->fp[i];
3528
3529        count = 1000;
3530
3531        while (bxe_has_tx_work(fp)) {
3532
3533            BXE_FP_TX_LOCK(fp);
3534            bxe_txeof(sc, fp);
3535            BXE_FP_TX_UNLOCK(fp);
3536
3537            if (count == 0) {
3538                BLOGE(sc, "Timeout waiting for fp[%d] "
3539                          "transmits to complete!\n", i);
3540                bxe_panic(sc, ("tx drain failure\n"));
3541                return;
3542            }
3543
3544            count--;
3545            DELAY(1000);
3546            rmb();
3547        }
3548    }
3549
3550    return;
3551}
3552
3553static int
3554bxe_del_all_macs(struct bxe_softc          *sc,
3555                 struct ecore_vlan_mac_obj *mac_obj,
3556                 int                       mac_type,
3557                 uint8_t                   wait_for_comp)
3558{
3559    unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3560    int rc;
3561
3562    /* wait for completion of requested */
3563    if (wait_for_comp) {
3564        bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3565    }
3566
3567    /* Set the mac type of addresses we want to clear */
3568    bxe_set_bit(mac_type, &vlan_mac_flags);
3569
3570    rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3571    if (rc < 0) {
3572        BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3573            rc, mac_type, wait_for_comp);
3574    }
3575
3576    return (rc);
3577}
3578
3579static int
3580bxe_fill_accept_flags(struct bxe_softc *sc,
3581                      uint32_t         rx_mode,
3582                      unsigned long    *rx_accept_flags,
3583                      unsigned long    *tx_accept_flags)
3584{
3585    /* Clear the flags first */
3586    *rx_accept_flags = 0;
3587    *tx_accept_flags = 0;
3588
3589    switch (rx_mode) {
3590    case BXE_RX_MODE_NONE:
3591        /*
3592         * 'drop all' supersedes any accept flags that may have been
3593         * passed to the function.
3594         */
3595        break;
3596
3597    case BXE_RX_MODE_NORMAL:
3598        bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3599        bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3600        bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3601
3602        /* internal switching mode */
3603        bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3604        bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3605        bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3606
3607        break;
3608
3609    case BXE_RX_MODE_ALLMULTI:
3610        bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3611        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3612        bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3613
3614        /* internal switching mode */
3615        bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3616        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3617        bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3618
3619        break;
3620
3621    case BXE_RX_MODE_PROMISC:
3622        /*
3623         * According to deffinition of SI mode, iface in promisc mode
3624         * should receive matched and unmatched (in resolution of port)
3625         * unicast packets.
3626         */
3627        bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3628        bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3629        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3630        bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3631
3632        /* internal switching mode */
3633        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3634        bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3635
3636        if (IS_MF_SI(sc)) {
3637            bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3638        } else {
3639            bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3640        }
3641
3642        break;
3643
3644    default:
3645        BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3646        return (-1);
3647    }
3648
3649    /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3650    if (rx_mode != BXE_RX_MODE_NONE) {
3651        bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3652        bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3653    }
3654
3655    return (0);
3656}
3657
3658static int
3659bxe_set_q_rx_mode(struct bxe_softc *sc,
3660                  uint8_t          cl_id,
3661                  unsigned long    rx_mode_flags,
3662                  unsigned long    rx_accept_flags,
3663                  unsigned long    tx_accept_flags,
3664                  unsigned long    ramrod_flags)
3665{
3666    struct ecore_rx_mode_ramrod_params ramrod_param;
3667    int rc;
3668
3669    memset(&ramrod_param, 0, sizeof(ramrod_param));
3670
3671    /* Prepare ramrod parameters */
3672    ramrod_param.cid = 0;
3673    ramrod_param.cl_id = cl_id;
3674    ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3675    ramrod_param.func_id = SC_FUNC(sc);
3676
3677    ramrod_param.pstate = &sc->sp_state;
3678    ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3679
3680    ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3681    ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3682
3683    bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3684
3685    ramrod_param.ramrod_flags = ramrod_flags;
3686    ramrod_param.rx_mode_flags = rx_mode_flags;
3687
3688    ramrod_param.rx_accept_flags = rx_accept_flags;
3689    ramrod_param.tx_accept_flags = tx_accept_flags;
3690
3691    rc = ecore_config_rx_mode(sc, &ramrod_param);
3692    if (rc < 0) {
3693        BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3694            "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3695            "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3696            (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3697            (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3698        return (rc);
3699    }
3700
3701    return (0);
3702}
3703
3704static int
3705bxe_set_storm_rx_mode(struct bxe_softc *sc)
3706{
3707    unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3708    unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3709    int rc;
3710
3711    rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3712                               &tx_accept_flags);
3713    if (rc) {
3714        return (rc);
3715    }
3716
3717    bxe_set_bit(RAMROD_RX, &ramrod_flags);
3718    bxe_set_bit(RAMROD_TX, &ramrod_flags);
3719
3720    /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3721    return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3722                              rx_accept_flags, tx_accept_flags,
3723                              ramrod_flags));
3724}
3725
3726/* returns the "mcp load_code" according to global load_count array */
3727static int
3728bxe_nic_load_no_mcp(struct bxe_softc *sc)
3729{
3730    int path = SC_PATH(sc);
3731    int port = SC_PORT(sc);
3732
3733    BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3734          path, load_count[path][0], load_count[path][1],
3735          load_count[path][2]);
3736    load_count[path][0]++;
3737    load_count[path][1 + port]++;
3738    BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3739          path, load_count[path][0], load_count[path][1],
3740          load_count[path][2]);
3741    if (load_count[path][0] == 1) {
3742        return (FW_MSG_CODE_DRV_LOAD_COMMON);
3743    } else if (load_count[path][1 + port] == 1) {
3744        return (FW_MSG_CODE_DRV_LOAD_PORT);
3745    } else {
3746        return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3747    }
3748}
3749
3750/* returns the "mcp load_code" according to global load_count array */
3751static int
3752bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3753{
3754    int port = SC_PORT(sc);
3755    int path = SC_PATH(sc);
3756
3757    BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3758          path, load_count[path][0], load_count[path][1],
3759          load_count[path][2]);
3760    load_count[path][0]--;
3761    load_count[path][1 + port]--;
3762    BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3763          path, load_count[path][0], load_count[path][1],
3764          load_count[path][2]);
3765    if (load_count[path][0] == 0) {
3766        return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3767    } else if (load_count[path][1 + port] == 0) {
3768        return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3769    } else {
3770        return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3771    }
3772}
3773
3774/* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3775static uint32_t
3776bxe_send_unload_req(struct bxe_softc *sc,
3777                    int              unload_mode)
3778{
3779    uint32_t reset_code = 0;
3780
3781    /* Select the UNLOAD request mode */
3782    if (unload_mode == UNLOAD_NORMAL) {
3783        reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3784    } else {
3785        reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3786    }
3787
3788    /* Send the request to the MCP */
3789    if (!BXE_NOMCP(sc)) {
3790        reset_code = bxe_fw_command(sc, reset_code, 0);
3791    } else {
3792        reset_code = bxe_nic_unload_no_mcp(sc);
3793    }
3794
3795    return (reset_code);
3796}
3797
3798/* send UNLOAD_DONE command to the MCP */
3799static void
3800bxe_send_unload_done(struct bxe_softc *sc,
3801                     uint8_t          keep_link)
3802{
3803    uint32_t reset_param =
3804        keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3805
3806    /* Report UNLOAD_DONE to MCP */
3807    if (!BXE_NOMCP(sc)) {
3808        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3809    }
3810}
3811
3812static int
3813bxe_func_wait_started(struct bxe_softc *sc)
3814{
3815    int tout = 50;
3816
3817    if (!sc->port.pmf) {
3818        return (0);
3819    }
3820
3821    /*
3822     * (assumption: No Attention from MCP at this stage)
3823     * PMF probably in the middle of TX disable/enable transaction
3824     * 1. Sync IRS for default SB
3825     * 2. Sync SP queue - this guarantees us that attention handling started
3826     * 3. Wait, that TX disable/enable transaction completes
3827     *
3828     * 1+2 guarantee that if DCBX attention was scheduled it already changed
3829     * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3830     * received completion for the transaction the state is TX_STOPPED.
3831     * State will return to STARTED after completion of TX_STOPPED-->STARTED
3832     * transaction.
3833     */
3834
3835    /* XXX make sure default SB ISR is done */
3836    /* need a way to synchronize an irq (intr_mtx?) */
3837
3838    /* XXX flush any work queues */
3839
3840    while (ecore_func_get_state(sc, &sc->func_obj) !=
3841           ECORE_F_STATE_STARTED && tout--) {
3842        DELAY(20000);
3843    }
3844
3845    if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3846        /*
3847         * Failed to complete the transaction in a "good way"
3848         * Force both transactions with CLR bit.
3849         */
3850        struct ecore_func_state_params func_params = { NULL };
3851
3852        BLOGE(sc, "Unexpected function state! "
3853                  "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3854
3855        func_params.f_obj = &sc->func_obj;
3856        bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3857
3858        /* STARTED-->TX_STOPPED */
3859        func_params.cmd = ECORE_F_CMD_TX_STOP;
3860        ecore_func_state_change(sc, &func_params);
3861
3862        /* TX_STOPPED-->STARTED */
3863        func_params.cmd = ECORE_F_CMD_TX_START;
3864        return (ecore_func_state_change(sc, &func_params));
3865    }
3866
3867    return (0);
3868}
3869
3870static int
3871bxe_stop_queue(struct bxe_softc *sc,
3872               int              index)
3873{
3874    struct bxe_fastpath *fp = &sc->fp[index];
3875    struct ecore_queue_state_params q_params = { NULL };
3876    int rc;
3877
3878    BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3879
3880    q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3881    /* We want to wait for completion in this context */
3882    bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3883
3884    /* Stop the primary connection: */
3885
3886    /* ...halt the connection */
3887    q_params.cmd = ECORE_Q_CMD_HALT;
3888    rc = ecore_queue_state_change(sc, &q_params);
3889    if (rc) {
3890        return (rc);
3891    }
3892
3893    /* ...terminate the connection */
3894    q_params.cmd = ECORE_Q_CMD_TERMINATE;
3895    memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3896    q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3897    rc = ecore_queue_state_change(sc, &q_params);
3898    if (rc) {
3899        return (rc);
3900    }
3901
3902    /* ...delete cfc entry */
3903    q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3904    memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3905    q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3906    return (ecore_queue_state_change(sc, &q_params));
3907}
3908
3909/* wait for the outstanding SP commands */
3910static inline uint8_t
3911bxe_wait_sp_comp(struct bxe_softc *sc,
3912                 unsigned long    mask)
3913{
3914    unsigned long tmp;
3915    int tout = 5000; /* wait for 5 secs tops */
3916
3917    while (tout--) {
3918        mb();
3919        if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3920            return (TRUE);
3921        }
3922
3923        DELAY(1000);
3924    }
3925
3926    mb();
3927
3928    tmp = atomic_load_acq_long(&sc->sp_state);
3929    if (tmp & mask) {
3930        BLOGE(sc, "Filtering completion timed out: "
3931                  "sp_state 0x%lx, mask 0x%lx\n",
3932              tmp, mask);
3933        return (FALSE);
3934    }
3935
3936    return (FALSE);
3937}
3938
3939static int
3940bxe_func_stop(struct bxe_softc *sc)
3941{
3942    struct ecore_func_state_params func_params = { NULL };
3943    int rc;
3944
3945    /* prepare parameters for function state transitions */
3946    bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3947    func_params.f_obj = &sc->func_obj;
3948    func_params.cmd = ECORE_F_CMD_STOP;
3949
3950    /*
3951     * Try to stop the function the 'good way'. If it fails (in case
3952     * of a parity error during bxe_chip_cleanup()) and we are
3953     * not in a debug mode, perform a state transaction in order to
3954     * enable further HW_RESET transaction.
3955     */
3956    rc = ecore_func_state_change(sc, &func_params);
3957    if (rc) {
3958        BLOGE(sc, "FUNC_STOP ramrod failed. "
3959                  "Running a dry transaction (%d)\n", rc);
3960        bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3961        return (ecore_func_state_change(sc, &func_params));
3962    }
3963
3964    return (0);
3965}
3966
3967static int
3968bxe_reset_hw(struct bxe_softc *sc,
3969             uint32_t         load_code)
3970{
3971    struct ecore_func_state_params func_params = { NULL };
3972
3973    /* Prepare parameters for function state transitions */
3974    bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3975
3976    func_params.f_obj = &sc->func_obj;
3977    func_params.cmd = ECORE_F_CMD_HW_RESET;
3978
3979    func_params.params.hw_init.load_phase = load_code;
3980
3981    return (ecore_func_state_change(sc, &func_params));
3982}
3983
3984static void
3985bxe_int_disable_sync(struct bxe_softc *sc,
3986                     int              disable_hw)
3987{
3988    if (disable_hw) {
3989        /* prevent the HW from sending interrupts */
3990        bxe_int_disable(sc);
3991    }
3992
3993    /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
3994    /* make sure all ISRs are done */
3995
3996    /* XXX make sure sp_task is not running */
3997    /* cancel and flush work queues */
3998}
3999
4000static void
4001bxe_chip_cleanup(struct bxe_softc *sc,
4002                 uint32_t         unload_mode,
4003                 uint8_t          keep_link)
4004{
4005    int port = SC_PORT(sc);
4006    struct ecore_mcast_ramrod_params rparam = { NULL };
4007    uint32_t reset_code;
4008    int i, rc = 0;
4009
4010    bxe_drain_tx_queues(sc);
4011
4012    /* give HW time to discard old tx messages */
4013    DELAY(1000);
4014
4015    /* Clean all ETH MACs */
4016    rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4017    if (rc < 0) {
4018        BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4019    }
4020
4021    /* Clean up UC list  */
4022    rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4023    if (rc < 0) {
4024        BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4025    }
4026
4027    /* Disable LLH */
4028    if (!CHIP_IS_E1(sc)) {
4029        REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4030    }
4031
4032    /* Set "drop all" to stop Rx */
4033
4034    /*
4035     * We need to take the BXE_MCAST_LOCK() here in order to prevent
4036     * a race between the completion code and this code.
4037     */
4038    BXE_MCAST_LOCK(sc);
4039
4040    if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4041        bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4042    } else {
4043        bxe_set_storm_rx_mode(sc);
4044    }
4045
4046    /* Clean up multicast configuration */
4047    rparam.mcast_obj = &sc->mcast_obj;
4048    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4049    if (rc < 0) {
4050        BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4051    }
4052
4053    BXE_MCAST_UNLOCK(sc);
4054
4055    // XXX bxe_iov_chip_cleanup(sc);
4056
4057    /*
4058     * Send the UNLOAD_REQUEST to the MCP. This will return if
4059     * this function should perform FUNCTION, PORT, or COMMON HW
4060     * reset.
4061     */
4062    reset_code = bxe_send_unload_req(sc, unload_mode);
4063
4064    /*
4065     * (assumption: No Attention from MCP at this stage)
4066     * PMF probably in the middle of TX disable/enable transaction
4067     */
4068    rc = bxe_func_wait_started(sc);
4069    if (rc) {
4070        BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4071    }
4072
4073    /*
4074     * Close multi and leading connections
4075     * Completions for ramrods are collected in a synchronous way
4076     */
4077    for (i = 0; i < sc->num_queues; i++) {
4078        if (bxe_stop_queue(sc, i)) {
4079            goto unload_error;
4080        }
4081    }
4082
4083    /*
4084     * If SP settings didn't get completed so far - something
4085     * very wrong has happen.
4086     */
4087    if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4088        BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4089    }
4090
4091unload_error:
4092
4093    rc = bxe_func_stop(sc);
4094    if (rc) {
4095        BLOGE(sc, "Function stop failed!(%d)\n", rc);
4096    }
4097
4098    /* disable HW interrupts */
4099    bxe_int_disable_sync(sc, TRUE);
4100
4101    /* detach interrupts */
4102    bxe_interrupt_detach(sc);
4103
4104    /* Reset the chip */
4105    rc = bxe_reset_hw(sc, reset_code);
4106    if (rc) {
4107        BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4108    }
4109
4110    /* Report UNLOAD_DONE to MCP */
4111    bxe_send_unload_done(sc, keep_link);
4112}
4113
4114static void
4115bxe_disable_close_the_gate(struct bxe_softc *sc)
4116{
4117    uint32_t val;
4118    int port = SC_PORT(sc);
4119
4120    BLOGD(sc, DBG_LOAD,
4121          "Disabling 'close the gates'\n");
4122
4123    if (CHIP_IS_E1(sc)) {
4124        uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4125                               MISC_REG_AEU_MASK_ATTN_FUNC_0;
4126        val = REG_RD(sc, addr);
4127        val &= ~(0x300);
4128        REG_WR(sc, addr, val);
4129    } else {
4130        val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4131        val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4132                 MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4133        REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4134    }
4135}
4136
4137/*
4138 * Cleans the object that have internal lists without sending
4139 * ramrods. Should be run when interrutps are disabled.
4140 */
4141static void
4142bxe_squeeze_objects(struct bxe_softc *sc)
4143{
4144    unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4145    struct ecore_mcast_ramrod_params rparam = { NULL };
4146    struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4147    int rc;
4148
4149    /* Cleanup MACs' object first... */
4150
4151    /* Wait for completion of requested */
4152    bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4153    /* Perform a dry cleanup */
4154    bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4155
4156    /* Clean ETH primary MAC */
4157    bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4158    rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4159                             &ramrod_flags);
4160    if (rc != 0) {
4161        BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4162    }
4163
4164    /* Cleanup UC list */
4165    vlan_mac_flags = 0;
4166    bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4167    rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4168                             &ramrod_flags);
4169    if (rc != 0) {
4170        BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4171    }
4172
4173    /* Now clean mcast object... */
4174
4175    rparam.mcast_obj = &sc->mcast_obj;
4176    bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4177
4178    /* Add a DEL command... */
4179    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4180    if (rc < 0) {
4181        BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4182    }
4183
4184    /* now wait until all pending commands are cleared */
4185
4186    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4187    while (rc != 0) {
4188        if (rc < 0) {
4189            BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4190            return;
4191        }
4192
4193        rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4194    }
4195}
4196
4197/* stop the controller */
4198static __noinline int
4199bxe_nic_unload(struct bxe_softc *sc,
4200               uint32_t         unload_mode,
4201               uint8_t          keep_link)
4202{
4203    uint8_t global = FALSE;
4204    uint32_t val;
4205    int i;
4206
4207    BXE_CORE_LOCK_ASSERT(sc);
4208
4209    if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
4210
4211    for (i = 0; i < sc->num_queues; i++) {
4212        struct bxe_fastpath *fp;
4213
4214        fp = &sc->fp[i];
4215        BXE_FP_TX_LOCK(fp);
4216        BXE_FP_TX_UNLOCK(fp);
4217    }
4218
4219    BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4220
4221    /* mark driver as unloaded in shmem2 */
4222    if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4223        val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4224        SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4225                  val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4226    }
4227
4228    if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4229        (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4230        /*
4231         * We can get here if the driver has been unloaded
4232         * during parity error recovery and is either waiting for a
4233         * leader to complete or for other functions to unload and
4234         * then ifconfig down has been issued. In this case we want to
4235         * unload and let other functions to complete a recovery
4236         * process.
4237         */
4238        sc->recovery_state = BXE_RECOVERY_DONE;
4239        sc->is_leader = 0;
4240        bxe_release_leader_lock(sc);
4241        mb();
4242
4243        BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4244        BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4245            " state = 0x%x\n", sc->recovery_state, sc->state);
4246        return (-1);
4247    }
4248
4249    /*
4250     * Nothing to do during unload if previous bxe_nic_load()
4251     * did not completed successfully - all resourses are released.
4252     */
4253    if ((sc->state == BXE_STATE_CLOSED) ||
4254        (sc->state == BXE_STATE_ERROR)) {
4255        return (0);
4256    }
4257
4258    sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4259    mb();
4260
4261    /* stop tx */
4262    bxe_tx_disable(sc);
4263
4264    sc->rx_mode = BXE_RX_MODE_NONE;
4265    /* XXX set rx mode ??? */
4266
4267    if (IS_PF(sc) && !sc->grcdump_done) {
4268        /* set ALWAYS_ALIVE bit in shmem */
4269        sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4270
4271        bxe_drv_pulse(sc);
4272
4273        bxe_stats_handle(sc, STATS_EVENT_STOP);
4274        bxe_save_statistics(sc);
4275    }
4276
4277    /* wait till consumers catch up with producers in all queues */
4278    bxe_drain_tx_queues(sc);
4279
4280    /* if VF indicate to PF this function is going down (PF will delete sp
4281     * elements and clear initializations
4282     */
4283    if (IS_VF(sc)) {
4284        ; /* bxe_vfpf_close_vf(sc); */
4285    } else if (unload_mode != UNLOAD_RECOVERY) {
4286        /* if this is a normal/close unload need to clean up chip */
4287        if (!sc->grcdump_done)
4288            bxe_chip_cleanup(sc, unload_mode, keep_link);
4289    } else {
4290        /* Send the UNLOAD_REQUEST to the MCP */
4291        bxe_send_unload_req(sc, unload_mode);
4292
4293        /*
4294         * Prevent transactions to host from the functions on the
4295         * engine that doesn't reset global blocks in case of global
4296         * attention once gloabl blocks are reset and gates are opened
4297         * (the engine which leader will perform the recovery
4298         * last).
4299         */
4300        if (!CHIP_IS_E1x(sc)) {
4301            bxe_pf_disable(sc);
4302        }
4303
4304        /* disable HW interrupts */
4305        bxe_int_disable_sync(sc, TRUE);
4306
4307        /* detach interrupts */
4308        bxe_interrupt_detach(sc);
4309
4310        /* Report UNLOAD_DONE to MCP */
4311        bxe_send_unload_done(sc, FALSE);
4312    }
4313
4314    /*
4315     * At this stage no more interrupts will arrive so we may safely clean
4316     * the queue'able objects here in case they failed to get cleaned so far.
4317     */
4318    if (IS_PF(sc)) {
4319        bxe_squeeze_objects(sc);
4320    }
4321
4322    /* There should be no more pending SP commands at this stage */
4323    sc->sp_state = 0;
4324
4325    sc->port.pmf = 0;
4326
4327    bxe_free_fp_buffers(sc);
4328
4329    if (IS_PF(sc)) {
4330        bxe_free_mem(sc);
4331    }
4332
4333    bxe_free_fw_stats_mem(sc);
4334
4335    sc->state = BXE_STATE_CLOSED;
4336
4337    /*
4338     * Check if there are pending parity attentions. If there are - set
4339     * RECOVERY_IN_PROGRESS.
4340     */
4341    if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4342        bxe_set_reset_in_progress(sc);
4343
4344        /* Set RESET_IS_GLOBAL if needed */
4345        if (global) {
4346            bxe_set_reset_global(sc);
4347        }
4348    }
4349
4350    /*
4351     * The last driver must disable a "close the gate" if there is no
4352     * parity attention or "process kill" pending.
4353     */
4354    if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4355        bxe_reset_is_done(sc, SC_PATH(sc))) {
4356        bxe_disable_close_the_gate(sc);
4357    }
4358
4359    BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4360
4361    return (0);
4362}
4363
4364/*
4365 * Called by the OS to set various media options (i.e. link, speed, etc.) when
4366 * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4367 */
4368static int
4369bxe_ifmedia_update(struct ifnet  *ifp)
4370{
4371    struct bxe_softc *sc = (struct bxe_softc *)if_getsoftc(ifp);
4372    struct ifmedia *ifm;
4373
4374    ifm = &sc->ifmedia;
4375
4376    /* We only support Ethernet media type. */
4377    if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4378        return (EINVAL);
4379    }
4380
4381    switch (IFM_SUBTYPE(ifm->ifm_media)) {
4382    case IFM_AUTO:
4383         break;
4384    case IFM_10G_CX4:
4385    case IFM_10G_SR:
4386    case IFM_10G_T:
4387    case IFM_10G_TWINAX:
4388    default:
4389        /* We don't support changing the media type. */
4390        BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4391              IFM_SUBTYPE(ifm->ifm_media));
4392        return (EINVAL);
4393    }
4394
4395    return (0);
4396}
4397
4398/*
4399 * Called by the OS to get the current media status (i.e. link, speed, etc.).
4400 */
4401static void
4402bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4403{
4404    struct bxe_softc *sc = if_getsoftc(ifp);
4405
4406    /* Report link down if the driver isn't running. */
4407    if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0) {
4408        ifmr->ifm_active |= IFM_NONE;
4409        return;
4410    }
4411
4412    /* Setup the default interface info. */
4413    ifmr->ifm_status = IFM_AVALID;
4414    ifmr->ifm_active = IFM_ETHER;
4415
4416    if (sc->link_vars.link_up) {
4417        ifmr->ifm_status |= IFM_ACTIVE;
4418    } else {
4419        ifmr->ifm_active |= IFM_NONE;
4420        return;
4421    }
4422
4423    ifmr->ifm_active |= sc->media;
4424
4425    if (sc->link_vars.duplex == DUPLEX_FULL) {
4426        ifmr->ifm_active |= IFM_FDX;
4427    } else {
4428        ifmr->ifm_active |= IFM_HDX;
4429    }
4430}
4431
4432static void
4433bxe_handle_chip_tq(void *context,
4434                   int  pending)
4435{
4436    struct bxe_softc *sc = (struct bxe_softc *)context;
4437    long work = atomic_load_acq_long(&sc->chip_tq_flags);
4438
4439    switch (work)
4440    {
4441
4442    case CHIP_TQ_REINIT:
4443        if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
4444            /* restart the interface */
4445            BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4446            bxe_periodic_stop(sc);
4447            BXE_CORE_LOCK(sc);
4448            bxe_stop_locked(sc);
4449            bxe_init_locked(sc);
4450            BXE_CORE_UNLOCK(sc);
4451        }
4452        break;
4453
4454    default:
4455        break;
4456    }
4457}
4458
4459/*
4460 * Handles any IOCTL calls from the operating system.
4461 *
4462 * Returns:
4463 *   0 = Success, >0 Failure
4464 */
4465static int
4466bxe_ioctl(if_t ifp,
4467          u_long       command,
4468          caddr_t      data)
4469{
4470    struct bxe_softc *sc = if_getsoftc(ifp);
4471    struct ifreq *ifr = (struct ifreq *)data;
4472    int mask = 0;
4473    int reinit = 0;
4474    int error = 0;
4475
4476    int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4477    int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4478
4479    switch (command)
4480    {
4481    case SIOCSIFMTU:
4482        BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4483              ifr->ifr_mtu);
4484
4485        if (sc->mtu == ifr->ifr_mtu) {
4486            /* nothing to change */
4487            break;
4488        }
4489
4490        if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4491            BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4492                  ifr->ifr_mtu, mtu_min, mtu_max);
4493            error = EINVAL;
4494            break;
4495        }
4496
4497        atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4498                             (unsigned long)ifr->ifr_mtu);
4499	/*
4500        atomic_store_rel_long((volatile unsigned long *)&if_getmtu(ifp),
4501                              (unsigned long)ifr->ifr_mtu);
4502	XXX - Not sure why it needs to be atomic
4503	*/
4504	if_setmtu(ifp, ifr->ifr_mtu);
4505        reinit = 1;
4506        break;
4507
4508    case SIOCSIFFLAGS:
4509        /* toggle the interface state up or down */
4510        BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4511
4512	BXE_CORE_LOCK(sc);
4513        /* check if the interface is up */
4514        if (if_getflags(ifp) & IFF_UP) {
4515            if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4516                /* set the receive mode flags */
4517                bxe_set_rx_mode(sc);
4518            } else if(sc->state != BXE_STATE_DISABLED) {
4519		bxe_init_locked(sc);
4520            }
4521        } else {
4522            if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4523		bxe_periodic_stop(sc);
4524		bxe_stop_locked(sc);
4525            }
4526        }
4527	BXE_CORE_UNLOCK(sc);
4528
4529        break;
4530
4531    case SIOCADDMULTI:
4532    case SIOCDELMULTI:
4533        /* add/delete multicast addresses */
4534        BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4535
4536        /* check if the interface is up */
4537        if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4538            /* set the receive mode flags */
4539	    BXE_CORE_LOCK(sc);
4540            bxe_set_rx_mode(sc);
4541	    BXE_CORE_UNLOCK(sc);
4542        }
4543
4544        break;
4545
4546    case SIOCSIFCAP:
4547        /* find out which capabilities have changed */
4548        mask = (ifr->ifr_reqcap ^ if_getcapenable(ifp));
4549
4550        BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4551              mask);
4552
4553        /* toggle the LRO capabilites enable flag */
4554        if (mask & IFCAP_LRO) {
4555	    if_togglecapenable(ifp, IFCAP_LRO);
4556            BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4557                  (if_getcapenable(ifp) & IFCAP_LRO) ? "ON" : "OFF");
4558            reinit = 1;
4559        }
4560
4561        /* toggle the TXCSUM checksum capabilites enable flag */
4562        if (mask & IFCAP_TXCSUM) {
4563	    if_togglecapenable(ifp, IFCAP_TXCSUM);
4564            BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4565                  (if_getcapenable(ifp) & IFCAP_TXCSUM) ? "ON" : "OFF");
4566            if (if_getcapenable(ifp) & IFCAP_TXCSUM) {
4567                if_sethwassistbits(ifp, (CSUM_IP      |
4568                                    CSUM_TCP      |
4569                                    CSUM_UDP      |
4570                                    CSUM_TSO      |
4571                                    CSUM_TCP_IPV6 |
4572                                    CSUM_UDP_IPV6), 0);
4573            } else {
4574		if_clearhwassist(ifp); /* XXX */
4575            }
4576        }
4577
4578        /* toggle the RXCSUM checksum capabilities enable flag */
4579        if (mask & IFCAP_RXCSUM) {
4580	    if_togglecapenable(ifp, IFCAP_RXCSUM);
4581            BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4582                  (if_getcapenable(ifp) & IFCAP_RXCSUM) ? "ON" : "OFF");
4583            if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
4584                if_sethwassistbits(ifp, (CSUM_IP      |
4585                                    CSUM_TCP      |
4586                                    CSUM_UDP      |
4587                                    CSUM_TSO      |
4588                                    CSUM_TCP_IPV6 |
4589                                    CSUM_UDP_IPV6), 0);
4590            } else {
4591		if_clearhwassist(ifp); /* XXX */
4592            }
4593        }
4594
4595        /* toggle TSO4 capabilities enabled flag */
4596        if (mask & IFCAP_TSO4) {
4597            if_togglecapenable(ifp, IFCAP_TSO4);
4598            BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4599                  (if_getcapenable(ifp) & IFCAP_TSO4) ? "ON" : "OFF");
4600        }
4601
4602        /* toggle TSO6 capabilities enabled flag */
4603        if (mask & IFCAP_TSO6) {
4604	    if_togglecapenable(ifp, IFCAP_TSO6);
4605            BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4606                  (if_getcapenable(ifp) & IFCAP_TSO6) ? "ON" : "OFF");
4607        }
4608
4609        /* toggle VLAN_HWTSO capabilities enabled flag */
4610        if (mask & IFCAP_VLAN_HWTSO) {
4611
4612	    if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
4613            BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4614                  (if_getcapenable(ifp) & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4615        }
4616
4617        /* toggle VLAN_HWCSUM capabilities enabled flag */
4618        if (mask & IFCAP_VLAN_HWCSUM) {
4619            /* XXX investigate this... */
4620            BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4621            error = EINVAL;
4622        }
4623
4624        /* toggle VLAN_MTU capabilities enable flag */
4625        if (mask & IFCAP_VLAN_MTU) {
4626            /* XXX investigate this... */
4627            BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4628            error = EINVAL;
4629        }
4630
4631        /* toggle VLAN_HWTAGGING capabilities enabled flag */
4632        if (mask & IFCAP_VLAN_HWTAGGING) {
4633            /* XXX investigate this... */
4634            BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4635            error = EINVAL;
4636        }
4637
4638        /* toggle VLAN_HWFILTER capabilities enabled flag */
4639        if (mask & IFCAP_VLAN_HWFILTER) {
4640            /* XXX investigate this... */
4641            BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4642            error = EINVAL;
4643        }
4644
4645        /* XXX not yet...
4646         * IFCAP_WOL_MAGIC
4647         */
4648
4649        break;
4650
4651    case SIOCSIFMEDIA:
4652    case SIOCGIFMEDIA:
4653        /* set/get interface media */
4654        BLOGD(sc, DBG_IOCTL,
4655              "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4656              (command & 0xff));
4657        error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4658        break;
4659
4660    default:
4661        BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4662              (command & 0xff));
4663        error = ether_ioctl(ifp, command, data);
4664        break;
4665    }
4666
4667    if (reinit && (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4668        BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4669              "Re-initializing hardware from IOCTL change\n");
4670	bxe_periodic_stop(sc);
4671	BXE_CORE_LOCK(sc);
4672	bxe_stop_locked(sc);
4673	bxe_init_locked(sc);
4674	BXE_CORE_UNLOCK(sc);
4675    }
4676
4677    return (error);
4678}
4679
4680static __noinline void
4681bxe_dump_mbuf(struct bxe_softc *sc,
4682              struct mbuf      *m,
4683              uint8_t          contents)
4684{
4685    char * type;
4686    int i = 0;
4687
4688    if (!(sc->debug & DBG_MBUF)) {
4689        return;
4690    }
4691
4692    if (m == NULL) {
4693        BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4694        return;
4695    }
4696
4697    while (m) {
4698
4699#if __FreeBSD_version >= 1000000
4700        BLOGD(sc, DBG_MBUF,
4701              "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4702              i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4703
4704        if (m->m_flags & M_PKTHDR) {
4705             BLOGD(sc, DBG_MBUF,
4706                   "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4707                   i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4708                   (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4709        }
4710#else
4711        BLOGD(sc, DBG_MBUF,
4712              "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4713              i, m, m->m_len, m->m_flags,
4714              "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4715
4716        if (m->m_flags & M_PKTHDR) {
4717             BLOGD(sc, DBG_MBUF,
4718                   "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4719                   i, m->m_pkthdr.len, m->m_flags,
4720                   "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4721                   "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4722                   "\22M_PROMISC\23M_NOFREE",
4723                   (int)m->m_pkthdr.csum_flags,
4724                   "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4725                   "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4726                   "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4727                   "\14CSUM_PSEUDO_HDR");
4728        }
4729#endif /* #if __FreeBSD_version >= 1000000 */
4730
4731        if (m->m_flags & M_EXT) {
4732            switch (m->m_ext.ext_type) {
4733            case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4734            case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4735            case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4736            case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4737            case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4738            case EXT_PACKET:     type = "EXT_PACKET";     break;
4739            case EXT_MBUF:       type = "EXT_MBUF";       break;
4740            case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4741            case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4742            case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4743            case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4744            default:             type = "UNKNOWN";        break;
4745            }
4746
4747            BLOGD(sc, DBG_MBUF,
4748                  "%02d: - m_ext: %p ext_size=%d type=%s\n",
4749                  i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4750        }
4751
4752        if (contents) {
4753            bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4754        }
4755
4756        m = m->m_next;
4757        i++;
4758    }
4759}
4760
4761/*
4762 * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4763 * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4764 * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4765 * The headers comes in a separate bd in FreeBSD so 13-3=10.
4766 * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4767 */
4768static int
4769bxe_chktso_window(struct bxe_softc  *sc,
4770                  int               nsegs,
4771                  bus_dma_segment_t *segs,
4772                  struct mbuf       *m)
4773{
4774    uint32_t num_wnds, wnd_size, wnd_sum;
4775    int32_t frag_idx, wnd_idx;
4776    unsigned short lso_mss;
4777    int defrag;
4778
4779    defrag = 0;
4780    wnd_sum = 0;
4781    wnd_size = 10;
4782    num_wnds = nsegs - wnd_size;
4783    lso_mss = htole16(m->m_pkthdr.tso_segsz);
4784
4785    /*
4786     * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4787     * first window sum of data while skipping the first assuming it is the
4788     * header in FreeBSD.
4789     */
4790    for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4791        wnd_sum += htole16(segs[frag_idx].ds_len);
4792    }
4793
4794    /* check the first 10 bd window size */
4795    if (wnd_sum < lso_mss) {
4796        return (1);
4797    }
4798
4799    /* run through the windows */
4800    for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4801        /* subtract the first mbuf->m_len of the last wndw(-header) */
4802        wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4803        /* add the next mbuf len to the len of our new window */
4804        wnd_sum += htole16(segs[frag_idx].ds_len);
4805        if (wnd_sum < lso_mss) {
4806            return (1);
4807        }
4808    }
4809
4810    return (0);
4811}
4812
4813static uint8_t
4814bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4815                    struct mbuf         *m,
4816                    uint32_t            *parsing_data)
4817{
4818    struct ether_vlan_header *eh = NULL;
4819    struct ip *ip4 = NULL;
4820    struct ip6_hdr *ip6 = NULL;
4821    caddr_t ip = NULL;
4822    struct tcphdr *th = NULL;
4823    int e_hlen, ip_hlen, l4_off;
4824    uint16_t proto;
4825
4826    if (m->m_pkthdr.csum_flags == CSUM_IP) {
4827        /* no L4 checksum offload needed */
4828        return (0);
4829    }
4830
4831    /* get the Ethernet header */
4832    eh = mtod(m, struct ether_vlan_header *);
4833
4834    /* handle VLAN encapsulation if present */
4835    if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4836        e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4837        proto  = ntohs(eh->evl_proto);
4838    } else {
4839        e_hlen = ETHER_HDR_LEN;
4840        proto  = ntohs(eh->evl_encap_proto);
4841    }
4842
4843    switch (proto) {
4844    case ETHERTYPE_IP:
4845        /* get the IP header, if mbuf len < 20 then header in next mbuf */
4846        ip4 = (m->m_len < sizeof(struct ip)) ?
4847                  (struct ip *)m->m_next->m_data :
4848                  (struct ip *)(m->m_data + e_hlen);
4849        /* ip_hl is number of 32-bit words */
4850        ip_hlen = (ip4->ip_hl << 2);
4851        ip = (caddr_t)ip4;
4852        break;
4853    case ETHERTYPE_IPV6:
4854        /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4855        ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4856                  (struct ip6_hdr *)m->m_next->m_data :
4857                  (struct ip6_hdr *)(m->m_data + e_hlen);
4858        /* XXX cannot support offload with IPv6 extensions */
4859        ip_hlen = sizeof(struct ip6_hdr);
4860        ip = (caddr_t)ip6;
4861        break;
4862    default:
4863        /* We can't offload in this case... */
4864        /* XXX error stat ??? */
4865        return (0);
4866    }
4867
4868    /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4869    l4_off = (e_hlen + ip_hlen);
4870
4871    *parsing_data |=
4872        (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4873         ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4874
4875    if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4876                                  CSUM_TSO |
4877                                  CSUM_TCP_IPV6)) {
4878        fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4879        th = (struct tcphdr *)(ip + ip_hlen);
4880        /* th_off is number of 32-bit words */
4881        *parsing_data |= ((th->th_off <<
4882                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4883                          ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4884        return (l4_off + (th->th_off << 2)); /* entire header length */
4885    } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4886                                         CSUM_UDP_IPV6)) {
4887        fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4888        return (l4_off + sizeof(struct udphdr)); /* entire header length */
4889    } else {
4890        /* XXX error stat ??? */
4891        return (0);
4892    }
4893}
4894
4895static uint8_t
4896bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4897                 struct mbuf                *m,
4898                 struct eth_tx_parse_bd_e1x *pbd)
4899{
4900    struct ether_vlan_header *eh = NULL;
4901    struct ip *ip4 = NULL;
4902    struct ip6_hdr *ip6 = NULL;
4903    caddr_t ip = NULL;
4904    struct tcphdr *th = NULL;
4905    struct udphdr *uh = NULL;
4906    int e_hlen, ip_hlen;
4907    uint16_t proto;
4908    uint8_t hlen;
4909    uint16_t tmp_csum;
4910    uint32_t *tmp_uh;
4911
4912    /* get the Ethernet header */
4913    eh = mtod(m, struct ether_vlan_header *);
4914
4915    /* handle VLAN encapsulation if present */
4916    if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4917        e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4918        proto  = ntohs(eh->evl_proto);
4919    } else {
4920        e_hlen = ETHER_HDR_LEN;
4921        proto  = ntohs(eh->evl_encap_proto);
4922    }
4923
4924    switch (proto) {
4925    case ETHERTYPE_IP:
4926        /* get the IP header, if mbuf len < 20 then header in next mbuf */
4927        ip4 = (m->m_len < sizeof(struct ip)) ?
4928                  (struct ip *)m->m_next->m_data :
4929                  (struct ip *)(m->m_data + e_hlen);
4930        /* ip_hl is number of 32-bit words */
4931        ip_hlen = (ip4->ip_hl << 1);
4932        ip = (caddr_t)ip4;
4933        break;
4934    case ETHERTYPE_IPV6:
4935        /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4936        ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4937                  (struct ip6_hdr *)m->m_next->m_data :
4938                  (struct ip6_hdr *)(m->m_data + e_hlen);
4939        /* XXX cannot support offload with IPv6 extensions */
4940        ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4941        ip = (caddr_t)ip6;
4942        break;
4943    default:
4944        /* We can't offload in this case... */
4945        /* XXX error stat ??? */
4946        return (0);
4947    }
4948
4949    hlen = (e_hlen >> 1);
4950
4951    /* note that rest of global_data is indirectly zeroed here */
4952    if (m->m_flags & M_VLANTAG) {
4953        pbd->global_data =
4954            htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
4955    } else {
4956        pbd->global_data = htole16(hlen);
4957    }
4958
4959    pbd->ip_hlen_w = ip_hlen;
4960
4961    hlen += pbd->ip_hlen_w;
4962
4963    /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4964
4965    if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4966                                  CSUM_TSO |
4967                                  CSUM_TCP_IPV6)) {
4968        th = (struct tcphdr *)(ip + (ip_hlen << 1));
4969        /* th_off is number of 32-bit words */
4970        hlen += (uint16_t)(th->th_off << 1);
4971    } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4972                                         CSUM_UDP_IPV6)) {
4973        uh = (struct udphdr *)(ip + (ip_hlen << 1));
4974        hlen += (sizeof(struct udphdr) / 2);
4975    } else {
4976        /* valid case as only CSUM_IP was set */
4977        return (0);
4978    }
4979
4980    pbd->total_hlen_w = htole16(hlen);
4981
4982    if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4983                                  CSUM_TSO |
4984                                  CSUM_TCP_IPV6)) {
4985        fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4986        pbd->tcp_pseudo_csum = ntohs(th->th_sum);
4987    } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4988                                         CSUM_UDP_IPV6)) {
4989        fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4990
4991        /*
4992         * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
4993         * checksums and does not know anything about the UDP header and where
4994         * the checksum field is located. It only knows about TCP. Therefore
4995         * we "lie" to the hardware for outgoing UDP packets w/ checksum
4996         * offload. Since the checksum field offset for TCP is 16 bytes and
4997         * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
4998         * bytes less than the start of the UDP header. This allows the
4999         * hardware to write the checksum in the correct spot. But the
5000         * hardware will compute a checksum which includes the last 10 bytes
5001         * of the IP header. To correct this we tweak the stack computed
5002         * pseudo checksum by folding in the calculation of the inverse
5003         * checksum for those final 10 bytes of the IP header. This allows
5004         * the correct checksum to be computed by the hardware.
5005         */
5006
5007        /* set pointer 10 bytes before UDP header */
5008        tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5009
5010        /* calculate a pseudo header checksum over the first 10 bytes */
5011        tmp_csum = in_pseudo(*tmp_uh,
5012                             *(tmp_uh + 1),
5013                             *(uint16_t *)(tmp_uh + 2));
5014
5015        pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5016    }
5017
5018    return (hlen * 2); /* entire header length, number of bytes */
5019}
5020
5021static void
5022bxe_set_pbd_lso_e2(struct mbuf *m,
5023                   uint32_t    *parsing_data)
5024{
5025    *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5026                       ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5027                      ETH_TX_PARSE_BD_E2_LSO_MSS);
5028
5029    /* XXX test for IPv6 with extension header... */
5030}
5031
5032static void
5033bxe_set_pbd_lso(struct mbuf                *m,
5034                struct eth_tx_parse_bd_e1x *pbd)
5035{
5036    struct ether_vlan_header *eh = NULL;
5037    struct ip *ip = NULL;
5038    struct tcphdr *th = NULL;
5039    int e_hlen;
5040
5041    /* get the Ethernet header */
5042    eh = mtod(m, struct ether_vlan_header *);
5043
5044    /* handle VLAN encapsulation if present */
5045    e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5046                 (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5047
5048    /* get the IP and TCP header, with LSO entire header in first mbuf */
5049    /* XXX assuming IPv4 */
5050    ip = (struct ip *)(m->m_data + e_hlen);
5051    th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5052
5053    pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5054    pbd->tcp_send_seq = ntohl(th->th_seq);
5055    pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5056
5057#if 1
5058        /* XXX IPv4 */
5059        pbd->ip_id = ntohs(ip->ip_id);
5060        pbd->tcp_pseudo_csum =
5061            ntohs(in_pseudo(ip->ip_src.s_addr,
5062                            ip->ip_dst.s_addr,
5063                            htons(IPPROTO_TCP)));
5064#else
5065        /* XXX IPv6 */
5066        pbd->tcp_pseudo_csum =
5067            ntohs(in_pseudo(&ip6->ip6_src,
5068                            &ip6->ip6_dst,
5069                            htons(IPPROTO_TCP)));
5070#endif
5071
5072    pbd->global_data |=
5073        htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5074}
5075
5076/*
5077 * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5078 * visible to the controller.
5079 *
5080 * If an mbuf is submitted to this routine and cannot be given to the
5081 * controller (e.g. it has too many fragments) then the function may free
5082 * the mbuf and return to the caller.
5083 *
5084 * Returns:
5085 *   0 = Success, !0 = Failure
5086 *   Note the side effect that an mbuf may be freed if it causes a problem.
5087 */
5088static int
5089bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5090{
5091    bus_dma_segment_t segs[32];
5092    struct mbuf *m0;
5093    struct bxe_sw_tx_bd *tx_buf;
5094    struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5095    struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5096    /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5097    struct eth_tx_bd *tx_data_bd;
5098    struct eth_tx_bd *tx_total_pkt_size_bd;
5099    struct eth_tx_start_bd *tx_start_bd;
5100    uint16_t bd_prod, pkt_prod, total_pkt_size;
5101    uint8_t mac_type;
5102    int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5103    struct bxe_softc *sc;
5104    uint16_t tx_bd_avail;
5105    struct ether_vlan_header *eh;
5106    uint32_t pbd_e2_parsing_data = 0;
5107    uint8_t hlen = 0;
5108    int tmp_bd;
5109    int i;
5110
5111    sc = fp->sc;
5112
5113#if __FreeBSD_version >= 800000
5114    M_ASSERTPKTHDR(*m_head);
5115#endif /* #if __FreeBSD_version >= 800000 */
5116
5117    m0 = *m_head;
5118    rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5119    tx_start_bd = NULL;
5120    tx_data_bd = NULL;
5121    tx_total_pkt_size_bd = NULL;
5122
5123    /* get the H/W pointer for packets and BDs */
5124    pkt_prod = fp->tx_pkt_prod;
5125    bd_prod = fp->tx_bd_prod;
5126
5127    mac_type = UNICAST_ADDRESS;
5128
5129    /* map the mbuf into the next open DMAable memory */
5130    tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5131    error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5132                                    tx_buf->m_map, m0,
5133                                    segs, &nsegs, BUS_DMA_NOWAIT);
5134
5135    /* mapping errors */
5136    if(__predict_false(error != 0)) {
5137        fp->eth_q_stats.tx_dma_mapping_failure++;
5138        if (error == ENOMEM) {
5139            /* resource issue, try again later */
5140            rc = ENOMEM;
5141        } else if (error == EFBIG) {
5142            /* possibly recoverable with defragmentation */
5143            fp->eth_q_stats.mbuf_defrag_attempts++;
5144            m0 = m_defrag(*m_head, M_NOWAIT);
5145            if (m0 == NULL) {
5146                fp->eth_q_stats.mbuf_defrag_failures++;
5147                rc = ENOBUFS;
5148            } else {
5149                /* defrag successful, try mapping again */
5150                *m_head = m0;
5151                error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5152                                                tx_buf->m_map, m0,
5153                                                segs, &nsegs, BUS_DMA_NOWAIT);
5154                if (error) {
5155                    fp->eth_q_stats.tx_dma_mapping_failure++;
5156                    rc = error;
5157                }
5158            }
5159        } else {
5160            /* unknown, unrecoverable mapping error */
5161            BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5162            bxe_dump_mbuf(sc, m0, FALSE);
5163            rc = error;
5164        }
5165
5166        goto bxe_tx_encap_continue;
5167    }
5168
5169    tx_bd_avail = bxe_tx_avail(sc, fp);
5170
5171    /* make sure there is enough room in the send queue */
5172    if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5173        /* Recoverable, try again later. */
5174        fp->eth_q_stats.tx_hw_queue_full++;
5175        bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5176        rc = ENOMEM;
5177        goto bxe_tx_encap_continue;
5178    }
5179
5180    /* capture the current H/W TX chain high watermark */
5181    if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5182                        (TX_BD_USABLE - tx_bd_avail))) {
5183        fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5184    }
5185
5186    /* make sure it fits in the packet window */
5187    if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5188        /*
5189         * The mbuf may be to big for the controller to handle. If the frame
5190         * is a TSO frame we'll need to do an additional check.
5191         */
5192        if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5193            if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5194                goto bxe_tx_encap_continue; /* OK to send */
5195            } else {
5196                fp->eth_q_stats.tx_window_violation_tso++;
5197            }
5198        } else {
5199            fp->eth_q_stats.tx_window_violation_std++;
5200        }
5201
5202        /* lets try to defragment this mbuf and remap it */
5203        fp->eth_q_stats.mbuf_defrag_attempts++;
5204        bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5205
5206        m0 = m_defrag(*m_head, M_NOWAIT);
5207        if (m0 == NULL) {
5208            fp->eth_q_stats.mbuf_defrag_failures++;
5209            /* Ugh, just drop the frame... :( */
5210            rc = ENOBUFS;
5211        } else {
5212            /* defrag successful, try mapping again */
5213            *m_head = m0;
5214            error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5215                                            tx_buf->m_map, m0,
5216                                            segs, &nsegs, BUS_DMA_NOWAIT);
5217            if (error) {
5218                fp->eth_q_stats.tx_dma_mapping_failure++;
5219                /* No sense in trying to defrag/copy chain, drop it. :( */
5220                rc = error;
5221            }
5222            else {
5223                /* if the chain is still too long then drop it */
5224                if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5225                    bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5226                    rc = ENODEV;
5227                }
5228            }
5229        }
5230    }
5231
5232bxe_tx_encap_continue:
5233
5234    /* Check for errors */
5235    if (rc) {
5236        if (rc == ENOMEM) {
5237            /* recoverable try again later  */
5238        } else {
5239            fp->eth_q_stats.tx_soft_errors++;
5240            fp->eth_q_stats.mbuf_alloc_tx--;
5241            m_freem(*m_head);
5242            *m_head = NULL;
5243        }
5244
5245        return (rc);
5246    }
5247
5248    /* set flag according to packet type (UNICAST_ADDRESS is default) */
5249    if (m0->m_flags & M_BCAST) {
5250        mac_type = BROADCAST_ADDRESS;
5251    } else if (m0->m_flags & M_MCAST) {
5252        mac_type = MULTICAST_ADDRESS;
5253    }
5254
5255    /* store the mbuf into the mbuf ring */
5256    tx_buf->m        = m0;
5257    tx_buf->first_bd = fp->tx_bd_prod;
5258    tx_buf->flags    = 0;
5259
5260    /* prepare the first transmit (start) BD for the mbuf */
5261    tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5262
5263    BLOGD(sc, DBG_TX,
5264          "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5265          pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5266
5267    tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5268    tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5269    tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5270    total_pkt_size += tx_start_bd->nbytes;
5271    tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5272
5273    tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5274
5275    /* all frames have at least Start BD + Parsing BD */
5276    nbds = nsegs + 1;
5277    tx_start_bd->nbd = htole16(nbds);
5278
5279    if (m0->m_flags & M_VLANTAG) {
5280        tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5281        tx_start_bd->bd_flags.as_bitfield |=
5282            (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5283    } else {
5284        /* vf tx, start bd must hold the ethertype for fw to enforce it */
5285        if (IS_VF(sc)) {
5286            /* map ethernet header to find type and header length */
5287            eh = mtod(m0, struct ether_vlan_header *);
5288            tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5289        } else {
5290            /* used by FW for packet accounting */
5291            tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5292        }
5293    }
5294
5295    /*
5296     * add a parsing BD from the chain. The parsing BD is always added
5297     * though it is only used for TSO and chksum
5298     */
5299    bd_prod = TX_BD_NEXT(bd_prod);
5300
5301    if (m0->m_pkthdr.csum_flags) {
5302        if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5303            fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5304            tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5305        }
5306
5307        if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5308            tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5309                                                  ETH_TX_BD_FLAGS_L4_CSUM);
5310        } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5311            tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5312                                                  ETH_TX_BD_FLAGS_IS_UDP |
5313                                                  ETH_TX_BD_FLAGS_L4_CSUM);
5314        } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5315                   (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5316            tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5317        } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5318            tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5319                                                  ETH_TX_BD_FLAGS_IS_UDP);
5320        }
5321    }
5322
5323    if (!CHIP_IS_E1x(sc)) {
5324        pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5325        memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5326
5327        if (m0->m_pkthdr.csum_flags) {
5328            hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5329        }
5330
5331        SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5332                 mac_type);
5333    } else {
5334        uint16_t global_data = 0;
5335
5336        pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5337        memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5338
5339        if (m0->m_pkthdr.csum_flags) {
5340            hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5341        }
5342
5343        SET_FLAG(global_data,
5344                 ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5345        pbd_e1x->global_data |= htole16(global_data);
5346    }
5347
5348    /* setup the parsing BD with TSO specific info */
5349    if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5350        fp->eth_q_stats.tx_ofld_frames_lso++;
5351        tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5352
5353        if (__predict_false(tx_start_bd->nbytes > hlen)) {
5354            fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5355
5356            /* split the first BD into header/data making the fw job easy */
5357            nbds++;
5358            tx_start_bd->nbd = htole16(nbds);
5359            tx_start_bd->nbytes = htole16(hlen);
5360
5361            bd_prod = TX_BD_NEXT(bd_prod);
5362
5363            /* new transmit BD after the tx_parse_bd */
5364            tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5365            tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5366            tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5367            tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5368            if (tx_total_pkt_size_bd == NULL) {
5369                tx_total_pkt_size_bd = tx_data_bd;
5370            }
5371
5372            BLOGD(sc, DBG_TX,
5373                  "TSO split header size is %d (%x:%x) nbds %d\n",
5374                  le16toh(tx_start_bd->nbytes),
5375                  le32toh(tx_start_bd->addr_hi),
5376                  le32toh(tx_start_bd->addr_lo),
5377                  nbds);
5378        }
5379
5380        if (!CHIP_IS_E1x(sc)) {
5381            bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5382        } else {
5383            bxe_set_pbd_lso(m0, pbd_e1x);
5384        }
5385    }
5386
5387    if (pbd_e2_parsing_data) {
5388        pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5389    }
5390
5391    /* prepare remaining BDs, start tx bd contains first seg/frag */
5392    for (i = 1; i < nsegs ; i++) {
5393        bd_prod = TX_BD_NEXT(bd_prod);
5394        tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5395        tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5396        tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5397        tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5398        if (tx_total_pkt_size_bd == NULL) {
5399            tx_total_pkt_size_bd = tx_data_bd;
5400        }
5401        total_pkt_size += tx_data_bd->nbytes;
5402    }
5403
5404    BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5405
5406    if (tx_total_pkt_size_bd != NULL) {
5407        tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5408    }
5409
5410    if (__predict_false(sc->debug & DBG_TX)) {
5411        tmp_bd = tx_buf->first_bd;
5412        for (i = 0; i < nbds; i++)
5413        {
5414            if (i == 0) {
5415                BLOGD(sc, DBG_TX,
5416                      "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5417                      "bd_flags=0x%x hdr_nbds=%d\n",
5418                      tx_start_bd,
5419                      tmp_bd,
5420                      le16toh(tx_start_bd->nbd),
5421                      le16toh(tx_start_bd->vlan_or_ethertype),
5422                      tx_start_bd->bd_flags.as_bitfield,
5423                      (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5424            } else if (i == 1) {
5425                if (pbd_e1x) {
5426                    BLOGD(sc, DBG_TX,
5427                          "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5428                          "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5429                          "tcp_seq=%u total_hlen_w=%u\n",
5430                          pbd_e1x,
5431                          tmp_bd,
5432                          pbd_e1x->global_data,
5433                          pbd_e1x->ip_hlen_w,
5434                          pbd_e1x->ip_id,
5435                          pbd_e1x->lso_mss,
5436                          pbd_e1x->tcp_flags,
5437                          pbd_e1x->tcp_pseudo_csum,
5438                          pbd_e1x->tcp_send_seq,
5439                          le16toh(pbd_e1x->total_hlen_w));
5440                } else { /* if (pbd_e2) */
5441                    BLOGD(sc, DBG_TX,
5442                          "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5443                          "src=%02x:%02x:%02x parsing_data=0x%x\n",
5444                          pbd_e2,
5445                          tmp_bd,
5446                          pbd_e2->data.mac_addr.dst_hi,
5447                          pbd_e2->data.mac_addr.dst_mid,
5448                          pbd_e2->data.mac_addr.dst_lo,
5449                          pbd_e2->data.mac_addr.src_hi,
5450                          pbd_e2->data.mac_addr.src_mid,
5451                          pbd_e2->data.mac_addr.src_lo,
5452                          pbd_e2->parsing_data);
5453                }
5454            }
5455
5456            if (i != 1) { /* skip parse db as it doesn't hold data */
5457                tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5458                BLOGD(sc, DBG_TX,
5459                      "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5460                      tx_data_bd,
5461                      tmp_bd,
5462                      le16toh(tx_data_bd->nbytes),
5463                      le32toh(tx_data_bd->addr_hi),
5464                      le32toh(tx_data_bd->addr_lo));
5465            }
5466
5467            tmp_bd = TX_BD_NEXT(tmp_bd);
5468        }
5469    }
5470
5471    BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5472
5473    /* update TX BD producer index value for next TX */
5474    bd_prod = TX_BD_NEXT(bd_prod);
5475
5476    /*
5477     * If the chain of tx_bd's describing this frame is adjacent to or spans
5478     * an eth_tx_next_bd element then we need to increment the nbds value.
5479     */
5480    if (TX_BD_IDX(bd_prod) < nbds) {
5481        nbds++;
5482    }
5483
5484    /* don't allow reordering of writes for nbd and packets */
5485    mb();
5486
5487    fp->tx_db.data.prod += nbds;
5488
5489    /* producer points to the next free tx_bd at this point */
5490    fp->tx_pkt_prod++;
5491    fp->tx_bd_prod = bd_prod;
5492
5493    DOORBELL(sc, fp->index, fp->tx_db.raw);
5494
5495    fp->eth_q_stats.tx_pkts++;
5496
5497    /* Prevent speculative reads from getting ahead of the status block. */
5498    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5499                      0, 0, BUS_SPACE_BARRIER_READ);
5500
5501    /* Prevent speculative reads from getting ahead of the doorbell. */
5502    bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5503                      0, 0, BUS_SPACE_BARRIER_READ);
5504
5505    return (0);
5506}
5507
5508static void
5509bxe_tx_start_locked(struct bxe_softc *sc,
5510                    if_t ifp,
5511                    struct bxe_fastpath *fp)
5512{
5513    struct mbuf *m = NULL;
5514    int tx_count = 0;
5515    uint16_t tx_bd_avail;
5516
5517    BXE_FP_TX_LOCK_ASSERT(fp);
5518
5519    /* keep adding entries while there are frames to send */
5520    while (!if_sendq_empty(ifp)) {
5521
5522        /*
5523         * check for any frames to send
5524         * dequeue can still be NULL even if queue is not empty
5525         */
5526        m = if_dequeue(ifp);
5527        if (__predict_false(m == NULL)) {
5528            break;
5529        }
5530
5531        /* the mbuf now belongs to us */
5532        fp->eth_q_stats.mbuf_alloc_tx++;
5533
5534        /*
5535         * Put the frame into the transmit ring. If we don't have room,
5536         * place the mbuf back at the head of the TX queue, set the
5537         * OACTIVE flag, and wait for the NIC to drain the chain.
5538         */
5539        if (__predict_false(bxe_tx_encap(fp, &m))) {
5540            fp->eth_q_stats.tx_encap_failures++;
5541            if (m != NULL) {
5542                /* mark the TX queue as full and return the frame */
5543                if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5544		if_sendq_prepend(ifp, m);
5545                fp->eth_q_stats.mbuf_alloc_tx--;
5546                fp->eth_q_stats.tx_queue_xoff++;
5547            }
5548
5549            /* stop looking for more work */
5550            break;
5551        }
5552
5553        /* the frame was enqueued successfully */
5554        tx_count++;
5555
5556        /* send a copy of the frame to any BPF listeners. */
5557        if_etherbpfmtap(ifp, m);
5558
5559        tx_bd_avail = bxe_tx_avail(sc, fp);
5560
5561        /* handle any completions if we're running low */
5562        if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5563            /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5564            bxe_txeof(sc, fp);
5565            if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5566                break;
5567            }
5568        }
5569    }
5570
5571    /* all TX packets were dequeued and/or the tx ring is full */
5572    if (tx_count > 0) {
5573        /* reset the TX watchdog timeout timer */
5574        fp->watchdog_timer = BXE_TX_TIMEOUT;
5575    }
5576}
5577
5578/* Legacy (non-RSS) dispatch routine */
5579static void
5580bxe_tx_start(if_t ifp)
5581{
5582    struct bxe_softc *sc;
5583    struct bxe_fastpath *fp;
5584
5585    sc = if_getsoftc(ifp);
5586
5587    if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5588        BLOGW(sc, "Interface not running, ignoring transmit request\n");
5589        return;
5590    }
5591
5592    if (!sc->link_vars.link_up) {
5593        BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5594        return;
5595    }
5596
5597    fp = &sc->fp[0];
5598
5599    if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5600        fp->eth_q_stats.tx_queue_full_return++;
5601        return;
5602    }
5603
5604    BXE_FP_TX_LOCK(fp);
5605    bxe_tx_start_locked(sc, ifp, fp);
5606    BXE_FP_TX_UNLOCK(fp);
5607}
5608
5609#if __FreeBSD_version >= 800000
5610
5611static int
5612bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5613                       if_t                ifp,
5614                       struct bxe_fastpath *fp,
5615                       struct mbuf         *m)
5616{
5617    struct buf_ring *tx_br = fp->tx_br;
5618    struct mbuf *next;
5619    int depth, rc, tx_count;
5620    uint16_t tx_bd_avail;
5621
5622    rc = tx_count = 0;
5623
5624    BXE_FP_TX_LOCK_ASSERT(fp);
5625
5626    if (!tx_br) {
5627        BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5628        return (EINVAL);
5629    }
5630
5631    if (!sc->link_vars.link_up ||
5632        (if_getdrvflags(ifp) &
5633        (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) != IFF_DRV_RUNNING) {
5634        rc = drbr_enqueue(ifp, tx_br, m);
5635        goto bxe_tx_mq_start_locked_exit;
5636    }
5637
5638    /* fetch the depth of the driver queue */
5639    depth = drbr_inuse_drv(ifp, tx_br);
5640    if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5641        fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5642    }
5643
5644    if (m == NULL) {
5645        /* no new work, check for pending frames */
5646        next = drbr_dequeue_drv(ifp, tx_br);
5647    } else if (drbr_needs_enqueue_drv(ifp, tx_br)) {
5648        /* have both new and pending work, maintain packet order */
5649        rc = drbr_enqueue(ifp, tx_br, m);
5650        if (rc != 0) {
5651            fp->eth_q_stats.tx_soft_errors++;
5652            goto bxe_tx_mq_start_locked_exit;
5653        }
5654        next = drbr_dequeue_drv(ifp, tx_br);
5655    } else {
5656        /* new work only and nothing pending */
5657        next = m;
5658    }
5659
5660    /* keep adding entries while there are frames to send */
5661    while (next != NULL) {
5662
5663        /* the mbuf now belongs to us */
5664        fp->eth_q_stats.mbuf_alloc_tx++;
5665
5666        /*
5667         * Put the frame into the transmit ring. If we don't have room,
5668         * place the mbuf back at the head of the TX queue, set the
5669         * OACTIVE flag, and wait for the NIC to drain the chain.
5670         */
5671        rc = bxe_tx_encap(fp, &next);
5672        if (__predict_false(rc != 0)) {
5673            fp->eth_q_stats.tx_encap_failures++;
5674            if (next != NULL) {
5675                /* mark the TX queue as full and save the frame */
5676                if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5677                /* XXX this may reorder the frame */
5678                rc = drbr_enqueue(ifp, tx_br, next);
5679                fp->eth_q_stats.mbuf_alloc_tx--;
5680                fp->eth_q_stats.tx_frames_deferred++;
5681            }
5682
5683            /* stop looking for more work */
5684            break;
5685        }
5686
5687        /* the transmit frame was enqueued successfully */
5688        tx_count++;
5689
5690        /* send a copy of the frame to any BPF listeners */
5691	if_etherbpfmtap(ifp, next);
5692
5693        tx_bd_avail = bxe_tx_avail(sc, fp);
5694
5695        /* handle any completions if we're running low */
5696        if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5697            /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5698            bxe_txeof(sc, fp);
5699            if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5700                break;
5701            }
5702        }
5703
5704        next = drbr_dequeue_drv(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
5715    return (rc);
5716}
5717
5718/* Multiqueue (TSS) dispatch routine. */
5719static int
5720bxe_tx_mq_start(struct ifnet *ifp,
5721                struct mbuf  *m)
5722{
5723    struct bxe_softc *sc = if_getsoftc(ifp);
5724    struct bxe_fastpath *fp;
5725    int fp_index, rc;
5726
5727    fp_index = 0; /* default is the first queue */
5728
5729    /* check if flowid is set */
5730
5731    if (BXE_VALID_FLOWID(m))
5732        fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5733
5734    fp = &sc->fp[fp_index];
5735
5736    if (BXE_FP_TX_TRYLOCK(fp)) {
5737        rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5738        BXE_FP_TX_UNLOCK(fp);
5739    } else
5740        rc = drbr_enqueue(ifp, fp->tx_br, m);
5741
5742    return (rc);
5743}
5744
5745static void
5746bxe_mq_flush(struct ifnet *ifp)
5747{
5748    struct bxe_softc *sc = if_getsoftc(ifp);
5749    struct bxe_fastpath *fp;
5750    struct mbuf *m;
5751    int i;
5752
5753    for (i = 0; i < sc->num_queues; i++) {
5754        fp = &sc->fp[i];
5755
5756        if (fp->state != BXE_FP_STATE_OPEN) {
5757            BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5758                  fp->index, fp->state);
5759            continue;
5760        }
5761
5762        if (fp->tx_br != NULL) {
5763            BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5764            BXE_FP_TX_LOCK(fp);
5765            while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5766                m_freem(m);
5767            }
5768            BXE_FP_TX_UNLOCK(fp);
5769        }
5770    }
5771
5772    if_qflush(ifp);
5773}
5774
5775#endif /* FreeBSD_version >= 800000 */
5776
5777static uint16_t
5778bxe_cid_ilt_lines(struct bxe_softc *sc)
5779{
5780    if (IS_SRIOV(sc)) {
5781        return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5782    }
5783    return (L2_ILT_LINES(sc));
5784}
5785
5786static void
5787bxe_ilt_set_info(struct bxe_softc *sc)
5788{
5789    struct ilt_client_info *ilt_client;
5790    struct ecore_ilt *ilt = sc->ilt;
5791    uint16_t line = 0;
5792
5793    ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5794    BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5795
5796    /* CDU */
5797    ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5798    ilt_client->client_num = ILT_CLIENT_CDU;
5799    ilt_client->page_size = CDU_ILT_PAGE_SZ;
5800    ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5801    ilt_client->start = line;
5802    line += bxe_cid_ilt_lines(sc);
5803
5804    if (CNIC_SUPPORT(sc)) {
5805        line += CNIC_ILT_LINES;
5806    }
5807
5808    ilt_client->end = (line - 1);
5809
5810    BLOGD(sc, DBG_LOAD,
5811          "ilt client[CDU]: start %d, end %d, "
5812          "psz 0x%x, flags 0x%x, hw psz %d\n",
5813          ilt_client->start, ilt_client->end,
5814          ilt_client->page_size,
5815          ilt_client->flags,
5816          ilog2(ilt_client->page_size >> 12));
5817
5818    /* QM */
5819    if (QM_INIT(sc->qm_cid_count)) {
5820        ilt_client = &ilt->clients[ILT_CLIENT_QM];
5821        ilt_client->client_num = ILT_CLIENT_QM;
5822        ilt_client->page_size = QM_ILT_PAGE_SZ;
5823        ilt_client->flags = 0;
5824        ilt_client->start = line;
5825
5826        /* 4 bytes for each cid */
5827        line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5828                             QM_ILT_PAGE_SZ);
5829
5830        ilt_client->end = (line - 1);
5831
5832        BLOGD(sc, DBG_LOAD,
5833              "ilt client[QM]: start %d, end %d, "
5834              "psz 0x%x, flags 0x%x, hw psz %d\n",
5835              ilt_client->start, ilt_client->end,
5836              ilt_client->page_size, ilt_client->flags,
5837              ilog2(ilt_client->page_size >> 12));
5838    }
5839
5840    if (CNIC_SUPPORT(sc)) {
5841        /* SRC */
5842        ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5843        ilt_client->client_num = ILT_CLIENT_SRC;
5844        ilt_client->page_size = SRC_ILT_PAGE_SZ;
5845        ilt_client->flags = 0;
5846        ilt_client->start = line;
5847        line += SRC_ILT_LINES;
5848        ilt_client->end = (line - 1);
5849
5850        BLOGD(sc, DBG_LOAD,
5851              "ilt client[SRC]: start %d, end %d, "
5852              "psz 0x%x, flags 0x%x, hw psz %d\n",
5853              ilt_client->start, ilt_client->end,
5854              ilt_client->page_size, ilt_client->flags,
5855              ilog2(ilt_client->page_size >> 12));
5856
5857        /* TM */
5858        ilt_client = &ilt->clients[ILT_CLIENT_TM];
5859        ilt_client->client_num = ILT_CLIENT_TM;
5860        ilt_client->page_size = TM_ILT_PAGE_SZ;
5861        ilt_client->flags = 0;
5862        ilt_client->start = line;
5863        line += TM_ILT_LINES;
5864        ilt_client->end = (line - 1);
5865
5866        BLOGD(sc, DBG_LOAD,
5867              "ilt client[TM]: start %d, end %d, "
5868              "psz 0x%x, flags 0x%x, hw psz %d\n",
5869              ilt_client->start, ilt_client->end,
5870              ilt_client->page_size, ilt_client->flags,
5871              ilog2(ilt_client->page_size >> 12));
5872    }
5873
5874    KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5875}
5876
5877static void
5878bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5879{
5880    int i;
5881    uint32_t rx_buf_size;
5882
5883    rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5884
5885    for (i = 0; i < sc->num_queues; i++) {
5886        if(rx_buf_size <= MCLBYTES){
5887            sc->fp[i].rx_buf_size = rx_buf_size;
5888            sc->fp[i].mbuf_alloc_size = MCLBYTES;
5889        }else if (rx_buf_size <= MJUMPAGESIZE){
5890            sc->fp[i].rx_buf_size = rx_buf_size;
5891            sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5892        }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5893            sc->fp[i].rx_buf_size = MCLBYTES;
5894            sc->fp[i].mbuf_alloc_size = MCLBYTES;
5895        }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5896            sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5897            sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5898        }else {
5899            sc->fp[i].rx_buf_size = MCLBYTES;
5900            sc->fp[i].mbuf_alloc_size = MCLBYTES;
5901        }
5902    }
5903}
5904
5905static int
5906bxe_alloc_ilt_mem(struct bxe_softc *sc)
5907{
5908    int rc = 0;
5909
5910    if ((sc->ilt =
5911         (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
5912                                    M_BXE_ILT,
5913                                    (M_NOWAIT | M_ZERO))) == NULL) {
5914        rc = 1;
5915    }
5916
5917    return (rc);
5918}
5919
5920static int
5921bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
5922{
5923    int rc = 0;
5924
5925    if ((sc->ilt->lines =
5926         (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
5927                                    M_BXE_ILT,
5928                                    (M_NOWAIT | M_ZERO))) == NULL) {
5929        rc = 1;
5930    }
5931
5932    return (rc);
5933}
5934
5935static void
5936bxe_free_ilt_mem(struct bxe_softc *sc)
5937{
5938    if (sc->ilt != NULL) {
5939        free(sc->ilt, M_BXE_ILT);
5940        sc->ilt = NULL;
5941    }
5942}
5943
5944static void
5945bxe_free_ilt_lines_mem(struct bxe_softc *sc)
5946{
5947    if (sc->ilt->lines != NULL) {
5948        free(sc->ilt->lines, M_BXE_ILT);
5949        sc->ilt->lines = NULL;
5950    }
5951}
5952
5953static void
5954bxe_free_mem(struct bxe_softc *sc)
5955{
5956    int i;
5957
5958    for (i = 0; i < L2_ILT_LINES(sc); i++) {
5959        bxe_dma_free(sc, &sc->context[i].vcxt_dma);
5960        sc->context[i].vcxt = NULL;
5961        sc->context[i].size = 0;
5962    }
5963
5964    ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
5965
5966    bxe_free_ilt_lines_mem(sc);
5967
5968}
5969
5970static int
5971bxe_alloc_mem(struct bxe_softc *sc)
5972{
5973    int context_size;
5974    int allocated;
5975    int i;
5976
5977    /*
5978     * Allocate memory for CDU context:
5979     * This memory is allocated separately and not in the generic ILT
5980     * functions because CDU differs in few aspects:
5981     * 1. There can be multiple entities allocating memory for context -
5982     * regular L2, CNIC, and SRIOV drivers. Each separately controls
5983     * its own ILT lines.
5984     * 2. Since CDU page-size is not a single 4KB page (which is the case
5985     * for the other ILT clients), to be efficient we want to support
5986     * allocation of sub-page-size in the last entry.
5987     * 3. Context pointers are used by the driver to pass to FW / update
5988     * the context (for the other ILT clients the pointers are used just to
5989     * free the memory during unload).
5990     */
5991    context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
5992    for (i = 0, allocated = 0; allocated < context_size; i++) {
5993        sc->context[i].size = min(CDU_ILT_PAGE_SZ,
5994                                  (context_size - allocated));
5995
5996        if (bxe_dma_alloc(sc, sc->context[i].size,
5997                          &sc->context[i].vcxt_dma,
5998                          "cdu context") != 0) {
5999            bxe_free_mem(sc);
6000            return (-1);
6001        }
6002
6003        sc->context[i].vcxt =
6004            (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6005
6006        allocated += sc->context[i].size;
6007    }
6008
6009    bxe_alloc_ilt_lines_mem(sc);
6010
6011    BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6012          sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6013    {
6014        for (i = 0; i < 4; i++) {
6015            BLOGD(sc, DBG_LOAD,
6016                  "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6017                  i,
6018                  sc->ilt->clients[i].page_size,
6019                  sc->ilt->clients[i].start,
6020                  sc->ilt->clients[i].end,
6021                  sc->ilt->clients[i].client_num,
6022                  sc->ilt->clients[i].flags);
6023        }
6024    }
6025    if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6026        BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6027        bxe_free_mem(sc);
6028        return (-1);
6029    }
6030
6031    return (0);
6032}
6033
6034static void
6035bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6036{
6037    struct bxe_softc *sc;
6038    int i;
6039
6040    sc = fp->sc;
6041
6042    if (fp->rx_mbuf_tag == NULL) {
6043        return;
6044    }
6045
6046    /* free all mbufs and unload all maps */
6047    for (i = 0; i < RX_BD_TOTAL; i++) {
6048        if (fp->rx_mbuf_chain[i].m_map != NULL) {
6049            bus_dmamap_sync(fp->rx_mbuf_tag,
6050                            fp->rx_mbuf_chain[i].m_map,
6051                            BUS_DMASYNC_POSTREAD);
6052            bus_dmamap_unload(fp->rx_mbuf_tag,
6053                              fp->rx_mbuf_chain[i].m_map);
6054        }
6055
6056        if (fp->rx_mbuf_chain[i].m != NULL) {
6057            m_freem(fp->rx_mbuf_chain[i].m);
6058            fp->rx_mbuf_chain[i].m = NULL;
6059            fp->eth_q_stats.mbuf_alloc_rx--;
6060        }
6061    }
6062}
6063
6064static void
6065bxe_free_tpa_pool(struct bxe_fastpath *fp)
6066{
6067    struct bxe_softc *sc;
6068    int i, max_agg_queues;
6069
6070    sc = fp->sc;
6071
6072    if (fp->rx_mbuf_tag == NULL) {
6073        return;
6074    }
6075
6076    max_agg_queues = MAX_AGG_QS(sc);
6077
6078    /* release all mbufs and unload all DMA maps in the TPA pool */
6079    for (i = 0; i < max_agg_queues; i++) {
6080        if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6081            bus_dmamap_sync(fp->rx_mbuf_tag,
6082                            fp->rx_tpa_info[i].bd.m_map,
6083                            BUS_DMASYNC_POSTREAD);
6084            bus_dmamap_unload(fp->rx_mbuf_tag,
6085                              fp->rx_tpa_info[i].bd.m_map);
6086        }
6087
6088        if (fp->rx_tpa_info[i].bd.m != NULL) {
6089            m_freem(fp->rx_tpa_info[i].bd.m);
6090            fp->rx_tpa_info[i].bd.m = NULL;
6091            fp->eth_q_stats.mbuf_alloc_tpa--;
6092        }
6093    }
6094}
6095
6096static void
6097bxe_free_sge_chain(struct bxe_fastpath *fp)
6098{
6099    struct bxe_softc *sc;
6100    int i;
6101
6102    sc = fp->sc;
6103
6104    if (fp->rx_sge_mbuf_tag == NULL) {
6105        return;
6106    }
6107
6108    /* rree all mbufs and unload all maps */
6109    for (i = 0; i < RX_SGE_TOTAL; i++) {
6110        if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6111            bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6112                            fp->rx_sge_mbuf_chain[i].m_map,
6113                            BUS_DMASYNC_POSTREAD);
6114            bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6115                              fp->rx_sge_mbuf_chain[i].m_map);
6116        }
6117
6118        if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6119            m_freem(fp->rx_sge_mbuf_chain[i].m);
6120            fp->rx_sge_mbuf_chain[i].m = NULL;
6121            fp->eth_q_stats.mbuf_alloc_sge--;
6122        }
6123    }
6124}
6125
6126static void
6127bxe_free_fp_buffers(struct bxe_softc *sc)
6128{
6129    struct bxe_fastpath *fp;
6130    int i;
6131
6132    for (i = 0; i < sc->num_queues; i++) {
6133        fp = &sc->fp[i];
6134
6135#if __FreeBSD_version >= 800000
6136        if (fp->tx_br != NULL) {
6137            /* just in case bxe_mq_flush() wasn't called */
6138            if (mtx_initialized(&fp->tx_mtx)) {
6139                struct mbuf *m;
6140
6141                BXE_FP_TX_LOCK(fp);
6142                while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6143                    m_freem(m);
6144                BXE_FP_TX_UNLOCK(fp);
6145            }
6146        }
6147#endif
6148
6149        /* free all RX buffers */
6150        bxe_free_rx_bd_chain(fp);
6151        bxe_free_tpa_pool(fp);
6152        bxe_free_sge_chain(fp);
6153
6154        if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6155            BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6156                  fp->eth_q_stats.mbuf_alloc_rx);
6157        }
6158
6159        if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6160            BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6161                  fp->eth_q_stats.mbuf_alloc_sge);
6162        }
6163
6164        if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6165            BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6166                  fp->eth_q_stats.mbuf_alloc_tpa);
6167        }
6168
6169        if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6170            BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6171                  fp->eth_q_stats.mbuf_alloc_tx);
6172        }
6173
6174        /* XXX verify all mbufs were reclaimed */
6175    }
6176}
6177
6178static int
6179bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6180                     uint16_t            prev_index,
6181                     uint16_t            index)
6182{
6183    struct bxe_sw_rx_bd *rx_buf;
6184    struct eth_rx_bd *rx_bd;
6185    bus_dma_segment_t segs[1];
6186    bus_dmamap_t map;
6187    struct mbuf *m;
6188    int nsegs, rc;
6189
6190    rc = 0;
6191
6192    /* allocate the new RX BD mbuf */
6193    m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6194    if (__predict_false(m == NULL)) {
6195        fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6196        return (ENOBUFS);
6197    }
6198
6199    fp->eth_q_stats.mbuf_alloc_rx++;
6200
6201    /* initialize the mbuf buffer length */
6202    m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6203
6204    /* map the mbuf into non-paged pool */
6205    rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6206                                 fp->rx_mbuf_spare_map,
6207                                 m, segs, &nsegs, BUS_DMA_NOWAIT);
6208    if (__predict_false(rc != 0)) {
6209        fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6210        m_freem(m);
6211        fp->eth_q_stats.mbuf_alloc_rx--;
6212        return (rc);
6213    }
6214
6215    /* all mbufs must map to a single segment */
6216    KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6217
6218    /* release any existing RX BD mbuf mappings */
6219
6220    if (prev_index != index) {
6221        rx_buf = &fp->rx_mbuf_chain[prev_index];
6222
6223        if (rx_buf->m_map != NULL) {
6224            bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6225                            BUS_DMASYNC_POSTREAD);
6226            bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6227        }
6228
6229        /*
6230         * We only get here from bxe_rxeof() when the maximum number
6231         * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6232         * holds the mbuf in the prev_index so it's OK to NULL it out
6233         * here without concern of a memory leak.
6234         */
6235        fp->rx_mbuf_chain[prev_index].m = NULL;
6236    }
6237
6238    rx_buf = &fp->rx_mbuf_chain[index];
6239
6240    if (rx_buf->m_map != NULL) {
6241        bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6242                        BUS_DMASYNC_POSTREAD);
6243        bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6244    }
6245
6246    /* save the mbuf and mapping info for a future packet */
6247    map = (prev_index != index) ?
6248              fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6249    rx_buf->m_map = fp->rx_mbuf_spare_map;
6250    fp->rx_mbuf_spare_map = map;
6251    bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6252                    BUS_DMASYNC_PREREAD);
6253    rx_buf->m = m;
6254
6255    rx_bd = &fp->rx_chain[index];
6256    rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6257    rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6258
6259    return (rc);
6260}
6261
6262static int
6263bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6264                      int                 queue)
6265{
6266    struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6267    bus_dma_segment_t segs[1];
6268    bus_dmamap_t map;
6269    struct mbuf *m;
6270    int nsegs;
6271    int rc = 0;
6272
6273    /* allocate the new TPA mbuf */
6274    m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6275    if (__predict_false(m == NULL)) {
6276        fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6277        return (ENOBUFS);
6278    }
6279
6280    fp->eth_q_stats.mbuf_alloc_tpa++;
6281
6282    /* initialize the mbuf buffer length */
6283    m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6284
6285    /* map the mbuf into non-paged pool */
6286    rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6287                                 fp->rx_tpa_info_mbuf_spare_map,
6288                                 m, segs, &nsegs, BUS_DMA_NOWAIT);
6289    if (__predict_false(rc != 0)) {
6290        fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6291        m_free(m);
6292        fp->eth_q_stats.mbuf_alloc_tpa--;
6293        return (rc);
6294    }
6295
6296    /* all mbufs must map to a single segment */
6297    KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6298
6299    /* release any existing TPA mbuf mapping */
6300    if (tpa_info->bd.m_map != NULL) {
6301        bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6302                        BUS_DMASYNC_POSTREAD);
6303        bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6304    }
6305
6306    /* save the mbuf and mapping info for the TPA mbuf */
6307    map = tpa_info->bd.m_map;
6308    tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6309    fp->rx_tpa_info_mbuf_spare_map = map;
6310    bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6311                    BUS_DMASYNC_PREREAD);
6312    tpa_info->bd.m = m;
6313    tpa_info->seg = segs[0];
6314
6315    return (rc);
6316}
6317
6318/*
6319 * Allocate an mbuf and assign it to the receive scatter gather chain. The
6320 * caller must take care to save a copy of the existing mbuf in the SG mbuf
6321 * chain.
6322 */
6323static int
6324bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6325                      uint16_t            index)
6326{
6327    struct bxe_sw_rx_bd *sge_buf;
6328    struct eth_rx_sge *sge;
6329    bus_dma_segment_t segs[1];
6330    bus_dmamap_t map;
6331    struct mbuf *m;
6332    int nsegs;
6333    int rc = 0;
6334
6335    /* allocate a new SGE mbuf */
6336    m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6337    if (__predict_false(m == NULL)) {
6338        fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6339        return (ENOMEM);
6340    }
6341
6342    fp->eth_q_stats.mbuf_alloc_sge++;
6343
6344    /* initialize the mbuf buffer length */
6345    m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6346
6347    /* map the SGE mbuf into non-paged pool */
6348    rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6349                                 fp->rx_sge_mbuf_spare_map,
6350                                 m, segs, &nsegs, BUS_DMA_NOWAIT);
6351    if (__predict_false(rc != 0)) {
6352        fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6353        m_freem(m);
6354        fp->eth_q_stats.mbuf_alloc_sge--;
6355        return (rc);
6356    }
6357
6358    /* all mbufs must map to a single segment */
6359    KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6360
6361    sge_buf = &fp->rx_sge_mbuf_chain[index];
6362
6363    /* release any existing SGE mbuf mapping */
6364    if (sge_buf->m_map != NULL) {
6365        bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6366                        BUS_DMASYNC_POSTREAD);
6367        bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6368    }
6369
6370    /* save the mbuf and mapping info for a future packet */
6371    map = sge_buf->m_map;
6372    sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6373    fp->rx_sge_mbuf_spare_map = map;
6374    bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6375                    BUS_DMASYNC_PREREAD);
6376    sge_buf->m = m;
6377
6378    sge = &fp->rx_sge_chain[index];
6379    sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6380    sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6381
6382    return (rc);
6383}
6384
6385static __noinline int
6386bxe_alloc_fp_buffers(struct bxe_softc *sc)
6387{
6388    struct bxe_fastpath *fp;
6389    int i, j, rc = 0;
6390    int ring_prod, cqe_ring_prod;
6391    int max_agg_queues;
6392
6393    for (i = 0; i < sc->num_queues; i++) {
6394        fp = &sc->fp[i];
6395
6396        ring_prod = cqe_ring_prod = 0;
6397        fp->rx_bd_cons = 0;
6398        fp->rx_cq_cons = 0;
6399
6400        /* allocate buffers for the RX BDs in RX BD chain */
6401        for (j = 0; j < sc->max_rx_bufs; j++) {
6402            rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6403            if (rc != 0) {
6404                BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6405                      i, rc);
6406                goto bxe_alloc_fp_buffers_error;
6407            }
6408
6409            ring_prod     = RX_BD_NEXT(ring_prod);
6410            cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6411        }
6412
6413        fp->rx_bd_prod = ring_prod;
6414        fp->rx_cq_prod = cqe_ring_prod;
6415        fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6416
6417        max_agg_queues = MAX_AGG_QS(sc);
6418
6419        fp->tpa_enable = TRUE;
6420
6421        /* fill the TPA pool */
6422        for (j = 0; j < max_agg_queues; j++) {
6423            rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6424            if (rc != 0) {
6425                BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6426                          i, j);
6427                fp->tpa_enable = FALSE;
6428                goto bxe_alloc_fp_buffers_error;
6429            }
6430
6431            fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6432        }
6433
6434        if (fp->tpa_enable) {
6435            /* fill the RX SGE chain */
6436            ring_prod = 0;
6437            for (j = 0; j < RX_SGE_USABLE; j++) {
6438                rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6439                if (rc != 0) {
6440                    BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6441                              i, ring_prod);
6442                    fp->tpa_enable = FALSE;
6443                    ring_prod = 0;
6444                    goto bxe_alloc_fp_buffers_error;
6445                }
6446
6447                ring_prod = RX_SGE_NEXT(ring_prod);
6448            }
6449
6450            fp->rx_sge_prod = ring_prod;
6451        }
6452    }
6453
6454    return (0);
6455
6456bxe_alloc_fp_buffers_error:
6457
6458    /* unwind what was already allocated */
6459    bxe_free_rx_bd_chain(fp);
6460    bxe_free_tpa_pool(fp);
6461    bxe_free_sge_chain(fp);
6462
6463    return (ENOBUFS);
6464}
6465
6466static void
6467bxe_free_fw_stats_mem(struct bxe_softc *sc)
6468{
6469    bxe_dma_free(sc, &sc->fw_stats_dma);
6470
6471    sc->fw_stats_num = 0;
6472
6473    sc->fw_stats_req_size = 0;
6474    sc->fw_stats_req = NULL;
6475    sc->fw_stats_req_mapping = 0;
6476
6477    sc->fw_stats_data_size = 0;
6478    sc->fw_stats_data = NULL;
6479    sc->fw_stats_data_mapping = 0;
6480}
6481
6482static int
6483bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6484{
6485    uint8_t num_queue_stats;
6486    int num_groups;
6487
6488    /* number of queues for statistics is number of eth queues */
6489    num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6490
6491    /*
6492     * Total number of FW statistics requests =
6493     *   1 for port stats + 1 for PF stats + num of queues
6494     */
6495    sc->fw_stats_num = (2 + num_queue_stats);
6496
6497    /*
6498     * Request is built from stats_query_header and an array of
6499     * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6500     * rules. The real number or requests is configured in the
6501     * stats_query_header.
6502     */
6503    num_groups =
6504        ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6505         ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6506
6507    BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6508          sc->fw_stats_num, num_groups);
6509
6510    sc->fw_stats_req_size =
6511        (sizeof(struct stats_query_header) +
6512         (num_groups * sizeof(struct stats_query_cmd_group)));
6513
6514    /*
6515     * Data for statistics requests + stats_counter.
6516     * stats_counter holds per-STORM counters that are incremented when
6517     * STORM has finished with the current request. Memory for FCoE
6518     * offloaded statistics are counted anyway, even if they will not be sent.
6519     * VF stats are not accounted for here as the data of VF stats is stored
6520     * in memory allocated by the VF, not here.
6521     */
6522    sc->fw_stats_data_size =
6523        (sizeof(struct stats_counter) +
6524         sizeof(struct per_port_stats) +
6525         sizeof(struct per_pf_stats) +
6526         /* sizeof(struct fcoe_statistics_params) + */
6527         (sizeof(struct per_queue_stats) * num_queue_stats));
6528
6529    if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6530                      &sc->fw_stats_dma, "fw stats") != 0) {
6531        bxe_free_fw_stats_mem(sc);
6532        return (-1);
6533    }
6534
6535    /* set up the shortcuts */
6536
6537    sc->fw_stats_req =
6538        (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6539    sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6540
6541    sc->fw_stats_data =
6542        (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6543                                     sc->fw_stats_req_size);
6544    sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6545                                 sc->fw_stats_req_size);
6546
6547    BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6548          (uintmax_t)sc->fw_stats_req_mapping);
6549
6550    BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6551          (uintmax_t)sc->fw_stats_data_mapping);
6552
6553    return (0);
6554}
6555
6556/*
6557 * Bits map:
6558 * 0-7  - Engine0 load counter.
6559 * 8-15 - Engine1 load counter.
6560 * 16   - Engine0 RESET_IN_PROGRESS bit.
6561 * 17   - Engine1 RESET_IN_PROGRESS bit.
6562 * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6563 *        function on the engine
6564 * 19   - Engine1 ONE_IS_LOADED.
6565 * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6566 *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6567 *        for just the one belonging to its engine).
6568 */
6569#define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6570#define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6571#define BXE_PATH0_LOAD_CNT_SHIFT  0
6572#define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6573#define BXE_PATH1_LOAD_CNT_SHIFT  8
6574#define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6575#define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6576#define BXE_GLOBAL_RESET_BIT      0x00040000
6577
6578/* set the GLOBAL_RESET bit, should be run under rtnl lock */
6579static void
6580bxe_set_reset_global(struct bxe_softc *sc)
6581{
6582    uint32_t val;
6583    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6584    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6585    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6586    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6587}
6588
6589/* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6590static void
6591bxe_clear_reset_global(struct bxe_softc *sc)
6592{
6593    uint32_t val;
6594    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6595    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6596    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6597    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6598}
6599
6600/* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6601static uint8_t
6602bxe_reset_is_global(struct bxe_softc *sc)
6603{
6604    uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6605    BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6606    return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6607}
6608
6609/* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6610static void
6611bxe_set_reset_done(struct bxe_softc *sc)
6612{
6613    uint32_t val;
6614    uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6615                                 BXE_PATH0_RST_IN_PROG_BIT;
6616
6617    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6618
6619    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6620    /* Clear the bit */
6621    val &= ~bit;
6622    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6623
6624    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6625}
6626
6627/* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6628static void
6629bxe_set_reset_in_progress(struct bxe_softc *sc)
6630{
6631    uint32_t val;
6632    uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6633                                 BXE_PATH0_RST_IN_PROG_BIT;
6634
6635    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6636
6637    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6638    /* Set the bit */
6639    val |= bit;
6640    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6641
6642    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6643}
6644
6645/* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6646static uint8_t
6647bxe_reset_is_done(struct bxe_softc *sc,
6648                  int              engine)
6649{
6650    uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6651    uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6652                            BXE_PATH0_RST_IN_PROG_BIT;
6653
6654    /* return false if bit is set */
6655    return (val & bit) ? FALSE : TRUE;
6656}
6657
6658/* get the load status for an engine, should be run under rtnl lock */
6659static uint8_t
6660bxe_get_load_status(struct bxe_softc *sc,
6661                    int              engine)
6662{
6663    uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6664                             BXE_PATH0_LOAD_CNT_MASK;
6665    uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6666                              BXE_PATH0_LOAD_CNT_SHIFT;
6667    uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6668
6669    BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6670
6671    val = ((val & mask) >> shift);
6672
6673    BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6674
6675    return (val != 0);
6676}
6677
6678/* set pf load mark */
6679/* XXX needs to be under rtnl lock */
6680static void
6681bxe_set_pf_load(struct bxe_softc *sc)
6682{
6683    uint32_t val;
6684    uint32_t val1;
6685    uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6686                                  BXE_PATH0_LOAD_CNT_MASK;
6687    uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6688                                   BXE_PATH0_LOAD_CNT_SHIFT;
6689
6690    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6691
6692    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6693    BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6694
6695    /* get the current counter value */
6696    val1 = ((val & mask) >> shift);
6697
6698    /* set bit of this PF */
6699    val1 |= (1 << SC_ABS_FUNC(sc));
6700
6701    /* clear the old value */
6702    val &= ~mask;
6703
6704    /* set the new one */
6705    val |= ((val1 << shift) & mask);
6706
6707    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6708
6709    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6710}
6711
6712/* clear pf load mark */
6713/* XXX needs to be under rtnl lock */
6714static uint8_t
6715bxe_clear_pf_load(struct bxe_softc *sc)
6716{
6717    uint32_t val1, val;
6718    uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6719                                  BXE_PATH0_LOAD_CNT_MASK;
6720    uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6721                                   BXE_PATH0_LOAD_CNT_SHIFT;
6722
6723    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6724    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6725    BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6726
6727    /* get the current counter value */
6728    val1 = (val & mask) >> shift;
6729
6730    /* clear bit of that PF */
6731    val1 &= ~(1 << SC_ABS_FUNC(sc));
6732
6733    /* clear the old value */
6734    val &= ~mask;
6735
6736    /* set the new one */
6737    val |= ((val1 << shift) & mask);
6738
6739    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6740    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6741    return (val1 != 0);
6742}
6743
6744/* send load requrest to mcp and analyze response */
6745static int
6746bxe_nic_load_request(struct bxe_softc *sc,
6747                     uint32_t         *load_code)
6748{
6749    /* init fw_seq */
6750    sc->fw_seq =
6751        (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6752         DRV_MSG_SEQ_NUMBER_MASK);
6753
6754    BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6755
6756    /* get the current FW pulse sequence */
6757    sc->fw_drv_pulse_wr_seq =
6758        (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6759         DRV_PULSE_SEQ_MASK);
6760
6761    BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6762          sc->fw_drv_pulse_wr_seq);
6763
6764    /* load request */
6765    (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6766                                  DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6767
6768    /* if the MCP fails to respond we must abort */
6769    if (!(*load_code)) {
6770        BLOGE(sc, "MCP response failure!\n");
6771        return (-1);
6772    }
6773
6774    /* if MCP refused then must abort */
6775    if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6776        BLOGE(sc, "MCP refused load request\n");
6777        return (-1);
6778    }
6779
6780    return (0);
6781}
6782
6783/*
6784 * Check whether another PF has already loaded FW to chip. In virtualized
6785 * environments a pf from anoth VM may have already initialized the device
6786 * including loading FW.
6787 */
6788static int
6789bxe_nic_load_analyze_req(struct bxe_softc *sc,
6790                         uint32_t         load_code)
6791{
6792    uint32_t my_fw, loaded_fw;
6793
6794    /* is another pf loaded on this engine? */
6795    if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6796        (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6797        /* build my FW version dword */
6798        my_fw = (BCM_5710_FW_MAJOR_VERSION +
6799                 (BCM_5710_FW_MINOR_VERSION << 8 ) +
6800                 (BCM_5710_FW_REVISION_VERSION << 16) +
6801                 (BCM_5710_FW_ENGINEERING_VERSION << 24));
6802
6803        /* read loaded FW from chip */
6804        loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6805        BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6806              loaded_fw, my_fw);
6807
6808        /* abort nic load if version mismatch */
6809        if (my_fw != loaded_fw) {
6810            BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6811                  loaded_fw, my_fw);
6812            return (-1);
6813        }
6814    }
6815
6816    return (0);
6817}
6818
6819/* mark PMF if applicable */
6820static void
6821bxe_nic_load_pmf(struct bxe_softc *sc,
6822                 uint32_t         load_code)
6823{
6824    uint32_t ncsi_oem_data_addr;
6825
6826    if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6827        (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6828        (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6829        /*
6830         * Barrier here for ordering between the writing to sc->port.pmf here
6831         * and reading it from the periodic task.
6832         */
6833        sc->port.pmf = 1;
6834        mb();
6835    } else {
6836        sc->port.pmf = 0;
6837    }
6838
6839    BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6840
6841    /* XXX needed? */
6842    if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6843        if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6844            ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6845            if (ncsi_oem_data_addr) {
6846                REG_WR(sc,
6847                       (ncsi_oem_data_addr +
6848                        offsetof(struct glob_ncsi_oem_data, driver_version)),
6849                       0);
6850            }
6851        }
6852    }
6853}
6854
6855static void
6856bxe_read_mf_cfg(struct bxe_softc *sc)
6857{
6858    int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6859    int abs_func;
6860    int vn;
6861
6862    if (BXE_NOMCP(sc)) {
6863        return; /* what should be the default bvalue in this case */
6864    }
6865
6866    /*
6867     * The formula for computing the absolute function number is...
6868     * For 2 port configuration (4 functions per port):
6869     *   abs_func = 2 * vn + SC_PORT + SC_PATH
6870     * For 4 port configuration (2 functions per port):
6871     *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6872     */
6873    for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6874        abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6875        if (abs_func >= E1H_FUNC_MAX) {
6876            break;
6877        }
6878        sc->devinfo.mf_info.mf_config[vn] =
6879            MFCFG_RD(sc, func_mf_config[abs_func].config);
6880    }
6881
6882    if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6883        FUNC_MF_CFG_FUNC_DISABLED) {
6884        BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6885        sc->flags |= BXE_MF_FUNC_DIS;
6886    } else {
6887        BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6888        sc->flags &= ~BXE_MF_FUNC_DIS;
6889    }
6890}
6891
6892/* acquire split MCP access lock register */
6893static int bxe_acquire_alr(struct bxe_softc *sc)
6894{
6895    uint32_t j, val;
6896
6897    for (j = 0; j < 1000; j++) {
6898        val = (1UL << 31);
6899        REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6900        val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6901        if (val & (1L << 31))
6902            break;
6903
6904        DELAY(5000);
6905    }
6906
6907    if (!(val & (1L << 31))) {
6908        BLOGE(sc, "Cannot acquire MCP access lock register\n");
6909        return (-1);
6910    }
6911
6912    return (0);
6913}
6914
6915/* release split MCP access lock register */
6916static void bxe_release_alr(struct bxe_softc *sc)
6917{
6918    REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
6919}
6920
6921static void
6922bxe_fan_failure(struct bxe_softc *sc)
6923{
6924    int port = SC_PORT(sc);
6925    uint32_t ext_phy_config;
6926
6927    /* mark the failure */
6928    ext_phy_config =
6929        SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
6930
6931    ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
6932    ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
6933    SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
6934             ext_phy_config);
6935
6936    /* log the failure */
6937    BLOGW(sc, "Fan Failure has caused the driver to shutdown "
6938              "the card to prevent permanent damage. "
6939              "Please contact OEM Support for assistance\n");
6940
6941    /* XXX */
6942#if 1
6943    bxe_panic(sc, ("Schedule task to handle fan failure\n"));
6944#else
6945    /*
6946     * Schedule device reset (unload)
6947     * This is due to some boards consuming sufficient power when driver is
6948     * up to overheat if fan fails.
6949     */
6950    bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
6951    schedule_delayed_work(&sc->sp_rtnl_task, 0);
6952#endif
6953}
6954
6955/* this function is called upon a link interrupt */
6956static void
6957bxe_link_attn(struct bxe_softc *sc)
6958{
6959    uint32_t pause_enabled = 0;
6960    struct host_port_stats *pstats;
6961    int cmng_fns;
6962
6963    /* Make sure that we are synced with the current statistics */
6964    bxe_stats_handle(sc, STATS_EVENT_STOP);
6965
6966    elink_link_update(&sc->link_params, &sc->link_vars);
6967
6968    if (sc->link_vars.link_up) {
6969
6970        /* dropless flow control */
6971        if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
6972            pause_enabled = 0;
6973
6974            if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
6975                pause_enabled = 1;
6976            }
6977
6978            REG_WR(sc,
6979                   (BAR_USTRORM_INTMEM +
6980                    USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
6981                   pause_enabled);
6982        }
6983
6984        if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
6985            pstats = BXE_SP(sc, port_stats);
6986            /* reset old mac stats */
6987            memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
6988        }
6989
6990        if (sc->state == BXE_STATE_OPEN) {
6991            bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
6992        }
6993    }
6994
6995    if (sc->link_vars.link_up && sc->link_vars.line_speed) {
6996        cmng_fns = bxe_get_cmng_fns_mode(sc);
6997
6998        if (cmng_fns != CMNG_FNS_NONE) {
6999            bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7000            storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7001        } else {
7002            /* rate shaping and fairness are disabled */
7003            BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7004        }
7005    }
7006
7007    bxe_link_report_locked(sc);
7008
7009    if (IS_MF(sc)) {
7010        ; // XXX bxe_link_sync_notify(sc);
7011    }
7012}
7013
7014static void
7015bxe_attn_int_asserted(struct bxe_softc *sc,
7016                      uint32_t         asserted)
7017{
7018    int port = SC_PORT(sc);
7019    uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7020                               MISC_REG_AEU_MASK_ATTN_FUNC_0;
7021    uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7022                                        NIG_REG_MASK_INTERRUPT_PORT0;
7023    uint32_t aeu_mask;
7024    uint32_t nig_mask = 0;
7025    uint32_t reg_addr;
7026    uint32_t igu_acked;
7027    uint32_t cnt;
7028
7029    if (sc->attn_state & asserted) {
7030        BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7031    }
7032
7033    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7034
7035    aeu_mask = REG_RD(sc, aeu_addr);
7036
7037    BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7038          aeu_mask, asserted);
7039
7040    aeu_mask &= ~(asserted & 0x3ff);
7041
7042    BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7043
7044    REG_WR(sc, aeu_addr, aeu_mask);
7045
7046    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7047
7048    BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7049    sc->attn_state |= asserted;
7050    BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7051
7052    if (asserted & ATTN_HARD_WIRED_MASK) {
7053        if (asserted & ATTN_NIG_FOR_FUNC) {
7054
7055	    bxe_acquire_phy_lock(sc);
7056            /* save nig interrupt mask */
7057            nig_mask = REG_RD(sc, nig_int_mask_addr);
7058
7059            /* If nig_mask is not set, no need to call the update function */
7060            if (nig_mask) {
7061                REG_WR(sc, nig_int_mask_addr, 0);
7062
7063                bxe_link_attn(sc);
7064            }
7065
7066            /* handle unicore attn? */
7067        }
7068
7069        if (asserted & ATTN_SW_TIMER_4_FUNC) {
7070            BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7071        }
7072
7073        if (asserted & GPIO_2_FUNC) {
7074            BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7075        }
7076
7077        if (asserted & GPIO_3_FUNC) {
7078            BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7079        }
7080
7081        if (asserted & GPIO_4_FUNC) {
7082            BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7083        }
7084
7085        if (port == 0) {
7086            if (asserted & ATTN_GENERAL_ATTN_1) {
7087                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7088                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7089            }
7090            if (asserted & ATTN_GENERAL_ATTN_2) {
7091                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7092                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7093            }
7094            if (asserted & ATTN_GENERAL_ATTN_3) {
7095                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7096                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7097            }
7098        } else {
7099            if (asserted & ATTN_GENERAL_ATTN_4) {
7100                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7101                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7102            }
7103            if (asserted & ATTN_GENERAL_ATTN_5) {
7104                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7105                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7106            }
7107            if (asserted & ATTN_GENERAL_ATTN_6) {
7108                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7109                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7110            }
7111        }
7112    } /* hardwired */
7113
7114    if (sc->devinfo.int_block == INT_BLOCK_HC) {
7115        reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7116    } else {
7117        reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7118    }
7119
7120    BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7121          asserted,
7122          (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7123    REG_WR(sc, reg_addr, asserted);
7124
7125    /* now set back the mask */
7126    if (asserted & ATTN_NIG_FOR_FUNC) {
7127        /*
7128         * Verify that IGU ack through BAR was written before restoring
7129         * NIG mask. This loop should exit after 2-3 iterations max.
7130         */
7131        if (sc->devinfo.int_block != INT_BLOCK_HC) {
7132            cnt = 0;
7133
7134            do {
7135                igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7136            } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7137                     (++cnt < MAX_IGU_ATTN_ACK_TO));
7138
7139            if (!igu_acked) {
7140                BLOGE(sc, "Failed to verify IGU ack on time\n");
7141            }
7142
7143            mb();
7144        }
7145
7146        REG_WR(sc, nig_int_mask_addr, nig_mask);
7147
7148	bxe_release_phy_lock(sc);
7149    }
7150}
7151
7152static void
7153bxe_print_next_block(struct bxe_softc *sc,
7154                     int              idx,
7155                     const char       *blk)
7156{
7157    BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7158}
7159
7160static int
7161bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7162                              uint32_t         sig,
7163                              int              par_num,
7164                              uint8_t          print)
7165{
7166    uint32_t cur_bit = 0;
7167    int i = 0;
7168
7169    for (i = 0; sig; i++) {
7170        cur_bit = ((uint32_t)0x1 << i);
7171        if (sig & cur_bit) {
7172            switch (cur_bit) {
7173            case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7174                if (print)
7175                    bxe_print_next_block(sc, par_num++, "BRB");
7176                break;
7177            case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7178                if (print)
7179                    bxe_print_next_block(sc, par_num++, "PARSER");
7180                break;
7181            case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7182                if (print)
7183                    bxe_print_next_block(sc, par_num++, "TSDM");
7184                break;
7185            case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7186                if (print)
7187                    bxe_print_next_block(sc, par_num++, "SEARCHER");
7188                break;
7189            case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7190                if (print)
7191                    bxe_print_next_block(sc, par_num++, "TCM");
7192                break;
7193            case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7194                if (print)
7195                    bxe_print_next_block(sc, par_num++, "TSEMI");
7196                break;
7197            case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7198                if (print)
7199                    bxe_print_next_block(sc, par_num++, "XPB");
7200                break;
7201            }
7202
7203            /* Clear the bit */
7204            sig &= ~cur_bit;
7205        }
7206    }
7207
7208    return (par_num);
7209}
7210
7211static int
7212bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7213                              uint32_t         sig,
7214                              int              par_num,
7215                              uint8_t          *global,
7216                              uint8_t          print)
7217{
7218    int i = 0;
7219    uint32_t cur_bit = 0;
7220    for (i = 0; sig; i++) {
7221        cur_bit = ((uint32_t)0x1 << i);
7222        if (sig & cur_bit) {
7223            switch (cur_bit) {
7224            case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7225                if (print)
7226                    bxe_print_next_block(sc, par_num++, "PBF");
7227                break;
7228            case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7229                if (print)
7230                    bxe_print_next_block(sc, par_num++, "QM");
7231                break;
7232            case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7233                if (print)
7234                    bxe_print_next_block(sc, par_num++, "TM");
7235                break;
7236            case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7237                if (print)
7238                    bxe_print_next_block(sc, par_num++, "XSDM");
7239                break;
7240            case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7241                if (print)
7242                    bxe_print_next_block(sc, par_num++, "XCM");
7243                break;
7244            case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7245                if (print)
7246                    bxe_print_next_block(sc, par_num++, "XSEMI");
7247                break;
7248            case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7249                if (print)
7250                    bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7251                break;
7252            case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7253                if (print)
7254                    bxe_print_next_block(sc, par_num++, "NIG");
7255                break;
7256            case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7257                if (print)
7258                    bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7259                *global = TRUE;
7260                break;
7261            case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7262                if (print)
7263                    bxe_print_next_block(sc, par_num++, "DEBUG");
7264                break;
7265            case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7266                if (print)
7267                    bxe_print_next_block(sc, par_num++, "USDM");
7268                break;
7269            case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7270                if (print)
7271                    bxe_print_next_block(sc, par_num++, "UCM");
7272                break;
7273            case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7274                if (print)
7275                    bxe_print_next_block(sc, par_num++, "USEMI");
7276                break;
7277            case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7278                if (print)
7279                    bxe_print_next_block(sc, par_num++, "UPB");
7280                break;
7281            case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7282                if (print)
7283                    bxe_print_next_block(sc, par_num++, "CSDM");
7284                break;
7285            case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7286                if (print)
7287                    bxe_print_next_block(sc, par_num++, "CCM");
7288                break;
7289            }
7290
7291            /* Clear the bit */
7292            sig &= ~cur_bit;
7293        }
7294    }
7295
7296    return (par_num);
7297}
7298
7299static int
7300bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7301                              uint32_t         sig,
7302                              int              par_num,
7303                              uint8_t          print)
7304{
7305    uint32_t cur_bit = 0;
7306    int i = 0;
7307
7308    for (i = 0; sig; i++) {
7309        cur_bit = ((uint32_t)0x1 << i);
7310        if (sig & cur_bit) {
7311            switch (cur_bit) {
7312            case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7313                if (print)
7314                    bxe_print_next_block(sc, par_num++, "CSEMI");
7315                break;
7316            case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7317                if (print)
7318                    bxe_print_next_block(sc, par_num++, "PXP");
7319                break;
7320            case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7321                if (print)
7322                    bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7323                break;
7324            case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7325                if (print)
7326                    bxe_print_next_block(sc, par_num++, "CFC");
7327                break;
7328            case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7329                if (print)
7330                    bxe_print_next_block(sc, par_num++, "CDU");
7331                break;
7332            case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7333                if (print)
7334                    bxe_print_next_block(sc, par_num++, "DMAE");
7335                break;
7336            case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7337                if (print)
7338                    bxe_print_next_block(sc, par_num++, "IGU");
7339                break;
7340            case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7341                if (print)
7342                    bxe_print_next_block(sc, par_num++, "MISC");
7343                break;
7344            }
7345
7346            /* Clear the bit */
7347            sig &= ~cur_bit;
7348        }
7349    }
7350
7351    return (par_num);
7352}
7353
7354static int
7355bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7356                              uint32_t         sig,
7357                              int              par_num,
7358                              uint8_t          *global,
7359                              uint8_t          print)
7360{
7361    uint32_t cur_bit = 0;
7362    int i = 0;
7363
7364    for (i = 0; sig; i++) {
7365        cur_bit = ((uint32_t)0x1 << i);
7366        if (sig & cur_bit) {
7367            switch (cur_bit) {
7368            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7369                if (print)
7370                    bxe_print_next_block(sc, par_num++, "MCP ROM");
7371                *global = TRUE;
7372                break;
7373            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7374                if (print)
7375                    bxe_print_next_block(sc, par_num++,
7376                              "MCP UMP RX");
7377                *global = TRUE;
7378                break;
7379            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7380                if (print)
7381                    bxe_print_next_block(sc, par_num++,
7382                              "MCP UMP TX");
7383                *global = TRUE;
7384                break;
7385            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7386                if (print)
7387                    bxe_print_next_block(sc, par_num++,
7388                              "MCP SCPAD");
7389                *global = TRUE;
7390                break;
7391            }
7392
7393            /* Clear the bit */
7394            sig &= ~cur_bit;
7395        }
7396    }
7397
7398    return (par_num);
7399}
7400
7401static int
7402bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7403                              uint32_t         sig,
7404                              int              par_num,
7405                              uint8_t          print)
7406{
7407    uint32_t cur_bit = 0;
7408    int i = 0;
7409
7410    for (i = 0; sig; i++) {
7411        cur_bit = ((uint32_t)0x1 << i);
7412        if (sig & cur_bit) {
7413            switch (cur_bit) {
7414            case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7415                if (print)
7416                    bxe_print_next_block(sc, par_num++, "PGLUE_B");
7417                break;
7418            case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7419                if (print)
7420                    bxe_print_next_block(sc, par_num++, "ATC");
7421                break;
7422            }
7423
7424            /* Clear the bit */
7425            sig &= ~cur_bit;
7426        }
7427    }
7428
7429    return (par_num);
7430}
7431
7432static uint8_t
7433bxe_parity_attn(struct bxe_softc *sc,
7434                uint8_t          *global,
7435                uint8_t          print,
7436                uint32_t         *sig)
7437{
7438    int par_num = 0;
7439
7440    if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7441        (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7442        (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7443        (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7444        (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7445        BLOGE(sc, "Parity error: HW block parity attention:\n"
7446                  "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7447              (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7448              (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7449              (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7450              (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7451              (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7452
7453        if (print)
7454            BLOGI(sc, "Parity errors detected in blocks: ");
7455
7456        par_num =
7457            bxe_check_blocks_with_parity0(sc, sig[0] &
7458                                          HW_PRTY_ASSERT_SET_0,
7459                                          par_num, print);
7460        par_num =
7461            bxe_check_blocks_with_parity1(sc, sig[1] &
7462                                          HW_PRTY_ASSERT_SET_1,
7463                                          par_num, global, print);
7464        par_num =
7465            bxe_check_blocks_with_parity2(sc, sig[2] &
7466                                          HW_PRTY_ASSERT_SET_2,
7467                                          par_num, print);
7468        par_num =
7469            bxe_check_blocks_with_parity3(sc, sig[3] &
7470                                          HW_PRTY_ASSERT_SET_3,
7471                                          par_num, global, print);
7472        par_num =
7473            bxe_check_blocks_with_parity4(sc, sig[4] &
7474                                          HW_PRTY_ASSERT_SET_4,
7475                                          par_num, print);
7476
7477        if (print)
7478            BLOGI(sc, "\n");
7479
7480        return (TRUE);
7481    }
7482
7483    return (FALSE);
7484}
7485
7486static uint8_t
7487bxe_chk_parity_attn(struct bxe_softc *sc,
7488                    uint8_t          *global,
7489                    uint8_t          print)
7490{
7491    struct attn_route attn = { {0} };
7492    int port = SC_PORT(sc);
7493
7494    attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7495    attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7496    attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7497    attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7498
7499    /*
7500     * Since MCP attentions can't be disabled inside the block, we need to
7501     * read AEU registers to see whether they're currently disabled
7502     */
7503    attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7504                                      : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7505                         MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7506                        ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7507
7508
7509    if (!CHIP_IS_E1x(sc))
7510        attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7511
7512    return (bxe_parity_attn(sc, global, print, attn.sig));
7513}
7514
7515static void
7516bxe_attn_int_deasserted4(struct bxe_softc *sc,
7517                         uint32_t         attn)
7518{
7519    uint32_t val;
7520
7521    if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7522        val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7523        BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7524        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7525            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7526        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7527            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7528        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7529            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7530        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7531            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7532        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7533            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7534        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7535            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7536        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7537            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7538        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7539            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7540        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7541            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7542    }
7543
7544    if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7545        val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7546        BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7547        if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7548            BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7549        if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7550            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7551        if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7552            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7553        if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7554            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7555        if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7556            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7557        if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7558            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7559    }
7560
7561    if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7562                AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7563        BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7564              (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7565                                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7566    }
7567}
7568
7569static void
7570bxe_e1h_disable(struct bxe_softc *sc)
7571{
7572    int port = SC_PORT(sc);
7573
7574    bxe_tx_disable(sc);
7575
7576    REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7577}
7578
7579static void
7580bxe_e1h_enable(struct bxe_softc *sc)
7581{
7582    int port = SC_PORT(sc);
7583
7584    REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7585
7586    // XXX bxe_tx_enable(sc);
7587}
7588
7589/*
7590 * called due to MCP event (on pmf):
7591 *   reread new bandwidth configuration
7592 *   configure FW
7593 *   notify others function about the change
7594 */
7595static void
7596bxe_config_mf_bw(struct bxe_softc *sc)
7597{
7598    if (sc->link_vars.link_up) {
7599        bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7600        // XXX bxe_link_sync_notify(sc);
7601    }
7602
7603    storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7604}
7605
7606static void
7607bxe_set_mf_bw(struct bxe_softc *sc)
7608{
7609    bxe_config_mf_bw(sc);
7610    bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7611}
7612
7613static void
7614bxe_handle_eee_event(struct bxe_softc *sc)
7615{
7616    BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7617    bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7618}
7619
7620#define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7621
7622static void
7623bxe_drv_info_ether_stat(struct bxe_softc *sc)
7624{
7625    struct eth_stats_info *ether_stat =
7626        &sc->sp->drv_info_to_mcp.ether_stat;
7627
7628    strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7629            ETH_STAT_INFO_VERSION_LEN);
7630
7631    /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7632    sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7633                                          DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7634                                          ether_stat->mac_local + MAC_PAD,
7635                                          MAC_PAD, ETH_ALEN);
7636
7637    ether_stat->mtu_size = sc->mtu;
7638
7639    ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7640    if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
7641        ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7642    }
7643
7644    // XXX ether_stat->feature_flags |= ???;
7645
7646    ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7647
7648    ether_stat->txq_size = sc->tx_ring_size;
7649    ether_stat->rxq_size = sc->rx_ring_size;
7650}
7651
7652static void
7653bxe_handle_drv_info_req(struct bxe_softc *sc)
7654{
7655    enum drv_info_opcode op_code;
7656    uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7657
7658    /* if drv_info version supported by MFW doesn't match - send NACK */
7659    if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7660        bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7661        return;
7662    }
7663
7664    op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7665               DRV_INFO_CONTROL_OP_CODE_SHIFT);
7666
7667    memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7668
7669    switch (op_code) {
7670    case ETH_STATS_OPCODE:
7671        bxe_drv_info_ether_stat(sc);
7672        break;
7673    case FCOE_STATS_OPCODE:
7674    case ISCSI_STATS_OPCODE:
7675    default:
7676        /* if op code isn't supported - send NACK */
7677        bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7678        return;
7679    }
7680
7681    /*
7682     * If we got drv_info attn from MFW then these fields are defined in
7683     * shmem2 for sure
7684     */
7685    SHMEM2_WR(sc, drv_info_host_addr_lo,
7686              U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7687    SHMEM2_WR(sc, drv_info_host_addr_hi,
7688              U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7689
7690    bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7691}
7692
7693static void
7694bxe_dcc_event(struct bxe_softc *sc,
7695              uint32_t         dcc_event)
7696{
7697    BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7698
7699    if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7700        /*
7701         * This is the only place besides the function initialization
7702         * where the sc->flags can change so it is done without any
7703         * locks
7704         */
7705        if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7706            BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7707            sc->flags |= BXE_MF_FUNC_DIS;
7708            bxe_e1h_disable(sc);
7709        } else {
7710            BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7711            sc->flags &= ~BXE_MF_FUNC_DIS;
7712            bxe_e1h_enable(sc);
7713        }
7714        dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7715    }
7716
7717    if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7718        bxe_config_mf_bw(sc);
7719        dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7720    }
7721
7722    /* Report results to MCP */
7723    if (dcc_event)
7724        bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7725    else
7726        bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7727}
7728
7729static void
7730bxe_pmf_update(struct bxe_softc *sc)
7731{
7732    int port = SC_PORT(sc);
7733    uint32_t val;
7734
7735    sc->port.pmf = 1;
7736    BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7737
7738    /*
7739     * We need the mb() to ensure the ordering between the writing to
7740     * sc->port.pmf here and reading it from the bxe_periodic_task().
7741     */
7742    mb();
7743
7744    /* queue a periodic task */
7745    // XXX schedule task...
7746
7747    // XXX bxe_dcbx_pmf_update(sc);
7748
7749    /* enable nig attention */
7750    val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7751    if (sc->devinfo.int_block == INT_BLOCK_HC) {
7752        REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7753        REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7754    } else if (!CHIP_IS_E1x(sc)) {
7755        REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7756        REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7757    }
7758
7759    bxe_stats_handle(sc, STATS_EVENT_PMF);
7760}
7761
7762static int
7763bxe_mc_assert(struct bxe_softc *sc)
7764{
7765    char last_idx;
7766    int i, rc = 0;
7767    uint32_t row0, row1, row2, row3;
7768
7769    /* XSTORM */
7770    last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7771    if (last_idx)
7772        BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7773
7774    /* print the asserts */
7775    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7776
7777        row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7778        row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7779        row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7780        row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7781
7782        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7783            BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7784                  i, row3, row2, row1, row0);
7785            rc++;
7786        } else {
7787            break;
7788        }
7789    }
7790
7791    /* TSTORM */
7792    last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7793    if (last_idx) {
7794        BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7795    }
7796
7797    /* print the asserts */
7798    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7799
7800        row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7801        row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7802        row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7803        row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7804
7805        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7806            BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7807                  i, row3, row2, row1, row0);
7808            rc++;
7809        } else {
7810            break;
7811        }
7812    }
7813
7814    /* CSTORM */
7815    last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7816    if (last_idx) {
7817        BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7818    }
7819
7820    /* print the asserts */
7821    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7822
7823        row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7824        row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7825        row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7826        row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7827
7828        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7829            BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7830                  i, row3, row2, row1, row0);
7831            rc++;
7832        } else {
7833            break;
7834        }
7835    }
7836
7837    /* USTORM */
7838    last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7839    if (last_idx) {
7840        BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7841    }
7842
7843    /* print the asserts */
7844    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7845
7846        row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7847        row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7848        row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7849        row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7850
7851        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7852            BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7853                  i, row3, row2, row1, row0);
7854            rc++;
7855        } else {
7856            break;
7857        }
7858    }
7859
7860    return (rc);
7861}
7862
7863static void
7864bxe_attn_int_deasserted3(struct bxe_softc *sc,
7865                         uint32_t         attn)
7866{
7867    int func = SC_FUNC(sc);
7868    uint32_t val;
7869
7870    if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7871
7872        if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7873
7874            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7875            bxe_read_mf_cfg(sc);
7876            sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7877                MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7878            val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7879
7880            if (val & DRV_STATUS_DCC_EVENT_MASK)
7881                bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7882
7883            if (val & DRV_STATUS_SET_MF_BW)
7884                bxe_set_mf_bw(sc);
7885
7886            if (val & DRV_STATUS_DRV_INFO_REQ)
7887                bxe_handle_drv_info_req(sc);
7888
7889            if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
7890                bxe_pmf_update(sc);
7891
7892            if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
7893                bxe_handle_eee_event(sc);
7894
7895            if (sc->link_vars.periodic_flags &
7896                ELINK_PERIODIC_FLAGS_LINK_EVENT) {
7897                /* sync with link */
7898		bxe_acquire_phy_lock(sc);
7899                sc->link_vars.periodic_flags &=
7900                    ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
7901		bxe_release_phy_lock(sc);
7902                if (IS_MF(sc))
7903                    ; // XXX bxe_link_sync_notify(sc);
7904                bxe_link_report(sc);
7905            }
7906
7907            /*
7908             * Always call it here: bxe_link_report() will
7909             * prevent the link indication duplication.
7910             */
7911            bxe_link_status_update(sc);
7912
7913        } else if (attn & BXE_MC_ASSERT_BITS) {
7914
7915            BLOGE(sc, "MC assert!\n");
7916            bxe_mc_assert(sc);
7917            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
7918            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
7919            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
7920            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
7921            bxe_panic(sc, ("MC assert!\n"));
7922
7923        } else if (attn & BXE_MCP_ASSERT) {
7924
7925            BLOGE(sc, "MCP assert!\n");
7926            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
7927            // XXX bxe_fw_dump(sc);
7928
7929        } else {
7930            BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
7931        }
7932    }
7933
7934    if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
7935        BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
7936        if (attn & BXE_GRC_TIMEOUT) {
7937            val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
7938            BLOGE(sc, "GRC time-out 0x%08x\n", val);
7939        }
7940        if (attn & BXE_GRC_RSV) {
7941            val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
7942            BLOGE(sc, "GRC reserved 0x%08x\n", val);
7943        }
7944        REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
7945    }
7946}
7947
7948static void
7949bxe_attn_int_deasserted2(struct bxe_softc *sc,
7950                         uint32_t         attn)
7951{
7952    int port = SC_PORT(sc);
7953    int reg_offset;
7954    uint32_t val0, mask0, val1, mask1;
7955    uint32_t val;
7956
7957    if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
7958        val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
7959        BLOGE(sc, "CFC hw attention 0x%08x\n", val);
7960        /* CFC error attention */
7961        if (val & 0x2) {
7962            BLOGE(sc, "FATAL error from CFC\n");
7963        }
7964    }
7965
7966    if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
7967        val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
7968        BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
7969        /* RQ_USDMDP_FIFO_OVERFLOW */
7970        if (val & 0x18000) {
7971            BLOGE(sc, "FATAL error from PXP\n");
7972        }
7973
7974        if (!CHIP_IS_E1x(sc)) {
7975            val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
7976            BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
7977        }
7978    }
7979
7980#define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
7981#define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
7982
7983    if (attn & AEU_PXP2_HW_INT_BIT) {
7984        /*  CQ47854 workaround do not panic on
7985         *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
7986         */
7987        if (!CHIP_IS_E1x(sc)) {
7988            mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
7989            val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
7990            mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
7991            val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
7992            /*
7993             * If the only PXP2_EOP_ERROR_BIT is set in
7994             * STS0 and STS1 - clear it
7995             *
7996             * probably we lose additional attentions between
7997             * STS0 and STS_CLR0, in this case user will not
7998             * be notified about them
7999             */
8000            if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8001                !(val1 & mask1))
8002                val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8003
8004            /* print the register, since no one can restore it */
8005            BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8006
8007            /*
8008             * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8009             * then notify
8010             */
8011            if (val0 & PXP2_EOP_ERROR_BIT) {
8012                BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8013
8014                /*
8015                 * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8016                 * set then clear attention from PXP2 block without panic
8017                 */
8018                if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8019                    ((val1 & mask1) == 0))
8020                    attn &= ~AEU_PXP2_HW_INT_BIT;
8021            }
8022        }
8023    }
8024
8025    if (attn & HW_INTERRUT_ASSERT_SET_2) {
8026        reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8027                             MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8028
8029        val = REG_RD(sc, reg_offset);
8030        val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8031        REG_WR(sc, reg_offset, val);
8032
8033        BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8034              (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8035        bxe_panic(sc, ("HW block attention set2\n"));
8036    }
8037}
8038
8039static void
8040bxe_attn_int_deasserted1(struct bxe_softc *sc,
8041                         uint32_t         attn)
8042{
8043    int port = SC_PORT(sc);
8044    int reg_offset;
8045    uint32_t val;
8046
8047    if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8048        val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8049        BLOGE(sc, "DB hw attention 0x%08x\n", val);
8050        /* DORQ discard attention */
8051        if (val & 0x2) {
8052            BLOGE(sc, "FATAL error from DORQ\n");
8053        }
8054    }
8055
8056    if (attn & HW_INTERRUT_ASSERT_SET_1) {
8057        reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8058                             MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8059
8060        val = REG_RD(sc, reg_offset);
8061        val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8062        REG_WR(sc, reg_offset, val);
8063
8064        BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8065              (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8066        bxe_panic(sc, ("HW block attention set1\n"));
8067    }
8068}
8069
8070static void
8071bxe_attn_int_deasserted0(struct bxe_softc *sc,
8072                         uint32_t         attn)
8073{
8074    int port = SC_PORT(sc);
8075    int reg_offset;
8076    uint32_t val;
8077
8078    reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8079                          MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8080
8081    if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8082        val = REG_RD(sc, reg_offset);
8083        val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8084        REG_WR(sc, reg_offset, val);
8085
8086        BLOGW(sc, "SPIO5 hw attention\n");
8087
8088        /* Fan failure attention */
8089        elink_hw_reset_phy(&sc->link_params);
8090        bxe_fan_failure(sc);
8091    }
8092
8093    if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8094	bxe_acquire_phy_lock(sc);
8095        elink_handle_module_detect_int(&sc->link_params);
8096	bxe_release_phy_lock(sc);
8097    }
8098
8099    if (attn & HW_INTERRUT_ASSERT_SET_0) {
8100        val = REG_RD(sc, reg_offset);
8101        val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8102        REG_WR(sc, reg_offset, val);
8103
8104        bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8105                       (attn & HW_INTERRUT_ASSERT_SET_0)));
8106    }
8107}
8108
8109static void
8110bxe_attn_int_deasserted(struct bxe_softc *sc,
8111                        uint32_t         deasserted)
8112{
8113    struct attn_route attn;
8114    struct attn_route *group_mask;
8115    int port = SC_PORT(sc);
8116    int index;
8117    uint32_t reg_addr;
8118    uint32_t val;
8119    uint32_t aeu_mask;
8120    uint8_t global = FALSE;
8121
8122    /*
8123     * Need to take HW lock because MCP or other port might also
8124     * try to handle this event.
8125     */
8126    bxe_acquire_alr(sc);
8127
8128    if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8129        /* XXX
8130         * In case of parity errors don't handle attentions so that
8131         * other function would "see" parity errors.
8132         */
8133        sc->recovery_state = BXE_RECOVERY_INIT;
8134        // XXX schedule a recovery task...
8135        /* disable HW interrupts */
8136        bxe_int_disable(sc);
8137        bxe_release_alr(sc);
8138        return;
8139    }
8140
8141    attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8142    attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8143    attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8144    attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8145    if (!CHIP_IS_E1x(sc)) {
8146        attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8147    } else {
8148        attn.sig[4] = 0;
8149    }
8150
8151    BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8152          attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8153
8154    for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8155        if (deasserted & (1 << index)) {
8156            group_mask = &sc->attn_group[index];
8157
8158            BLOGD(sc, DBG_INTR,
8159                  "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8160                  group_mask->sig[0], group_mask->sig[1],
8161                  group_mask->sig[2], group_mask->sig[3],
8162                  group_mask->sig[4]);
8163
8164            bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8165            bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8166            bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8167            bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8168            bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8169        }
8170    }
8171
8172    bxe_release_alr(sc);
8173
8174    if (sc->devinfo.int_block == INT_BLOCK_HC) {
8175        reg_addr = (HC_REG_COMMAND_REG + port*32 +
8176                    COMMAND_REG_ATTN_BITS_CLR);
8177    } else {
8178        reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8179    }
8180
8181    val = ~deasserted;
8182    BLOGD(sc, DBG_INTR,
8183          "about to mask 0x%08x at %s addr 0x%08x\n", val,
8184          (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8185    REG_WR(sc, reg_addr, val);
8186
8187    if (~sc->attn_state & deasserted) {
8188        BLOGE(sc, "IGU error\n");
8189    }
8190
8191    reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8192                      MISC_REG_AEU_MASK_ATTN_FUNC_0;
8193
8194    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8195
8196    aeu_mask = REG_RD(sc, reg_addr);
8197
8198    BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8199          aeu_mask, deasserted);
8200    aeu_mask |= (deasserted & 0x3ff);
8201    BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8202
8203    REG_WR(sc, reg_addr, aeu_mask);
8204    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8205
8206    BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8207    sc->attn_state &= ~deasserted;
8208    BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8209}
8210
8211static void
8212bxe_attn_int(struct bxe_softc *sc)
8213{
8214    /* read local copy of bits */
8215    uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8216    uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8217    uint32_t attn_state = sc->attn_state;
8218
8219    /* look for changed bits */
8220    uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8221    uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8222
8223    BLOGD(sc, DBG_INTR,
8224          "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8225          attn_bits, attn_ack, asserted, deasserted);
8226
8227    if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8228        BLOGE(sc, "BAD attention state\n");
8229    }
8230
8231    /* handle bits that were raised */
8232    if (asserted) {
8233        bxe_attn_int_asserted(sc, asserted);
8234    }
8235
8236    if (deasserted) {
8237        bxe_attn_int_deasserted(sc, deasserted);
8238    }
8239}
8240
8241static uint16_t
8242bxe_update_dsb_idx(struct bxe_softc *sc)
8243{
8244    struct host_sp_status_block *def_sb = sc->def_sb;
8245    uint16_t rc = 0;
8246
8247    mb(); /* status block is written to by the chip */
8248
8249    if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8250        sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8251        rc |= BXE_DEF_SB_ATT_IDX;
8252    }
8253
8254    if (sc->def_idx != def_sb->sp_sb.running_index) {
8255        sc->def_idx = def_sb->sp_sb.running_index;
8256        rc |= BXE_DEF_SB_IDX;
8257    }
8258
8259    mb();
8260
8261    return (rc);
8262}
8263
8264static inline struct ecore_queue_sp_obj *
8265bxe_cid_to_q_obj(struct bxe_softc *sc,
8266                 uint32_t         cid)
8267{
8268    BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8269    return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8270}
8271
8272static void
8273bxe_handle_mcast_eqe(struct bxe_softc *sc)
8274{
8275    struct ecore_mcast_ramrod_params rparam;
8276    int rc;
8277
8278    memset(&rparam, 0, sizeof(rparam));
8279
8280    rparam.mcast_obj = &sc->mcast_obj;
8281
8282    BXE_MCAST_LOCK(sc);
8283
8284    /* clear pending state for the last command */
8285    sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8286
8287    /* if there are pending mcast commands - send them */
8288    if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8289        rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8290        if (rc < 0) {
8291            BLOGD(sc, DBG_SP,
8292                "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8293        }
8294    }
8295
8296    BXE_MCAST_UNLOCK(sc);
8297}
8298
8299static void
8300bxe_handle_classification_eqe(struct bxe_softc      *sc,
8301                              union event_ring_elem *elem)
8302{
8303    unsigned long ramrod_flags = 0;
8304    int rc = 0;
8305    uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8306    struct ecore_vlan_mac_obj *vlan_mac_obj;
8307
8308    /* always push next commands out, don't wait here */
8309    bit_set(&ramrod_flags, RAMROD_CONT);
8310
8311    switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8312    case ECORE_FILTER_MAC_PENDING:
8313        BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8314        vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8315        break;
8316
8317    case ECORE_FILTER_MCAST_PENDING:
8318        BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8319        /*
8320         * This is only relevant for 57710 where multicast MACs are
8321         * configured as unicast MACs using the same ramrod.
8322         */
8323        bxe_handle_mcast_eqe(sc);
8324        return;
8325
8326    default:
8327        BLOGE(sc, "Unsupported classification command: %d\n",
8328              elem->message.data.eth_event.echo);
8329        return;
8330    }
8331
8332    rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8333
8334    if (rc < 0) {
8335        BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8336    } else if (rc > 0) {
8337        BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8338    }
8339}
8340
8341static void
8342bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8343                       union event_ring_elem *elem)
8344{
8345    bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8346
8347    /* send rx_mode command again if was requested */
8348    if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8349                               &sc->sp_state)) {
8350        bxe_set_storm_rx_mode(sc);
8351    }
8352}
8353
8354static void
8355bxe_update_eq_prod(struct bxe_softc *sc,
8356                   uint16_t         prod)
8357{
8358    storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8359    wmb(); /* keep prod updates ordered */
8360}
8361
8362static void
8363bxe_eq_int(struct bxe_softc *sc)
8364{
8365    uint16_t hw_cons, sw_cons, sw_prod;
8366    union event_ring_elem *elem;
8367    uint8_t echo;
8368    uint32_t cid;
8369    uint8_t opcode;
8370    int spqe_cnt = 0;
8371    struct ecore_queue_sp_obj *q_obj;
8372    struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8373    struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8374
8375    hw_cons = le16toh(*sc->eq_cons_sb);
8376
8377    /*
8378     * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8379     * when we get to the next-page we need to adjust so the loop
8380     * condition below will be met. The next element is the size of a
8381     * regular element and hence incrementing by 1
8382     */
8383    if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8384        hw_cons++;
8385    }
8386
8387    /*
8388     * This function may never run in parallel with itself for a
8389     * specific sc and no need for a read memory barrier here.
8390     */
8391    sw_cons = sc->eq_cons;
8392    sw_prod = sc->eq_prod;
8393
8394    BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8395          hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8396
8397    for (;
8398         sw_cons != hw_cons;
8399         sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8400
8401        elem = &sc->eq[EQ_DESC(sw_cons)];
8402
8403        /* elem CID originates from FW, actually LE */
8404        cid = SW_CID(elem->message.data.cfc_del_event.cid);
8405        opcode = elem->message.opcode;
8406
8407        /* handle eq element */
8408        switch (opcode) {
8409
8410        case EVENT_RING_OPCODE_STAT_QUERY:
8411            BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8412                  sc->stats_comp++);
8413            /* nothing to do with stats comp */
8414            goto next_spqe;
8415
8416        case EVENT_RING_OPCODE_CFC_DEL:
8417            /* handle according to cid range */
8418            /* we may want to verify here that the sc state is HALTING */
8419            BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8420            q_obj = bxe_cid_to_q_obj(sc, cid);
8421            if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8422                break;
8423            }
8424            goto next_spqe;
8425
8426        case EVENT_RING_OPCODE_STOP_TRAFFIC:
8427            BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8428            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8429                break;
8430            }
8431            // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8432            goto next_spqe;
8433
8434        case EVENT_RING_OPCODE_START_TRAFFIC:
8435            BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8436            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8437                break;
8438            }
8439            // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8440            goto next_spqe;
8441
8442        case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8443            echo = elem->message.data.function_update_event.echo;
8444            if (echo == SWITCH_UPDATE) {
8445                BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8446                if (f_obj->complete_cmd(sc, f_obj,
8447                                        ECORE_F_CMD_SWITCH_UPDATE)) {
8448                    break;
8449                }
8450            }
8451            else {
8452                BLOGD(sc, DBG_SP,
8453                      "AFEX: ramrod completed FUNCTION_UPDATE\n");
8454            }
8455            goto next_spqe;
8456
8457        case EVENT_RING_OPCODE_FORWARD_SETUP:
8458            q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8459            if (q_obj->complete_cmd(sc, q_obj,
8460                                    ECORE_Q_CMD_SETUP_TX_ONLY)) {
8461                break;
8462            }
8463            goto next_spqe;
8464
8465        case EVENT_RING_OPCODE_FUNCTION_START:
8466            BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8467            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8468                break;
8469            }
8470            goto next_spqe;
8471
8472        case EVENT_RING_OPCODE_FUNCTION_STOP:
8473            BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8474            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8475                break;
8476            }
8477            goto next_spqe;
8478        }
8479
8480        switch (opcode | sc->state) {
8481        case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8482        case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8483            cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8484            BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8485            rss_raw->clear_pending(rss_raw);
8486            break;
8487
8488        case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8489        case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8490        case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8491        case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8492        case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8493        case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8494            BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8495            bxe_handle_classification_eqe(sc, elem);
8496            break;
8497
8498        case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8499        case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8500        case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8501            BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8502            bxe_handle_mcast_eqe(sc);
8503            break;
8504
8505        case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8506        case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8507        case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8508            BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8509            bxe_handle_rx_mode_eqe(sc, elem);
8510            break;
8511
8512        default:
8513            /* unknown event log error and continue */
8514            BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8515                  elem->message.opcode, sc->state);
8516        }
8517
8518next_spqe:
8519        spqe_cnt++;
8520    } /* for */
8521
8522    mb();
8523    atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8524
8525    sc->eq_cons = sw_cons;
8526    sc->eq_prod = sw_prod;
8527
8528    /* make sure that above mem writes were issued towards the memory */
8529    wmb();
8530
8531    /* update producer */
8532    bxe_update_eq_prod(sc, sc->eq_prod);
8533}
8534
8535static void
8536bxe_handle_sp_tq(void *context,
8537                 int  pending)
8538{
8539    struct bxe_softc *sc = (struct bxe_softc *)context;
8540    uint16_t status;
8541
8542    BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8543
8544    /* what work needs to be performed? */
8545    status = bxe_update_dsb_idx(sc);
8546
8547    BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8548
8549    /* HW attentions */
8550    if (status & BXE_DEF_SB_ATT_IDX) {
8551        BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8552        bxe_attn_int(sc);
8553        status &= ~BXE_DEF_SB_ATT_IDX;
8554    }
8555
8556    /* SP events: STAT_QUERY and others */
8557    if (status & BXE_DEF_SB_IDX) {
8558        /* handle EQ completions */
8559        BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8560        bxe_eq_int(sc);
8561        bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8562                   le16toh(sc->def_idx), IGU_INT_NOP, 1);
8563        status &= ~BXE_DEF_SB_IDX;
8564    }
8565
8566    /* if status is non zero then something went wrong */
8567    if (__predict_false(status)) {
8568        BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8569    }
8570
8571    /* ack status block only if something was actually handled */
8572    bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8573               le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8574
8575    /*
8576     * Must be called after the EQ processing (since eq leads to sriov
8577     * ramrod completion flows).
8578     * This flow may have been scheduled by the arrival of a ramrod
8579     * completion, or by the sriov code rescheduling itself.
8580     */
8581    // XXX bxe_iov_sp_task(sc);
8582
8583}
8584
8585static void
8586bxe_handle_fp_tq(void *context,
8587                 int  pending)
8588{
8589    struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8590    struct bxe_softc *sc = fp->sc;
8591    uint8_t more_tx = FALSE;
8592    uint8_t more_rx = FALSE;
8593
8594    BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8595
8596    /* XXX
8597     * IFF_DRV_RUNNING state can't be checked here since we process
8598     * slowpath events on a client queue during setup. Instead
8599     * we need to add a "process/continue" flag here that the driver
8600     * can use to tell the task here not to do anything.
8601     */
8602#if 0
8603    if (!(if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
8604        return;
8605    }
8606#endif
8607
8608    /* update the fastpath index */
8609    bxe_update_fp_sb_idx(fp);
8610
8611    /* XXX add loop here if ever support multiple tx CoS */
8612    /* fp->txdata[cos] */
8613    if (bxe_has_tx_work(fp)) {
8614        BXE_FP_TX_LOCK(fp);
8615        more_tx = bxe_txeof(sc, fp);
8616        BXE_FP_TX_UNLOCK(fp);
8617    }
8618
8619    if (bxe_has_rx_work(fp)) {
8620        more_rx = bxe_rxeof(sc, fp);
8621    }
8622
8623    if (more_rx /*|| more_tx*/) {
8624        /* still more work to do */
8625        taskqueue_enqueue(fp->tq, &fp->tq_task);
8626        return;
8627    }
8628
8629    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8630               le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8631}
8632
8633static void
8634bxe_task_fp(struct bxe_fastpath *fp)
8635{
8636    struct bxe_softc *sc = fp->sc;
8637    uint8_t more_tx = FALSE;
8638    uint8_t more_rx = FALSE;
8639
8640    BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8641
8642    /* update the fastpath index */
8643    bxe_update_fp_sb_idx(fp);
8644
8645    /* XXX add loop here if ever support multiple tx CoS */
8646    /* fp->txdata[cos] */
8647    if (bxe_has_tx_work(fp)) {
8648        BXE_FP_TX_LOCK(fp);
8649        more_tx = bxe_txeof(sc, fp);
8650        BXE_FP_TX_UNLOCK(fp);
8651    }
8652
8653    if (bxe_has_rx_work(fp)) {
8654        more_rx = bxe_rxeof(sc, fp);
8655    }
8656
8657    if (more_rx /*|| more_tx*/) {
8658        /* still more work to do, bail out if this ISR and process later */
8659        taskqueue_enqueue(fp->tq, &fp->tq_task);
8660        return;
8661    }
8662
8663    /*
8664     * Here we write the fastpath index taken before doing any tx or rx work.
8665     * It is very well possible other hw events occurred up to this point and
8666     * they were actually processed accordingly above. Since we're going to
8667     * write an older fastpath index, an interrupt is coming which we might
8668     * not do any work in.
8669     */
8670    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8671               le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8672}
8673
8674/*
8675 * Legacy interrupt entry point.
8676 *
8677 * Verifies that the controller generated the interrupt and
8678 * then calls a separate routine to handle the various
8679 * interrupt causes: link, RX, and TX.
8680 */
8681static void
8682bxe_intr_legacy(void *xsc)
8683{
8684    struct bxe_softc *sc = (struct bxe_softc *)xsc;
8685    struct bxe_fastpath *fp;
8686    uint16_t status, mask;
8687    int i;
8688
8689    BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8690
8691    /*
8692     * 0 for ustorm, 1 for cstorm
8693     * the bits returned from ack_int() are 0-15
8694     * bit 0 = attention status block
8695     * bit 1 = fast path status block
8696     * a mask of 0x2 or more = tx/rx event
8697     * a mask of 1 = slow path event
8698     */
8699
8700    status = bxe_ack_int(sc);
8701
8702    /* the interrupt is not for us */
8703    if (__predict_false(status == 0)) {
8704        BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8705        return;
8706    }
8707
8708    BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8709
8710    FOR_EACH_ETH_QUEUE(sc, i) {
8711        fp = &sc->fp[i];
8712        mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8713        if (status & mask) {
8714            /* acknowledge and disable further fastpath interrupts */
8715            bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8716            bxe_task_fp(fp);
8717            status &= ~mask;
8718        }
8719    }
8720
8721    if (__predict_false(status & 0x1)) {
8722        /* acknowledge and disable further slowpath interrupts */
8723        bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8724
8725        /* schedule slowpath handler */
8726        taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8727
8728        status &= ~0x1;
8729    }
8730
8731    if (__predict_false(status)) {
8732        BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8733    }
8734}
8735
8736/* slowpath interrupt entry point */
8737static void
8738bxe_intr_sp(void *xsc)
8739{
8740    struct bxe_softc *sc = (struct bxe_softc *)xsc;
8741
8742    BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8743
8744    /* acknowledge and disable further slowpath interrupts */
8745    bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8746
8747    /* schedule slowpath handler */
8748    taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8749}
8750
8751/* fastpath interrupt entry point */
8752static void
8753bxe_intr_fp(void *xfp)
8754{
8755    struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8756    struct bxe_softc *sc = fp->sc;
8757
8758    BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8759
8760    BLOGD(sc, DBG_INTR,
8761          "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8762          curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8763
8764    /* acknowledge and disable further fastpath interrupts */
8765    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8766
8767    bxe_task_fp(fp);
8768}
8769
8770/* Release all interrupts allocated by the driver. */
8771static void
8772bxe_interrupt_free(struct bxe_softc *sc)
8773{
8774    int i;
8775
8776    switch (sc->interrupt_mode) {
8777    case INTR_MODE_INTX:
8778        BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8779        if (sc->intr[0].resource != NULL) {
8780            bus_release_resource(sc->dev,
8781                                 SYS_RES_IRQ,
8782                                 sc->intr[0].rid,
8783                                 sc->intr[0].resource);
8784        }
8785        break;
8786    case INTR_MODE_MSI:
8787        for (i = 0; i < sc->intr_count; i++) {
8788            BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8789            if (sc->intr[i].resource && sc->intr[i].rid) {
8790                bus_release_resource(sc->dev,
8791                                     SYS_RES_IRQ,
8792                                     sc->intr[i].rid,
8793                                     sc->intr[i].resource);
8794            }
8795        }
8796        pci_release_msi(sc->dev);
8797        break;
8798    case INTR_MODE_MSIX:
8799        for (i = 0; i < sc->intr_count; i++) {
8800            BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8801            if (sc->intr[i].resource && sc->intr[i].rid) {
8802                bus_release_resource(sc->dev,
8803                                     SYS_RES_IRQ,
8804                                     sc->intr[i].rid,
8805                                     sc->intr[i].resource);
8806            }
8807        }
8808        pci_release_msi(sc->dev);
8809        break;
8810    default:
8811        /* nothing to do as initial allocation failed */
8812        break;
8813    }
8814}
8815
8816/*
8817 * This function determines and allocates the appropriate
8818 * interrupt based on system capabilites and user request.
8819 *
8820 * The user may force a particular interrupt mode, specify
8821 * the number of receive queues, specify the method for
8822 * distribuitng received frames to receive queues, or use
8823 * the default settings which will automatically select the
8824 * best supported combination.  In addition, the OS may or
8825 * may not support certain combinations of these settings.
8826 * This routine attempts to reconcile the settings requested
8827 * by the user with the capabilites available from the system
8828 * to select the optimal combination of features.
8829 *
8830 * Returns:
8831 *   0 = Success, !0 = Failure.
8832 */
8833static int
8834bxe_interrupt_alloc(struct bxe_softc *sc)
8835{
8836    int msix_count = 0;
8837    int msi_count = 0;
8838    int num_requested = 0;
8839    int num_allocated = 0;
8840    int rid, i, j;
8841    int rc;
8842
8843    /* get the number of available MSI/MSI-X interrupts from the OS */
8844    if (sc->interrupt_mode > 0) {
8845        if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8846            msix_count = pci_msix_count(sc->dev);
8847        }
8848
8849        if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8850            msi_count = pci_msi_count(sc->dev);
8851        }
8852
8853        BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8854              msi_count, msix_count);
8855    }
8856
8857    do { /* try allocating MSI-X interrupt resources (at least 2) */
8858        if (sc->interrupt_mode != INTR_MODE_MSIX) {
8859            break;
8860        }
8861
8862        if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
8863            (msix_count < 2)) {
8864            sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8865            break;
8866        }
8867
8868        /* ask for the necessary number of MSI-X vectors */
8869        num_requested = min((sc->num_queues + 1), msix_count);
8870
8871        BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
8872
8873        num_allocated = num_requested;
8874        if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
8875            BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
8876            sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8877            break;
8878        }
8879
8880        if (num_allocated < 2) { /* possible? */
8881            BLOGE(sc, "MSI-X allocation less than 2!\n");
8882            sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8883            pci_release_msi(sc->dev);
8884            break;
8885        }
8886
8887        BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
8888              num_requested, num_allocated);
8889
8890        /* best effort so use the number of vectors allocated to us */
8891        sc->intr_count = num_allocated;
8892        sc->num_queues = num_allocated - 1;
8893
8894        rid = 1; /* initial resource identifier */
8895
8896        /* allocate the MSI-X vectors */
8897        for (i = 0; i < num_allocated; i++) {
8898            sc->intr[i].rid = (rid + i);
8899
8900            if ((sc->intr[i].resource =
8901                 bus_alloc_resource_any(sc->dev,
8902                                        SYS_RES_IRQ,
8903                                        &sc->intr[i].rid,
8904                                        RF_ACTIVE)) == NULL) {
8905                BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
8906                      i, (rid + i));
8907
8908                for (j = (i - 1); j >= 0; j--) {
8909                    bus_release_resource(sc->dev,
8910                                         SYS_RES_IRQ,
8911                                         sc->intr[j].rid,
8912                                         sc->intr[j].resource);
8913                }
8914
8915                sc->intr_count = 0;
8916                sc->num_queues = 0;
8917                sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8918                pci_release_msi(sc->dev);
8919                break;
8920            }
8921
8922            BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
8923        }
8924    } while (0);
8925
8926    do { /* try allocating MSI vector resources (at least 2) */
8927        if (sc->interrupt_mode != INTR_MODE_MSI) {
8928            break;
8929        }
8930
8931        if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
8932            (msi_count < 1)) {
8933            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8934            break;
8935        }
8936
8937        /* ask for a single MSI vector */
8938        num_requested = 1;
8939
8940        BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
8941
8942        num_allocated = num_requested;
8943        if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
8944            BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
8945            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8946            break;
8947        }
8948
8949        if (num_allocated != 1) { /* possible? */
8950            BLOGE(sc, "MSI allocation is not 1!\n");
8951            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8952            pci_release_msi(sc->dev);
8953            break;
8954        }
8955
8956        BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
8957              num_requested, num_allocated);
8958
8959        /* best effort so use the number of vectors allocated to us */
8960        sc->intr_count = num_allocated;
8961        sc->num_queues = num_allocated;
8962
8963        rid = 1; /* initial resource identifier */
8964
8965        sc->intr[0].rid = rid;
8966
8967        if ((sc->intr[0].resource =
8968             bus_alloc_resource_any(sc->dev,
8969                                    SYS_RES_IRQ,
8970                                    &sc->intr[0].rid,
8971                                    RF_ACTIVE)) == NULL) {
8972            BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
8973            sc->intr_count = 0;
8974            sc->num_queues = 0;
8975            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8976            pci_release_msi(sc->dev);
8977            break;
8978        }
8979
8980        BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
8981    } while (0);
8982
8983    do { /* try allocating INTx vector resources */
8984        if (sc->interrupt_mode != INTR_MODE_INTX) {
8985            break;
8986        }
8987
8988        BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
8989
8990        /* only one vector for INTx */
8991        sc->intr_count = 1;
8992        sc->num_queues = 1;
8993
8994        rid = 0; /* initial resource identifier */
8995
8996        sc->intr[0].rid = rid;
8997
8998        if ((sc->intr[0].resource =
8999             bus_alloc_resource_any(sc->dev,
9000                                    SYS_RES_IRQ,
9001                                    &sc->intr[0].rid,
9002                                    (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9003            BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9004            sc->intr_count = 0;
9005            sc->num_queues = 0;
9006            sc->interrupt_mode = -1; /* Failed! */
9007            break;
9008        }
9009
9010        BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9011    } while (0);
9012
9013    if (sc->interrupt_mode == -1) {
9014        BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9015        rc = 1;
9016    } else {
9017        BLOGD(sc, DBG_LOAD,
9018              "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9019              sc->interrupt_mode, sc->num_queues);
9020        rc = 0;
9021    }
9022
9023    return (rc);
9024}
9025
9026static void
9027bxe_interrupt_detach(struct bxe_softc *sc)
9028{
9029    struct bxe_fastpath *fp;
9030    int i;
9031
9032    /* release interrupt resources */
9033    for (i = 0; i < sc->intr_count; i++) {
9034        if (sc->intr[i].resource && sc->intr[i].tag) {
9035            BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9036            bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9037        }
9038    }
9039
9040    for (i = 0; i < sc->num_queues; i++) {
9041        fp = &sc->fp[i];
9042        if (fp->tq) {
9043            taskqueue_drain(fp->tq, &fp->tq_task);
9044            taskqueue_free(fp->tq);
9045            fp->tq = NULL;
9046        }
9047    }
9048
9049
9050    if (sc->sp_tq) {
9051        taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9052        taskqueue_free(sc->sp_tq);
9053        sc->sp_tq = NULL;
9054    }
9055}
9056
9057/*
9058 * Enables interrupts and attach to the ISR.
9059 *
9060 * When using multiple MSI/MSI-X vectors the first vector
9061 * is used for slowpath operations while all remaining
9062 * vectors are used for fastpath operations.  If only a
9063 * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9064 * ISR must look for both slowpath and fastpath completions.
9065 */
9066static int
9067bxe_interrupt_attach(struct bxe_softc *sc)
9068{
9069    struct bxe_fastpath *fp;
9070    int rc = 0;
9071    int i;
9072
9073    snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9074             "bxe%d_sp_tq", sc->unit);
9075    TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9076    sc->sp_tq = taskqueue_create_fast(sc->sp_tq_name, M_NOWAIT,
9077                                      taskqueue_thread_enqueue,
9078                                      &sc->sp_tq);
9079    taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9080                            "%s", sc->sp_tq_name);
9081
9082
9083    for (i = 0; i < sc->num_queues; i++) {
9084        fp = &sc->fp[i];
9085        snprintf(fp->tq_name, sizeof(fp->tq_name),
9086                 "bxe%d_fp%d_tq", sc->unit, i);
9087        TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9088        fp->tq = taskqueue_create_fast(fp->tq_name, M_NOWAIT,
9089                                       taskqueue_thread_enqueue,
9090                                       &fp->tq);
9091        taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9092                                "%s", fp->tq_name);
9093    }
9094
9095    /* setup interrupt handlers */
9096    if (sc->interrupt_mode == INTR_MODE_MSIX) {
9097        BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9098
9099        /*
9100         * Setup the interrupt handler. Note that we pass the driver instance
9101         * to the interrupt handler for the slowpath.
9102         */
9103        if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9104                                 (INTR_TYPE_NET | INTR_MPSAFE),
9105                                 NULL, bxe_intr_sp, sc,
9106                                 &sc->intr[0].tag)) != 0) {
9107            BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9108            goto bxe_interrupt_attach_exit;
9109        }
9110
9111        bus_describe_intr(sc->dev, sc->intr[0].resource,
9112                          sc->intr[0].tag, "sp");
9113
9114        /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9115
9116        /* initialize the fastpath vectors (note the first was used for sp) */
9117        for (i = 0; i < sc->num_queues; i++) {
9118            fp = &sc->fp[i];
9119            BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9120
9121            /*
9122             * Setup the interrupt handler. Note that we pass the
9123             * fastpath context to the interrupt handler in this
9124             * case.
9125             */
9126            if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9127                                     (INTR_TYPE_NET | INTR_MPSAFE),
9128                                     NULL, bxe_intr_fp, fp,
9129                                     &sc->intr[i + 1].tag)) != 0) {
9130                BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9131                      (i + 1), rc);
9132                goto bxe_interrupt_attach_exit;
9133            }
9134
9135            bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9136                              sc->intr[i + 1].tag, "fp%02d", i);
9137
9138            /* bind the fastpath instance to a cpu */
9139            if (sc->num_queues > 1) {
9140                bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9141            }
9142
9143            fp->state = BXE_FP_STATE_IRQ;
9144        }
9145    } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9146        BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9147
9148        /*
9149         * Setup the interrupt handler. Note that we pass the
9150         * driver instance to the interrupt handler which
9151         * will handle both the slowpath and fastpath.
9152         */
9153        if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9154                                 (INTR_TYPE_NET | INTR_MPSAFE),
9155                                 NULL, bxe_intr_legacy, sc,
9156                                 &sc->intr[0].tag)) != 0) {
9157            BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9158            goto bxe_interrupt_attach_exit;
9159        }
9160
9161    } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9162        BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9163
9164        /*
9165         * Setup the interrupt handler. Note that we pass the
9166         * driver instance to the interrupt handler which
9167         * will handle both the slowpath and fastpath.
9168         */
9169        if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9170                                 (INTR_TYPE_NET | INTR_MPSAFE),
9171                                 NULL, bxe_intr_legacy, sc,
9172                                 &sc->intr[0].tag)) != 0) {
9173            BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9174            goto bxe_interrupt_attach_exit;
9175        }
9176    }
9177
9178bxe_interrupt_attach_exit:
9179
9180    return (rc);
9181}
9182
9183static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9184static int  bxe_init_hw_common(struct bxe_softc *sc);
9185static int  bxe_init_hw_port(struct bxe_softc *sc);
9186static int  bxe_init_hw_func(struct bxe_softc *sc);
9187static void bxe_reset_common(struct bxe_softc *sc);
9188static void bxe_reset_port(struct bxe_softc *sc);
9189static void bxe_reset_func(struct bxe_softc *sc);
9190static int  bxe_gunzip_init(struct bxe_softc *sc);
9191static void bxe_gunzip_end(struct bxe_softc *sc);
9192static int  bxe_init_firmware(struct bxe_softc *sc);
9193static void bxe_release_firmware(struct bxe_softc *sc);
9194
9195static struct
9196ecore_func_sp_drv_ops bxe_func_sp_drv = {
9197    .init_hw_cmn_chip = bxe_init_hw_common_chip,
9198    .init_hw_cmn      = bxe_init_hw_common,
9199    .init_hw_port     = bxe_init_hw_port,
9200    .init_hw_func     = bxe_init_hw_func,
9201
9202    .reset_hw_cmn     = bxe_reset_common,
9203    .reset_hw_port    = bxe_reset_port,
9204    .reset_hw_func    = bxe_reset_func,
9205
9206    .gunzip_init      = bxe_gunzip_init,
9207    .gunzip_end       = bxe_gunzip_end,
9208
9209    .init_fw          = bxe_init_firmware,
9210    .release_fw       = bxe_release_firmware,
9211};
9212
9213static void
9214bxe_init_func_obj(struct bxe_softc *sc)
9215{
9216    sc->dmae_ready = 0;
9217
9218    ecore_init_func_obj(sc,
9219                        &sc->func_obj,
9220                        BXE_SP(sc, func_rdata),
9221                        BXE_SP_MAPPING(sc, func_rdata),
9222                        BXE_SP(sc, func_afex_rdata),
9223                        BXE_SP_MAPPING(sc, func_afex_rdata),
9224                        &bxe_func_sp_drv);
9225}
9226
9227static int
9228bxe_init_hw(struct bxe_softc *sc,
9229            uint32_t         load_code)
9230{
9231    struct ecore_func_state_params func_params = { NULL };
9232    int rc;
9233
9234    /* prepare the parameters for function state transitions */
9235    bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9236
9237    func_params.f_obj = &sc->func_obj;
9238    func_params.cmd = ECORE_F_CMD_HW_INIT;
9239
9240    func_params.params.hw_init.load_phase = load_code;
9241
9242    /*
9243     * Via a plethora of function pointers, we will eventually reach
9244     * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9245     */
9246    rc = ecore_func_state_change(sc, &func_params);
9247
9248    return (rc);
9249}
9250
9251static void
9252bxe_fill(struct bxe_softc *sc,
9253         uint32_t         addr,
9254         int              fill,
9255         uint32_t         len)
9256{
9257    uint32_t i;
9258
9259    if (!(len % 4) && !(addr % 4)) {
9260        for (i = 0; i < len; i += 4) {
9261            REG_WR(sc, (addr + i), fill);
9262        }
9263    } else {
9264        for (i = 0; i < len; i++) {
9265            REG_WR8(sc, (addr + i), fill);
9266        }
9267    }
9268}
9269
9270/* writes FP SP data to FW - data_size in dwords */
9271static void
9272bxe_wr_fp_sb_data(struct bxe_softc *sc,
9273                  int              fw_sb_id,
9274                  uint32_t         *sb_data_p,
9275                  uint32_t         data_size)
9276{
9277    int index;
9278
9279    for (index = 0; index < data_size; index++) {
9280        REG_WR(sc,
9281               (BAR_CSTRORM_INTMEM +
9282                CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9283                (sizeof(uint32_t) * index)),
9284               *(sb_data_p + index));
9285    }
9286}
9287
9288static void
9289bxe_zero_fp_sb(struct bxe_softc *sc,
9290               int              fw_sb_id)
9291{
9292    struct hc_status_block_data_e2 sb_data_e2;
9293    struct hc_status_block_data_e1x sb_data_e1x;
9294    uint32_t *sb_data_p;
9295    uint32_t data_size = 0;
9296
9297    if (!CHIP_IS_E1x(sc)) {
9298        memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9299        sb_data_e2.common.state = SB_DISABLED;
9300        sb_data_e2.common.p_func.vf_valid = FALSE;
9301        sb_data_p = (uint32_t *)&sb_data_e2;
9302        data_size = (sizeof(struct hc_status_block_data_e2) /
9303                     sizeof(uint32_t));
9304    } else {
9305        memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9306        sb_data_e1x.common.state = SB_DISABLED;
9307        sb_data_e1x.common.p_func.vf_valid = FALSE;
9308        sb_data_p = (uint32_t *)&sb_data_e1x;
9309        data_size = (sizeof(struct hc_status_block_data_e1x) /
9310                     sizeof(uint32_t));
9311    }
9312
9313    bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9314
9315    bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9316             0, CSTORM_STATUS_BLOCK_SIZE);
9317    bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9318             0, CSTORM_SYNC_BLOCK_SIZE);
9319}
9320
9321static void
9322bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9323                  struct hc_sp_status_block_data *sp_sb_data)
9324{
9325    int i;
9326
9327    for (i = 0;
9328         i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9329         i++) {
9330        REG_WR(sc,
9331               (BAR_CSTRORM_INTMEM +
9332                CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9333                (i * sizeof(uint32_t))),
9334               *((uint32_t *)sp_sb_data + i));
9335    }
9336}
9337
9338static void
9339bxe_zero_sp_sb(struct bxe_softc *sc)
9340{
9341    struct hc_sp_status_block_data sp_sb_data;
9342
9343    memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9344
9345    sp_sb_data.state           = SB_DISABLED;
9346    sp_sb_data.p_func.vf_valid = FALSE;
9347
9348    bxe_wr_sp_sb_data(sc, &sp_sb_data);
9349
9350    bxe_fill(sc,
9351             (BAR_CSTRORM_INTMEM +
9352              CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9353              0, CSTORM_SP_STATUS_BLOCK_SIZE);
9354    bxe_fill(sc,
9355             (BAR_CSTRORM_INTMEM +
9356              CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9357              0, CSTORM_SP_SYNC_BLOCK_SIZE);
9358}
9359
9360static void
9361bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9362                             int                       igu_sb_id,
9363                             int                       igu_seg_id)
9364{
9365    hc_sm->igu_sb_id      = igu_sb_id;
9366    hc_sm->igu_seg_id     = igu_seg_id;
9367    hc_sm->timer_value    = 0xFF;
9368    hc_sm->time_to_expire = 0xFFFFFFFF;
9369}
9370
9371static void
9372bxe_map_sb_state_machines(struct hc_index_data *index_data)
9373{
9374    /* zero out state machine indices */
9375
9376    /* rx indices */
9377    index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9378
9379    /* tx indices */
9380    index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9381    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9382    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9383    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9384
9385    /* map indices */
9386
9387    /* rx indices */
9388    index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9389        (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9390
9391    /* tx indices */
9392    index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9393        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9394    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9395        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9396    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9397        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9398    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9399        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9400}
9401
9402static void
9403bxe_init_sb(struct bxe_softc *sc,
9404            bus_addr_t       busaddr,
9405            int              vfid,
9406            uint8_t          vf_valid,
9407            int              fw_sb_id,
9408            int              igu_sb_id)
9409{
9410    struct hc_status_block_data_e2  sb_data_e2;
9411    struct hc_status_block_data_e1x sb_data_e1x;
9412    struct hc_status_block_sm       *hc_sm_p;
9413    uint32_t *sb_data_p;
9414    int igu_seg_id;
9415    int data_size;
9416
9417    if (CHIP_INT_MODE_IS_BC(sc)) {
9418        igu_seg_id = HC_SEG_ACCESS_NORM;
9419    } else {
9420        igu_seg_id = IGU_SEG_ACCESS_NORM;
9421    }
9422
9423    bxe_zero_fp_sb(sc, fw_sb_id);
9424
9425    if (!CHIP_IS_E1x(sc)) {
9426        memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9427        sb_data_e2.common.state = SB_ENABLED;
9428        sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9429        sb_data_e2.common.p_func.vf_id = vfid;
9430        sb_data_e2.common.p_func.vf_valid = vf_valid;
9431        sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9432        sb_data_e2.common.same_igu_sb_1b = TRUE;
9433        sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9434        sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9435        hc_sm_p = sb_data_e2.common.state_machine;
9436        sb_data_p = (uint32_t *)&sb_data_e2;
9437        data_size = (sizeof(struct hc_status_block_data_e2) /
9438                     sizeof(uint32_t));
9439        bxe_map_sb_state_machines(sb_data_e2.index_data);
9440    } else {
9441        memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9442        sb_data_e1x.common.state = SB_ENABLED;
9443        sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9444        sb_data_e1x.common.p_func.vf_id = 0xff;
9445        sb_data_e1x.common.p_func.vf_valid = FALSE;
9446        sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9447        sb_data_e1x.common.same_igu_sb_1b = TRUE;
9448        sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9449        sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9450        hc_sm_p = sb_data_e1x.common.state_machine;
9451        sb_data_p = (uint32_t *)&sb_data_e1x;
9452        data_size = (sizeof(struct hc_status_block_data_e1x) /
9453                     sizeof(uint32_t));
9454        bxe_map_sb_state_machines(sb_data_e1x.index_data);
9455    }
9456
9457    bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9458    bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9459
9460    BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9461
9462    /* write indices to HW - PCI guarantees endianity of regpairs */
9463    bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9464}
9465
9466static inline uint8_t
9467bxe_fp_qzone_id(struct bxe_fastpath *fp)
9468{
9469    if (CHIP_IS_E1x(fp->sc)) {
9470        return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9471    } else {
9472        return (fp->cl_id);
9473    }
9474}
9475
9476static inline uint32_t
9477bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9478                           struct bxe_fastpath *fp)
9479{
9480    uint32_t offset = BAR_USTRORM_INTMEM;
9481
9482    if (!CHIP_IS_E1x(sc)) {
9483        offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9484    } else {
9485        offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9486    }
9487
9488    return (offset);
9489}
9490
9491static void
9492bxe_init_eth_fp(struct bxe_softc *sc,
9493                int              idx)
9494{
9495    struct bxe_fastpath *fp = &sc->fp[idx];
9496    uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9497    unsigned long q_type = 0;
9498    int cos;
9499
9500    fp->sc    = sc;
9501    fp->index = idx;
9502
9503    fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9504    fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9505
9506    fp->cl_id = (CHIP_IS_E1x(sc)) ?
9507                    (SC_L_ID(sc) + idx) :
9508                    /* want client ID same as IGU SB ID for non-E1 */
9509                    fp->igu_sb_id;
9510    fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9511
9512    /* setup sb indices */
9513    if (!CHIP_IS_E1x(sc)) {
9514        fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9515        fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9516    } else {
9517        fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9518        fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9519    }
9520
9521    /* init shortcut */
9522    fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9523
9524    fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9525
9526    /*
9527     * XXX If multiple CoS is ever supported then each fastpath structure
9528     * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9529     */
9530    for (cos = 0; cos < sc->max_cos; cos++) {
9531        cids[cos] = idx;
9532    }
9533    fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9534
9535    /* nothing more for a VF to do */
9536    if (IS_VF(sc)) {
9537        return;
9538    }
9539
9540    bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9541                fp->fw_sb_id, fp->igu_sb_id);
9542
9543    bxe_update_fp_sb_idx(fp);
9544
9545    /* Configure Queue State object */
9546    bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9547    bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9548
9549    ecore_init_queue_obj(sc,
9550                         &sc->sp_objs[idx].q_obj,
9551                         fp->cl_id,
9552                         cids,
9553                         sc->max_cos,
9554                         SC_FUNC(sc),
9555                         BXE_SP(sc, q_rdata),
9556                         BXE_SP_MAPPING(sc, q_rdata),
9557                         q_type);
9558
9559    /* configure classification DBs */
9560    ecore_init_mac_obj(sc,
9561                       &sc->sp_objs[idx].mac_obj,
9562                       fp->cl_id,
9563                       idx,
9564                       SC_FUNC(sc),
9565                       BXE_SP(sc, mac_rdata),
9566                       BXE_SP_MAPPING(sc, mac_rdata),
9567                       ECORE_FILTER_MAC_PENDING,
9568                       &sc->sp_state,
9569                       ECORE_OBJ_TYPE_RX_TX,
9570                       &sc->macs_pool);
9571
9572    BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9573          idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9574}
9575
9576static inline void
9577bxe_update_rx_prod(struct bxe_softc    *sc,
9578                   struct bxe_fastpath *fp,
9579                   uint16_t            rx_bd_prod,
9580                   uint16_t            rx_cq_prod,
9581                   uint16_t            rx_sge_prod)
9582{
9583    struct ustorm_eth_rx_producers rx_prods = { 0 };
9584    uint32_t i;
9585
9586    /* update producers */
9587    rx_prods.bd_prod  = rx_bd_prod;
9588    rx_prods.cqe_prod = rx_cq_prod;
9589    rx_prods.sge_prod = rx_sge_prod;
9590
9591    /*
9592     * Make sure that the BD and SGE data is updated before updating the
9593     * producers since FW might read the BD/SGE right after the producer
9594     * is updated.
9595     * This is only applicable for weak-ordered memory model archs such
9596     * as IA-64. The following barrier is also mandatory since FW will
9597     * assumes BDs must have buffers.
9598     */
9599    wmb();
9600
9601    for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9602        REG_WR(sc,
9603               (fp->ustorm_rx_prods_offset + (i * 4)),
9604               ((uint32_t *)&rx_prods)[i]);
9605    }
9606
9607    wmb(); /* keep prod updates ordered */
9608
9609    BLOGD(sc, DBG_RX,
9610          "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9611          fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9612}
9613
9614static void
9615bxe_init_rx_rings(struct bxe_softc *sc)
9616{
9617    struct bxe_fastpath *fp;
9618    int i;
9619
9620    for (i = 0; i < sc->num_queues; i++) {
9621        fp = &sc->fp[i];
9622
9623        fp->rx_bd_cons = 0;
9624
9625        /*
9626         * Activate the BD ring...
9627         * Warning, this will generate an interrupt (to the TSTORM)
9628         * so this can only be done after the chip is initialized
9629         */
9630        bxe_update_rx_prod(sc, fp,
9631                           fp->rx_bd_prod,
9632                           fp->rx_cq_prod,
9633                           fp->rx_sge_prod);
9634
9635        if (i != 0) {
9636            continue;
9637        }
9638
9639        if (CHIP_IS_E1(sc)) {
9640            REG_WR(sc,
9641                   (BAR_USTRORM_INTMEM +
9642                    USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9643                   U64_LO(fp->rcq_dma.paddr));
9644            REG_WR(sc,
9645                   (BAR_USTRORM_INTMEM +
9646                    USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9647                   U64_HI(fp->rcq_dma.paddr));
9648        }
9649    }
9650}
9651
9652static void
9653bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9654{
9655    SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9656    fp->tx_db.data.zero_fill1 = 0;
9657    fp->tx_db.data.prod = 0;
9658
9659    fp->tx_pkt_prod = 0;
9660    fp->tx_pkt_cons = 0;
9661    fp->tx_bd_prod = 0;
9662    fp->tx_bd_cons = 0;
9663    fp->eth_q_stats.tx_pkts = 0;
9664}
9665
9666static inline void
9667bxe_init_tx_rings(struct bxe_softc *sc)
9668{
9669    int i;
9670
9671    for (i = 0; i < sc->num_queues; i++) {
9672        bxe_init_tx_ring_one(&sc->fp[i]);
9673    }
9674}
9675
9676static void
9677bxe_init_def_sb(struct bxe_softc *sc)
9678{
9679    struct host_sp_status_block *def_sb = sc->def_sb;
9680    bus_addr_t mapping = sc->def_sb_dma.paddr;
9681    int igu_sp_sb_index;
9682    int igu_seg_id;
9683    int port = SC_PORT(sc);
9684    int func = SC_FUNC(sc);
9685    int reg_offset, reg_offset_en5;
9686    uint64_t section;
9687    int index, sindex;
9688    struct hc_sp_status_block_data sp_sb_data;
9689
9690    memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9691
9692    if (CHIP_INT_MODE_IS_BC(sc)) {
9693        igu_sp_sb_index = DEF_SB_IGU_ID;
9694        igu_seg_id = HC_SEG_ACCESS_DEF;
9695    } else {
9696        igu_sp_sb_index = sc->igu_dsb_id;
9697        igu_seg_id = IGU_SEG_ACCESS_DEF;
9698    }
9699
9700    /* attentions */
9701    section = ((uint64_t)mapping +
9702               offsetof(struct host_sp_status_block, atten_status_block));
9703    def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9704    sc->attn_state = 0;
9705
9706    reg_offset = (port) ?
9707                     MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9708                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9709    reg_offset_en5 = (port) ?
9710                         MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9711                         MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9712
9713    for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9714        /* take care of sig[0]..sig[4] */
9715        for (sindex = 0; sindex < 4; sindex++) {
9716            sc->attn_group[index].sig[sindex] =
9717                REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9718        }
9719
9720        if (!CHIP_IS_E1x(sc)) {
9721            /*
9722             * enable5 is separate from the rest of the registers,
9723             * and the address skip is 4 and not 16 between the
9724             * different groups
9725             */
9726            sc->attn_group[index].sig[4] =
9727                REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9728        } else {
9729            sc->attn_group[index].sig[4] = 0;
9730        }
9731    }
9732
9733    if (sc->devinfo.int_block == INT_BLOCK_HC) {
9734        reg_offset = (port) ?
9735                         HC_REG_ATTN_MSG1_ADDR_L :
9736                         HC_REG_ATTN_MSG0_ADDR_L;
9737        REG_WR(sc, reg_offset, U64_LO(section));
9738        REG_WR(sc, (reg_offset + 4), U64_HI(section));
9739    } else if (!CHIP_IS_E1x(sc)) {
9740        REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9741        REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9742    }
9743
9744    section = ((uint64_t)mapping +
9745               offsetof(struct host_sp_status_block, sp_sb));
9746
9747    bxe_zero_sp_sb(sc);
9748
9749    /* PCI guarantees endianity of regpair */
9750    sp_sb_data.state           = SB_ENABLED;
9751    sp_sb_data.host_sb_addr.lo = U64_LO(section);
9752    sp_sb_data.host_sb_addr.hi = U64_HI(section);
9753    sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9754    sp_sb_data.igu_seg_id      = igu_seg_id;
9755    sp_sb_data.p_func.pf_id    = func;
9756    sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9757    sp_sb_data.p_func.vf_id    = 0xff;
9758
9759    bxe_wr_sp_sb_data(sc, &sp_sb_data);
9760
9761    bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9762}
9763
9764static void
9765bxe_init_sp_ring(struct bxe_softc *sc)
9766{
9767    atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9768    sc->spq_prod_idx = 0;
9769    sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9770    sc->spq_prod_bd = sc->spq;
9771    sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9772}
9773
9774static void
9775bxe_init_eq_ring(struct bxe_softc *sc)
9776{
9777    union event_ring_elem *elem;
9778    int i;
9779
9780    for (i = 1; i <= NUM_EQ_PAGES; i++) {
9781        elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9782
9783        elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9784                                                 BCM_PAGE_SIZE *
9785                                                 (i % NUM_EQ_PAGES)));
9786        elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9787                                                 BCM_PAGE_SIZE *
9788                                                 (i % NUM_EQ_PAGES)));
9789    }
9790
9791    sc->eq_cons    = 0;
9792    sc->eq_prod    = NUM_EQ_DESC;
9793    sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9794
9795    atomic_store_rel_long(&sc->eq_spq_left,
9796                          (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9797                               NUM_EQ_DESC) - 1));
9798}
9799
9800static void
9801bxe_init_internal_common(struct bxe_softc *sc)
9802{
9803    int i;
9804
9805    /*
9806     * Zero this manually as its initialization is currently missing
9807     * in the initTool.
9808     */
9809    for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9810        REG_WR(sc,
9811               (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9812               0);
9813    }
9814
9815    if (!CHIP_IS_E1x(sc)) {
9816        REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9817                CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9818    }
9819}
9820
9821static void
9822bxe_init_internal(struct bxe_softc *sc,
9823                  uint32_t         load_code)
9824{
9825    switch (load_code) {
9826    case FW_MSG_CODE_DRV_LOAD_COMMON:
9827    case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9828        bxe_init_internal_common(sc);
9829        /* no break */
9830
9831    case FW_MSG_CODE_DRV_LOAD_PORT:
9832        /* nothing to do */
9833        /* no break */
9834
9835    case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9836        /* internal memory per function is initialized inside bxe_pf_init */
9837        break;
9838
9839    default:
9840        BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9841        break;
9842    }
9843}
9844
9845static void
9846storm_memset_func_cfg(struct bxe_softc                         *sc,
9847                      struct tstorm_eth_function_common_config *tcfg,
9848                      uint16_t                                  abs_fid)
9849{
9850    uint32_t addr;
9851    size_t size;
9852
9853    addr = (BAR_TSTRORM_INTMEM +
9854            TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
9855    size = sizeof(struct tstorm_eth_function_common_config);
9856    ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
9857}
9858
9859static void
9860bxe_func_init(struct bxe_softc            *sc,
9861              struct bxe_func_init_params *p)
9862{
9863    struct tstorm_eth_function_common_config tcfg = { 0 };
9864
9865    if (CHIP_IS_E1x(sc)) {
9866        storm_memset_func_cfg(sc, &tcfg, p->func_id);
9867    }
9868
9869    /* Enable the function in the FW */
9870    storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
9871    storm_memset_func_en(sc, p->func_id, 1);
9872
9873    /* spq */
9874    if (p->func_flgs & FUNC_FLG_SPQ) {
9875        storm_memset_spq_addr(sc, p->spq_map, p->func_id);
9876        REG_WR(sc,
9877               (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
9878               p->spq_prod);
9879    }
9880}
9881
9882/*
9883 * Calculates the sum of vn_min_rates.
9884 * It's needed for further normalizing of the min_rates.
9885 * Returns:
9886 *   sum of vn_min_rates.
9887 *     or
9888 *   0 - if all the min_rates are 0.
9889 * In the later case fainess algorithm should be deactivated.
9890 * If all min rates are not zero then those that are zeroes will be set to 1.
9891 */
9892static void
9893bxe_calc_vn_min(struct bxe_softc       *sc,
9894                struct cmng_init_input *input)
9895{
9896    uint32_t vn_cfg;
9897    uint32_t vn_min_rate;
9898    int all_zero = 1;
9899    int vn;
9900
9901    for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
9902        vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9903        vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
9904                        FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
9905
9906        if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9907            /* skip hidden VNs */
9908            vn_min_rate = 0;
9909        } else if (!vn_min_rate) {
9910            /* If min rate is zero - set it to 100 */
9911            vn_min_rate = DEF_MIN_RATE;
9912        } else {
9913            all_zero = 0;
9914        }
9915
9916        input->vnic_min_rate[vn] = vn_min_rate;
9917    }
9918
9919    /* if ETS or all min rates are zeros - disable fairness */
9920    if (BXE_IS_ETS_ENABLED(sc)) {
9921        input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9922        BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
9923    } else if (all_zero) {
9924        input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9925        BLOGD(sc, DBG_LOAD,
9926              "Fariness disabled (all MIN values are zeroes)\n");
9927    } else {
9928        input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9929    }
9930}
9931
9932static inline uint16_t
9933bxe_extract_max_cfg(struct bxe_softc *sc,
9934                    uint32_t         mf_cfg)
9935{
9936    uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
9937                        FUNC_MF_CFG_MAX_BW_SHIFT);
9938
9939    if (!max_cfg) {
9940        BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
9941        max_cfg = 100;
9942    }
9943
9944    return (max_cfg);
9945}
9946
9947static void
9948bxe_calc_vn_max(struct bxe_softc       *sc,
9949                int                    vn,
9950                struct cmng_init_input *input)
9951{
9952    uint16_t vn_max_rate;
9953    uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9954    uint32_t max_cfg;
9955
9956    if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9957        vn_max_rate = 0;
9958    } else {
9959        max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
9960
9961        if (IS_MF_SI(sc)) {
9962            /* max_cfg in percents of linkspeed */
9963            vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
9964        } else { /* SD modes */
9965            /* max_cfg is absolute in 100Mb units */
9966            vn_max_rate = (max_cfg * 100);
9967        }
9968    }
9969
9970    BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
9971
9972    input->vnic_max_rate[vn] = vn_max_rate;
9973}
9974
9975static void
9976bxe_cmng_fns_init(struct bxe_softc *sc,
9977                  uint8_t          read_cfg,
9978                  uint8_t          cmng_type)
9979{
9980    struct cmng_init_input input;
9981    int vn;
9982
9983    memset(&input, 0, sizeof(struct cmng_init_input));
9984
9985    input.port_rate = sc->link_vars.line_speed;
9986
9987    if (cmng_type == CMNG_FNS_MINMAX) {
9988        /* read mf conf from shmem */
9989        if (read_cfg) {
9990            bxe_read_mf_cfg(sc);
9991        }
9992
9993        /* get VN min rate and enable fairness if not 0 */
9994        bxe_calc_vn_min(sc, &input);
9995
9996        /* get VN max rate */
9997        if (sc->port.pmf) {
9998            for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
9999                bxe_calc_vn_max(sc, vn, &input);
10000            }
10001        }
10002
10003        /* always enable rate shaping and fairness */
10004        input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10005
10006        ecore_init_cmng(&input, &sc->cmng);
10007        return;
10008    }
10009
10010    /* rate shaping and fairness are disabled */
10011    BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10012}
10013
10014static int
10015bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10016{
10017    if (CHIP_REV_IS_SLOW(sc)) {
10018        return (CMNG_FNS_NONE);
10019    }
10020
10021    if (IS_MF(sc)) {
10022        return (CMNG_FNS_MINMAX);
10023    }
10024
10025    return (CMNG_FNS_NONE);
10026}
10027
10028static void
10029storm_memset_cmng(struct bxe_softc *sc,
10030                  struct cmng_init *cmng,
10031                  uint8_t          port)
10032{
10033    int vn;
10034    int func;
10035    uint32_t addr;
10036    size_t size;
10037
10038    addr = (BAR_XSTRORM_INTMEM +
10039            XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10040    size = sizeof(struct cmng_struct_per_port);
10041    ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10042
10043    for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10044        func = func_by_vn(sc, vn);
10045
10046        addr = (BAR_XSTRORM_INTMEM +
10047                XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10048        size = sizeof(struct rate_shaping_vars_per_vn);
10049        ecore_storm_memset_struct(sc, addr, size,
10050                                  (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10051
10052        addr = (BAR_XSTRORM_INTMEM +
10053                XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10054        size = sizeof(struct fairness_vars_per_vn);
10055        ecore_storm_memset_struct(sc, addr, size,
10056                                  (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10057    }
10058}
10059
10060static void
10061bxe_pf_init(struct bxe_softc *sc)
10062{
10063    struct bxe_func_init_params func_init = { 0 };
10064    struct event_ring_data eq_data = { { 0 } };
10065    uint16_t flags;
10066
10067    if (!CHIP_IS_E1x(sc)) {
10068        /* reset IGU PF statistics: MSIX + ATTN */
10069        /* PF */
10070        REG_WR(sc,
10071               (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10072                (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10073                ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10074               0);
10075        /* ATTN */
10076        REG_WR(sc,
10077               (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10078                (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10079                (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10080                ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10081               0);
10082    }
10083
10084    /* function setup flags */
10085    flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10086
10087    /*
10088     * This flag is relevant for E1x only.
10089     * E2 doesn't have a TPA configuration in a function level.
10090     */
10091    flags |= (if_getcapenable(sc->ifp) & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10092
10093    func_init.func_flgs = flags;
10094    func_init.pf_id     = SC_FUNC(sc);
10095    func_init.func_id   = SC_FUNC(sc);
10096    func_init.spq_map   = sc->spq_dma.paddr;
10097    func_init.spq_prod  = sc->spq_prod_idx;
10098
10099    bxe_func_init(sc, &func_init);
10100
10101    memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10102
10103    /*
10104     * Congestion management values depend on the link rate.
10105     * There is no active link so initial link rate is set to 10Gbps.
10106     * When the link comes up the congestion management values are
10107     * re-calculated according to the actual link rate.
10108     */
10109    sc->link_vars.line_speed = SPEED_10000;
10110    bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10111
10112    /* Only the PMF sets the HW */
10113    if (sc->port.pmf) {
10114        storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10115    }
10116
10117    /* init Event Queue - PCI bus guarantees correct endainity */
10118    eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10119    eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10120    eq_data.producer     = sc->eq_prod;
10121    eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10122    eq_data.sb_id        = DEF_SB_ID;
10123    storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10124}
10125
10126static void
10127bxe_hc_int_enable(struct bxe_softc *sc)
10128{
10129    int port = SC_PORT(sc);
10130    uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10131    uint32_t val = REG_RD(sc, addr);
10132    uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10133    uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10134                           (sc->intr_count == 1)) ? TRUE : FALSE;
10135    uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10136
10137    if (msix) {
10138        val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10139                 HC_CONFIG_0_REG_INT_LINE_EN_0);
10140        val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10141                HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10142        if (single_msix) {
10143            val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10144        }
10145    } else if (msi) {
10146        val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10147        val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10148                HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10149                HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10150    } else {
10151        val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10152                HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10153                HC_CONFIG_0_REG_INT_LINE_EN_0 |
10154                HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10155
10156        if (!CHIP_IS_E1(sc)) {
10157            BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10158                  val, port, addr);
10159
10160            REG_WR(sc, addr, val);
10161
10162            val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10163        }
10164    }
10165
10166    if (CHIP_IS_E1(sc)) {
10167        REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10168    }
10169
10170    BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10171          val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10172
10173    REG_WR(sc, addr, val);
10174
10175    /* ensure that HC_CONFIG is written before leading/trailing edge config */
10176    mb();
10177
10178    if (!CHIP_IS_E1(sc)) {
10179        /* init leading/trailing edge */
10180        if (IS_MF(sc)) {
10181            val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10182            if (sc->port.pmf) {
10183                /* enable nig and gpio3 attention */
10184                val |= 0x1100;
10185            }
10186        } else {
10187            val = 0xffff;
10188        }
10189
10190        REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10191        REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10192    }
10193
10194    /* make sure that interrupts are indeed enabled from here on */
10195    mb();
10196}
10197
10198static void
10199bxe_igu_int_enable(struct bxe_softc *sc)
10200{
10201    uint32_t val;
10202    uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10203    uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10204                           (sc->intr_count == 1)) ? TRUE : FALSE;
10205    uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10206
10207    val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10208
10209    if (msix) {
10210        val &= ~(IGU_PF_CONF_INT_LINE_EN |
10211                 IGU_PF_CONF_SINGLE_ISR_EN);
10212        val |= (IGU_PF_CONF_MSI_MSIX_EN |
10213                IGU_PF_CONF_ATTN_BIT_EN);
10214        if (single_msix) {
10215            val |= IGU_PF_CONF_SINGLE_ISR_EN;
10216        }
10217    } else if (msi) {
10218        val &= ~IGU_PF_CONF_INT_LINE_EN;
10219        val |= (IGU_PF_CONF_MSI_MSIX_EN |
10220                IGU_PF_CONF_ATTN_BIT_EN |
10221                IGU_PF_CONF_SINGLE_ISR_EN);
10222    } else {
10223        val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10224        val |= (IGU_PF_CONF_INT_LINE_EN |
10225                IGU_PF_CONF_ATTN_BIT_EN |
10226                IGU_PF_CONF_SINGLE_ISR_EN);
10227    }
10228
10229    /* clean previous status - need to configure igu prior to ack*/
10230    if ((!msix) || single_msix) {
10231        REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10232        bxe_ack_int(sc);
10233    }
10234
10235    val |= IGU_PF_CONF_FUNC_EN;
10236
10237    BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10238          val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10239
10240    REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10241
10242    mb();
10243
10244    /* init leading/trailing edge */
10245    if (IS_MF(sc)) {
10246        val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10247        if (sc->port.pmf) {
10248            /* enable nig and gpio3 attention */
10249            val |= 0x1100;
10250        }
10251    } else {
10252        val = 0xffff;
10253    }
10254
10255    REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10256    REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10257
10258    /* make sure that interrupts are indeed enabled from here on */
10259    mb();
10260}
10261
10262static void
10263bxe_int_enable(struct bxe_softc *sc)
10264{
10265    if (sc->devinfo.int_block == INT_BLOCK_HC) {
10266        bxe_hc_int_enable(sc);
10267    } else {
10268        bxe_igu_int_enable(sc);
10269    }
10270}
10271
10272static void
10273bxe_hc_int_disable(struct bxe_softc *sc)
10274{
10275    int port = SC_PORT(sc);
10276    uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10277    uint32_t val = REG_RD(sc, addr);
10278
10279    /*
10280     * In E1 we must use only PCI configuration space to disable MSI/MSIX
10281     * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10282     * block
10283     */
10284    if (CHIP_IS_E1(sc)) {
10285        /*
10286         * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10287         * to prevent from HC sending interrupts after we exit the function
10288         */
10289        REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10290
10291        val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10292                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10293                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10294    } else {
10295        val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10296                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10297                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10298                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10299    }
10300
10301    BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10302
10303    /* flush all outstanding writes */
10304    mb();
10305
10306    REG_WR(sc, addr, val);
10307    if (REG_RD(sc, addr) != val) {
10308        BLOGE(sc, "proper val not read from HC IGU!\n");
10309    }
10310}
10311
10312static void
10313bxe_igu_int_disable(struct bxe_softc *sc)
10314{
10315    uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10316
10317    val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10318             IGU_PF_CONF_INT_LINE_EN |
10319             IGU_PF_CONF_ATTN_BIT_EN);
10320
10321    BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10322
10323    /* flush all outstanding writes */
10324    mb();
10325
10326    REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10327    if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10328        BLOGE(sc, "proper val not read from IGU!\n");
10329    }
10330}
10331
10332static void
10333bxe_int_disable(struct bxe_softc *sc)
10334{
10335    if (sc->devinfo.int_block == INT_BLOCK_HC) {
10336        bxe_hc_int_disable(sc);
10337    } else {
10338        bxe_igu_int_disable(sc);
10339    }
10340}
10341
10342static void
10343bxe_nic_init(struct bxe_softc *sc,
10344             int              load_code)
10345{
10346    int i;
10347
10348    for (i = 0; i < sc->num_queues; i++) {
10349        bxe_init_eth_fp(sc, i);
10350    }
10351
10352    rmb(); /* ensure status block indices were read */
10353
10354    bxe_init_rx_rings(sc);
10355    bxe_init_tx_rings(sc);
10356
10357    if (IS_VF(sc)) {
10358        return;
10359    }
10360
10361    /* initialize MOD_ABS interrupts */
10362    elink_init_mod_abs_int(sc, &sc->link_vars,
10363                           sc->devinfo.chip_id,
10364                           sc->devinfo.shmem_base,
10365                           sc->devinfo.shmem2_base,
10366                           SC_PORT(sc));
10367
10368    bxe_init_def_sb(sc);
10369    bxe_update_dsb_idx(sc);
10370    bxe_init_sp_ring(sc);
10371    bxe_init_eq_ring(sc);
10372    bxe_init_internal(sc, load_code);
10373    bxe_pf_init(sc);
10374    bxe_stats_init(sc);
10375
10376    /* flush all before enabling interrupts */
10377    mb();
10378
10379    bxe_int_enable(sc);
10380
10381    /* check for SPIO5 */
10382    bxe_attn_int_deasserted0(sc,
10383                             REG_RD(sc,
10384                                    (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10385                                     SC_PORT(sc)*4)) &
10386                             AEU_INPUTS_ATTN_BITS_SPIO5);
10387}
10388
10389static inline void
10390bxe_init_objs(struct bxe_softc *sc)
10391{
10392    /* mcast rules must be added to tx if tx switching is enabled */
10393    ecore_obj_type o_type =
10394        (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10395                                         ECORE_OBJ_TYPE_RX;
10396
10397    /* RX_MODE controlling object */
10398    ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10399
10400    /* multicast configuration controlling object */
10401    ecore_init_mcast_obj(sc,
10402                         &sc->mcast_obj,
10403                         sc->fp[0].cl_id,
10404                         sc->fp[0].index,
10405                         SC_FUNC(sc),
10406                         SC_FUNC(sc),
10407                         BXE_SP(sc, mcast_rdata),
10408                         BXE_SP_MAPPING(sc, mcast_rdata),
10409                         ECORE_FILTER_MCAST_PENDING,
10410                         &sc->sp_state,
10411                         o_type);
10412
10413    /* Setup CAM credit pools */
10414    ecore_init_mac_credit_pool(sc,
10415                               &sc->macs_pool,
10416                               SC_FUNC(sc),
10417                               CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10418                                                 VNICS_PER_PATH(sc));
10419
10420    ecore_init_vlan_credit_pool(sc,
10421                                &sc->vlans_pool,
10422                                SC_ABS_FUNC(sc) >> 1,
10423                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10424                                                  VNICS_PER_PATH(sc));
10425
10426    /* RSS configuration object */
10427    ecore_init_rss_config_obj(sc,
10428                              &sc->rss_conf_obj,
10429                              sc->fp[0].cl_id,
10430                              sc->fp[0].index,
10431                              SC_FUNC(sc),
10432                              SC_FUNC(sc),
10433                              BXE_SP(sc, rss_rdata),
10434                              BXE_SP_MAPPING(sc, rss_rdata),
10435                              ECORE_FILTER_RSS_CONF_PENDING,
10436                              &sc->sp_state, ECORE_OBJ_TYPE_RX);
10437}
10438
10439/*
10440 * Initialize the function. This must be called before sending CLIENT_SETUP
10441 * for the first client.
10442 */
10443static inline int
10444bxe_func_start(struct bxe_softc *sc)
10445{
10446    struct ecore_func_state_params func_params = { NULL };
10447    struct ecore_func_start_params *start_params = &func_params.params.start;
10448
10449    /* Prepare parameters for function state transitions */
10450    bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10451
10452    func_params.f_obj = &sc->func_obj;
10453    func_params.cmd = ECORE_F_CMD_START;
10454
10455    /* Function parameters */
10456    start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10457    start_params->sd_vlan_tag = OVLAN(sc);
10458
10459    if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10460        start_params->network_cos_mode = STATIC_COS;
10461    } else { /* CHIP_IS_E1X */
10462        start_params->network_cos_mode = FW_WRR;
10463    }
10464
10465    //start_params->gre_tunnel_mode = 0;
10466    //start_params->gre_tunnel_rss  = 0;
10467
10468    return (ecore_func_state_change(sc, &func_params));
10469}
10470
10471static int
10472bxe_set_power_state(struct bxe_softc *sc,
10473                    uint8_t          state)
10474{
10475    uint16_t pmcsr;
10476
10477    /* If there is no power capability, silently succeed */
10478    if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10479        BLOGW(sc, "No power capability\n");
10480        return (0);
10481    }
10482
10483    pmcsr = pci_read_config(sc->dev,
10484                            (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10485                            2);
10486
10487    switch (state) {
10488    case PCI_PM_D0:
10489        pci_write_config(sc->dev,
10490                         (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10491                         ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10492
10493        if (pmcsr & PCIM_PSTAT_DMASK) {
10494            /* delay required during transition out of D3hot */
10495            DELAY(20000);
10496        }
10497
10498        break;
10499
10500    case PCI_PM_D3hot:
10501        /* XXX if there are other clients above don't shut down the power */
10502
10503        /* don't shut down the power for emulation and FPGA */
10504        if (CHIP_REV_IS_SLOW(sc)) {
10505            return (0);
10506        }
10507
10508        pmcsr &= ~PCIM_PSTAT_DMASK;
10509        pmcsr |= PCIM_PSTAT_D3;
10510
10511        if (sc->wol) {
10512            pmcsr |= PCIM_PSTAT_PMEENABLE;
10513        }
10514
10515        pci_write_config(sc->dev,
10516                         (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10517                         pmcsr, 4);
10518
10519        /*
10520         * No more memory access after this point until device is brought back
10521         * to D0 state.
10522         */
10523        break;
10524
10525    default:
10526        BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10527            state, pmcsr);
10528        return (-1);
10529    }
10530
10531    return (0);
10532}
10533
10534
10535/* return true if succeeded to acquire the lock */
10536static uint8_t
10537bxe_trylock_hw_lock(struct bxe_softc *sc,
10538                    uint32_t         resource)
10539{
10540    uint32_t lock_status;
10541    uint32_t resource_bit = (1 << resource);
10542    int func = SC_FUNC(sc);
10543    uint32_t hw_lock_control_reg;
10544
10545    BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10546
10547    /* Validating that the resource is within range */
10548    if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10549        BLOGD(sc, DBG_LOAD,
10550              "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10551              resource, HW_LOCK_MAX_RESOURCE_VALUE);
10552        return (FALSE);
10553    }
10554
10555    if (func <= 5) {
10556        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10557    } else {
10558        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10559    }
10560
10561    /* try to acquire the lock */
10562    REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10563    lock_status = REG_RD(sc, hw_lock_control_reg);
10564    if (lock_status & resource_bit) {
10565        return (TRUE);
10566    }
10567
10568    BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10569        "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10570        lock_status, resource_bit);
10571
10572    return (FALSE);
10573}
10574
10575/*
10576 * Get the recovery leader resource id according to the engine this function
10577 * belongs to. Currently only only 2 engines is supported.
10578 */
10579static int
10580bxe_get_leader_lock_resource(struct bxe_softc *sc)
10581{
10582    if (SC_PATH(sc)) {
10583        return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10584    } else {
10585        return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10586    }
10587}
10588
10589/* try to acquire a leader lock for current engine */
10590static uint8_t
10591bxe_trylock_leader_lock(struct bxe_softc *sc)
10592{
10593    return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10594}
10595
10596static int
10597bxe_release_leader_lock(struct bxe_softc *sc)
10598{
10599    return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10600}
10601
10602/* close gates #2, #3 and #4 */
10603static void
10604bxe_set_234_gates(struct bxe_softc *sc,
10605                  uint8_t          close)
10606{
10607    uint32_t val;
10608
10609    /* gates #2 and #4a are closed/opened for "not E1" only */
10610    if (!CHIP_IS_E1(sc)) {
10611        /* #4 */
10612        REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10613        /* #2 */
10614        REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10615    }
10616
10617    /* #3 */
10618    if (CHIP_IS_E1x(sc)) {
10619        /* prevent interrupts from HC on both ports */
10620        val = REG_RD(sc, HC_REG_CONFIG_1);
10621        REG_WR(sc, HC_REG_CONFIG_1,
10622               (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10623               (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10624
10625        val = REG_RD(sc, HC_REG_CONFIG_0);
10626        REG_WR(sc, HC_REG_CONFIG_0,
10627               (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10628               (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10629    } else {
10630        /* Prevent incoming interrupts in IGU */
10631        val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10632
10633        REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10634               (!close) ?
10635               (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10636               (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10637    }
10638
10639    BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10640          close ? "closing" : "opening");
10641
10642    wmb();
10643}
10644
10645/* poll for pending writes bit, it should get cleared in no more than 1s */
10646static int
10647bxe_er_poll_igu_vq(struct bxe_softc *sc)
10648{
10649    uint32_t cnt = 1000;
10650    uint32_t pend_bits = 0;
10651
10652    do {
10653        pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10654
10655        if (pend_bits == 0) {
10656            break;
10657        }
10658
10659        DELAY(1000);
10660    } while (--cnt > 0);
10661
10662    if (cnt == 0) {
10663        BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10664        return (-1);
10665    }
10666
10667    return (0);
10668}
10669
10670#define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10671
10672static void
10673bxe_clp_reset_prep(struct bxe_softc *sc,
10674                   uint32_t         *magic_val)
10675{
10676    /* Do some magic... */
10677    uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10678    *magic_val = val & SHARED_MF_CLP_MAGIC;
10679    MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10680}
10681
10682/* restore the value of the 'magic' bit */
10683static void
10684bxe_clp_reset_done(struct bxe_softc *sc,
10685                   uint32_t         magic_val)
10686{
10687    /* Restore the 'magic' bit value... */
10688    uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10689    MFCFG_WR(sc, shared_mf_config.clp_mb,
10690              (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10691}
10692
10693/* prepare for MCP reset, takes care of CLP configurations */
10694static void
10695bxe_reset_mcp_prep(struct bxe_softc *sc,
10696                   uint32_t         *magic_val)
10697{
10698    uint32_t shmem;
10699    uint32_t validity_offset;
10700
10701    /* set `magic' bit in order to save MF config */
10702    if (!CHIP_IS_E1(sc)) {
10703        bxe_clp_reset_prep(sc, magic_val);
10704    }
10705
10706    /* get shmem offset */
10707    shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10708    validity_offset =
10709        offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10710
10711    /* Clear validity map flags */
10712    if (shmem > 0) {
10713        REG_WR(sc, shmem + validity_offset, 0);
10714    }
10715}
10716
10717#define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10718#define MCP_ONE_TIMEOUT  100    /* 100 ms */
10719
10720static void
10721bxe_mcp_wait_one(struct bxe_softc *sc)
10722{
10723    /* special handling for emulation and FPGA (10 times longer) */
10724    if (CHIP_REV_IS_SLOW(sc)) {
10725        DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10726    } else {
10727        DELAY((MCP_ONE_TIMEOUT) * 1000);
10728    }
10729}
10730
10731/* initialize shmem_base and waits for validity signature to appear */
10732static int
10733bxe_init_shmem(struct bxe_softc *sc)
10734{
10735    int cnt = 0;
10736    uint32_t val = 0;
10737
10738    do {
10739        sc->devinfo.shmem_base     =
10740        sc->link_params.shmem_base =
10741            REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10742
10743        if (sc->devinfo.shmem_base) {
10744            val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10745            if (val & SHR_MEM_VALIDITY_MB)
10746                return (0);
10747        }
10748
10749        bxe_mcp_wait_one(sc);
10750
10751    } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10752
10753    BLOGE(sc, "BAD MCP validity signature\n");
10754
10755    return (-1);
10756}
10757
10758static int
10759bxe_reset_mcp_comp(struct bxe_softc *sc,
10760                   uint32_t         magic_val)
10761{
10762    int rc = bxe_init_shmem(sc);
10763
10764    /* Restore the `magic' bit value */
10765    if (!CHIP_IS_E1(sc)) {
10766        bxe_clp_reset_done(sc, magic_val);
10767    }
10768
10769    return (rc);
10770}
10771
10772static void
10773bxe_pxp_prep(struct bxe_softc *sc)
10774{
10775    if (!CHIP_IS_E1(sc)) {
10776        REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10777        REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10778        wmb();
10779    }
10780}
10781
10782/*
10783 * Reset the whole chip except for:
10784 *      - PCIE core
10785 *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10786 *      - IGU
10787 *      - MISC (including AEU)
10788 *      - GRC
10789 *      - RBCN, RBCP
10790 */
10791static void
10792bxe_process_kill_chip_reset(struct bxe_softc *sc,
10793                            uint8_t          global)
10794{
10795    uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10796    uint32_t global_bits2, stay_reset2;
10797
10798    /*
10799     * Bits that have to be set in reset_mask2 if we want to reset 'global'
10800     * (per chip) blocks.
10801     */
10802    global_bits2 =
10803        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10804        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10805
10806    /*
10807     * Don't reset the following blocks.
10808     * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10809     *            reset, as in 4 port device they might still be owned
10810     *            by the MCP (there is only one leader per path).
10811     */
10812    not_reset_mask1 =
10813        MISC_REGISTERS_RESET_REG_1_RST_HC |
10814        MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10815        MISC_REGISTERS_RESET_REG_1_RST_PXP;
10816
10817    not_reset_mask2 =
10818        MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10819        MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10820        MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10821        MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10822        MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10823        MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10824        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10825        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10826        MISC_REGISTERS_RESET_REG_2_RST_ATC |
10827        MISC_REGISTERS_RESET_REG_2_PGLC |
10828        MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10829        MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10830        MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10831        MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10832        MISC_REGISTERS_RESET_REG_2_UMAC0 |
10833        MISC_REGISTERS_RESET_REG_2_UMAC1;
10834
10835    /*
10836     * Keep the following blocks in reset:
10837     *  - all xxMACs are handled by the elink code.
10838     */
10839    stay_reset2 =
10840        MISC_REGISTERS_RESET_REG_2_XMAC |
10841        MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10842
10843    /* Full reset masks according to the chip */
10844    reset_mask1 = 0xffffffff;
10845
10846    if (CHIP_IS_E1(sc))
10847        reset_mask2 = 0xffff;
10848    else if (CHIP_IS_E1H(sc))
10849        reset_mask2 = 0x1ffff;
10850    else if (CHIP_IS_E2(sc))
10851        reset_mask2 = 0xfffff;
10852    else /* CHIP_IS_E3 */
10853        reset_mask2 = 0x3ffffff;
10854
10855    /* Don't reset global blocks unless we need to */
10856    if (!global)
10857        reset_mask2 &= ~global_bits2;
10858
10859    /*
10860     * In case of attention in the QM, we need to reset PXP
10861     * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
10862     * because otherwise QM reset would release 'close the gates' shortly
10863     * before resetting the PXP, then the PSWRQ would send a write
10864     * request to PGLUE. Then when PXP is reset, PGLUE would try to
10865     * read the payload data from PSWWR, but PSWWR would not
10866     * respond. The write queue in PGLUE would stuck, dmae commands
10867     * would not return. Therefore it's important to reset the second
10868     * reset register (containing the
10869     * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
10870     * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
10871     * bit).
10872     */
10873    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
10874           reset_mask2 & (~not_reset_mask2));
10875
10876    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
10877           reset_mask1 & (~not_reset_mask1));
10878
10879    mb();
10880    wmb();
10881
10882    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
10883           reset_mask2 & (~stay_reset2));
10884
10885    mb();
10886    wmb();
10887
10888    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
10889    wmb();
10890}
10891
10892static int
10893bxe_process_kill(struct bxe_softc *sc,
10894                 uint8_t          global)
10895{
10896    int cnt = 1000;
10897    uint32_t val = 0;
10898    uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
10899    uint32_t tags_63_32 = 0;
10900
10901    /* Empty the Tetris buffer, wait for 1s */
10902    do {
10903        sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
10904        blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
10905        port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
10906        port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
10907        pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
10908        if (CHIP_IS_E3(sc)) {
10909            tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
10910        }
10911
10912        if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
10913            ((port_is_idle_0 & 0x1) == 0x1) &&
10914            ((port_is_idle_1 & 0x1) == 0x1) &&
10915            (pgl_exp_rom2 == 0xffffffff) &&
10916            (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
10917            break;
10918        DELAY(1000);
10919    } while (cnt-- > 0);
10920
10921    if (cnt <= 0) {
10922        BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
10923                  "are still outstanding read requests after 1s! "
10924                  "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
10925                  "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
10926              sr_cnt, blk_cnt, port_is_idle_0,
10927              port_is_idle_1, pgl_exp_rom2);
10928        return (-1);
10929    }
10930
10931    mb();
10932
10933    /* Close gates #2, #3 and #4 */
10934    bxe_set_234_gates(sc, TRUE);
10935
10936    /* Poll for IGU VQs for 57712 and newer chips */
10937    if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
10938        return (-1);
10939    }
10940
10941    /* XXX indicate that "process kill" is in progress to MCP */
10942
10943    /* clear "unprepared" bit */
10944    REG_WR(sc, MISC_REG_UNPREPARED, 0);
10945    mb();
10946
10947    /* Make sure all is written to the chip before the reset */
10948    wmb();
10949
10950    /*
10951     * Wait for 1ms to empty GLUE and PCI-E core queues,
10952     * PSWHST, GRC and PSWRD Tetris buffer.
10953     */
10954    DELAY(1000);
10955
10956    /* Prepare to chip reset: */
10957    /* MCP */
10958    if (global) {
10959        bxe_reset_mcp_prep(sc, &val);
10960    }
10961
10962    /* PXP */
10963    bxe_pxp_prep(sc);
10964    mb();
10965
10966    /* reset the chip */
10967    bxe_process_kill_chip_reset(sc, global);
10968    mb();
10969
10970    /* clear errors in PGB */
10971    if (!CHIP_IS_E1(sc))
10972        REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
10973
10974    /* Recover after reset: */
10975    /* MCP */
10976    if (global && bxe_reset_mcp_comp(sc, val)) {
10977        return (-1);
10978    }
10979
10980    /* XXX add resetting the NO_MCP mode DB here */
10981
10982    /* Open the gates #2, #3 and #4 */
10983    bxe_set_234_gates(sc, FALSE);
10984
10985    /* XXX
10986     * IGU/AEU preparation bring back the AEU/IGU to a reset state
10987     * re-enable attentions
10988     */
10989
10990    return (0);
10991}
10992
10993static int
10994bxe_leader_reset(struct bxe_softc *sc)
10995{
10996    int rc = 0;
10997    uint8_t global = bxe_reset_is_global(sc);
10998    uint32_t load_code;
10999
11000    /*
11001     * If not going to reset MCP, load "fake" driver to reset HW while
11002     * driver is owner of the HW.
11003     */
11004    if (!global && !BXE_NOMCP(sc)) {
11005        load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11006                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11007        if (!load_code) {
11008            BLOGE(sc, "MCP response failure, aborting\n");
11009            rc = -1;
11010            goto exit_leader_reset;
11011        }
11012
11013        if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11014            (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11015            BLOGE(sc, "MCP unexpected response, aborting\n");
11016            rc = -1;
11017            goto exit_leader_reset2;
11018        }
11019
11020        load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11021        if (!load_code) {
11022            BLOGE(sc, "MCP response failure, aborting\n");
11023            rc = -1;
11024            goto exit_leader_reset2;
11025        }
11026    }
11027
11028    /* try to recover after the failure */
11029    if (bxe_process_kill(sc, global)) {
11030        BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11031        rc = -1;
11032        goto exit_leader_reset2;
11033    }
11034
11035    /*
11036     * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11037     * state.
11038     */
11039    bxe_set_reset_done(sc);
11040    if (global) {
11041        bxe_clear_reset_global(sc);
11042    }
11043
11044exit_leader_reset2:
11045
11046    /* unload "fake driver" if it was loaded */
11047    if (!global && !BXE_NOMCP(sc)) {
11048        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11049        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11050    }
11051
11052exit_leader_reset:
11053
11054    sc->is_leader = 0;
11055    bxe_release_leader_lock(sc);
11056
11057    mb();
11058    return (rc);
11059}
11060
11061/*
11062 * prepare INIT transition, parameters configured:
11063 *   - HC configuration
11064 *   - Queue's CDU context
11065 */
11066static void
11067bxe_pf_q_prep_init(struct bxe_softc               *sc,
11068                   struct bxe_fastpath            *fp,
11069                   struct ecore_queue_init_params *init_params)
11070{
11071    uint8_t cos;
11072    int cxt_index, cxt_offset;
11073
11074    bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11075    bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11076
11077    bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11078    bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11079
11080    /* HC rate */
11081    init_params->rx.hc_rate =
11082        sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11083    init_params->tx.hc_rate =
11084        sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11085
11086    /* FW SB ID */
11087    init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11088
11089    /* CQ index among the SB indices */
11090    init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11091    init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11092
11093    /* set maximum number of COSs supported by this queue */
11094    init_params->max_cos = sc->max_cos;
11095
11096    BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11097          fp->index, init_params->max_cos);
11098
11099    /* set the context pointers queue object */
11100    for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11101        /* XXX change index/cid here if ever support multiple tx CoS */
11102        /* fp->txdata[cos]->cid */
11103        cxt_index = fp->index / ILT_PAGE_CIDS;
11104        cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11105        init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11106    }
11107}
11108
11109/* set flags that are common for the Tx-only and not normal connections */
11110static unsigned long
11111bxe_get_common_flags(struct bxe_softc    *sc,
11112                     struct bxe_fastpath *fp,
11113                     uint8_t             zero_stats)
11114{
11115    unsigned long flags = 0;
11116
11117    /* PF driver will always initialize the Queue to an ACTIVE state */
11118    bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11119
11120    /*
11121     * tx only connections collect statistics (on the same index as the
11122     * parent connection). The statistics are zeroed when the parent
11123     * connection is initialized.
11124     */
11125
11126    bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11127    if (zero_stats) {
11128        bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11129    }
11130
11131    /*
11132     * tx only connections can support tx-switching, though their
11133     * CoS-ness doesn't survive the loopback
11134     */
11135    if (sc->flags & BXE_TX_SWITCHING) {
11136        bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11137    }
11138
11139    bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11140
11141    return (flags);
11142}
11143
11144static unsigned long
11145bxe_get_q_flags(struct bxe_softc    *sc,
11146                struct bxe_fastpath *fp,
11147                uint8_t             leading)
11148{
11149    unsigned long flags = 0;
11150
11151    if (IS_MF_SD(sc)) {
11152        bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11153    }
11154
11155    if (if_getcapenable(sc->ifp) & IFCAP_LRO) {
11156        bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11157        bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11158    }
11159
11160    if (leading) {
11161        bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11162        bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11163    }
11164
11165    bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11166
11167    /* merge with common flags */
11168    return (flags | bxe_get_common_flags(sc, fp, TRUE));
11169}
11170
11171static void
11172bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11173                      struct bxe_fastpath               *fp,
11174                      struct ecore_general_setup_params *gen_init,
11175                      uint8_t                           cos)
11176{
11177    gen_init->stat_id = bxe_stats_id(fp);
11178    gen_init->spcl_id = fp->cl_id;
11179    gen_init->mtu = sc->mtu;
11180    gen_init->cos = cos;
11181}
11182
11183static void
11184bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11185                 struct bxe_fastpath           *fp,
11186                 struct rxq_pause_params       *pause,
11187                 struct ecore_rxq_setup_params *rxq_init)
11188{
11189    uint8_t max_sge = 0;
11190    uint16_t sge_sz = 0;
11191    uint16_t tpa_agg_size = 0;
11192
11193    pause->sge_th_lo = SGE_TH_LO(sc);
11194    pause->sge_th_hi = SGE_TH_HI(sc);
11195
11196    /* validate SGE ring has enough to cross high threshold */
11197    if (sc->dropless_fc &&
11198            (pause->sge_th_hi + FW_PREFETCH_CNT) >
11199            (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11200        BLOGW(sc, "sge ring threshold limit\n");
11201    }
11202
11203    /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11204    tpa_agg_size = (2 * sc->mtu);
11205    if (tpa_agg_size < sc->max_aggregation_size) {
11206        tpa_agg_size = sc->max_aggregation_size;
11207    }
11208
11209    max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11210    max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11211                   (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11212    sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11213
11214    /* pause - not for e1 */
11215    if (!CHIP_IS_E1(sc)) {
11216        pause->bd_th_lo = BD_TH_LO(sc);
11217        pause->bd_th_hi = BD_TH_HI(sc);
11218
11219        pause->rcq_th_lo = RCQ_TH_LO(sc);
11220        pause->rcq_th_hi = RCQ_TH_HI(sc);
11221
11222        /* validate rings have enough entries to cross high thresholds */
11223        if (sc->dropless_fc &&
11224            pause->bd_th_hi + FW_PREFETCH_CNT >
11225            sc->rx_ring_size) {
11226            BLOGW(sc, "rx bd ring threshold limit\n");
11227        }
11228
11229        if (sc->dropless_fc &&
11230            pause->rcq_th_hi + FW_PREFETCH_CNT >
11231            RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11232            BLOGW(sc, "rcq ring threshold limit\n");
11233        }
11234
11235        pause->pri_map = 1;
11236    }
11237
11238    /* rxq setup */
11239    rxq_init->dscr_map   = fp->rx_dma.paddr;
11240    rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11241    rxq_init->rcq_map    = fp->rcq_dma.paddr;
11242    rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11243
11244    /*
11245     * This should be a maximum number of data bytes that may be
11246     * placed on the BD (not including paddings).
11247     */
11248    rxq_init->buf_sz = (fp->rx_buf_size -
11249                        IP_HEADER_ALIGNMENT_PADDING);
11250
11251    rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11252    rxq_init->tpa_agg_sz      = tpa_agg_size;
11253    rxq_init->sge_buf_sz      = sge_sz;
11254    rxq_init->max_sges_pkt    = max_sge;
11255    rxq_init->rss_engine_id   = SC_FUNC(sc);
11256    rxq_init->mcast_engine_id = SC_FUNC(sc);
11257
11258    /*
11259     * Maximum number or simultaneous TPA aggregation for this Queue.
11260     * For PF Clients it should be the maximum available number.
11261     * VF driver(s) may want to define it to a smaller value.
11262     */
11263    rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11264
11265    rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11266    rxq_init->fw_sb_id = fp->fw_sb_id;
11267
11268    rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11269
11270    /*
11271     * configure silent vlan removal
11272     * if multi function mode is afex, then mask default vlan
11273     */
11274    if (IS_MF_AFEX(sc)) {
11275        rxq_init->silent_removal_value =
11276            sc->devinfo.mf_info.afex_def_vlan_tag;
11277        rxq_init->silent_removal_mask = EVL_VLID_MASK;
11278    }
11279}
11280
11281static void
11282bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11283                 struct bxe_fastpath           *fp,
11284                 struct ecore_txq_setup_params *txq_init,
11285                 uint8_t                       cos)
11286{
11287    /*
11288     * XXX If multiple CoS is ever supported then each fastpath structure
11289     * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11290     * fp->txdata[cos]->tx_dma.paddr;
11291     */
11292    txq_init->dscr_map     = fp->tx_dma.paddr;
11293    txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11294    txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11295    txq_init->fw_sb_id     = fp->fw_sb_id;
11296
11297    /*
11298     * set the TSS leading client id for TX classfication to the
11299     * leading RSS client id
11300     */
11301    txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11302}
11303
11304/*
11305 * This function performs 2 steps in a queue state machine:
11306 *   1) RESET->INIT
11307 *   2) INIT->SETUP
11308 */
11309static int
11310bxe_setup_queue(struct bxe_softc    *sc,
11311                struct bxe_fastpath *fp,
11312                uint8_t             leading)
11313{
11314    struct ecore_queue_state_params q_params = { NULL };
11315    struct ecore_queue_setup_params *setup_params =
11316                        &q_params.params.setup;
11317    int rc;
11318
11319    BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11320
11321    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11322
11323    q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11324
11325    /* we want to wait for completion in this context */
11326    bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11327
11328    /* prepare the INIT parameters */
11329    bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11330
11331    /* Set the command */
11332    q_params.cmd = ECORE_Q_CMD_INIT;
11333
11334    /* Change the state to INIT */
11335    rc = ecore_queue_state_change(sc, &q_params);
11336    if (rc) {
11337        BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11338        return (rc);
11339    }
11340
11341    BLOGD(sc, DBG_LOAD, "init complete\n");
11342
11343    /* now move the Queue to the SETUP state */
11344    memset(setup_params, 0, sizeof(*setup_params));
11345
11346    /* set Queue flags */
11347    setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11348
11349    /* set general SETUP parameters */
11350    bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11351                          FIRST_TX_COS_INDEX);
11352
11353    bxe_pf_rx_q_prep(sc, fp,
11354                     &setup_params->pause_params,
11355                     &setup_params->rxq_params);
11356
11357    bxe_pf_tx_q_prep(sc, fp,
11358                     &setup_params->txq_params,
11359                     FIRST_TX_COS_INDEX);
11360
11361    /* Set the command */
11362    q_params.cmd = ECORE_Q_CMD_SETUP;
11363
11364    /* change the state to SETUP */
11365    rc = ecore_queue_state_change(sc, &q_params);
11366    if (rc) {
11367        BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11368        return (rc);
11369    }
11370
11371    return (rc);
11372}
11373
11374static int
11375bxe_setup_leading(struct bxe_softc *sc)
11376{
11377    return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11378}
11379
11380static int
11381bxe_config_rss_pf(struct bxe_softc            *sc,
11382                  struct ecore_rss_config_obj *rss_obj,
11383                  uint8_t                     config_hash)
11384{
11385    struct ecore_config_rss_params params = { NULL };
11386    int i;
11387
11388    /*
11389     * Although RSS is meaningless when there is a single HW queue we
11390     * still need it enabled in order to have HW Rx hash generated.
11391     */
11392
11393    params.rss_obj = rss_obj;
11394
11395    bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11396
11397    bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11398
11399    /* RSS configuration */
11400    bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11401    bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11402    bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11403    bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11404    if (rss_obj->udp_rss_v4) {
11405        bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11406    }
11407    if (rss_obj->udp_rss_v6) {
11408        bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11409    }
11410
11411    /* Hash bits */
11412    params.rss_result_mask = MULTI_MASK;
11413
11414    memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11415
11416    if (config_hash) {
11417        /* RSS keys */
11418        for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11419            params.rss_key[i] = arc4random();
11420        }
11421
11422        bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11423    }
11424
11425    return (ecore_config_rss(sc, &params));
11426}
11427
11428static int
11429bxe_config_rss_eth(struct bxe_softc *sc,
11430                   uint8_t          config_hash)
11431{
11432    return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11433}
11434
11435static int
11436bxe_init_rss_pf(struct bxe_softc *sc)
11437{
11438    uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11439    int i;
11440
11441    /*
11442     * Prepare the initial contents of the indirection table if
11443     * RSS is enabled
11444     */
11445    for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11446        sc->rss_conf_obj.ind_table[i] =
11447            (sc->fp->cl_id + (i % num_eth_queues));
11448    }
11449
11450    if (sc->udp_rss) {
11451        sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11452    }
11453
11454    /*
11455     * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11456     * per-port, so if explicit configuration is needed, do it only
11457     * for a PMF.
11458     *
11459     * For 57712 and newer it's a per-function configuration.
11460     */
11461    return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11462}
11463
11464static int
11465bxe_set_mac_one(struct bxe_softc          *sc,
11466                uint8_t                   *mac,
11467                struct ecore_vlan_mac_obj *obj,
11468                uint8_t                   set,
11469                int                       mac_type,
11470                unsigned long             *ramrod_flags)
11471{
11472    struct ecore_vlan_mac_ramrod_params ramrod_param;
11473    int rc;
11474
11475    memset(&ramrod_param, 0, sizeof(ramrod_param));
11476
11477    /* fill in general parameters */
11478    ramrod_param.vlan_mac_obj = obj;
11479    ramrod_param.ramrod_flags = *ramrod_flags;
11480
11481    /* fill a user request section if needed */
11482    if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11483        memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11484
11485        bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11486
11487        /* Set the command: ADD or DEL */
11488        ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11489                                            ECORE_VLAN_MAC_DEL;
11490    }
11491
11492    rc = ecore_config_vlan_mac(sc, &ramrod_param);
11493
11494    if (rc == ECORE_EXISTS) {
11495        BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11496        /* do not treat adding same MAC as error */
11497        rc = 0;
11498    } else if (rc < 0) {
11499        BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11500    }
11501
11502    return (rc);
11503}
11504
11505static int
11506bxe_set_eth_mac(struct bxe_softc *sc,
11507                uint8_t          set)
11508{
11509    unsigned long ramrod_flags = 0;
11510
11511    BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11512
11513    bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11514
11515    /* Eth MAC is set on RSS leading client (fp[0]) */
11516    return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11517                            &sc->sp_objs->mac_obj,
11518                            set, ECORE_ETH_MAC, &ramrod_flags));
11519}
11520
11521static int
11522bxe_get_cur_phy_idx(struct bxe_softc *sc)
11523{
11524    uint32_t sel_phy_idx = 0;
11525
11526    if (sc->link_params.num_phys <= 1) {
11527        return (ELINK_INT_PHY);
11528    }
11529
11530    if (sc->link_vars.link_up) {
11531        sel_phy_idx = ELINK_EXT_PHY1;
11532        /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11533        if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11534            (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11535             ELINK_SUPPORTED_FIBRE))
11536            sel_phy_idx = ELINK_EXT_PHY2;
11537    } else {
11538        switch (elink_phy_selection(&sc->link_params)) {
11539        case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11540        case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11541        case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11542               sel_phy_idx = ELINK_EXT_PHY1;
11543               break;
11544        case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11545        case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11546               sel_phy_idx = ELINK_EXT_PHY2;
11547               break;
11548        }
11549    }
11550
11551    return (sel_phy_idx);
11552}
11553
11554static int
11555bxe_get_link_cfg_idx(struct bxe_softc *sc)
11556{
11557    uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11558
11559    /*
11560     * The selected activated PHY is always after swapping (in case PHY
11561     * swapping is enabled). So when swapping is enabled, we need to reverse
11562     * the configuration
11563     */
11564
11565    if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11566        if (sel_phy_idx == ELINK_EXT_PHY1)
11567            sel_phy_idx = ELINK_EXT_PHY2;
11568        else if (sel_phy_idx == ELINK_EXT_PHY2)
11569            sel_phy_idx = ELINK_EXT_PHY1;
11570    }
11571
11572    return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11573}
11574
11575static void
11576bxe_set_requested_fc(struct bxe_softc *sc)
11577{
11578    /*
11579     * Initialize link parameters structure variables
11580     * It is recommended to turn off RX FC for jumbo frames
11581     * for better performance
11582     */
11583    if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11584        sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11585    } else {
11586        sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11587    }
11588}
11589
11590static void
11591bxe_calc_fc_adv(struct bxe_softc *sc)
11592{
11593    uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11594    switch (sc->link_vars.ieee_fc &
11595            MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11596    case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
11597    default:
11598        sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11599                                           ADVERTISED_Pause);
11600        break;
11601
11602    case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11603        sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11604                                          ADVERTISED_Pause);
11605        break;
11606
11607    case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11608        sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11609        break;
11610    }
11611}
11612
11613static uint16_t
11614bxe_get_mf_speed(struct bxe_softc *sc)
11615{
11616    uint16_t line_speed = sc->link_vars.line_speed;
11617    if (IS_MF(sc)) {
11618        uint16_t maxCfg =
11619            bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11620
11621        /* calculate the current MAX line speed limit for the MF devices */
11622        if (IS_MF_SI(sc)) {
11623            line_speed = (line_speed * maxCfg) / 100;
11624        } else { /* SD mode */
11625            uint16_t vn_max_rate = maxCfg * 100;
11626
11627            if (vn_max_rate < line_speed) {
11628                line_speed = vn_max_rate;
11629            }
11630        }
11631    }
11632
11633    return (line_speed);
11634}
11635
11636static void
11637bxe_fill_report_data(struct bxe_softc            *sc,
11638                     struct bxe_link_report_data *data)
11639{
11640    uint16_t line_speed = bxe_get_mf_speed(sc);
11641
11642    memset(data, 0, sizeof(*data));
11643
11644    /* fill the report data with the effective line speed */
11645    data->line_speed = line_speed;
11646
11647    /* Link is down */
11648    if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11649        bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11650    }
11651
11652    /* Full DUPLEX */
11653    if (sc->link_vars.duplex == DUPLEX_FULL) {
11654        bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11655    }
11656
11657    /* Rx Flow Control is ON */
11658    if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11659        bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11660    }
11661
11662    /* Tx Flow Control is ON */
11663    if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11664        bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11665    }
11666}
11667
11668/* report link status to OS, should be called under phy_lock */
11669static void
11670bxe_link_report_locked(struct bxe_softc *sc)
11671{
11672    struct bxe_link_report_data cur_data;
11673
11674    /* reread mf_cfg */
11675    if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11676        bxe_read_mf_cfg(sc);
11677    }
11678
11679    /* Read the current link report info */
11680    bxe_fill_report_data(sc, &cur_data);
11681
11682    /* Don't report link down or exactly the same link status twice */
11683    if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11684        (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11685                      &sc->last_reported_link.link_report_flags) &&
11686         bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11687                      &cur_data.link_report_flags))) {
11688        return;
11689    }
11690
11691    sc->link_cnt++;
11692
11693    /* report new link params and remember the state for the next time */
11694    memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11695
11696    if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11697                     &cur_data.link_report_flags)) {
11698        if_link_state_change(sc->ifp, LINK_STATE_DOWN);
11699        BLOGI(sc, "NIC Link is Down\n");
11700    } else {
11701        const char *duplex;
11702        const char *flow;
11703
11704        if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11705                                   &cur_data.link_report_flags)) {
11706            duplex = "full";
11707        } else {
11708            duplex = "half";
11709        }
11710
11711        /*
11712         * Handle the FC at the end so that only these flags would be
11713         * possibly set. This way we may easily check if there is no FC
11714         * enabled.
11715         */
11716        if (cur_data.link_report_flags) {
11717            if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11718                             &cur_data.link_report_flags) &&
11719                bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11720                             &cur_data.link_report_flags)) {
11721                flow = "ON - receive & transmit";
11722            } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11723                                    &cur_data.link_report_flags) &&
11724                       !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11725                                     &cur_data.link_report_flags)) {
11726                flow = "ON - receive";
11727            } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11728                                     &cur_data.link_report_flags) &&
11729                       bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11730                                    &cur_data.link_report_flags)) {
11731                flow = "ON - transmit";
11732            } else {
11733                flow = "none"; /* possible? */
11734            }
11735        } else {
11736            flow = "none";
11737        }
11738
11739        if_link_state_change(sc->ifp, LINK_STATE_UP);
11740        BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11741              cur_data.line_speed, duplex, flow);
11742    }
11743}
11744
11745static void
11746bxe_link_report(struct bxe_softc *sc)
11747{
11748    bxe_acquire_phy_lock(sc);
11749    bxe_link_report_locked(sc);
11750    bxe_release_phy_lock(sc);
11751}
11752
11753static void
11754bxe_link_status_update(struct bxe_softc *sc)
11755{
11756    if (sc->state != BXE_STATE_OPEN) {
11757        return;
11758    }
11759
11760    if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11761        elink_link_status_update(&sc->link_params, &sc->link_vars);
11762    } else {
11763        sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11764                                  ELINK_SUPPORTED_10baseT_Full |
11765                                  ELINK_SUPPORTED_100baseT_Half |
11766                                  ELINK_SUPPORTED_100baseT_Full |
11767                                  ELINK_SUPPORTED_1000baseT_Full |
11768                                  ELINK_SUPPORTED_2500baseX_Full |
11769                                  ELINK_SUPPORTED_10000baseT_Full |
11770                                  ELINK_SUPPORTED_TP |
11771                                  ELINK_SUPPORTED_FIBRE |
11772                                  ELINK_SUPPORTED_Autoneg |
11773                                  ELINK_SUPPORTED_Pause |
11774                                  ELINK_SUPPORTED_Asym_Pause);
11775        sc->port.advertising[0] = sc->port.supported[0];
11776
11777        sc->link_params.sc                = sc;
11778        sc->link_params.port              = SC_PORT(sc);
11779        sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11780        sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11781        sc->link_params.req_line_speed[0] = SPEED_10000;
11782        sc->link_params.speed_cap_mask[0] = 0x7f0000;
11783        sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11784
11785        if (CHIP_REV_IS_FPGA(sc)) {
11786            sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11787            sc->link_vars.line_speed  = ELINK_SPEED_1000;
11788            sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11789                                         LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11790        } else {
11791            sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11792            sc->link_vars.line_speed  = ELINK_SPEED_10000;
11793            sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11794                                         LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11795        }
11796
11797        sc->link_vars.link_up = 1;
11798
11799        sc->link_vars.duplex    = DUPLEX_FULL;
11800        sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11801
11802        if (IS_PF(sc)) {
11803            REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11804            bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11805            bxe_link_report(sc);
11806        }
11807    }
11808
11809    if (IS_PF(sc)) {
11810        if (sc->link_vars.link_up) {
11811            bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11812        } else {
11813            bxe_stats_handle(sc, STATS_EVENT_STOP);
11814        }
11815        bxe_link_report(sc);
11816    } else {
11817        bxe_link_report(sc);
11818        bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11819    }
11820}
11821
11822static int
11823bxe_initial_phy_init(struct bxe_softc *sc,
11824                     int              load_mode)
11825{
11826    int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11827    uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11828    struct elink_params *lp = &sc->link_params;
11829
11830    bxe_set_requested_fc(sc);
11831
11832    if (CHIP_REV_IS_SLOW(sc)) {
11833        uint32_t bond = CHIP_BOND_ID(sc);
11834        uint32_t feat = 0;
11835
11836        if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11837            feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11838        } else if (bond & 0x4) {
11839            if (CHIP_IS_E3(sc)) {
11840                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11841            } else {
11842                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11843            }
11844        } else if (bond & 0x8) {
11845            if (CHIP_IS_E3(sc)) {
11846                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11847            } else {
11848                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11849            }
11850        }
11851
11852        /* disable EMAC for E3 and above */
11853        if (bond & 0x2) {
11854            feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11855        }
11856
11857        sc->link_params.feature_config_flags |= feat;
11858    }
11859
11860    bxe_acquire_phy_lock(sc);
11861
11862    if (load_mode == LOAD_DIAG) {
11863        lp->loopback_mode = ELINK_LOOPBACK_XGXS;
11864        /* Prefer doing PHY loopback at 10G speed, if possible */
11865        if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
11866            if (lp->speed_cap_mask[cfg_idx] &
11867                PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
11868                lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
11869            } else {
11870                lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
11871            }
11872        }
11873    }
11874
11875    if (load_mode == LOAD_LOOPBACK_EXT) {
11876        lp->loopback_mode = ELINK_LOOPBACK_EXT;
11877    }
11878
11879    rc = elink_phy_init(&sc->link_params, &sc->link_vars);
11880
11881    bxe_release_phy_lock(sc);
11882
11883    bxe_calc_fc_adv(sc);
11884
11885    if (sc->link_vars.link_up) {
11886        bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11887        bxe_link_report(sc);
11888    }
11889
11890    if (!CHIP_REV_IS_SLOW(sc)) {
11891        bxe_periodic_start(sc);
11892    }
11893
11894    sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
11895    return (rc);
11896}
11897
11898/* must be called under IF_ADDR_LOCK */
11899
11900static int
11901bxe_set_mc_list(struct bxe_softc *sc)
11902{
11903    struct ecore_mcast_ramrod_params rparam = { NULL };
11904    int rc = 0;
11905    int mc_count = 0;
11906    int mcnt, i;
11907    struct ecore_mcast_list_elem *mc_mac, *mc_mac_start;
11908    unsigned char *mta;
11909    if_t ifp = sc->ifp;
11910
11911    mc_count = if_multiaddr_count(ifp, -1);/* XXX they don't have a limit */
11912    if (!mc_count)
11913        return (0);
11914
11915    mta = malloc(sizeof(unsigned char) * ETHER_ADDR_LEN *
11916            mc_count, M_DEVBUF, M_NOWAIT);
11917
11918    if(mta == NULL) {
11919        BLOGE(sc, "Failed to allocate temp mcast list\n");
11920        return (-1);
11921    }
11922    bzero(mta, (sizeof(unsigned char) * ETHER_ADDR_LEN * mc_count));
11923
11924    mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF, (M_NOWAIT | M_ZERO));
11925    mc_mac_start = mc_mac;
11926
11927    if (!mc_mac) {
11928        free(mta, M_DEVBUF);
11929        BLOGE(sc, "Failed to allocate temp mcast list\n");
11930        return (-1);
11931    }
11932    bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
11933
11934    /* mta and mcnt not expected to be  different */
11935    if_multiaddr_array(ifp, mta, &mcnt, mc_count);
11936
11937
11938    rparam.mcast_obj = &sc->mcast_obj;
11939    ECORE_LIST_INIT(&rparam.mcast_list);
11940
11941    for(i=0; i< mcnt; i++) {
11942
11943        mc_mac->mac = (uint8_t *)(mta + (i * ETHER_ADDR_LEN));
11944        ECORE_LIST_PUSH_TAIL(&mc_mac->link, &rparam.mcast_list);
11945
11946        BLOGD(sc, DBG_LOAD,
11947              "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
11948              mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
11949              mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
11950
11951        mc_mac++;
11952    }
11953    rparam.mcast_list_len = mc_count;
11954
11955    BXE_MCAST_LOCK(sc);
11956
11957    /* first, clear all configured multicast MACs */
11958    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
11959    if (rc < 0) {
11960        BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
11961        BXE_MCAST_UNLOCK(sc);
11962    	free(mc_mac_start, M_DEVBUF);
11963        free(mta, M_DEVBUF);
11964        return (rc);
11965    }
11966
11967    /* Now add the new MACs */
11968    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
11969    if (rc < 0) {
11970        BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
11971    }
11972
11973    BXE_MCAST_UNLOCK(sc);
11974
11975    free(mc_mac_start, M_DEVBUF);
11976    free(mta, M_DEVBUF);
11977
11978    return (rc);
11979}
11980
11981static int
11982bxe_set_uc_list(struct bxe_softc *sc)
11983{
11984    if_t ifp = sc->ifp;
11985    struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
11986    struct ifaddr *ifa;
11987    unsigned long ramrod_flags = 0;
11988    int rc;
11989
11990#if __FreeBSD_version < 800000
11991    IF_ADDR_LOCK(ifp);
11992#else
11993    if_addr_rlock(ifp);
11994#endif
11995
11996    /* first schedule a cleanup up of old configuration */
11997    rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
11998    if (rc < 0) {
11999        BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12000#if __FreeBSD_version < 800000
12001        IF_ADDR_UNLOCK(ifp);
12002#else
12003        if_addr_runlock(ifp);
12004#endif
12005        return (rc);
12006    }
12007
12008    ifa = if_getifaddr(ifp); /* XXX Is this structure */
12009    while (ifa) {
12010        if (ifa->ifa_addr->sa_family != AF_LINK) {
12011            ifa = TAILQ_NEXT(ifa, ifa_link);
12012            continue;
12013        }
12014
12015        rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12016                             mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12017        if (rc == -EEXIST) {
12018            BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12019            /* do not treat adding same MAC as an error */
12020            rc = 0;
12021        } else if (rc < 0) {
12022            BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12023#if __FreeBSD_version < 800000
12024            IF_ADDR_UNLOCK(ifp);
12025#else
12026            if_addr_runlock(ifp);
12027#endif
12028            return (rc);
12029        }
12030
12031        ifa = TAILQ_NEXT(ifa, ifa_link);
12032    }
12033
12034#if __FreeBSD_version < 800000
12035    IF_ADDR_UNLOCK(ifp);
12036#else
12037    if_addr_runlock(ifp);
12038#endif
12039
12040    /* Execute the pending commands */
12041    bit_set(&ramrod_flags, RAMROD_CONT);
12042    return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12043                            ECORE_UC_LIST_MAC, &ramrod_flags));
12044}
12045
12046static void
12047bxe_set_rx_mode(struct bxe_softc *sc)
12048{
12049    if_t ifp = sc->ifp;
12050    uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12051
12052    if (sc->state != BXE_STATE_OPEN) {
12053        BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12054        return;
12055    }
12056
12057    BLOGD(sc, DBG_SP, "if_flags(ifp)=0x%x\n", if_getflags(sc->ifp));
12058
12059    if (if_getflags(ifp) & IFF_PROMISC) {
12060        rx_mode = BXE_RX_MODE_PROMISC;
12061    } else if ((if_getflags(ifp) & IFF_ALLMULTI) ||
12062               ((if_getamcount(ifp) > BXE_MAX_MULTICAST) &&
12063                CHIP_IS_E1(sc))) {
12064        rx_mode = BXE_RX_MODE_ALLMULTI;
12065    } else {
12066        if (IS_PF(sc)) {
12067            /* some multicasts */
12068            if (bxe_set_mc_list(sc) < 0) {
12069                rx_mode = BXE_RX_MODE_ALLMULTI;
12070            }
12071            if (bxe_set_uc_list(sc) < 0) {
12072                rx_mode = BXE_RX_MODE_PROMISC;
12073            }
12074        }
12075    }
12076
12077    sc->rx_mode = rx_mode;
12078
12079    /* schedule the rx_mode command */
12080    if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12081        BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12082        bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12083        return;
12084    }
12085
12086    if (IS_PF(sc)) {
12087        bxe_set_storm_rx_mode(sc);
12088    }
12089}
12090
12091
12092/* update flags in shmem */
12093static void
12094bxe_update_drv_flags(struct bxe_softc *sc,
12095                     uint32_t         flags,
12096                     uint32_t         set)
12097{
12098    uint32_t drv_flags;
12099
12100    if (SHMEM2_HAS(sc, drv_flags)) {
12101        bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12102        drv_flags = SHMEM2_RD(sc, drv_flags);
12103
12104        if (set) {
12105            SET_FLAGS(drv_flags, flags);
12106        } else {
12107            RESET_FLAGS(drv_flags, flags);
12108        }
12109
12110        SHMEM2_WR(sc, drv_flags, drv_flags);
12111        BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12112
12113        bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12114    }
12115}
12116
12117/* periodic timer callout routine, only runs when the interface is up */
12118
12119static void
12120bxe_periodic_callout_func(void *xsc)
12121{
12122    struct bxe_softc *sc = (struct bxe_softc *)xsc;
12123    struct bxe_fastpath *fp;
12124    uint16_t tx_bd_avail;
12125    int i;
12126
12127    if (!BXE_CORE_TRYLOCK(sc)) {
12128        /* just bail and try again next time */
12129
12130        if ((sc->state == BXE_STATE_OPEN) &&
12131            (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12132            /* schedule the next periodic callout */
12133            callout_reset(&sc->periodic_callout, hz,
12134                          bxe_periodic_callout_func, sc);
12135        }
12136
12137        return;
12138    }
12139
12140    if ((sc->state != BXE_STATE_OPEN) ||
12141        (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12142        BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12143        BXE_CORE_UNLOCK(sc);
12144        return;
12145    }
12146
12147#if __FreeBSD_version >= 800000
12148
12149    FOR_EACH_QUEUE(sc, i) {
12150        fp = &sc->fp[i];
12151
12152        if (BXE_FP_TX_TRYLOCK(fp)) {
12153            if_t ifp = sc->ifp;
12154            /*
12155             * If interface was stopped due to unavailable
12156             * bds, try to process some tx completions
12157             */
12158            (void) bxe_txeof(sc, fp);
12159
12160            tx_bd_avail = bxe_tx_avail(sc, fp);
12161            if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12162                bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
12163            }
12164            BXE_FP_TX_UNLOCK(fp);
12165        }
12166    }
12167
12168#else
12169
12170    fp = &sc->fp[0];
12171    if (BXE_FP_TX_TRYLOCK(fp)) {
12172        struct ifnet *ifp = sc->ifnet;
12173        /*
12174         * If interface was stopped due to unavailable
12175         * bds, try to process some tx completions
12176         */
12177        (void) bxe_txeof(sc, fp);
12178
12179        tx_bd_avail = bxe_tx_avail(sc, fp);
12180        if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12181            bxe_tx_start_locked(sc, ifp, fp);
12182        }
12183
12184        BXE_FP_TX_UNLOCK(fp);
12185    }
12186
12187#endif /* #if __FreeBSD_version >= 800000 */
12188
12189    /* Check for TX timeouts on any fastpath. */
12190    FOR_EACH_QUEUE(sc, i) {
12191        if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12192            /* Ruh-Roh, chip was reset! */
12193            break;
12194        }
12195    }
12196
12197    if (!CHIP_REV_IS_SLOW(sc)) {
12198        /*
12199         * This barrier is needed to ensure the ordering between the writing
12200         * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12201         * the reading here.
12202         */
12203        mb();
12204        if (sc->port.pmf) {
12205	    bxe_acquire_phy_lock(sc);
12206            elink_period_func(&sc->link_params, &sc->link_vars);
12207	    bxe_release_phy_lock(sc);
12208        }
12209    }
12210
12211    if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12212        int mb_idx = SC_FW_MB_IDX(sc);
12213        uint32_t drv_pulse;
12214        uint32_t mcp_pulse;
12215
12216        ++sc->fw_drv_pulse_wr_seq;
12217        sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12218
12219        drv_pulse = sc->fw_drv_pulse_wr_seq;
12220        bxe_drv_pulse(sc);
12221
12222        mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12223                     MCP_PULSE_SEQ_MASK);
12224
12225        /*
12226         * The delta between driver pulse and mcp response should
12227         * be 1 (before mcp response) or 0 (after mcp response).
12228         */
12229        if ((drv_pulse != mcp_pulse) &&
12230            (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12231            /* someone lost a heartbeat... */
12232            BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12233                  drv_pulse, mcp_pulse);
12234        }
12235    }
12236
12237    /* state is BXE_STATE_OPEN */
12238    bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12239
12240    BXE_CORE_UNLOCK(sc);
12241
12242    if ((sc->state == BXE_STATE_OPEN) &&
12243        (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12244        /* schedule the next periodic callout */
12245        callout_reset(&sc->periodic_callout, hz,
12246                      bxe_periodic_callout_func, sc);
12247    }
12248}
12249
12250static void
12251bxe_periodic_start(struct bxe_softc *sc)
12252{
12253    atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12254    callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12255}
12256
12257static void
12258bxe_periodic_stop(struct bxe_softc *sc)
12259{
12260    atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12261    callout_drain(&sc->periodic_callout);
12262}
12263
12264/* start the controller */
12265static __noinline int
12266bxe_nic_load(struct bxe_softc *sc,
12267             int              load_mode)
12268{
12269    uint32_t val;
12270    int load_code = 0;
12271    int i, rc = 0;
12272
12273    BXE_CORE_LOCK_ASSERT(sc);
12274
12275    BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12276
12277    sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12278
12279    if (IS_PF(sc)) {
12280        /* must be called before memory allocation and HW init */
12281        bxe_ilt_set_info(sc);
12282    }
12283
12284    sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12285
12286    bxe_set_fp_rx_buf_size(sc);
12287
12288    if (bxe_alloc_fp_buffers(sc) != 0) {
12289        BLOGE(sc, "Failed to allocate fastpath memory\n");
12290        sc->state = BXE_STATE_CLOSED;
12291        rc = ENOMEM;
12292        goto bxe_nic_load_error0;
12293    }
12294
12295    if (bxe_alloc_mem(sc) != 0) {
12296        sc->state = BXE_STATE_CLOSED;
12297        rc = ENOMEM;
12298        goto bxe_nic_load_error0;
12299    }
12300
12301    if (bxe_alloc_fw_stats_mem(sc) != 0) {
12302        sc->state = BXE_STATE_CLOSED;
12303        rc = ENOMEM;
12304        goto bxe_nic_load_error0;
12305    }
12306
12307    if (IS_PF(sc)) {
12308        /* set pf load just before approaching the MCP */
12309        bxe_set_pf_load(sc);
12310
12311        /* if MCP exists send load request and analyze response */
12312        if (!BXE_NOMCP(sc)) {
12313            /* attempt to load pf */
12314            if (bxe_nic_load_request(sc, &load_code) != 0) {
12315                sc->state = BXE_STATE_CLOSED;
12316                rc = ENXIO;
12317                goto bxe_nic_load_error1;
12318            }
12319
12320            /* what did the MCP say? */
12321            if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12322                bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12323                sc->state = BXE_STATE_CLOSED;
12324                rc = ENXIO;
12325                goto bxe_nic_load_error2;
12326            }
12327        } else {
12328            BLOGI(sc, "Device has no MCP!\n");
12329            load_code = bxe_nic_load_no_mcp(sc);
12330        }
12331
12332        /* mark PMF if applicable */
12333        bxe_nic_load_pmf(sc, load_code);
12334
12335        /* Init Function state controlling object */
12336        bxe_init_func_obj(sc);
12337
12338        /* Initialize HW */
12339        if (bxe_init_hw(sc, load_code) != 0) {
12340            BLOGE(sc, "HW init failed\n");
12341            bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12342            sc->state = BXE_STATE_CLOSED;
12343            rc = ENXIO;
12344            goto bxe_nic_load_error2;
12345        }
12346    }
12347
12348    /* set ALWAYS_ALIVE bit in shmem */
12349    sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12350    bxe_drv_pulse(sc);
12351    sc->flags |= BXE_NO_PULSE;
12352
12353    /* attach interrupts */
12354    if (bxe_interrupt_attach(sc) != 0) {
12355        sc->state = BXE_STATE_CLOSED;
12356        rc = ENXIO;
12357        goto bxe_nic_load_error2;
12358    }
12359
12360    bxe_nic_init(sc, load_code);
12361
12362    /* Init per-function objects */
12363    if (IS_PF(sc)) {
12364        bxe_init_objs(sc);
12365        // XXX bxe_iov_nic_init(sc);
12366
12367        /* set AFEX default VLAN tag to an invalid value */
12368        sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12369        // XXX bxe_nic_load_afex_dcc(sc, load_code);
12370
12371        sc->state = BXE_STATE_OPENING_WAITING_PORT;
12372        rc = bxe_func_start(sc);
12373        if (rc) {
12374            BLOGE(sc, "Function start failed! rc = %d\n", rc);
12375            bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12376            sc->state = BXE_STATE_ERROR;
12377            goto bxe_nic_load_error3;
12378        }
12379
12380        /* send LOAD_DONE command to MCP */
12381        if (!BXE_NOMCP(sc)) {
12382            load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12383            if (!load_code) {
12384                BLOGE(sc, "MCP response failure, aborting\n");
12385                sc->state = BXE_STATE_ERROR;
12386                rc = ENXIO;
12387                goto bxe_nic_load_error3;
12388            }
12389        }
12390
12391        rc = bxe_setup_leading(sc);
12392        if (rc) {
12393            BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12394            sc->state = BXE_STATE_ERROR;
12395            goto bxe_nic_load_error3;
12396        }
12397
12398        FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12399            rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12400            if (rc) {
12401                BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12402                sc->state = BXE_STATE_ERROR;
12403                goto bxe_nic_load_error3;
12404            }
12405        }
12406
12407        rc = bxe_init_rss_pf(sc);
12408        if (rc) {
12409            BLOGE(sc, "PF RSS init failed\n");
12410            sc->state = BXE_STATE_ERROR;
12411            goto bxe_nic_load_error3;
12412        }
12413    }
12414    /* XXX VF */
12415
12416    /* now when Clients are configured we are ready to work */
12417    sc->state = BXE_STATE_OPEN;
12418
12419    /* Configure a ucast MAC */
12420    if (IS_PF(sc)) {
12421        rc = bxe_set_eth_mac(sc, TRUE);
12422    }
12423    if (rc) {
12424        BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12425        sc->state = BXE_STATE_ERROR;
12426        goto bxe_nic_load_error3;
12427    }
12428
12429    if (sc->port.pmf) {
12430        rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12431        if (rc) {
12432            sc->state = BXE_STATE_ERROR;
12433            goto bxe_nic_load_error3;
12434        }
12435    }
12436
12437    sc->link_params.feature_config_flags &=
12438        ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12439
12440    /* start fast path */
12441
12442    /* Initialize Rx filter */
12443    bxe_set_rx_mode(sc);
12444
12445    /* start the Tx */
12446    switch (/* XXX load_mode */LOAD_OPEN) {
12447    case LOAD_NORMAL:
12448    case LOAD_OPEN:
12449        break;
12450
12451    case LOAD_DIAG:
12452    case LOAD_LOOPBACK_EXT:
12453        sc->state = BXE_STATE_DIAG;
12454        break;
12455
12456    default:
12457        break;
12458    }
12459
12460    if (sc->port.pmf) {
12461        bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12462    } else {
12463        bxe_link_status_update(sc);
12464    }
12465
12466    /* start the periodic timer callout */
12467    bxe_periodic_start(sc);
12468
12469    if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12470        /* mark driver is loaded in shmem2 */
12471        val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12472        SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12473                  (val |
12474                   DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12475                   DRV_FLAGS_CAPABILITIES_LOADED_L2));
12476    }
12477
12478    /* wait for all pending SP commands to complete */
12479    if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12480        BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12481        bxe_periodic_stop(sc);
12482        bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12483        return (ENXIO);
12484    }
12485
12486    /* Tell the stack the driver is running! */
12487    if_setdrvflags(sc->ifp, IFF_DRV_RUNNING);
12488
12489    BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12490
12491    return (0);
12492
12493bxe_nic_load_error3:
12494
12495    if (IS_PF(sc)) {
12496        bxe_int_disable_sync(sc, 1);
12497
12498        /* clean out queued objects */
12499        bxe_squeeze_objects(sc);
12500    }
12501
12502    bxe_interrupt_detach(sc);
12503
12504bxe_nic_load_error2:
12505
12506    if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12507        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12508        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12509    }
12510
12511    sc->port.pmf = 0;
12512
12513bxe_nic_load_error1:
12514
12515    /* clear pf_load status, as it was already set */
12516    if (IS_PF(sc)) {
12517        bxe_clear_pf_load(sc);
12518    }
12519
12520bxe_nic_load_error0:
12521
12522    bxe_free_fw_stats_mem(sc);
12523    bxe_free_fp_buffers(sc);
12524    bxe_free_mem(sc);
12525
12526    return (rc);
12527}
12528
12529static int
12530bxe_init_locked(struct bxe_softc *sc)
12531{
12532    int other_engine = SC_PATH(sc) ? 0 : 1;
12533    uint8_t other_load_status, load_status;
12534    uint8_t global = FALSE;
12535    int rc;
12536
12537    BXE_CORE_LOCK_ASSERT(sc);
12538
12539    /* check if the driver is already running */
12540    if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12541        BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12542        return (0);
12543    }
12544
12545    bxe_set_power_state(sc, PCI_PM_D0);
12546
12547    /*
12548     * If parity occurred during the unload, then attentions and/or
12549     * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12550     * loaded on the current engine to complete the recovery. Parity recovery
12551     * is only relevant for PF driver.
12552     */
12553    if (IS_PF(sc)) {
12554        other_load_status = bxe_get_load_status(sc, other_engine);
12555        load_status = bxe_get_load_status(sc, SC_PATH(sc));
12556
12557        if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12558            bxe_chk_parity_attn(sc, &global, TRUE)) {
12559            do {
12560                /*
12561                 * If there are attentions and they are in global blocks, set
12562                 * the GLOBAL_RESET bit regardless whether it will be this
12563                 * function that will complete the recovery or not.
12564                 */
12565                if (global) {
12566                    bxe_set_reset_global(sc);
12567                }
12568
12569                /*
12570                 * Only the first function on the current engine should try
12571                 * to recover in open. In case of attentions in global blocks
12572                 * only the first in the chip should try to recover.
12573                 */
12574                if ((!load_status && (!global || !other_load_status)) &&
12575                    bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12576                    BLOGI(sc, "Recovered during init\n");
12577                    break;
12578                }
12579
12580                /* recovery has failed... */
12581                bxe_set_power_state(sc, PCI_PM_D3hot);
12582                sc->recovery_state = BXE_RECOVERY_FAILED;
12583
12584                BLOGE(sc, "Recovery flow hasn't properly "
12585                          "completed yet, try again later. "
12586                          "If you still see this message after a "
12587                          "few retries then power cycle is required.\n");
12588
12589                rc = ENXIO;
12590                goto bxe_init_locked_done;
12591            } while (0);
12592        }
12593    }
12594
12595    sc->recovery_state = BXE_RECOVERY_DONE;
12596
12597    rc = bxe_nic_load(sc, LOAD_OPEN);
12598
12599bxe_init_locked_done:
12600
12601    if (rc) {
12602        /* Tell the stack the driver is NOT running! */
12603        BLOGE(sc, "Initialization failed, "
12604                  "stack notified driver is NOT running!\n");
12605	if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
12606    }
12607
12608    return (rc);
12609}
12610
12611static int
12612bxe_stop_locked(struct bxe_softc *sc)
12613{
12614    BXE_CORE_LOCK_ASSERT(sc);
12615    return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12616}
12617
12618/*
12619 * Handles controller initialization when called from an unlocked routine.
12620 * ifconfig calls this function.
12621 *
12622 * Returns:
12623 *   void
12624 */
12625static void
12626bxe_init(void *xsc)
12627{
12628    struct bxe_softc *sc = (struct bxe_softc *)xsc;
12629
12630    BXE_CORE_LOCK(sc);
12631    bxe_init_locked(sc);
12632    BXE_CORE_UNLOCK(sc);
12633}
12634
12635static int
12636bxe_init_ifnet(struct bxe_softc *sc)
12637{
12638    if_t ifp;
12639    int capabilities;
12640
12641    /* ifconfig entrypoint for media type/status reporting */
12642    ifmedia_init(&sc->ifmedia, IFM_IMASK,
12643                 bxe_ifmedia_update,
12644                 bxe_ifmedia_status);
12645
12646    /* set the default interface values */
12647    ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12648    ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12649    ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12650
12651    sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12652
12653    /* allocate the ifnet structure */
12654    if ((ifp = if_gethandle(IFT_ETHER)) == NULL) {
12655        BLOGE(sc, "Interface allocation failed!\n");
12656        return (ENXIO);
12657    }
12658
12659    if_setsoftc(ifp, sc);
12660    if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12661    if_setflags(ifp, (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST));
12662    if_setioctlfn(ifp, bxe_ioctl);
12663    if_setstartfn(ifp, bxe_tx_start);
12664    if_setgetcounterfn(ifp, bxe_get_counter);
12665#if __FreeBSD_version >= 800000
12666    if_settransmitfn(ifp, bxe_tx_mq_start);
12667    if_setqflushfn(ifp, bxe_mq_flush);
12668#endif
12669#ifdef FreeBSD8_0
12670    if_settimer(ifp, 0);
12671#endif
12672    if_setinitfn(ifp, bxe_init);
12673    if_setmtu(ifp, sc->mtu);
12674    if_sethwassist(ifp, (CSUM_IP      |
12675                        CSUM_TCP      |
12676                        CSUM_UDP      |
12677                        CSUM_TSO      |
12678                        CSUM_TCP_IPV6 |
12679                        CSUM_UDP_IPV6));
12680
12681    capabilities =
12682#if __FreeBSD_version < 700000
12683        (IFCAP_VLAN_MTU       |
12684         IFCAP_VLAN_HWTAGGING |
12685         IFCAP_HWCSUM         |
12686         IFCAP_JUMBO_MTU      |
12687         IFCAP_LRO);
12688#else
12689        (IFCAP_VLAN_MTU       |
12690         IFCAP_VLAN_HWTAGGING |
12691         IFCAP_VLAN_HWTSO     |
12692         IFCAP_VLAN_HWFILTER  |
12693         IFCAP_VLAN_HWCSUM    |
12694         IFCAP_HWCSUM         |
12695         IFCAP_JUMBO_MTU      |
12696         IFCAP_LRO            |
12697         IFCAP_TSO4           |
12698         IFCAP_TSO6           |
12699         IFCAP_WOL_MAGIC);
12700#endif
12701    if_setcapabilitiesbit(ifp, capabilities, 0); /* XXX */
12702    if_setbaudrate(ifp, IF_Gbps(10));
12703/* XXX */
12704    if_setsendqlen(ifp, sc->tx_ring_size);
12705    if_setsendqready(ifp);
12706/* XXX */
12707
12708    sc->ifp = ifp;
12709
12710    /* attach to the Ethernet interface list */
12711    ether_ifattach(ifp, sc->link_params.mac_addr);
12712
12713    return (0);
12714}
12715
12716static void
12717bxe_deallocate_bars(struct bxe_softc *sc)
12718{
12719    int i;
12720
12721    for (i = 0; i < MAX_BARS; i++) {
12722        if (sc->bar[i].resource != NULL) {
12723            bus_release_resource(sc->dev,
12724                                 SYS_RES_MEMORY,
12725                                 sc->bar[i].rid,
12726                                 sc->bar[i].resource);
12727            BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12728                  i, PCIR_BAR(i));
12729        }
12730    }
12731}
12732
12733static int
12734bxe_allocate_bars(struct bxe_softc *sc)
12735{
12736    u_int flags;
12737    int i;
12738
12739    memset(sc->bar, 0, sizeof(sc->bar));
12740
12741    for (i = 0; i < MAX_BARS; i++) {
12742
12743        /* memory resources reside at BARs 0, 2, 4 */
12744        /* Run `pciconf -lb` to see mappings */
12745        if ((i != 0) && (i != 2) && (i != 4)) {
12746            continue;
12747        }
12748
12749        sc->bar[i].rid = PCIR_BAR(i);
12750
12751        flags = RF_ACTIVE;
12752        if (i == 0) {
12753            flags |= RF_SHAREABLE;
12754        }
12755
12756        if ((sc->bar[i].resource =
12757             bus_alloc_resource_any(sc->dev,
12758                                    SYS_RES_MEMORY,
12759                                    &sc->bar[i].rid,
12760                                    flags)) == NULL) {
12761            return (0);
12762        }
12763
12764        sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12765        sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12766        sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12767
12768        BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%jd) -> %p\n",
12769              i, PCIR_BAR(i),
12770              (void *)rman_get_start(sc->bar[i].resource),
12771              (void *)rman_get_end(sc->bar[i].resource),
12772              rman_get_size(sc->bar[i].resource),
12773              (void *)sc->bar[i].kva);
12774    }
12775
12776    return (0);
12777}
12778
12779static void
12780bxe_get_function_num(struct bxe_softc *sc)
12781{
12782    uint32_t val = 0;
12783
12784    /*
12785     * Read the ME register to get the function number. The ME register
12786     * holds the relative-function number and absolute-function number. The
12787     * absolute-function number appears only in E2 and above. Before that
12788     * these bits always contained zero, therefore we cannot blindly use them.
12789     */
12790
12791    val = REG_RD(sc, BAR_ME_REGISTER);
12792
12793    sc->pfunc_rel =
12794        (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12795    sc->path_id =
12796        (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12797
12798    if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12799        sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12800    } else {
12801        sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12802    }
12803
12804    BLOGD(sc, DBG_LOAD,
12805          "Relative function %d, Absolute function %d, Path %d\n",
12806          sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12807}
12808
12809static uint32_t
12810bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12811{
12812    uint32_t shmem2_size;
12813    uint32_t offset;
12814    uint32_t mf_cfg_offset_value;
12815
12816    /* Non 57712 */
12817    offset = (SHMEM_RD(sc, func_mb) +
12818              (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12819
12820    /* 57712 plus */
12821    if (sc->devinfo.shmem2_base != 0) {
12822        shmem2_size = SHMEM2_RD(sc, size);
12823        if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12824            mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12825            if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12826                offset = mf_cfg_offset_value;
12827            }
12828        }
12829    }
12830
12831    return (offset);
12832}
12833
12834static uint32_t
12835bxe_pcie_capability_read(struct bxe_softc *sc,
12836                         int    reg,
12837                         int    width)
12838{
12839    int pcie_reg;
12840
12841    /* ensure PCIe capability is enabled */
12842    if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12843        if (pcie_reg != 0) {
12844            BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12845            return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12846        }
12847    }
12848
12849    BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12850
12851    return (0);
12852}
12853
12854static uint8_t
12855bxe_is_pcie_pending(struct bxe_softc *sc)
12856{
12857    return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12858            PCIM_EXP_STA_TRANSACTION_PND);
12859}
12860
12861/*
12862 * Walk the PCI capabiites list for the device to find what features are
12863 * supported. These capabilites may be enabled/disabled by firmware so it's
12864 * best to walk the list rather than make assumptions.
12865 */
12866static void
12867bxe_probe_pci_caps(struct bxe_softc *sc)
12868{
12869    uint16_t link_status;
12870    int reg;
12871
12872    /* check if PCI Power Management is enabled */
12873    if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
12874        if (reg != 0) {
12875            BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
12876
12877            sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
12878            sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
12879        }
12880    }
12881
12882    link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
12883
12884    /* handle PCIe 2.0 workarounds for 57710 */
12885    if (CHIP_IS_E1(sc)) {
12886        /* workaround for 57710 errata E4_57710_27462 */
12887        sc->devinfo.pcie_link_speed =
12888            (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
12889
12890        /* workaround for 57710 errata E4_57710_27488 */
12891        sc->devinfo.pcie_link_width =
12892            ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12893        if (sc->devinfo.pcie_link_speed > 1) {
12894            sc->devinfo.pcie_link_width =
12895                ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
12896        }
12897    } else {
12898        sc->devinfo.pcie_link_speed =
12899            (link_status & PCIM_LINK_STA_SPEED);
12900        sc->devinfo.pcie_link_width =
12901            ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12902    }
12903
12904    BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
12905          sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
12906
12907    sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
12908    sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
12909
12910    /* check if MSI capability is enabled */
12911    if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
12912        if (reg != 0) {
12913            BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
12914
12915            sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
12916            sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
12917        }
12918    }
12919
12920    /* check if MSI-X capability is enabled */
12921    if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
12922        if (reg != 0) {
12923            BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
12924
12925            sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
12926            sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
12927        }
12928    }
12929}
12930
12931static int
12932bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
12933{
12934    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
12935    uint32_t val;
12936
12937    /* get the outer vlan if we're in switch-dependent mode */
12938
12939    val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
12940    mf_info->ext_id = (uint16_t)val;
12941
12942    mf_info->multi_vnics_mode = 1;
12943
12944    if (!VALID_OVLAN(mf_info->ext_id)) {
12945        BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
12946        return (1);
12947    }
12948
12949    /* get the capabilities */
12950    if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
12951        FUNC_MF_CFG_PROTOCOL_ISCSI) {
12952        mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
12953    } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
12954               FUNC_MF_CFG_PROTOCOL_FCOE) {
12955        mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
12956    } else {
12957        mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
12958    }
12959
12960    mf_info->vnics_per_port =
12961        (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
12962
12963    return (0);
12964}
12965
12966static uint32_t
12967bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
12968{
12969    uint32_t retval = 0;
12970    uint32_t val;
12971
12972    val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
12973
12974    if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
12975        if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
12976            retval |= MF_PROTO_SUPPORT_ETHERNET;
12977        }
12978        if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
12979            retval |= MF_PROTO_SUPPORT_ISCSI;
12980        }
12981        if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
12982            retval |= MF_PROTO_SUPPORT_FCOE;
12983        }
12984    }
12985
12986    return (retval);
12987}
12988
12989static int
12990bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
12991{
12992    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
12993    uint32_t val;
12994
12995    /*
12996     * There is no outer vlan if we're in switch-independent mode.
12997     * If the mac is valid then assume multi-function.
12998     */
12999
13000    val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13001
13002    mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13003
13004    mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13005
13006    mf_info->vnics_per_port =
13007        (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13008
13009    return (0);
13010}
13011
13012static int
13013bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13014{
13015    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13016    uint32_t e1hov_tag;
13017    uint32_t func_config;
13018    uint32_t niv_config;
13019
13020    mf_info->multi_vnics_mode = 1;
13021
13022    e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13023    func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13024    niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13025
13026    mf_info->ext_id =
13027        (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13028                   FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13029
13030    mf_info->default_vlan =
13031        (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13032                   FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13033
13034    mf_info->niv_allowed_priorities =
13035        (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13036                  FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13037
13038    mf_info->niv_default_cos =
13039        (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13040                  FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13041
13042    mf_info->afex_vlan_mode =
13043        ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13044         FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13045
13046    mf_info->niv_mba_enabled =
13047        ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13048         FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13049
13050    mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13051
13052    mf_info->vnics_per_port =
13053        (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13054
13055    return (0);
13056}
13057
13058static int
13059bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13060{
13061    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13062    uint32_t mf_cfg1;
13063    uint32_t mf_cfg2;
13064    uint32_t ovlan1;
13065    uint32_t ovlan2;
13066    uint8_t i, j;
13067
13068    BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13069          SC_PORT(sc));
13070    BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13071          mf_info->mf_config[SC_VN(sc)]);
13072    BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13073          mf_info->multi_vnics_mode);
13074    BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13075          mf_info->vnics_per_port);
13076    BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13077          mf_info->ext_id);
13078    BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13079          mf_info->min_bw[0], mf_info->min_bw[1],
13080          mf_info->min_bw[2], mf_info->min_bw[3]);
13081    BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13082          mf_info->max_bw[0], mf_info->max_bw[1],
13083          mf_info->max_bw[2], mf_info->max_bw[3]);
13084    BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13085          sc->mac_addr_str);
13086
13087    /* various MF mode sanity checks... */
13088
13089    if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13090        BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13091              SC_PORT(sc));
13092        return (1);
13093    }
13094
13095    if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13096        BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13097              mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13098        return (1);
13099    }
13100
13101    if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13102        /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13103        if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13104            BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13105                  SC_VN(sc), OVLAN(sc));
13106            return (1);
13107        }
13108
13109        if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13110            BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13111                  mf_info->multi_vnics_mode, OVLAN(sc));
13112            return (1);
13113        }
13114
13115        /*
13116         * Verify all functions are either MF or SF mode. If MF, make sure
13117         * sure that all non-hidden functions have a valid ovlan. If SF,
13118         * make sure that all non-hidden functions have an invalid ovlan.
13119         */
13120        FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13121            mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13122            ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13123            if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13124                (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13125                 ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13126                BLOGE(sc, "mf_mode=SD function %d MF config "
13127                          "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13128                      i, mf_info->multi_vnics_mode, ovlan1);
13129                return (1);
13130            }
13131        }
13132
13133        /* Verify all funcs on the same port each have a different ovlan. */
13134        FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13135            mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13136            ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13137            /* iterate from the next function on the port to the max func */
13138            for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13139                mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13140                ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13141                if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13142                    VALID_OVLAN(ovlan1) &&
13143                    !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13144                    VALID_OVLAN(ovlan2) &&
13145                    (ovlan1 == ovlan2)) {
13146                    BLOGE(sc, "mf_mode=SD functions %d and %d "
13147                              "have the same ovlan (%d)\n",
13148                          i, j, ovlan1);
13149                    return (1);
13150                }
13151            }
13152        }
13153    } /* MULTI_FUNCTION_SD */
13154
13155    return (0);
13156}
13157
13158static int
13159bxe_get_mf_cfg_info(struct bxe_softc *sc)
13160{
13161    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13162    uint32_t val, mac_upper;
13163    uint8_t i, vnic;
13164
13165    /* initialize mf_info defaults */
13166    mf_info->vnics_per_port   = 1;
13167    mf_info->multi_vnics_mode = FALSE;
13168    mf_info->path_has_ovlan   = FALSE;
13169    mf_info->mf_mode          = SINGLE_FUNCTION;
13170
13171    if (!CHIP_IS_MF_CAP(sc)) {
13172        return (0);
13173    }
13174
13175    if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13176        BLOGE(sc, "Invalid mf_cfg_base!\n");
13177        return (1);
13178    }
13179
13180    /* get the MF mode (switch dependent / independent / single-function) */
13181
13182    val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13183
13184    switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13185    {
13186    case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13187
13188        mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13189
13190        /* check for legal upper mac bytes */
13191        if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13192            mf_info->mf_mode = MULTI_FUNCTION_SI;
13193        } else {
13194            BLOGE(sc, "Invalid config for Switch Independent mode\n");
13195        }
13196
13197        break;
13198
13199    case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13200    case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13201
13202        /* get outer vlan configuration */
13203        val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13204
13205        if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13206            FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13207            mf_info->mf_mode = MULTI_FUNCTION_SD;
13208        } else {
13209            BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13210        }
13211
13212        break;
13213
13214    case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13215
13216        /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13217        return (0);
13218
13219    case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13220
13221        /*
13222         * Mark MF mode as NIV if MCP version includes NPAR-SD support
13223         * and the MAC address is valid.
13224         */
13225        mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13226
13227        if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13228            (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13229            mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13230        } else {
13231            BLOGE(sc, "Invalid config for AFEX mode\n");
13232        }
13233
13234        break;
13235
13236    default:
13237
13238        BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13239              (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13240
13241        return (1);
13242    }
13243
13244    /* set path mf_mode (which could be different than function mf_mode) */
13245    if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13246        mf_info->path_has_ovlan = TRUE;
13247    } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13248        /*
13249         * Decide on path multi vnics mode. If we're not in MF mode and in
13250         * 4-port mode, this is good enough to check vnic-0 of the other port
13251         * on the same path
13252         */
13253        if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13254            uint8_t other_port = !(PORT_ID(sc) & 1);
13255            uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13256
13257            val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13258
13259            mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13260        }
13261    }
13262
13263    if (mf_info->mf_mode == SINGLE_FUNCTION) {
13264        /* invalid MF config */
13265        if (SC_VN(sc) >= 1) {
13266            BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13267            return (1);
13268        }
13269
13270        return (0);
13271    }
13272
13273    /* get the MF configuration */
13274    mf_info->mf_config[SC_VN(sc)] =
13275        MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13276
13277    switch(mf_info->mf_mode)
13278    {
13279    case MULTI_FUNCTION_SD:
13280
13281        bxe_get_shmem_mf_cfg_info_sd(sc);
13282        break;
13283
13284    case MULTI_FUNCTION_SI:
13285
13286        bxe_get_shmem_mf_cfg_info_si(sc);
13287        break;
13288
13289    case MULTI_FUNCTION_AFEX:
13290
13291        bxe_get_shmem_mf_cfg_info_niv(sc);
13292        break;
13293
13294    default:
13295
13296        BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13297              mf_info->mf_mode);
13298        return (1);
13299    }
13300
13301    /* get the congestion management parameters */
13302
13303    vnic = 0;
13304    FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13305        /* get min/max bw */
13306        val = MFCFG_RD(sc, func_mf_config[i].config);
13307        mf_info->min_bw[vnic] =
13308            ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13309        mf_info->max_bw[vnic] =
13310            ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13311        vnic++;
13312    }
13313
13314    return (bxe_check_valid_mf_cfg(sc));
13315}
13316
13317static int
13318bxe_get_shmem_info(struct bxe_softc *sc)
13319{
13320    int port;
13321    uint32_t mac_hi, mac_lo, val;
13322
13323    port = SC_PORT(sc);
13324    mac_hi = mac_lo = 0;
13325
13326    sc->link_params.sc   = sc;
13327    sc->link_params.port = port;
13328
13329    /* get the hardware config info */
13330    sc->devinfo.hw_config =
13331        SHMEM_RD(sc, dev_info.shared_hw_config.config);
13332    sc->devinfo.hw_config2 =
13333        SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13334
13335    sc->link_params.hw_led_mode =
13336        ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13337         SHARED_HW_CFG_LED_MODE_SHIFT);
13338
13339    /* get the port feature config */
13340    sc->port.config =
13341        SHMEM_RD(sc, dev_info.port_feature_config[port].config),
13342
13343    /* get the link params */
13344    sc->link_params.speed_cap_mask[0] =
13345        SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13346    sc->link_params.speed_cap_mask[1] =
13347        SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13348
13349    /* get the lane config */
13350    sc->link_params.lane_config =
13351        SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13352
13353    /* get the link config */
13354    val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13355    sc->port.link_config[ELINK_INT_PHY] = val;
13356    sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13357    sc->port.link_config[ELINK_EXT_PHY1] =
13358        SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13359
13360    /* get the override preemphasis flag and enable it or turn it off */
13361    val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13362    if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13363        sc->link_params.feature_config_flags |=
13364            ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13365    } else {
13366        sc->link_params.feature_config_flags &=
13367            ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13368    }
13369
13370    /* get the initial value of the link params */
13371    sc->link_params.multi_phy_config =
13372        SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13373
13374    /* get external phy info */
13375    sc->port.ext_phy_config =
13376        SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13377
13378    /* get the multifunction configuration */
13379    bxe_get_mf_cfg_info(sc);
13380
13381    /* get the mac address */
13382    if (IS_MF(sc)) {
13383        mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13384        mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13385    } else {
13386        mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13387        mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13388    }
13389
13390    if ((mac_lo == 0) && (mac_hi == 0)) {
13391        *sc->mac_addr_str = 0;
13392        BLOGE(sc, "No Ethernet address programmed!\n");
13393    } else {
13394        sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13395        sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13396        sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13397        sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13398        sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13399        sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13400        snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13401                 "%02x:%02x:%02x:%02x:%02x:%02x",
13402                 sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13403                 sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13404                 sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13405        BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13406    }
13407
13408    return (0);
13409}
13410
13411static void
13412bxe_get_tunable_params(struct bxe_softc *sc)
13413{
13414    /* sanity checks */
13415
13416    if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13417        (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13418        (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13419        BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13420        bxe_interrupt_mode = INTR_MODE_MSIX;
13421    }
13422
13423    if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13424        BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13425        bxe_queue_count = 0;
13426    }
13427
13428    if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13429        if (bxe_max_rx_bufs == 0) {
13430            bxe_max_rx_bufs = RX_BD_USABLE;
13431        } else {
13432            BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13433            bxe_max_rx_bufs = 2048;
13434        }
13435    }
13436
13437    if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13438        BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13439        bxe_hc_rx_ticks = 25;
13440    }
13441
13442    if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13443        BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13444        bxe_hc_tx_ticks = 50;
13445    }
13446
13447    if (bxe_max_aggregation_size == 0) {
13448        bxe_max_aggregation_size = TPA_AGG_SIZE;
13449    }
13450
13451    if (bxe_max_aggregation_size > 0xffff) {
13452        BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13453              bxe_max_aggregation_size);
13454        bxe_max_aggregation_size = TPA_AGG_SIZE;
13455    }
13456
13457    if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13458        BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13459        bxe_mrrs = -1;
13460    }
13461
13462    if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13463        BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13464        bxe_autogreeen = 0;
13465    }
13466
13467    if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13468        BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13469        bxe_udp_rss = 0;
13470    }
13471
13472    /* pull in user settings */
13473
13474    sc->interrupt_mode       = bxe_interrupt_mode;
13475    sc->max_rx_bufs          = bxe_max_rx_bufs;
13476    sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13477    sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13478    sc->max_aggregation_size = bxe_max_aggregation_size;
13479    sc->mrrs                 = bxe_mrrs;
13480    sc->autogreeen           = bxe_autogreeen;
13481    sc->udp_rss              = bxe_udp_rss;
13482
13483    if (bxe_interrupt_mode == INTR_MODE_INTX) {
13484        sc->num_queues = 1;
13485    } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13486        sc->num_queues =
13487            min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13488                MAX_RSS_CHAINS);
13489        if (sc->num_queues > mp_ncpus) {
13490            sc->num_queues = mp_ncpus;
13491        }
13492    }
13493
13494    BLOGD(sc, DBG_LOAD,
13495          "User Config: "
13496          "debug=0x%lx "
13497          "interrupt_mode=%d "
13498          "queue_count=%d "
13499          "hc_rx_ticks=%d "
13500          "hc_tx_ticks=%d "
13501          "rx_budget=%d "
13502          "max_aggregation_size=%d "
13503          "mrrs=%d "
13504          "autogreeen=%d "
13505          "udp_rss=%d\n",
13506          bxe_debug,
13507          sc->interrupt_mode,
13508          sc->num_queues,
13509          sc->hc_rx_ticks,
13510          sc->hc_tx_ticks,
13511          bxe_rx_budget,
13512          sc->max_aggregation_size,
13513          sc->mrrs,
13514          sc->autogreeen,
13515          sc->udp_rss);
13516}
13517
13518static int
13519bxe_media_detect(struct bxe_softc *sc)
13520{
13521    int port_type;
13522    uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13523
13524    switch (sc->link_params.phy[phy_idx].media_type) {
13525    case ELINK_ETH_PHY_SFPP_10G_FIBER:
13526    case ELINK_ETH_PHY_XFP_FIBER:
13527        BLOGI(sc, "Found 10Gb Fiber media.\n");
13528        sc->media = IFM_10G_SR;
13529        port_type = PORT_FIBRE;
13530        break;
13531    case ELINK_ETH_PHY_SFP_1G_FIBER:
13532        BLOGI(sc, "Found 1Gb Fiber media.\n");
13533        sc->media = IFM_1000_SX;
13534        port_type = PORT_FIBRE;
13535        break;
13536    case ELINK_ETH_PHY_KR:
13537    case ELINK_ETH_PHY_CX4:
13538        BLOGI(sc, "Found 10GBase-CX4 media.\n");
13539        sc->media = IFM_10G_CX4;
13540        port_type = PORT_FIBRE;
13541        break;
13542    case ELINK_ETH_PHY_DA_TWINAX:
13543        BLOGI(sc, "Found 10Gb Twinax media.\n");
13544        sc->media = IFM_10G_TWINAX;
13545        port_type = PORT_DA;
13546        break;
13547    case ELINK_ETH_PHY_BASE_T:
13548        if (sc->link_params.speed_cap_mask[0] &
13549            PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13550            BLOGI(sc, "Found 10GBase-T media.\n");
13551            sc->media = IFM_10G_T;
13552            port_type = PORT_TP;
13553        } else {
13554            BLOGI(sc, "Found 1000Base-T media.\n");
13555            sc->media = IFM_1000_T;
13556            port_type = PORT_TP;
13557        }
13558        break;
13559    case ELINK_ETH_PHY_NOT_PRESENT:
13560        BLOGI(sc, "Media not present.\n");
13561        sc->media = 0;
13562        port_type = PORT_OTHER;
13563        break;
13564    case ELINK_ETH_PHY_UNSPECIFIED:
13565    default:
13566        BLOGI(sc, "Unknown media!\n");
13567        sc->media = 0;
13568        port_type = PORT_OTHER;
13569        break;
13570    }
13571    return port_type;
13572}
13573
13574#define GET_FIELD(value, fname)                     \
13575    (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13576#define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13577#define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13578
13579static int
13580bxe_get_igu_cam_info(struct bxe_softc *sc)
13581{
13582    int pfid = SC_FUNC(sc);
13583    int igu_sb_id;
13584    uint32_t val;
13585    uint8_t fid, igu_sb_cnt = 0;
13586
13587    sc->igu_base_sb = 0xff;
13588
13589    if (CHIP_INT_MODE_IS_BC(sc)) {
13590        int vn = SC_VN(sc);
13591        igu_sb_cnt = sc->igu_sb_cnt;
13592        sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13593                           FP_SB_MAX_E1x);
13594        sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13595                          (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13596        return (0);
13597    }
13598
13599    /* IGU in normal mode - read CAM */
13600    for (igu_sb_id = 0;
13601         igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13602         igu_sb_id++) {
13603        val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13604        if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13605            continue;
13606        }
13607        fid = IGU_FID(val);
13608        if ((fid & IGU_FID_ENCODE_IS_PF)) {
13609            if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13610                continue;
13611            }
13612            if (IGU_VEC(val) == 0) {
13613                /* default status block */
13614                sc->igu_dsb_id = igu_sb_id;
13615            } else {
13616                if (sc->igu_base_sb == 0xff) {
13617                    sc->igu_base_sb = igu_sb_id;
13618                }
13619                igu_sb_cnt++;
13620            }
13621        }
13622    }
13623
13624    /*
13625     * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13626     * that number of CAM entries will not be equal to the value advertised in
13627     * PCI. Driver should use the minimal value of both as the actual status
13628     * block count
13629     */
13630    sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13631
13632    if (igu_sb_cnt == 0) {
13633        BLOGE(sc, "CAM configuration error\n");
13634        return (-1);
13635    }
13636
13637    return (0);
13638}
13639
13640/*
13641 * Gather various information from the device config space, the device itself,
13642 * shmem, and the user input.
13643 */
13644static int
13645bxe_get_device_info(struct bxe_softc *sc)
13646{
13647    uint32_t val;
13648    int rc;
13649
13650    /* Get the data for the device */
13651    sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13652    sc->devinfo.device_id    = pci_get_device(sc->dev);
13653    sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13654    sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13655
13656    /* get the chip revision (chip metal comes from pci config space) */
13657    sc->devinfo.chip_id     =
13658    sc->link_params.chip_id =
13659        (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13660         ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13661         (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13662         ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13663
13664    /* force 57811 according to MISC register */
13665    if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13666        if (CHIP_IS_57810(sc)) {
13667            sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13668                                   (sc->devinfo.chip_id & 0x0000ffff));
13669        } else if (CHIP_IS_57810_MF(sc)) {
13670            sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13671                                   (sc->devinfo.chip_id & 0x0000ffff));
13672        }
13673        sc->devinfo.chip_id |= 0x1;
13674    }
13675
13676    BLOGD(sc, DBG_LOAD,
13677          "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13678          sc->devinfo.chip_id,
13679          ((sc->devinfo.chip_id >> 16) & 0xffff),
13680          ((sc->devinfo.chip_id >> 12) & 0xf),
13681          ((sc->devinfo.chip_id >>  4) & 0xff),
13682          ((sc->devinfo.chip_id >>  0) & 0xf));
13683
13684    val = (REG_RD(sc, 0x2874) & 0x55);
13685    if ((sc->devinfo.chip_id & 0x1) ||
13686        (CHIP_IS_E1(sc) && val) ||
13687        (CHIP_IS_E1H(sc) && (val == 0x55))) {
13688        sc->flags |= BXE_ONE_PORT_FLAG;
13689        BLOGD(sc, DBG_LOAD, "single port device\n");
13690    }
13691
13692    /* set the doorbell size */
13693    sc->doorbell_size = (1 << BXE_DB_SHIFT);
13694
13695    /* determine whether the device is in 2 port or 4 port mode */
13696    sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13697    if (CHIP_IS_E2E3(sc)) {
13698        /*
13699         * Read port4mode_en_ovwr[0]:
13700         *   If 1, four port mode is in port4mode_en_ovwr[1].
13701         *   If 0, four port mode is in port4mode_en[0].
13702         */
13703        val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13704        if (val & 1) {
13705            val = ((val >> 1) & 1);
13706        } else {
13707            val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13708        }
13709
13710        sc->devinfo.chip_port_mode =
13711            (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13712
13713        BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13714    }
13715
13716    /* get the function and path info for the device */
13717    bxe_get_function_num(sc);
13718
13719    /* get the shared memory base address */
13720    sc->devinfo.shmem_base     =
13721    sc->link_params.shmem_base =
13722        REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13723    sc->devinfo.shmem2_base =
13724        REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13725                                  MISC_REG_GENERIC_CR_0));
13726
13727    BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13728          sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13729
13730    if (!sc->devinfo.shmem_base) {
13731        /* this should ONLY prevent upcoming shmem reads */
13732        BLOGI(sc, "MCP not active\n");
13733        sc->flags |= BXE_NO_MCP_FLAG;
13734        return (0);
13735    }
13736
13737    /* make sure the shared memory contents are valid */
13738    val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13739    if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13740        (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13741        BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13742        return (0);
13743    }
13744    BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13745
13746    /* get the bootcode version */
13747    sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13748    snprintf(sc->devinfo.bc_ver_str,
13749             sizeof(sc->devinfo.bc_ver_str),
13750             "%d.%d.%d",
13751             ((sc->devinfo.bc_ver >> 24) & 0xff),
13752             ((sc->devinfo.bc_ver >> 16) & 0xff),
13753             ((sc->devinfo.bc_ver >>  8) & 0xff));
13754    BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13755
13756    /* get the bootcode shmem address */
13757    sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13758    BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13759
13760    /* clean indirect addresses as they're not used */
13761    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13762    if (IS_PF(sc)) {
13763        REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13764        REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13765        REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13766        REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13767        if (CHIP_IS_E1x(sc)) {
13768            REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13769            REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13770            REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13771            REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13772        }
13773
13774        /*
13775         * Enable internal target-read (in case we are probed after PF
13776         * FLR). Must be done prior to any BAR read access. Only for
13777         * 57712 and up
13778         */
13779        if (!CHIP_IS_E1x(sc)) {
13780            REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13781        }
13782    }
13783
13784    /* get the nvram size */
13785    val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13786    sc->devinfo.flash_size =
13787        (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13788    BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13789
13790    /* get PCI capabilites */
13791    bxe_probe_pci_caps(sc);
13792
13793    bxe_set_power_state(sc, PCI_PM_D0);
13794
13795    /* get various configuration parameters from shmem */
13796    bxe_get_shmem_info(sc);
13797
13798    if (sc->devinfo.pcie_msix_cap_reg != 0) {
13799        val = pci_read_config(sc->dev,
13800                              (sc->devinfo.pcie_msix_cap_reg +
13801                               PCIR_MSIX_CTRL),
13802                              2);
13803        sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13804    } else {
13805        sc->igu_sb_cnt = 1;
13806    }
13807
13808    sc->igu_base_addr = BAR_IGU_INTMEM;
13809
13810    /* initialize IGU parameters */
13811    if (CHIP_IS_E1x(sc)) {
13812        sc->devinfo.int_block = INT_BLOCK_HC;
13813        sc->igu_dsb_id = DEF_SB_IGU_ID;
13814        sc->igu_base_sb = 0;
13815    } else {
13816        sc->devinfo.int_block = INT_BLOCK_IGU;
13817
13818        /* do not allow device reset during IGU info preocessing */
13819        bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13820
13821        val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13822
13823        if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13824            int tout = 5000;
13825
13826            BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13827
13828            val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13829            REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13830            REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13831
13832            while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13833                tout--;
13834                DELAY(1000);
13835            }
13836
13837            if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13838                BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13839                bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13840                return (-1);
13841            }
13842        }
13843
13844        if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13845            BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13846            sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13847        } else {
13848            BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13849        }
13850
13851        rc = bxe_get_igu_cam_info(sc);
13852
13853        bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13854
13855        if (rc) {
13856            return (rc);
13857        }
13858    }
13859
13860    /*
13861     * Get base FW non-default (fast path) status block ID. This value is
13862     * used to initialize the fw_sb_id saved on the fp/queue structure to
13863     * determine the id used by the FW.
13864     */
13865    if (CHIP_IS_E1x(sc)) {
13866        sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
13867    } else {
13868        /*
13869         * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
13870         * the same queue are indicated on the same IGU SB). So we prefer
13871         * FW and IGU SBs to be the same value.
13872         */
13873        sc->base_fw_ndsb = sc->igu_base_sb;
13874    }
13875
13876    BLOGD(sc, DBG_LOAD,
13877          "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
13878          sc->igu_dsb_id, sc->igu_base_sb,
13879          sc->igu_sb_cnt, sc->base_fw_ndsb);
13880
13881    elink_phy_probe(&sc->link_params);
13882
13883    return (0);
13884}
13885
13886static void
13887bxe_link_settings_supported(struct bxe_softc *sc,
13888                            uint32_t         switch_cfg)
13889{
13890    uint32_t cfg_size = 0;
13891    uint32_t idx;
13892    uint8_t port = SC_PORT(sc);
13893
13894    /* aggregation of supported attributes of all external phys */
13895    sc->port.supported[0] = 0;
13896    sc->port.supported[1] = 0;
13897
13898    switch (sc->link_params.num_phys) {
13899    case 1:
13900        sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
13901        cfg_size = 1;
13902        break;
13903    case 2:
13904        sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
13905        cfg_size = 1;
13906        break;
13907    case 3:
13908        if (sc->link_params.multi_phy_config &
13909            PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
13910            sc->port.supported[1] =
13911                sc->link_params.phy[ELINK_EXT_PHY1].supported;
13912            sc->port.supported[0] =
13913                sc->link_params.phy[ELINK_EXT_PHY2].supported;
13914        } else {
13915            sc->port.supported[0] =
13916                sc->link_params.phy[ELINK_EXT_PHY1].supported;
13917            sc->port.supported[1] =
13918                sc->link_params.phy[ELINK_EXT_PHY2].supported;
13919        }
13920        cfg_size = 2;
13921        break;
13922    }
13923
13924    if (!(sc->port.supported[0] || sc->port.supported[1])) {
13925        BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
13926              SHMEM_RD(sc,
13927                       dev_info.port_hw_config[port].external_phy_config),
13928              SHMEM_RD(sc,
13929                       dev_info.port_hw_config[port].external_phy_config2));
13930        return;
13931    }
13932
13933    if (CHIP_IS_E3(sc))
13934        sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
13935    else {
13936        switch (switch_cfg) {
13937        case ELINK_SWITCH_CFG_1G:
13938            sc->port.phy_addr =
13939                REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
13940            break;
13941        case ELINK_SWITCH_CFG_10G:
13942            sc->port.phy_addr =
13943                REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
13944            break;
13945        default:
13946            BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
13947                  sc->port.link_config[0]);
13948            return;
13949        }
13950    }
13951
13952    BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
13953
13954    /* mask what we support according to speed_cap_mask per configuration */
13955    for (idx = 0; idx < cfg_size; idx++) {
13956        if (!(sc->link_params.speed_cap_mask[idx] &
13957              PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
13958            sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
13959        }
13960
13961        if (!(sc->link_params.speed_cap_mask[idx] &
13962              PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
13963            sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
13964        }
13965
13966        if (!(sc->link_params.speed_cap_mask[idx] &
13967              PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
13968            sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
13969        }
13970
13971        if (!(sc->link_params.speed_cap_mask[idx] &
13972              PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
13973            sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
13974        }
13975
13976        if (!(sc->link_params.speed_cap_mask[idx] &
13977              PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
13978            sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
13979        }
13980
13981        if (!(sc->link_params.speed_cap_mask[idx] &
13982              PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
13983            sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
13984        }
13985
13986        if (!(sc->link_params.speed_cap_mask[idx] &
13987              PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
13988            sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
13989        }
13990
13991        if (!(sc->link_params.speed_cap_mask[idx] &
13992              PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
13993            sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
13994        }
13995    }
13996
13997    BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
13998          sc->port.supported[0], sc->port.supported[1]);
13999}
14000
14001static void
14002bxe_link_settings_requested(struct bxe_softc *sc)
14003{
14004    uint32_t link_config;
14005    uint32_t idx;
14006    uint32_t cfg_size = 0;
14007
14008    sc->port.advertising[0] = 0;
14009    sc->port.advertising[1] = 0;
14010
14011    switch (sc->link_params.num_phys) {
14012    case 1:
14013    case 2:
14014        cfg_size = 1;
14015        break;
14016    case 3:
14017        cfg_size = 2;
14018        break;
14019    }
14020
14021    for (idx = 0; idx < cfg_size; idx++) {
14022        sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14023        link_config = sc->port.link_config[idx];
14024
14025        switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14026        case PORT_FEATURE_LINK_SPEED_AUTO:
14027            if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14028                sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14029                sc->port.advertising[idx] |= sc->port.supported[idx];
14030                if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14031                    PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14032                    sc->port.advertising[idx] |=
14033                        (ELINK_SUPPORTED_100baseT_Half |
14034                         ELINK_SUPPORTED_100baseT_Full);
14035            } else {
14036                /* force 10G, no AN */
14037                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14038                sc->port.advertising[idx] |=
14039                    (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14040                continue;
14041            }
14042            break;
14043
14044        case PORT_FEATURE_LINK_SPEED_10M_FULL:
14045            if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14046                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14047                sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14048                                              ADVERTISED_TP);
14049            } else {
14050                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14051                          "speed_cap_mask=0x%08x\n",
14052                      link_config, sc->link_params.speed_cap_mask[idx]);
14053                return;
14054            }
14055            break;
14056
14057        case PORT_FEATURE_LINK_SPEED_10M_HALF:
14058            if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14059                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14060                sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14061                sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14062                                              ADVERTISED_TP);
14063            } else {
14064                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14065                          "speed_cap_mask=0x%08x\n",
14066                      link_config, sc->link_params.speed_cap_mask[idx]);
14067                return;
14068            }
14069            break;
14070
14071        case PORT_FEATURE_LINK_SPEED_100M_FULL:
14072            if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14073                sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14074                sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14075                                              ADVERTISED_TP);
14076            } else {
14077                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14078                          "speed_cap_mask=0x%08x\n",
14079                      link_config, sc->link_params.speed_cap_mask[idx]);
14080                return;
14081            }
14082            break;
14083
14084        case PORT_FEATURE_LINK_SPEED_100M_HALF:
14085            if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14086                sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14087                sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14088                sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14089                                              ADVERTISED_TP);
14090            } else {
14091                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14092                          "speed_cap_mask=0x%08x\n",
14093                      link_config, sc->link_params.speed_cap_mask[idx]);
14094                return;
14095            }
14096            break;
14097
14098        case PORT_FEATURE_LINK_SPEED_1G:
14099            if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14100                sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14101                sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14102                                              ADVERTISED_TP);
14103            } else {
14104                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14105                          "speed_cap_mask=0x%08x\n",
14106                      link_config, sc->link_params.speed_cap_mask[idx]);
14107                return;
14108            }
14109            break;
14110
14111        case PORT_FEATURE_LINK_SPEED_2_5G:
14112            if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14113                sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14114                sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14115                                              ADVERTISED_TP);
14116            } else {
14117                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14118                          "speed_cap_mask=0x%08x\n",
14119                      link_config, sc->link_params.speed_cap_mask[idx]);
14120                return;
14121            }
14122            break;
14123
14124        case PORT_FEATURE_LINK_SPEED_10G_CX4:
14125            if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14126                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14127                sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14128                                              ADVERTISED_FIBRE);
14129            } else {
14130                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14131                          "speed_cap_mask=0x%08x\n",
14132                      link_config, sc->link_params.speed_cap_mask[idx]);
14133                return;
14134            }
14135            break;
14136
14137        case PORT_FEATURE_LINK_SPEED_20G:
14138            sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14139            break;
14140
14141        default:
14142            BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14143                      "speed_cap_mask=0x%08x\n",
14144                  link_config, sc->link_params.speed_cap_mask[idx]);
14145            sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14146            sc->port.advertising[idx] = sc->port.supported[idx];
14147            break;
14148        }
14149
14150        sc->link_params.req_flow_ctrl[idx] =
14151            (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14152
14153        if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14154            if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14155                sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14156            } else {
14157                bxe_set_requested_fc(sc);
14158            }
14159        }
14160
14161        BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14162                            "req_flow_ctrl=0x%x advertising=0x%x\n",
14163              sc->link_params.req_line_speed[idx],
14164              sc->link_params.req_duplex[idx],
14165              sc->link_params.req_flow_ctrl[idx],
14166              sc->port.advertising[idx]);
14167    }
14168}
14169
14170static void
14171bxe_get_phy_info(struct bxe_softc *sc)
14172{
14173    uint8_t port = SC_PORT(sc);
14174    uint32_t config = sc->port.config;
14175    uint32_t eee_mode;
14176
14177    /* shmem data already read in bxe_get_shmem_info() */
14178
14179    BLOGD(sc, DBG_LOAD, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14180                        "link_config0=0x%08x\n",
14181               sc->link_params.lane_config,
14182               sc->link_params.speed_cap_mask[0],
14183               sc->port.link_config[0]);
14184
14185    bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14186    bxe_link_settings_requested(sc);
14187
14188    if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14189        sc->link_params.feature_config_flags |=
14190            ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14191    } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14192        sc->link_params.feature_config_flags &=
14193            ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14194    } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14195        sc->link_params.feature_config_flags |=
14196            ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14197    }
14198
14199    /* configure link feature according to nvram value */
14200    eee_mode =
14201        (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14202          PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14203         PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14204    if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14205        sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14206                                    ELINK_EEE_MODE_ENABLE_LPI |
14207                                    ELINK_EEE_MODE_OUTPUT_TIME);
14208    } else {
14209        sc->link_params.eee_mode = 0;
14210    }
14211
14212    /* get the media type */
14213    bxe_media_detect(sc);
14214}
14215
14216static void
14217bxe_get_params(struct bxe_softc *sc)
14218{
14219    /* get user tunable params */
14220    bxe_get_tunable_params(sc);
14221
14222    /* select the RX and TX ring sizes */
14223    sc->tx_ring_size = TX_BD_USABLE;
14224    sc->rx_ring_size = RX_BD_USABLE;
14225
14226    /* XXX disable WoL */
14227    sc->wol = 0;
14228}
14229
14230static void
14231bxe_set_modes_bitmap(struct bxe_softc *sc)
14232{
14233    uint32_t flags = 0;
14234
14235    if (CHIP_REV_IS_FPGA(sc)) {
14236        SET_FLAGS(flags, MODE_FPGA);
14237    } else if (CHIP_REV_IS_EMUL(sc)) {
14238        SET_FLAGS(flags, MODE_EMUL);
14239    } else {
14240        SET_FLAGS(flags, MODE_ASIC);
14241    }
14242
14243    if (CHIP_IS_MODE_4_PORT(sc)) {
14244        SET_FLAGS(flags, MODE_PORT4);
14245    } else {
14246        SET_FLAGS(flags, MODE_PORT2);
14247    }
14248
14249    if (CHIP_IS_E2(sc)) {
14250        SET_FLAGS(flags, MODE_E2);
14251    } else if (CHIP_IS_E3(sc)) {
14252        SET_FLAGS(flags, MODE_E3);
14253        if (CHIP_REV(sc) == CHIP_REV_Ax) {
14254            SET_FLAGS(flags, MODE_E3_A0);
14255        } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14256            SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14257        }
14258    }
14259
14260    if (IS_MF(sc)) {
14261        SET_FLAGS(flags, MODE_MF);
14262        switch (sc->devinfo.mf_info.mf_mode) {
14263        case MULTI_FUNCTION_SD:
14264            SET_FLAGS(flags, MODE_MF_SD);
14265            break;
14266        case MULTI_FUNCTION_SI:
14267            SET_FLAGS(flags, MODE_MF_SI);
14268            break;
14269        case MULTI_FUNCTION_AFEX:
14270            SET_FLAGS(flags, MODE_MF_AFEX);
14271            break;
14272        }
14273    } else {
14274        SET_FLAGS(flags, MODE_SF);
14275    }
14276
14277#if defined(__LITTLE_ENDIAN)
14278    SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14279#else /* __BIG_ENDIAN */
14280    SET_FLAGS(flags, MODE_BIG_ENDIAN);
14281#endif
14282
14283    INIT_MODE_FLAGS(sc) = flags;
14284}
14285
14286static int
14287bxe_alloc_hsi_mem(struct bxe_softc *sc)
14288{
14289    struct bxe_fastpath *fp;
14290    bus_addr_t busaddr;
14291    int max_agg_queues;
14292    int max_segments;
14293    bus_size_t max_size;
14294    bus_size_t max_seg_size;
14295    char buf[32];
14296    int rc;
14297    int i, j;
14298
14299    /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14300
14301    /* allocate the parent bus DMA tag */
14302    rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14303                            1,                        /* alignment */
14304                            0,                        /* boundary limit */
14305                            BUS_SPACE_MAXADDR,        /* restricted low */
14306                            BUS_SPACE_MAXADDR,        /* restricted hi */
14307                            NULL,                     /* addr filter() */
14308                            NULL,                     /* addr filter() arg */
14309                            BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14310                            BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14311                            BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14312                            0,                        /* flags */
14313                            NULL,                     /* lock() */
14314                            NULL,                     /* lock() arg */
14315                            &sc->parent_dma_tag);     /* returned dma tag */
14316    if (rc != 0) {
14317        BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14318        return (1);
14319    }
14320
14321    /************************/
14322    /* DEFAULT STATUS BLOCK */
14323    /************************/
14324
14325    if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14326                      &sc->def_sb_dma, "default status block") != 0) {
14327        /* XXX */
14328        bus_dma_tag_destroy(sc->parent_dma_tag);
14329        return (1);
14330    }
14331
14332    sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14333
14334    /***************/
14335    /* EVENT QUEUE */
14336    /***************/
14337
14338    if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14339                      &sc->eq_dma, "event queue") != 0) {
14340        /* XXX */
14341        bxe_dma_free(sc, &sc->def_sb_dma);
14342        sc->def_sb = NULL;
14343        bus_dma_tag_destroy(sc->parent_dma_tag);
14344        return (1);
14345    }
14346
14347    sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14348
14349    /*************/
14350    /* SLOW PATH */
14351    /*************/
14352
14353    if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14354                      &sc->sp_dma, "slow path") != 0) {
14355        /* XXX */
14356        bxe_dma_free(sc, &sc->eq_dma);
14357        sc->eq = NULL;
14358        bxe_dma_free(sc, &sc->def_sb_dma);
14359        sc->def_sb = NULL;
14360        bus_dma_tag_destroy(sc->parent_dma_tag);
14361        return (1);
14362    }
14363
14364    sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14365
14366    /*******************/
14367    /* SLOW PATH QUEUE */
14368    /*******************/
14369
14370    if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14371                      &sc->spq_dma, "slow path queue") != 0) {
14372        /* XXX */
14373        bxe_dma_free(sc, &sc->sp_dma);
14374        sc->sp = NULL;
14375        bxe_dma_free(sc, &sc->eq_dma);
14376        sc->eq = NULL;
14377        bxe_dma_free(sc, &sc->def_sb_dma);
14378        sc->def_sb = NULL;
14379        bus_dma_tag_destroy(sc->parent_dma_tag);
14380        return (1);
14381    }
14382
14383    sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14384
14385    /***************************/
14386    /* FW DECOMPRESSION BUFFER */
14387    /***************************/
14388
14389    if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14390                      "fw decompression buffer") != 0) {
14391        /* XXX */
14392        bxe_dma_free(sc, &sc->spq_dma);
14393        sc->spq = NULL;
14394        bxe_dma_free(sc, &sc->sp_dma);
14395        sc->sp = NULL;
14396        bxe_dma_free(sc, &sc->eq_dma);
14397        sc->eq = NULL;
14398        bxe_dma_free(sc, &sc->def_sb_dma);
14399        sc->def_sb = NULL;
14400        bus_dma_tag_destroy(sc->parent_dma_tag);
14401        return (1);
14402    }
14403
14404    sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14405
14406    if ((sc->gz_strm =
14407         malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14408        /* XXX */
14409        bxe_dma_free(sc, &sc->gz_buf_dma);
14410        sc->gz_buf = NULL;
14411        bxe_dma_free(sc, &sc->spq_dma);
14412        sc->spq = NULL;
14413        bxe_dma_free(sc, &sc->sp_dma);
14414        sc->sp = NULL;
14415        bxe_dma_free(sc, &sc->eq_dma);
14416        sc->eq = NULL;
14417        bxe_dma_free(sc, &sc->def_sb_dma);
14418        sc->def_sb = NULL;
14419        bus_dma_tag_destroy(sc->parent_dma_tag);
14420        return (1);
14421    }
14422
14423    /*************/
14424    /* FASTPATHS */
14425    /*************/
14426
14427    /* allocate DMA memory for each fastpath structure */
14428    for (i = 0; i < sc->num_queues; i++) {
14429        fp = &sc->fp[i];
14430        fp->sc    = sc;
14431        fp->index = i;
14432
14433        /*******************/
14434        /* FP STATUS BLOCK */
14435        /*******************/
14436
14437        snprintf(buf, sizeof(buf), "fp %d status block", i);
14438        if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14439                          &fp->sb_dma, buf) != 0) {
14440            /* XXX unwind and free previous fastpath allocations */
14441            BLOGE(sc, "Failed to alloc %s\n", buf);
14442            return (1);
14443        } else {
14444            if (CHIP_IS_E2E3(sc)) {
14445                fp->status_block.e2_sb =
14446                    (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14447            } else {
14448                fp->status_block.e1x_sb =
14449                    (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14450            }
14451        }
14452
14453        /******************/
14454        /* FP TX BD CHAIN */
14455        /******************/
14456
14457        snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14458        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14459                          &fp->tx_dma, buf) != 0) {
14460            /* XXX unwind and free previous fastpath allocations */
14461            BLOGE(sc, "Failed to alloc %s\n", buf);
14462            return (1);
14463        } else {
14464            fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14465        }
14466
14467        /* link together the tx bd chain pages */
14468        for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14469            /* index into the tx bd chain array to last entry per page */
14470            struct eth_tx_next_bd *tx_next_bd =
14471                &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14472            /* point to the next page and wrap from last page */
14473            busaddr = (fp->tx_dma.paddr +
14474                       (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14475            tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14476            tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14477        }
14478
14479        /******************/
14480        /* FP RX BD CHAIN */
14481        /******************/
14482
14483        snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14484        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14485                          &fp->rx_dma, buf) != 0) {
14486            /* XXX unwind and free previous fastpath allocations */
14487            BLOGE(sc, "Failed to alloc %s\n", buf);
14488            return (1);
14489        } else {
14490            fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14491        }
14492
14493        /* link together the rx bd chain pages */
14494        for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14495            /* index into the rx bd chain array to last entry per page */
14496            struct eth_rx_bd *rx_bd =
14497                &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14498            /* point to the next page and wrap from last page */
14499            busaddr = (fp->rx_dma.paddr +
14500                       (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14501            rx_bd->addr_hi = htole32(U64_HI(busaddr));
14502            rx_bd->addr_lo = htole32(U64_LO(busaddr));
14503        }
14504
14505        /*******************/
14506        /* FP RX RCQ CHAIN */
14507        /*******************/
14508
14509        snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14510        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14511                          &fp->rcq_dma, buf) != 0) {
14512            /* XXX unwind and free previous fastpath allocations */
14513            BLOGE(sc, "Failed to alloc %s\n", buf);
14514            return (1);
14515        } else {
14516            fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14517        }
14518
14519        /* link together the rcq chain pages */
14520        for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14521            /* index into the rcq chain array to last entry per page */
14522            struct eth_rx_cqe_next_page *rx_cqe_next =
14523                (struct eth_rx_cqe_next_page *)
14524                &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14525            /* point to the next page and wrap from last page */
14526            busaddr = (fp->rcq_dma.paddr +
14527                       (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14528            rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14529            rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14530        }
14531
14532        /*******************/
14533        /* FP RX SGE CHAIN */
14534        /*******************/
14535
14536        snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14537        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14538                          &fp->rx_sge_dma, buf) != 0) {
14539            /* XXX unwind and free previous fastpath allocations */
14540            BLOGE(sc, "Failed to alloc %s\n", buf);
14541            return (1);
14542        } else {
14543            fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14544        }
14545
14546        /* link together the sge chain pages */
14547        for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14548            /* index into the rcq chain array to last entry per page */
14549            struct eth_rx_sge *rx_sge =
14550                &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14551            /* point to the next page and wrap from last page */
14552            busaddr = (fp->rx_sge_dma.paddr +
14553                       (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14554            rx_sge->addr_hi = htole32(U64_HI(busaddr));
14555            rx_sge->addr_lo = htole32(U64_LO(busaddr));
14556        }
14557
14558        /***********************/
14559        /* FP TX MBUF DMA MAPS */
14560        /***********************/
14561
14562        /* set required sizes before mapping to conserve resources */
14563        if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
14564            max_size     = BXE_TSO_MAX_SIZE;
14565            max_segments = BXE_TSO_MAX_SEGMENTS;
14566            max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14567        } else {
14568            max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14569            max_segments = BXE_MAX_SEGMENTS;
14570            max_seg_size = MCLBYTES;
14571        }
14572
14573        /* create a dma tag for the tx mbufs */
14574        rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14575                                1,                  /* alignment */
14576                                0,                  /* boundary limit */
14577                                BUS_SPACE_MAXADDR,  /* restricted low */
14578                                BUS_SPACE_MAXADDR,  /* restricted hi */
14579                                NULL,               /* addr filter() */
14580                                NULL,               /* addr filter() arg */
14581                                max_size,           /* max map size */
14582                                max_segments,       /* num discontinuous */
14583                                max_seg_size,       /* max seg size */
14584                                0,                  /* flags */
14585                                NULL,               /* lock() */
14586                                NULL,               /* lock() arg */
14587                                &fp->tx_mbuf_tag);  /* returned dma tag */
14588        if (rc != 0) {
14589            /* XXX unwind and free previous fastpath allocations */
14590            BLOGE(sc, "Failed to create dma tag for "
14591                      "'fp %d tx mbufs' (%d)\n", i, rc);
14592            return (1);
14593        }
14594
14595        /* create dma maps for each of the tx mbuf clusters */
14596        for (j = 0; j < TX_BD_TOTAL; j++) {
14597            if (bus_dmamap_create(fp->tx_mbuf_tag,
14598                                  BUS_DMA_NOWAIT,
14599                                  &fp->tx_mbuf_chain[j].m_map)) {
14600                /* XXX unwind and free previous fastpath allocations */
14601                BLOGE(sc, "Failed to create dma map for "
14602                          "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14603                return (1);
14604            }
14605        }
14606
14607        /***********************/
14608        /* FP RX MBUF DMA MAPS */
14609        /***********************/
14610
14611        /* create a dma tag for the rx mbufs */
14612        rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14613                                1,                  /* alignment */
14614                                0,                  /* boundary limit */
14615                                BUS_SPACE_MAXADDR,  /* restricted low */
14616                                BUS_SPACE_MAXADDR,  /* restricted hi */
14617                                NULL,               /* addr filter() */
14618                                NULL,               /* addr filter() arg */
14619                                MJUM9BYTES,         /* max map size */
14620                                1,                  /* num discontinuous */
14621                                MJUM9BYTES,         /* max seg size */
14622                                0,                  /* flags */
14623                                NULL,               /* lock() */
14624                                NULL,               /* lock() arg */
14625                                &fp->rx_mbuf_tag);  /* returned dma tag */
14626        if (rc != 0) {
14627            /* XXX unwind and free previous fastpath allocations */
14628            BLOGE(sc, "Failed to create dma tag for "
14629                      "'fp %d rx mbufs' (%d)\n", i, rc);
14630            return (1);
14631        }
14632
14633        /* create dma maps for each of the rx mbuf clusters */
14634        for (j = 0; j < RX_BD_TOTAL; j++) {
14635            if (bus_dmamap_create(fp->rx_mbuf_tag,
14636                                  BUS_DMA_NOWAIT,
14637                                  &fp->rx_mbuf_chain[j].m_map)) {
14638                /* XXX unwind and free previous fastpath allocations */
14639                BLOGE(sc, "Failed to create dma map for "
14640                          "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14641                return (1);
14642            }
14643        }
14644
14645        /* create dma map for the spare rx mbuf cluster */
14646        if (bus_dmamap_create(fp->rx_mbuf_tag,
14647                              BUS_DMA_NOWAIT,
14648                              &fp->rx_mbuf_spare_map)) {
14649            /* XXX unwind and free previous fastpath allocations */
14650            BLOGE(sc, "Failed to create dma map for "
14651                      "'fp %d spare rx mbuf' (%d)\n", i, rc);
14652            return (1);
14653        }
14654
14655        /***************************/
14656        /* FP RX SGE MBUF DMA MAPS */
14657        /***************************/
14658
14659        /* create a dma tag for the rx sge mbufs */
14660        rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14661                                1,                  /* alignment */
14662                                0,                  /* boundary limit */
14663                                BUS_SPACE_MAXADDR,  /* restricted low */
14664                                BUS_SPACE_MAXADDR,  /* restricted hi */
14665                                NULL,               /* addr filter() */
14666                                NULL,               /* addr filter() arg */
14667                                BCM_PAGE_SIZE,      /* max map size */
14668                                1,                  /* num discontinuous */
14669                                BCM_PAGE_SIZE,      /* max seg size */
14670                                0,                  /* flags */
14671                                NULL,               /* lock() */
14672                                NULL,               /* lock() arg */
14673                                &fp->rx_sge_mbuf_tag); /* returned dma tag */
14674        if (rc != 0) {
14675            /* XXX unwind and free previous fastpath allocations */
14676            BLOGE(sc, "Failed to create dma tag for "
14677                      "'fp %d rx sge mbufs' (%d)\n", i, rc);
14678            return (1);
14679        }
14680
14681        /* create dma maps for the rx sge mbuf clusters */
14682        for (j = 0; j < RX_SGE_TOTAL; j++) {
14683            if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14684                                  BUS_DMA_NOWAIT,
14685                                  &fp->rx_sge_mbuf_chain[j].m_map)) {
14686                /* XXX unwind and free previous fastpath allocations */
14687                BLOGE(sc, "Failed to create dma map for "
14688                          "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14689                return (1);
14690            }
14691        }
14692
14693        /* create dma map for the spare rx sge mbuf cluster */
14694        if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14695                              BUS_DMA_NOWAIT,
14696                              &fp->rx_sge_mbuf_spare_map)) {
14697            /* XXX unwind and free previous fastpath allocations */
14698            BLOGE(sc, "Failed to create dma map for "
14699                      "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14700            return (1);
14701        }
14702
14703        /***************************/
14704        /* FP RX TPA MBUF DMA MAPS */
14705        /***************************/
14706
14707        /* create dma maps for the rx tpa mbuf clusters */
14708        max_agg_queues = MAX_AGG_QS(sc);
14709
14710        for (j = 0; j < max_agg_queues; j++) {
14711            if (bus_dmamap_create(fp->rx_mbuf_tag,
14712                                  BUS_DMA_NOWAIT,
14713                                  &fp->rx_tpa_info[j].bd.m_map)) {
14714                /* XXX unwind and free previous fastpath allocations */
14715                BLOGE(sc, "Failed to create dma map for "
14716                          "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14717                return (1);
14718            }
14719        }
14720
14721        /* create dma map for the spare rx tpa mbuf cluster */
14722        if (bus_dmamap_create(fp->rx_mbuf_tag,
14723                              BUS_DMA_NOWAIT,
14724                              &fp->rx_tpa_info_mbuf_spare_map)) {
14725            /* XXX unwind and free previous fastpath allocations */
14726            BLOGE(sc, "Failed to create dma map for "
14727                      "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14728            return (1);
14729        }
14730
14731        bxe_init_sge_ring_bit_mask(fp);
14732    }
14733
14734    return (0);
14735}
14736
14737static void
14738bxe_free_hsi_mem(struct bxe_softc *sc)
14739{
14740    struct bxe_fastpath *fp;
14741    int max_agg_queues;
14742    int i, j;
14743
14744    if (sc->parent_dma_tag == NULL) {
14745        return; /* assume nothing was allocated */
14746    }
14747
14748    for (i = 0; i < sc->num_queues; i++) {
14749        fp = &sc->fp[i];
14750
14751        /*******************/
14752        /* FP STATUS BLOCK */
14753        /*******************/
14754
14755        bxe_dma_free(sc, &fp->sb_dma);
14756        memset(&fp->status_block, 0, sizeof(fp->status_block));
14757
14758        /******************/
14759        /* FP TX BD CHAIN */
14760        /******************/
14761
14762        bxe_dma_free(sc, &fp->tx_dma);
14763        fp->tx_chain = NULL;
14764
14765        /******************/
14766        /* FP RX BD CHAIN */
14767        /******************/
14768
14769        bxe_dma_free(sc, &fp->rx_dma);
14770        fp->rx_chain = NULL;
14771
14772        /*******************/
14773        /* FP RX RCQ CHAIN */
14774        /*******************/
14775
14776        bxe_dma_free(sc, &fp->rcq_dma);
14777        fp->rcq_chain = NULL;
14778
14779        /*******************/
14780        /* FP RX SGE CHAIN */
14781        /*******************/
14782
14783        bxe_dma_free(sc, &fp->rx_sge_dma);
14784        fp->rx_sge_chain = NULL;
14785
14786        /***********************/
14787        /* FP TX MBUF DMA MAPS */
14788        /***********************/
14789
14790        if (fp->tx_mbuf_tag != NULL) {
14791            for (j = 0; j < TX_BD_TOTAL; j++) {
14792                if (fp->tx_mbuf_chain[j].m_map != NULL) {
14793                    bus_dmamap_unload(fp->tx_mbuf_tag,
14794                                      fp->tx_mbuf_chain[j].m_map);
14795                    bus_dmamap_destroy(fp->tx_mbuf_tag,
14796                                       fp->tx_mbuf_chain[j].m_map);
14797                }
14798            }
14799
14800            bus_dma_tag_destroy(fp->tx_mbuf_tag);
14801            fp->tx_mbuf_tag = NULL;
14802        }
14803
14804        /***********************/
14805        /* FP RX MBUF DMA MAPS */
14806        /***********************/
14807
14808        if (fp->rx_mbuf_tag != NULL) {
14809            for (j = 0; j < RX_BD_TOTAL; j++) {
14810                if (fp->rx_mbuf_chain[j].m_map != NULL) {
14811                    bus_dmamap_unload(fp->rx_mbuf_tag,
14812                                      fp->rx_mbuf_chain[j].m_map);
14813                    bus_dmamap_destroy(fp->rx_mbuf_tag,
14814                                       fp->rx_mbuf_chain[j].m_map);
14815                }
14816            }
14817
14818            if (fp->rx_mbuf_spare_map != NULL) {
14819                bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14820                bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14821            }
14822
14823            /***************************/
14824            /* FP RX TPA MBUF DMA MAPS */
14825            /***************************/
14826
14827            max_agg_queues = MAX_AGG_QS(sc);
14828
14829            for (j = 0; j < max_agg_queues; j++) {
14830                if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14831                    bus_dmamap_unload(fp->rx_mbuf_tag,
14832                                      fp->rx_tpa_info[j].bd.m_map);
14833                    bus_dmamap_destroy(fp->rx_mbuf_tag,
14834                                       fp->rx_tpa_info[j].bd.m_map);
14835                }
14836            }
14837
14838            if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14839                bus_dmamap_unload(fp->rx_mbuf_tag,
14840                                  fp->rx_tpa_info_mbuf_spare_map);
14841                bus_dmamap_destroy(fp->rx_mbuf_tag,
14842                                   fp->rx_tpa_info_mbuf_spare_map);
14843            }
14844
14845            bus_dma_tag_destroy(fp->rx_mbuf_tag);
14846            fp->rx_mbuf_tag = NULL;
14847        }
14848
14849        /***************************/
14850        /* FP RX SGE MBUF DMA MAPS */
14851        /***************************/
14852
14853        if (fp->rx_sge_mbuf_tag != NULL) {
14854            for (j = 0; j < RX_SGE_TOTAL; j++) {
14855                if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14856                    bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14857                                      fp->rx_sge_mbuf_chain[j].m_map);
14858                    bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14859                                       fp->rx_sge_mbuf_chain[j].m_map);
14860                }
14861            }
14862
14863            if (fp->rx_sge_mbuf_spare_map != NULL) {
14864                bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14865                                  fp->rx_sge_mbuf_spare_map);
14866                bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14867                                   fp->rx_sge_mbuf_spare_map);
14868            }
14869
14870            bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
14871            fp->rx_sge_mbuf_tag = NULL;
14872        }
14873    }
14874
14875    /***************************/
14876    /* FW DECOMPRESSION BUFFER */
14877    /***************************/
14878
14879    bxe_dma_free(sc, &sc->gz_buf_dma);
14880    sc->gz_buf = NULL;
14881    free(sc->gz_strm, M_DEVBUF);
14882    sc->gz_strm = NULL;
14883
14884    /*******************/
14885    /* SLOW PATH QUEUE */
14886    /*******************/
14887
14888    bxe_dma_free(sc, &sc->spq_dma);
14889    sc->spq = NULL;
14890
14891    /*************/
14892    /* SLOW PATH */
14893    /*************/
14894
14895    bxe_dma_free(sc, &sc->sp_dma);
14896    sc->sp = NULL;
14897
14898    /***************/
14899    /* EVENT QUEUE */
14900    /***************/
14901
14902    bxe_dma_free(sc, &sc->eq_dma);
14903    sc->eq = NULL;
14904
14905    /************************/
14906    /* DEFAULT STATUS BLOCK */
14907    /************************/
14908
14909    bxe_dma_free(sc, &sc->def_sb_dma);
14910    sc->def_sb = NULL;
14911
14912    bus_dma_tag_destroy(sc->parent_dma_tag);
14913    sc->parent_dma_tag = NULL;
14914}
14915
14916/*
14917 * Previous driver DMAE transaction may have occurred when pre-boot stage
14918 * ended and boot began. This would invalidate the addresses of the
14919 * transaction, resulting in was-error bit set in the PCI causing all
14920 * hw-to-host PCIe transactions to timeout. If this happened we want to clear
14921 * the interrupt which detected this from the pglueb and the was-done bit
14922 */
14923static void
14924bxe_prev_interrupted_dmae(struct bxe_softc *sc)
14925{
14926    uint32_t val;
14927
14928    if (!CHIP_IS_E1x(sc)) {
14929        val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
14930        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
14931            BLOGD(sc, DBG_LOAD,
14932                  "Clearing 'was-error' bit that was set in pglueb");
14933            REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
14934        }
14935    }
14936}
14937
14938static int
14939bxe_prev_mcp_done(struct bxe_softc *sc)
14940{
14941    uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
14942                                 DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
14943    if (!rc) {
14944        BLOGE(sc, "MCP response failure, aborting\n");
14945        return (-1);
14946    }
14947
14948    return (0);
14949}
14950
14951static struct bxe_prev_list_node *
14952bxe_prev_path_get_entry(struct bxe_softc *sc)
14953{
14954    struct bxe_prev_list_node *tmp;
14955
14956    LIST_FOREACH(tmp, &bxe_prev_list, node) {
14957        if ((sc->pcie_bus == tmp->bus) &&
14958            (sc->pcie_device == tmp->slot) &&
14959            (SC_PATH(sc) == tmp->path)) {
14960            return (tmp);
14961        }
14962    }
14963
14964    return (NULL);
14965}
14966
14967static uint8_t
14968bxe_prev_is_path_marked(struct bxe_softc *sc)
14969{
14970    struct bxe_prev_list_node *tmp;
14971    int rc = FALSE;
14972
14973    mtx_lock(&bxe_prev_mtx);
14974
14975    tmp = bxe_prev_path_get_entry(sc);
14976    if (tmp) {
14977        if (tmp->aer) {
14978            BLOGD(sc, DBG_LOAD,
14979                  "Path %d/%d/%d was marked by AER\n",
14980                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
14981        } else {
14982            rc = TRUE;
14983            BLOGD(sc, DBG_LOAD,
14984                  "Path %d/%d/%d was already cleaned from previous drivers\n",
14985                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
14986        }
14987    }
14988
14989    mtx_unlock(&bxe_prev_mtx);
14990
14991    return (rc);
14992}
14993
14994static int
14995bxe_prev_mark_path(struct bxe_softc *sc,
14996                   uint8_t          after_undi)
14997{
14998    struct bxe_prev_list_node *tmp;
14999
15000    mtx_lock(&bxe_prev_mtx);
15001
15002    /* Check whether the entry for this path already exists */
15003    tmp = bxe_prev_path_get_entry(sc);
15004    if (tmp) {
15005        if (!tmp->aer) {
15006            BLOGD(sc, DBG_LOAD,
15007                  "Re-marking AER in path %d/%d/%d\n",
15008                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15009        } else {
15010            BLOGD(sc, DBG_LOAD,
15011                  "Removing AER indication from path %d/%d/%d\n",
15012                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15013            tmp->aer = 0;
15014        }
15015
15016        mtx_unlock(&bxe_prev_mtx);
15017        return (0);
15018    }
15019
15020    mtx_unlock(&bxe_prev_mtx);
15021
15022    /* Create an entry for this path and add it */
15023    tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15024                 (M_NOWAIT | M_ZERO));
15025    if (!tmp) {
15026        BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15027        return (-1);
15028    }
15029
15030    tmp->bus  = sc->pcie_bus;
15031    tmp->slot = sc->pcie_device;
15032    tmp->path = SC_PATH(sc);
15033    tmp->aer  = 0;
15034    tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15035
15036    mtx_lock(&bxe_prev_mtx);
15037
15038    BLOGD(sc, DBG_LOAD,
15039          "Marked path %d/%d/%d - finished previous unload\n",
15040          sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15041    LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15042
15043    mtx_unlock(&bxe_prev_mtx);
15044
15045    return (0);
15046}
15047
15048static int
15049bxe_do_flr(struct bxe_softc *sc)
15050{
15051    int i;
15052
15053    /* only E2 and onwards support FLR */
15054    if (CHIP_IS_E1x(sc)) {
15055        BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15056        return (-1);
15057    }
15058
15059    /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15060    if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15061        BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15062              sc->devinfo.bc_ver);
15063        return (-1);
15064    }
15065
15066    /* Wait for Transaction Pending bit clean */
15067    for (i = 0; i < 4; i++) {
15068        if (i) {
15069            DELAY(((1 << (i - 1)) * 100) * 1000);
15070        }
15071
15072        if (!bxe_is_pcie_pending(sc)) {
15073            goto clear;
15074        }
15075    }
15076
15077    BLOGE(sc, "PCIE transaction is not cleared, "
15078              "proceeding with reset anyway\n");
15079
15080clear:
15081
15082    BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15083    bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15084
15085    return (0);
15086}
15087
15088struct bxe_mac_vals {
15089    uint32_t xmac_addr;
15090    uint32_t xmac_val;
15091    uint32_t emac_addr;
15092    uint32_t emac_val;
15093    uint32_t umac_addr;
15094    uint32_t umac_val;
15095    uint32_t bmac_addr;
15096    uint32_t bmac_val[2];
15097};
15098
15099static void
15100bxe_prev_unload_close_mac(struct bxe_softc *sc,
15101                          struct bxe_mac_vals *vals)
15102{
15103    uint32_t val, base_addr, offset, mask, reset_reg;
15104    uint8_t mac_stopped = FALSE;
15105    uint8_t port = SC_PORT(sc);
15106    uint32_t wb_data[2];
15107
15108    /* reset addresses as they also mark which values were changed */
15109    vals->bmac_addr = 0;
15110    vals->umac_addr = 0;
15111    vals->xmac_addr = 0;
15112    vals->emac_addr = 0;
15113
15114    reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15115
15116    if (!CHIP_IS_E3(sc)) {
15117        val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15118        mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15119        if ((mask & reset_reg) && val) {
15120            BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15121            base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15122                                    : NIG_REG_INGRESS_BMAC0_MEM;
15123            offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15124                                    : BIGMAC_REGISTER_BMAC_CONTROL;
15125
15126            /*
15127             * use rd/wr since we cannot use dmae. This is safe
15128             * since MCP won't access the bus due to the request
15129             * to unload, and no function on the path can be
15130             * loaded at this time.
15131             */
15132            wb_data[0] = REG_RD(sc, base_addr + offset);
15133            wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15134            vals->bmac_addr = base_addr + offset;
15135            vals->bmac_val[0] = wb_data[0];
15136            vals->bmac_val[1] = wb_data[1];
15137            wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15138            REG_WR(sc, vals->bmac_addr, wb_data[0]);
15139            REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15140        }
15141
15142        BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15143        vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15144        vals->emac_val = REG_RD(sc, vals->emac_addr);
15145        REG_WR(sc, vals->emac_addr, 0);
15146        mac_stopped = TRUE;
15147    } else {
15148        if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15149            BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15150            base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15151            val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15152            REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15153            REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15154            vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15155            vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15156            REG_WR(sc, vals->xmac_addr, 0);
15157            mac_stopped = TRUE;
15158        }
15159
15160        mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15161        if (mask & reset_reg) {
15162            BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15163            base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15164            vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15165            vals->umac_val = REG_RD(sc, vals->umac_addr);
15166            REG_WR(sc, vals->umac_addr, 0);
15167            mac_stopped = TRUE;
15168        }
15169    }
15170
15171    if (mac_stopped) {
15172        DELAY(20000);
15173    }
15174}
15175
15176#define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15177#define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15178#define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15179#define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15180
15181static void
15182bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15183                         uint8_t          port,
15184                         uint8_t          inc)
15185{
15186    uint16_t rcq, bd;
15187    uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15188
15189    rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15190    bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15191
15192    tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15193    REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15194
15195    BLOGD(sc, DBG_LOAD,
15196          "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15197          port, bd, rcq);
15198}
15199
15200static int
15201bxe_prev_unload_common(struct bxe_softc *sc)
15202{
15203    uint32_t reset_reg, tmp_reg = 0, rc;
15204    uint8_t prev_undi = FALSE;
15205    struct bxe_mac_vals mac_vals;
15206    uint32_t timer_count = 1000;
15207    uint32_t prev_brb;
15208
15209    /*
15210     * It is possible a previous function received 'common' answer,
15211     * but hasn't loaded yet, therefore creating a scenario of
15212     * multiple functions receiving 'common' on the same path.
15213     */
15214    BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15215
15216    memset(&mac_vals, 0, sizeof(mac_vals));
15217
15218    if (bxe_prev_is_path_marked(sc)) {
15219        return (bxe_prev_mcp_done(sc));
15220    }
15221
15222    reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15223
15224    /* Reset should be performed after BRB is emptied */
15225    if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15226        /* Close the MAC Rx to prevent BRB from filling up */
15227        bxe_prev_unload_close_mac(sc, &mac_vals);
15228
15229        /* close LLH filters towards the BRB */
15230        elink_set_rx_filter(&sc->link_params, 0);
15231
15232        /*
15233         * Check if the UNDI driver was previously loaded.
15234         * UNDI driver initializes CID offset for normal bell to 0x7
15235         */
15236        if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15237            tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15238            if (tmp_reg == 0x7) {
15239                BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15240                prev_undi = TRUE;
15241                /* clear the UNDI indication */
15242                REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15243                /* clear possible idle check errors */
15244                REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15245            }
15246        }
15247
15248        /* wait until BRB is empty */
15249        tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15250        while (timer_count) {
15251            prev_brb = tmp_reg;
15252
15253            tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15254            if (!tmp_reg) {
15255                break;
15256            }
15257
15258            BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15259
15260            /* reset timer as long as BRB actually gets emptied */
15261            if (prev_brb > tmp_reg) {
15262                timer_count = 1000;
15263            } else {
15264                timer_count--;
15265            }
15266
15267            /* If UNDI resides in memory, manually increment it */
15268            if (prev_undi) {
15269                bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15270            }
15271
15272            DELAY(10);
15273        }
15274
15275        if (!timer_count) {
15276            BLOGE(sc, "Failed to empty BRB\n");
15277        }
15278    }
15279
15280    /* No packets are in the pipeline, path is ready for reset */
15281    bxe_reset_common(sc);
15282
15283    if (mac_vals.xmac_addr) {
15284        REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15285    }
15286    if (mac_vals.umac_addr) {
15287        REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15288    }
15289    if (mac_vals.emac_addr) {
15290        REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15291    }
15292    if (mac_vals.bmac_addr) {
15293        REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15294        REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15295    }
15296
15297    rc = bxe_prev_mark_path(sc, prev_undi);
15298    if (rc) {
15299        bxe_prev_mcp_done(sc);
15300        return (rc);
15301    }
15302
15303    return (bxe_prev_mcp_done(sc));
15304}
15305
15306static int
15307bxe_prev_unload_uncommon(struct bxe_softc *sc)
15308{
15309    int rc;
15310
15311    BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15312
15313    /* Test if previous unload process was already finished for this path */
15314    if (bxe_prev_is_path_marked(sc)) {
15315        return (bxe_prev_mcp_done(sc));
15316    }
15317
15318    BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15319
15320    /*
15321     * If function has FLR capabilities, and existing FW version matches
15322     * the one required, then FLR will be sufficient to clean any residue
15323     * left by previous driver
15324     */
15325    rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15326    if (!rc) {
15327        /* fw version is good */
15328        BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15329        rc = bxe_do_flr(sc);
15330    }
15331
15332    if (!rc) {
15333        /* FLR was performed */
15334        BLOGD(sc, DBG_LOAD, "FLR successful\n");
15335        return (0);
15336    }
15337
15338    BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15339
15340    /* Close the MCP request, return failure*/
15341    rc = bxe_prev_mcp_done(sc);
15342    if (!rc) {
15343        rc = BXE_PREV_WAIT_NEEDED;
15344    }
15345
15346    return (rc);
15347}
15348
15349static int
15350bxe_prev_unload(struct bxe_softc *sc)
15351{
15352    int time_counter = 10;
15353    uint32_t fw, hw_lock_reg, hw_lock_val;
15354    uint32_t rc = 0;
15355
15356    /*
15357     * Clear HW from errors which may have resulted from an interrupted
15358     * DMAE transaction.
15359     */
15360    bxe_prev_interrupted_dmae(sc);
15361
15362    /* Release previously held locks */
15363    hw_lock_reg =
15364        (SC_FUNC(sc) <= 5) ?
15365            (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15366            (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15367
15368    hw_lock_val = (REG_RD(sc, hw_lock_reg));
15369    if (hw_lock_val) {
15370        if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15371            BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15372            REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15373                   (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15374        }
15375        BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15376        REG_WR(sc, hw_lock_reg, 0xffffffff);
15377    } else {
15378        BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15379    }
15380
15381    if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15382        BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15383        REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15384    }
15385
15386    do {
15387        /* Lock MCP using an unload request */
15388        fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15389        if (!fw) {
15390            BLOGE(sc, "MCP response failure, aborting\n");
15391            rc = -1;
15392            break;
15393        }
15394
15395        if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15396            rc = bxe_prev_unload_common(sc);
15397            break;
15398        }
15399
15400        /* non-common reply from MCP night require looping */
15401        rc = bxe_prev_unload_uncommon(sc);
15402        if (rc != BXE_PREV_WAIT_NEEDED) {
15403            break;
15404        }
15405
15406        DELAY(20000);
15407    } while (--time_counter);
15408
15409    if (!time_counter || rc) {
15410        BLOGE(sc, "Failed to unload previous driver!"
15411            " time_counter %d rc %d\n", time_counter, rc);
15412        rc = -1;
15413    }
15414
15415    return (rc);
15416}
15417
15418void
15419bxe_dcbx_set_state(struct bxe_softc *sc,
15420                   uint8_t          dcb_on,
15421                   uint32_t         dcbx_enabled)
15422{
15423    if (!CHIP_IS_E1x(sc)) {
15424        sc->dcb_state = dcb_on;
15425        sc->dcbx_enabled = dcbx_enabled;
15426    } else {
15427        sc->dcb_state = FALSE;
15428        sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15429    }
15430    BLOGD(sc, DBG_LOAD,
15431          "DCB state [%s:%s]\n",
15432          dcb_on ? "ON" : "OFF",
15433          (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15434          (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15435          (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15436          "on-chip with negotiation" : "invalid");
15437}
15438
15439/* must be called after sriov-enable */
15440static int
15441bxe_set_qm_cid_count(struct bxe_softc *sc)
15442{
15443    int cid_count = BXE_L2_MAX_CID(sc);
15444
15445    if (IS_SRIOV(sc)) {
15446        cid_count += BXE_VF_CIDS;
15447    }
15448
15449    if (CNIC_SUPPORT(sc)) {
15450        cid_count += CNIC_CID_MAX;
15451    }
15452
15453    return (roundup(cid_count, QM_CID_ROUND));
15454}
15455
15456static void
15457bxe_init_multi_cos(struct bxe_softc *sc)
15458{
15459    int pri, cos;
15460
15461    uint32_t pri_map = 0; /* XXX change to user config */
15462
15463    for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15464        cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15465        if (cos < sc->max_cos) {
15466            sc->prio_to_cos[pri] = cos;
15467        } else {
15468            BLOGW(sc, "Invalid COS %d for priority %d "
15469                      "(max COS is %d), setting to 0\n",
15470                  cos, pri, (sc->max_cos - 1));
15471            sc->prio_to_cos[pri] = 0;
15472        }
15473    }
15474}
15475
15476static int
15477bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15478{
15479    struct bxe_softc *sc;
15480    int error, result;
15481
15482    result = 0;
15483    error = sysctl_handle_int(oidp, &result, 0, req);
15484
15485    if (error || !req->newptr) {
15486        return (error);
15487    }
15488
15489    if (result == 1) {
15490        uint32_t  temp;
15491        sc = (struct bxe_softc *)arg1;
15492
15493        BLOGI(sc, "... dumping driver state ...\n");
15494        temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15495        BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15496    }
15497
15498    return (error);
15499}
15500
15501static int
15502bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15503{
15504    struct bxe_softc *sc = (struct bxe_softc *)arg1;
15505    uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15506    uint32_t *offset;
15507    uint64_t value = 0;
15508    int index = (int)arg2;
15509
15510    if (index >= BXE_NUM_ETH_STATS) {
15511        BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15512        return (-1);
15513    }
15514
15515    offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15516
15517    switch (bxe_eth_stats_arr[index].size) {
15518    case 4:
15519        value = (uint64_t)*offset;
15520        break;
15521    case 8:
15522        value = HILO_U64(*offset, *(offset + 1));
15523        break;
15524    default:
15525        BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15526              index, bxe_eth_stats_arr[index].size);
15527        return (-1);
15528    }
15529
15530    return (sysctl_handle_64(oidp, &value, 0, req));
15531}
15532
15533static int
15534bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15535{
15536    struct bxe_softc *sc = (struct bxe_softc *)arg1;
15537    uint32_t *eth_stats;
15538    uint32_t *offset;
15539    uint64_t value = 0;
15540    uint32_t q_stat = (uint32_t)arg2;
15541    uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15542    uint32_t index = (q_stat & 0xffff);
15543
15544    eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15545
15546    if (index >= BXE_NUM_ETH_Q_STATS) {
15547        BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15548        return (-1);
15549    }
15550
15551    offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15552
15553    switch (bxe_eth_q_stats_arr[index].size) {
15554    case 4:
15555        value = (uint64_t)*offset;
15556        break;
15557    case 8:
15558        value = HILO_U64(*offset, *(offset + 1));
15559        break;
15560    default:
15561        BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15562              index, bxe_eth_q_stats_arr[index].size);
15563        return (-1);
15564    }
15565
15566    return (sysctl_handle_64(oidp, &value, 0, req));
15567}
15568
15569static void
15570bxe_add_sysctls(struct bxe_softc *sc)
15571{
15572    struct sysctl_ctx_list *ctx;
15573    struct sysctl_oid_list *children;
15574    struct sysctl_oid *queue_top, *queue;
15575    struct sysctl_oid_list *queue_top_children, *queue_children;
15576    char queue_num_buf[32];
15577    uint32_t q_stat;
15578    int i, j;
15579
15580    ctx = device_get_sysctl_ctx(sc->dev);
15581    children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15582
15583    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15584                      CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15585                      "version");
15586
15587    snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15588             BCM_5710_FW_MAJOR_VERSION,
15589             BCM_5710_FW_MINOR_VERSION,
15590             BCM_5710_FW_REVISION_VERSION,
15591             BCM_5710_FW_ENGINEERING_VERSION);
15592
15593    snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15594        ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15595         (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15596         (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15597         (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15598                                                                "Unknown"));
15599    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15600                    CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15601                    "multifunction vnics per port");
15602
15603    snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15604        ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15605         (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15606         (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15607                                              "???GT/s"),
15608        sc->devinfo.pcie_link_width);
15609
15610    sc->debug = bxe_debug;
15611
15612#if __FreeBSD_version >= 900000
15613    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15614                      CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15615                      "bootcode version");
15616    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15617                      CTLFLAG_RD, sc->fw_ver_str, 0,
15618                      "firmware version");
15619    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15620                      CTLFLAG_RD, sc->mf_mode_str, 0,
15621                      "multifunction mode");
15622    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15623                      CTLFLAG_RD, sc->mac_addr_str, 0,
15624                      "mac address");
15625    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15626                      CTLFLAG_RD, sc->pci_link_str, 0,
15627                      "pci link status");
15628    SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
15629                    CTLFLAG_RW, &sc->debug,
15630                    "debug logging mode");
15631#else
15632    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15633                      CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15634                      "bootcode version");
15635    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15636                      CTLFLAG_RD, &sc->fw_ver_str, 0,
15637                      "firmware version");
15638    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15639                      CTLFLAG_RD, &sc->mf_mode_str, 0,
15640                      "multifunction mode");
15641    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15642                      CTLFLAG_RD, &sc->mac_addr_str, 0,
15643                      "mac address");
15644    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15645                      CTLFLAG_RD, &sc->pci_link_str, 0,
15646                      "pci link status");
15647    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15648                    CTLFLAG_RW, &sc->debug, 0,
15649                    "debug logging mode");
15650#endif /* #if __FreeBSD_version >= 900000 */
15651
15652    sc->trigger_grcdump = 0;
15653    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
15654                   CTLFLAG_RW, &sc->trigger_grcdump, 0,
15655                   "trigger grcdump should be invoked"
15656                   "  before collecting grcdump");
15657
15658    sc->grcdump_started = 0;
15659    sc->grcdump_done = 0;
15660    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15661                   CTLFLAG_RD, &sc->grcdump_done, 0,
15662                   "set by driver when grcdump is done");
15663
15664    sc->rx_budget = bxe_rx_budget;
15665    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15666                    CTLFLAG_RW, &sc->rx_budget, 0,
15667                    "rx processing budget");
15668
15669    SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15670                    CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15671                    bxe_sysctl_state, "IU", "dump driver state");
15672
15673    for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15674        SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15675                        bxe_eth_stats_arr[i].string,
15676                        CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15677                        bxe_sysctl_eth_stat, "LU",
15678                        bxe_eth_stats_arr[i].string);
15679    }
15680
15681    /* add a new parent node for all queues "dev.bxe.#.queue" */
15682    queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15683                                CTLFLAG_RD, NULL, "queue");
15684    queue_top_children = SYSCTL_CHILDREN(queue_top);
15685
15686    for (i = 0; i < sc->num_queues; i++) {
15687        /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15688        snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15689        queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15690                                queue_num_buf, CTLFLAG_RD, NULL,
15691                                "single queue");
15692        queue_children = SYSCTL_CHILDREN(queue);
15693
15694        for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15695            q_stat = ((i << 16) | j);
15696            SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15697                            bxe_eth_q_stats_arr[j].string,
15698                            CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15699                            bxe_sysctl_eth_q_stat, "LU",
15700                            bxe_eth_q_stats_arr[j].string);
15701        }
15702    }
15703}
15704
15705static int
15706bxe_alloc_buf_rings(struct bxe_softc *sc)
15707{
15708#if __FreeBSD_version >= 800000
15709
15710    int i;
15711    struct bxe_fastpath *fp;
15712
15713    for (i = 0; i < sc->num_queues; i++) {
15714
15715        fp = &sc->fp[i];
15716
15717        fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15718                                   M_NOWAIT, &fp->tx_mtx);
15719        if (fp->tx_br == NULL)
15720            return (-1);
15721    }
15722#endif
15723    return (0);
15724}
15725
15726static void
15727bxe_free_buf_rings(struct bxe_softc *sc)
15728{
15729#if __FreeBSD_version >= 800000
15730
15731    int i;
15732    struct bxe_fastpath *fp;
15733
15734    for (i = 0; i < sc->num_queues; i++) {
15735
15736        fp = &sc->fp[i];
15737
15738        if (fp->tx_br) {
15739            buf_ring_free(fp->tx_br, M_DEVBUF);
15740            fp->tx_br = NULL;
15741        }
15742    }
15743
15744#endif
15745}
15746
15747static void
15748bxe_init_fp_mutexs(struct bxe_softc *sc)
15749{
15750    int i;
15751    struct bxe_fastpath *fp;
15752
15753    for (i = 0; i < sc->num_queues; i++) {
15754
15755        fp = &sc->fp[i];
15756
15757        snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15758            "bxe%d_fp%d_tx_lock", sc->unit, i);
15759        mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15760
15761        snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15762            "bxe%d_fp%d_rx_lock", sc->unit, i);
15763        mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15764    }
15765}
15766
15767static void
15768bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15769{
15770    int i;
15771    struct bxe_fastpath *fp;
15772
15773    for (i = 0; i < sc->num_queues; i++) {
15774
15775        fp = &sc->fp[i];
15776
15777        if (mtx_initialized(&fp->tx_mtx)) {
15778            mtx_destroy(&fp->tx_mtx);
15779        }
15780
15781        if (mtx_initialized(&fp->rx_mtx)) {
15782            mtx_destroy(&fp->rx_mtx);
15783        }
15784    }
15785}
15786
15787
15788/*
15789 * Device attach function.
15790 *
15791 * Allocates device resources, performs secondary chip identification, and
15792 * initializes driver instance variables. This function is called from driver
15793 * load after a successful probe.
15794 *
15795 * Returns:
15796 *   0 = Success, >0 = Failure
15797 */
15798static int
15799bxe_attach(device_t dev)
15800{
15801    struct bxe_softc *sc;
15802
15803    sc = device_get_softc(dev);
15804
15805    BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15806
15807    sc->state = BXE_STATE_CLOSED;
15808
15809    sc->dev  = dev;
15810    sc->unit = device_get_unit(dev);
15811
15812    BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
15813
15814    sc->pcie_bus    = pci_get_bus(dev);
15815    sc->pcie_device = pci_get_slot(dev);
15816    sc->pcie_func   = pci_get_function(dev);
15817
15818    /* enable bus master capability */
15819    pci_enable_busmaster(dev);
15820
15821    /* get the BARs */
15822    if (bxe_allocate_bars(sc) != 0) {
15823        return (ENXIO);
15824    }
15825
15826    /* initialize the mutexes */
15827    bxe_init_mutexes(sc);
15828
15829    /* prepare the periodic callout */
15830    callout_init(&sc->periodic_callout, 0);
15831
15832    /* prepare the chip taskqueue */
15833    sc->chip_tq_flags = CHIP_TQ_NONE;
15834    snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
15835             "bxe%d_chip_tq", sc->unit);
15836    TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
15837    sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
15838                                   taskqueue_thread_enqueue,
15839                                   &sc->chip_tq);
15840    taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
15841                            "%s", sc->chip_tq_name);
15842
15843    /* get device info and set params */
15844    if (bxe_get_device_info(sc) != 0) {
15845        BLOGE(sc, "getting device info\n");
15846        bxe_deallocate_bars(sc);
15847        pci_disable_busmaster(dev);
15848        return (ENXIO);
15849    }
15850
15851    /* get final misc params */
15852    bxe_get_params(sc);
15853
15854    /* set the default MTU (changed via ifconfig) */
15855    sc->mtu = ETHERMTU;
15856
15857    bxe_set_modes_bitmap(sc);
15858
15859    /* XXX
15860     * If in AFEX mode and the function is configured for FCoE
15861     * then bail... no L2 allowed.
15862     */
15863
15864    /* get phy settings from shmem and 'and' against admin settings */
15865    bxe_get_phy_info(sc);
15866
15867    /* initialize the FreeBSD ifnet interface */
15868    if (bxe_init_ifnet(sc) != 0) {
15869        bxe_release_mutexes(sc);
15870        bxe_deallocate_bars(sc);
15871        pci_disable_busmaster(dev);
15872        return (ENXIO);
15873    }
15874
15875    if (bxe_add_cdev(sc) != 0) {
15876        if (sc->ifp != NULL) {
15877            ether_ifdetach(sc->ifp);
15878        }
15879        ifmedia_removeall(&sc->ifmedia);
15880        bxe_release_mutexes(sc);
15881        bxe_deallocate_bars(sc);
15882        pci_disable_busmaster(dev);
15883        return (ENXIO);
15884    }
15885
15886    /* allocate device interrupts */
15887    if (bxe_interrupt_alloc(sc) != 0) {
15888        bxe_del_cdev(sc);
15889        if (sc->ifp != NULL) {
15890            ether_ifdetach(sc->ifp);
15891        }
15892        ifmedia_removeall(&sc->ifmedia);
15893        bxe_release_mutexes(sc);
15894        bxe_deallocate_bars(sc);
15895        pci_disable_busmaster(dev);
15896        return (ENXIO);
15897    }
15898
15899    bxe_init_fp_mutexs(sc);
15900
15901    if (bxe_alloc_buf_rings(sc) != 0) {
15902	bxe_free_buf_rings(sc);
15903        bxe_interrupt_free(sc);
15904        bxe_del_cdev(sc);
15905        if (sc->ifp != NULL) {
15906            ether_ifdetach(sc->ifp);
15907        }
15908        ifmedia_removeall(&sc->ifmedia);
15909        bxe_release_mutexes(sc);
15910        bxe_deallocate_bars(sc);
15911        pci_disable_busmaster(dev);
15912        return (ENXIO);
15913    }
15914
15915    /* allocate ilt */
15916    if (bxe_alloc_ilt_mem(sc) != 0) {
15917	bxe_free_buf_rings(sc);
15918        bxe_interrupt_free(sc);
15919        bxe_del_cdev(sc);
15920        if (sc->ifp != NULL) {
15921            ether_ifdetach(sc->ifp);
15922        }
15923        ifmedia_removeall(&sc->ifmedia);
15924        bxe_release_mutexes(sc);
15925        bxe_deallocate_bars(sc);
15926        pci_disable_busmaster(dev);
15927        return (ENXIO);
15928    }
15929
15930    /* allocate the host hardware/software hsi structures */
15931    if (bxe_alloc_hsi_mem(sc) != 0) {
15932        bxe_free_ilt_mem(sc);
15933	bxe_free_buf_rings(sc);
15934        bxe_interrupt_free(sc);
15935        bxe_del_cdev(sc);
15936        if (sc->ifp != NULL) {
15937            ether_ifdetach(sc->ifp);
15938        }
15939        ifmedia_removeall(&sc->ifmedia);
15940        bxe_release_mutexes(sc);
15941        bxe_deallocate_bars(sc);
15942        pci_disable_busmaster(dev);
15943        return (ENXIO);
15944    }
15945
15946    /* need to reset chip if UNDI was active */
15947    if (IS_PF(sc) && !BXE_NOMCP(sc)) {
15948        /* init fw_seq */
15949        sc->fw_seq =
15950            (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
15951             DRV_MSG_SEQ_NUMBER_MASK);
15952        BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
15953        bxe_prev_unload(sc);
15954    }
15955
15956#if 1
15957    /* XXX */
15958    bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
15959#else
15960    if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
15961        SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
15962        SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
15963        SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
15964        bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
15965        bxe_dcbx_init_params(sc);
15966    } else {
15967        bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
15968    }
15969#endif
15970
15971    /* calculate qm_cid_count */
15972    sc->qm_cid_count = bxe_set_qm_cid_count(sc);
15973    BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
15974
15975    sc->max_cos = 1;
15976    bxe_init_multi_cos(sc);
15977
15978    bxe_add_sysctls(sc);
15979
15980    return (0);
15981}
15982
15983/*
15984 * Device detach function.
15985 *
15986 * Stops the controller, resets the controller, and releases resources.
15987 *
15988 * Returns:
15989 *   0 = Success, >0 = Failure
15990 */
15991static int
15992bxe_detach(device_t dev)
15993{
15994    struct bxe_softc *sc;
15995    if_t ifp;
15996
15997    sc = device_get_softc(dev);
15998
15999    BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16000
16001    ifp = sc->ifp;
16002    if (ifp != NULL && if_vlantrunkinuse(ifp)) {
16003        BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16004        return(EBUSY);
16005    }
16006
16007    bxe_del_cdev(sc);
16008
16009    /* stop the periodic callout */
16010    bxe_periodic_stop(sc);
16011
16012    /* stop the chip taskqueue */
16013    atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16014    if (sc->chip_tq) {
16015        taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16016        taskqueue_free(sc->chip_tq);
16017        sc->chip_tq = NULL;
16018    }
16019
16020    /* stop and reset the controller if it was open */
16021    if (sc->state != BXE_STATE_CLOSED) {
16022        BXE_CORE_LOCK(sc);
16023        bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16024        sc->state = BXE_STATE_DISABLED;
16025        BXE_CORE_UNLOCK(sc);
16026    }
16027
16028    /* release the network interface */
16029    if (ifp != NULL) {
16030        ether_ifdetach(ifp);
16031    }
16032    ifmedia_removeall(&sc->ifmedia);
16033
16034    /* XXX do the following based on driver state... */
16035
16036    /* free the host hardware/software hsi structures */
16037    bxe_free_hsi_mem(sc);
16038
16039    /* free ilt */
16040    bxe_free_ilt_mem(sc);
16041
16042    bxe_free_buf_rings(sc);
16043
16044    /* release the interrupts */
16045    bxe_interrupt_free(sc);
16046
16047    /* Release the mutexes*/
16048    bxe_destroy_fp_mutexs(sc);
16049    bxe_release_mutexes(sc);
16050
16051
16052    /* Release the PCIe BAR mapped memory */
16053    bxe_deallocate_bars(sc);
16054
16055    /* Release the FreeBSD interface. */
16056    if (sc->ifp != NULL) {
16057        if_free(sc->ifp);
16058    }
16059
16060    pci_disable_busmaster(dev);
16061
16062    return (0);
16063}
16064
16065/*
16066 * Device shutdown function.
16067 *
16068 * Stops and resets the controller.
16069 *
16070 * Returns:
16071 *   Nothing
16072 */
16073static int
16074bxe_shutdown(device_t dev)
16075{
16076    struct bxe_softc *sc;
16077
16078    sc = device_get_softc(dev);
16079
16080    BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16081
16082    /* stop the periodic callout */
16083    bxe_periodic_stop(sc);
16084
16085    BXE_CORE_LOCK(sc);
16086    bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16087    BXE_CORE_UNLOCK(sc);
16088
16089    return (0);
16090}
16091
16092void
16093bxe_igu_ack_sb(struct bxe_softc *sc,
16094               uint8_t          igu_sb_id,
16095               uint8_t          segment,
16096               uint16_t         index,
16097               uint8_t          op,
16098               uint8_t          update)
16099{
16100    uint32_t igu_addr = sc->igu_base_addr;
16101    igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16102    bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16103}
16104
16105static void
16106bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16107                     uint8_t          func,
16108                     uint8_t          idu_sb_id,
16109                     uint8_t          is_pf)
16110{
16111    uint32_t data, ctl, cnt = 100;
16112    uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16113    uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16114    uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16115    uint32_t sb_bit =  1 << (idu_sb_id%32);
16116    uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16117    uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16118
16119    /* Not supported in BC mode */
16120    if (CHIP_INT_MODE_IS_BC(sc)) {
16121        return;
16122    }
16123
16124    data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16125             IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16126            IGU_REGULAR_CLEANUP_SET |
16127            IGU_REGULAR_BCLEANUP);
16128
16129    ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16130           (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16131           (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16132
16133    BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16134            data, igu_addr_data);
16135    REG_WR(sc, igu_addr_data, data);
16136
16137    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16138                      BUS_SPACE_BARRIER_WRITE);
16139    mb();
16140
16141    BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16142            ctl, igu_addr_ctl);
16143    REG_WR(sc, igu_addr_ctl, ctl);
16144
16145    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16146                      BUS_SPACE_BARRIER_WRITE);
16147    mb();
16148
16149    /* wait for clean up to finish */
16150    while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16151        DELAY(20000);
16152    }
16153
16154    if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16155        BLOGD(sc, DBG_LOAD,
16156              "Unable to finish IGU cleanup: "
16157              "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16158              idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16159    }
16160}
16161
16162static void
16163bxe_igu_clear_sb(struct bxe_softc *sc,
16164                 uint8_t          idu_sb_id)
16165{
16166    bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16167}
16168
16169
16170
16171
16172
16173
16174
16175/*******************/
16176/* ECORE CALLBACKS */
16177/*******************/
16178
16179static void
16180bxe_reset_common(struct bxe_softc *sc)
16181{
16182    uint32_t val = 0x1400;
16183
16184    /* reset_common */
16185    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16186
16187    if (CHIP_IS_E3(sc)) {
16188        val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16189        val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16190    }
16191
16192    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16193}
16194
16195static void
16196bxe_common_init_phy(struct bxe_softc *sc)
16197{
16198    uint32_t shmem_base[2];
16199    uint32_t shmem2_base[2];
16200
16201    /* Avoid common init in case MFW supports LFA */
16202    if (SHMEM2_RD(sc, size) >
16203        (uint32_t)offsetof(struct shmem2_region,
16204                           lfa_host_addr[SC_PORT(sc)])) {
16205        return;
16206    }
16207
16208    shmem_base[0]  = sc->devinfo.shmem_base;
16209    shmem2_base[0] = sc->devinfo.shmem2_base;
16210
16211    if (!CHIP_IS_E1x(sc)) {
16212        shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16213        shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16214    }
16215
16216    bxe_acquire_phy_lock(sc);
16217    elink_common_init_phy(sc, shmem_base, shmem2_base,
16218                          sc->devinfo.chip_id, 0);
16219    bxe_release_phy_lock(sc);
16220}
16221
16222static void
16223bxe_pf_disable(struct bxe_softc *sc)
16224{
16225    uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16226
16227    val &= ~IGU_PF_CONF_FUNC_EN;
16228
16229    REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16230    REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16231    REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16232}
16233
16234static void
16235bxe_init_pxp(struct bxe_softc *sc)
16236{
16237    uint16_t devctl;
16238    int r_order, w_order;
16239
16240    devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16241
16242    BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16243
16244    w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16245
16246    if (sc->mrrs == -1) {
16247        r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16248    } else {
16249        BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16250        r_order = sc->mrrs;
16251    }
16252
16253    ecore_init_pxp_arb(sc, r_order, w_order);
16254}
16255
16256static uint32_t
16257bxe_get_pretend_reg(struct bxe_softc *sc)
16258{
16259    uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16260    uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16261    return (base + (SC_ABS_FUNC(sc)) * stride);
16262}
16263
16264/*
16265 * Called only on E1H or E2.
16266 * When pretending to be PF, the pretend value is the function number 0..7.
16267 * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16268 * combination.
16269 */
16270static int
16271bxe_pretend_func(struct bxe_softc *sc,
16272                 uint16_t         pretend_func_val)
16273{
16274    uint32_t pretend_reg;
16275
16276    if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16277        return (-1);
16278    }
16279
16280    /* get my own pretend register */
16281    pretend_reg = bxe_get_pretend_reg(sc);
16282    REG_WR(sc, pretend_reg, pretend_func_val);
16283    REG_RD(sc, pretend_reg);
16284    return (0);
16285}
16286
16287static void
16288bxe_iov_init_dmae(struct bxe_softc *sc)
16289{
16290    return;
16291}
16292
16293static void
16294bxe_iov_init_dq(struct bxe_softc *sc)
16295{
16296    return;
16297}
16298
16299/* send a NIG loopback debug packet */
16300static void
16301bxe_lb_pckt(struct bxe_softc *sc)
16302{
16303    uint32_t wb_write[3];
16304
16305    /* Ethernet source and destination addresses */
16306    wb_write[0] = 0x55555555;
16307    wb_write[1] = 0x55555555;
16308    wb_write[2] = 0x20;     /* SOP */
16309    REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16310
16311    /* NON-IP protocol */
16312    wb_write[0] = 0x09000000;
16313    wb_write[1] = 0x55555555;
16314    wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16315    REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16316}
16317
16318/*
16319 * Some of the internal memories are not directly readable from the driver.
16320 * To test them we send debug packets.
16321 */
16322static int
16323bxe_int_mem_test(struct bxe_softc *sc)
16324{
16325    int factor;
16326    int count, i;
16327    uint32_t val = 0;
16328
16329    if (CHIP_REV_IS_FPGA(sc)) {
16330        factor = 120;
16331    } else if (CHIP_REV_IS_EMUL(sc)) {
16332        factor = 200;
16333    } else {
16334        factor = 1;
16335    }
16336
16337    /* disable inputs of parser neighbor blocks */
16338    REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16339    REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16340    REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16341    REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16342
16343    /*  write 0 to parser credits for CFC search request */
16344    REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16345
16346    /* send Ethernet packet */
16347    bxe_lb_pckt(sc);
16348
16349    /* TODO do i reset NIG statistic? */
16350    /* Wait until NIG register shows 1 packet of size 0x10 */
16351    count = 1000 * factor;
16352    while (count) {
16353        bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16354        val = *BXE_SP(sc, wb_data[0]);
16355        if (val == 0x10) {
16356            break;
16357        }
16358
16359        DELAY(10000);
16360        count--;
16361    }
16362
16363    if (val != 0x10) {
16364        BLOGE(sc, "NIG timeout val=0x%x\n", val);
16365        return (-1);
16366    }
16367
16368    /* wait until PRS register shows 1 packet */
16369    count = (1000 * factor);
16370    while (count) {
16371        val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16372        if (val == 1) {
16373            break;
16374        }
16375
16376        DELAY(10000);
16377        count--;
16378    }
16379
16380    if (val != 0x1) {
16381        BLOGE(sc, "PRS timeout val=0x%x\n", val);
16382        return (-2);
16383    }
16384
16385    /* Reset and init BRB, PRS */
16386    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16387    DELAY(50000);
16388    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16389    DELAY(50000);
16390    ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16391    ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16392
16393    /* Disable inputs of parser neighbor blocks */
16394    REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16395    REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16396    REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16397    REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16398
16399    /* Write 0 to parser credits for CFC search request */
16400    REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16401
16402    /* send 10 Ethernet packets */
16403    for (i = 0; i < 10; i++) {
16404        bxe_lb_pckt(sc);
16405    }
16406
16407    /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16408    count = (1000 * factor);
16409    while (count) {
16410        bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16411        val = *BXE_SP(sc, wb_data[0]);
16412        if (val == 0xb0) {
16413            break;
16414        }
16415
16416        DELAY(10000);
16417        count--;
16418    }
16419
16420    if (val != 0xb0) {
16421        BLOGE(sc, "NIG timeout val=0x%x\n", val);
16422        return (-3);
16423    }
16424
16425    /* Wait until PRS register shows 2 packets */
16426    val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16427    if (val != 2) {
16428        BLOGE(sc, "PRS timeout val=0x%x\n", val);
16429    }
16430
16431    /* Write 1 to parser credits for CFC search request */
16432    REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16433
16434    /* Wait until PRS register shows 3 packets */
16435    DELAY(10000 * factor);
16436
16437    /* Wait until NIG register shows 1 packet of size 0x10 */
16438    val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16439    if (val != 3) {
16440        BLOGE(sc, "PRS timeout val=0x%x\n", val);
16441    }
16442
16443    /* clear NIG EOP FIFO */
16444    for (i = 0; i < 11; i++) {
16445        REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16446    }
16447
16448    val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16449    if (val != 1) {
16450        BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16451        return (-4);
16452    }
16453
16454    /* Reset and init BRB, PRS, NIG */
16455    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16456    DELAY(50000);
16457    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16458    DELAY(50000);
16459    ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16460    ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16461    if (!CNIC_SUPPORT(sc)) {
16462        /* set NIC mode */
16463        REG_WR(sc, PRS_REG_NIC_MODE, 1);
16464    }
16465
16466    /* Enable inputs of parser neighbor blocks */
16467    REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16468    REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16469    REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16470    REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16471
16472    return (0);
16473}
16474
16475static void
16476bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16477{
16478    int is_required;
16479    uint32_t val;
16480    int port;
16481
16482    is_required = 0;
16483    val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16484           SHARED_HW_CFG_FAN_FAILURE_MASK);
16485
16486    if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16487        is_required = 1;
16488    }
16489    /*
16490     * The fan failure mechanism is usually related to the PHY type since
16491     * the power consumption of the board is affected by the PHY. Currently,
16492     * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16493     */
16494    else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16495        for (port = PORT_0; port < PORT_MAX; port++) {
16496            is_required |= elink_fan_failure_det_req(sc,
16497                                                     sc->devinfo.shmem_base,
16498                                                     sc->devinfo.shmem2_base,
16499                                                     port);
16500        }
16501    }
16502
16503    BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16504
16505    if (is_required == 0) {
16506        return;
16507    }
16508
16509    /* Fan failure is indicated by SPIO 5 */
16510    bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16511
16512    /* set to active low mode */
16513    val = REG_RD(sc, MISC_REG_SPIO_INT);
16514    val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16515    REG_WR(sc, MISC_REG_SPIO_INT, val);
16516
16517    /* enable interrupt to signal the IGU */
16518    val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16519    val |= MISC_SPIO_SPIO5;
16520    REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16521}
16522
16523static void
16524bxe_enable_blocks_attention(struct bxe_softc *sc)
16525{
16526    uint32_t val;
16527
16528    REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16529    if (!CHIP_IS_E1x(sc)) {
16530        REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16531    } else {
16532        REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16533    }
16534    REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16535    REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16536    /*
16537     * mask read length error interrupts in brb for parser
16538     * (parsing unit and 'checksum and crc' unit)
16539     * these errors are legal (PU reads fixed length and CAC can cause
16540     * read length error on truncated packets)
16541     */
16542    REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16543    REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16544    REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16545    REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16546    REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16547    REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16548/*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16549/*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16550    REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16551    REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16552    REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16553/*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16554/*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16555    REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16556    REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16557    REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16558    REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16559/*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16560/*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16561
16562    val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16563           PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16564           PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16565    if (!CHIP_IS_E1x(sc)) {
16566        val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16567                PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16568    }
16569    REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16570
16571    REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16572    REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16573    REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16574/*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16575
16576    if (!CHIP_IS_E1x(sc)) {
16577        /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16578        REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16579    }
16580
16581    REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16582    REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16583/*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16584    REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16585}
16586
16587/**
16588 * bxe_init_hw_common - initialize the HW at the COMMON phase.
16589 *
16590 * @sc:     driver handle
16591 */
16592static int
16593bxe_init_hw_common(struct bxe_softc *sc)
16594{
16595    uint8_t abs_func_id;
16596    uint32_t val;
16597
16598    BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16599          SC_ABS_FUNC(sc));
16600
16601    /*
16602     * take the RESET lock to protect undi_unload flow from accessing
16603     * registers while we are resetting the chip
16604     */
16605    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16606
16607    bxe_reset_common(sc);
16608
16609    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16610
16611    val = 0xfffc;
16612    if (CHIP_IS_E3(sc)) {
16613        val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16614        val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16615    }
16616
16617    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16618
16619    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16620
16621    ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16622    BLOGD(sc, DBG_LOAD, "after misc block init\n");
16623
16624    if (!CHIP_IS_E1x(sc)) {
16625        /*
16626         * 4-port mode or 2-port mode we need to turn off master-enable for
16627         * everyone. After that we turn it back on for self. So, we disregard
16628         * multi-function, and always disable all functions on the given path,
16629         * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16630         */
16631        for (abs_func_id = SC_PATH(sc);
16632             abs_func_id < (E2_FUNC_MAX * 2);
16633             abs_func_id += 2) {
16634            if (abs_func_id == SC_ABS_FUNC(sc)) {
16635                REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16636                continue;
16637            }
16638
16639            bxe_pretend_func(sc, abs_func_id);
16640
16641            /* clear pf enable */
16642            bxe_pf_disable(sc);
16643
16644            bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16645        }
16646    }
16647
16648    BLOGD(sc, DBG_LOAD, "after pf disable\n");
16649
16650    ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16651
16652    if (CHIP_IS_E1(sc)) {
16653        /*
16654         * enable HW interrupt from PXP on USDM overflow
16655         * bit 16 on INT_MASK_0
16656         */
16657        REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16658    }
16659
16660    ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16661    bxe_init_pxp(sc);
16662
16663#ifdef __BIG_ENDIAN
16664    REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16665    REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16666    REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16667    REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16668    REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16669    /* make sure this value is 0 */
16670    REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16671
16672    //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16673    REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16674    REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16675    REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16676    REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16677#endif
16678
16679    ecore_ilt_init_page_size(sc, INITOP_SET);
16680
16681    if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16682        REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16683    }
16684
16685    /* let the HW do it's magic... */
16686    DELAY(100000);
16687
16688    /* finish PXP init */
16689    val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16690    if (val != 1) {
16691        BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16692            val);
16693        return (-1);
16694    }
16695    val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16696    if (val != 1) {
16697        BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16698        return (-1);
16699    }
16700
16701    BLOGD(sc, DBG_LOAD, "after pxp init\n");
16702
16703    /*
16704     * Timer bug workaround for E2 only. We need to set the entire ILT to have
16705     * entries with value "0" and valid bit on. This needs to be done by the
16706     * first PF that is loaded in a path (i.e. common phase)
16707     */
16708    if (!CHIP_IS_E1x(sc)) {
16709/*
16710 * In E2 there is a bug in the timers block that can cause function 6 / 7
16711 * (i.e. vnic3) to start even if it is marked as "scan-off".
16712 * This occurs when a different function (func2,3) is being marked
16713 * as "scan-off". Real-life scenario for example: if a driver is being
16714 * load-unloaded while func6,7 are down. This will cause the timer to access
16715 * the ilt, translate to a logical address and send a request to read/write.
16716 * Since the ilt for the function that is down is not valid, this will cause
16717 * a translation error which is unrecoverable.
16718 * The Workaround is intended to make sure that when this happens nothing
16719 * fatal will occur. The workaround:
16720 *  1.  First PF driver which loads on a path will:
16721 *      a.  After taking the chip out of reset, by using pretend,
16722 *          it will write "0" to the following registers of
16723 *          the other vnics.
16724 *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16725 *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16726 *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16727 *          And for itself it will write '1' to
16728 *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16729 *          dmae-operations (writing to pram for example.)
16730 *          note: can be done for only function 6,7 but cleaner this
16731 *            way.
16732 *      b.  Write zero+valid to the entire ILT.
16733 *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16734 *          VNIC3 (of that port). The range allocated will be the
16735 *          entire ILT. This is needed to prevent  ILT range error.
16736 *  2.  Any PF driver load flow:
16737 *      a.  ILT update with the physical addresses of the allocated
16738 *          logical pages.
16739 *      b.  Wait 20msec. - note that this timeout is needed to make
16740 *          sure there are no requests in one of the PXP internal
16741 *          queues with "old" ILT addresses.
16742 *      c.  PF enable in the PGLC.
16743 *      d.  Clear the was_error of the PF in the PGLC. (could have
16744 *          occurred while driver was down)
16745 *      e.  PF enable in the CFC (WEAK + STRONG)
16746 *      f.  Timers scan enable
16747 *  3.  PF driver unload flow:
16748 *      a.  Clear the Timers scan_en.
16749 *      b.  Polling for scan_on=0 for that PF.
16750 *      c.  Clear the PF enable bit in the PXP.
16751 *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16752 *      e.  Write zero+valid to all ILT entries (The valid bit must
16753 *          stay set)
16754 *      f.  If this is VNIC 3 of a port then also init
16755 *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16756 *          to the last enrty in the ILT.
16757 *
16758 *      Notes:
16759 *      Currently the PF error in the PGLC is non recoverable.
16760 *      In the future the there will be a recovery routine for this error.
16761 *      Currently attention is masked.
16762 *      Having an MCP lock on the load/unload process does not guarantee that
16763 *      there is no Timer disable during Func6/7 enable. This is because the
16764 *      Timers scan is currently being cleared by the MCP on FLR.
16765 *      Step 2.d can be done only for PF6/7 and the driver can also check if
16766 *      there is error before clearing it. But the flow above is simpler and
16767 *      more general.
16768 *      All ILT entries are written by zero+valid and not just PF6/7
16769 *      ILT entries since in the future the ILT entries allocation for
16770 *      PF-s might be dynamic.
16771 */
16772        struct ilt_client_info ilt_cli;
16773        struct ecore_ilt ilt;
16774
16775        memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16776        memset(&ilt, 0, sizeof(struct ecore_ilt));
16777
16778        /* initialize dummy TM client */
16779        ilt_cli.start      = 0;
16780        ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16781        ilt_cli.client_num = ILT_CLIENT_TM;
16782
16783        /*
16784         * Step 1: set zeroes to all ilt page entries with valid bit on
16785         * Step 2: set the timers first/last ilt entry to point
16786         * to the entire range to prevent ILT range error for 3rd/4th
16787         * vnic (this code assumes existence of the vnic)
16788         *
16789         * both steps performed by call to ecore_ilt_client_init_op()
16790         * with dummy TM client
16791         *
16792         * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16793         * and his brother are split registers
16794         */
16795
16796        bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16797        ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16798        bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16799
16800        REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16801        REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16802        REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16803    }
16804
16805    REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16806    REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16807
16808    if (!CHIP_IS_E1x(sc)) {
16809        int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16810                     (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
16811
16812        ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
16813        ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
16814
16815        /* let the HW do it's magic... */
16816        do {
16817            DELAY(200000);
16818            val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
16819        } while (factor-- && (val != 1));
16820
16821        if (val != 1) {
16822            BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
16823            return (-1);
16824        }
16825    }
16826
16827    BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
16828
16829    ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
16830
16831    bxe_iov_init_dmae(sc);
16832
16833    /* clean the DMAE memory */
16834    sc->dmae_ready = 1;
16835    ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
16836
16837    ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
16838
16839    ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
16840
16841    ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
16842
16843    ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
16844
16845    bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
16846    bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
16847    bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
16848    bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
16849
16850    ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
16851
16852    /* QM queues pointers table */
16853    ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
16854
16855    /* soft reset pulse */
16856    REG_WR(sc, QM_REG_SOFT_RESET, 1);
16857    REG_WR(sc, QM_REG_SOFT_RESET, 0);
16858
16859    if (CNIC_SUPPORT(sc))
16860        ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
16861
16862    ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
16863    REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
16864    if (!CHIP_REV_IS_SLOW(sc)) {
16865        /* enable hw interrupt from doorbell Q */
16866        REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16867    }
16868
16869    ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16870
16871    ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16872    REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
16873
16874    if (!CHIP_IS_E1(sc)) {
16875        REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
16876    }
16877
16878    if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
16879        if (IS_MF_AFEX(sc)) {
16880            /*
16881             * configure that AFEX and VLAN headers must be
16882             * received in AFEX mode
16883             */
16884            REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
16885            REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
16886            REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
16887            REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
16888            REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
16889        } else {
16890            /*
16891             * Bit-map indicating which L2 hdrs may appear
16892             * after the basic Ethernet header
16893             */
16894            REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
16895                   sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
16896        }
16897    }
16898
16899    ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
16900    ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
16901    ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
16902    ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
16903
16904    if (!CHIP_IS_E1x(sc)) {
16905        /* reset VFC memories */
16906        REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
16907               VFC_MEMORIES_RST_REG_CAM_RST |
16908               VFC_MEMORIES_RST_REG_RAM_RST);
16909        REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
16910               VFC_MEMORIES_RST_REG_CAM_RST |
16911               VFC_MEMORIES_RST_REG_RAM_RST);
16912
16913        DELAY(20000);
16914    }
16915
16916    ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
16917    ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
16918    ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
16919    ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
16920
16921    /* sync semi rtc */
16922    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
16923           0x80000000);
16924    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
16925           0x80000000);
16926
16927    ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
16928    ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
16929    ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
16930
16931    if (!CHIP_IS_E1x(sc)) {
16932        if (IS_MF_AFEX(sc)) {
16933            /*
16934             * configure that AFEX and VLAN headers must be
16935             * sent in AFEX mode
16936             */
16937            REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
16938            REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
16939            REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
16940            REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
16941            REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
16942        } else {
16943            REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
16944                   sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
16945        }
16946    }
16947
16948    REG_WR(sc, SRC_REG_SOFT_RST, 1);
16949
16950    ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
16951
16952    if (CNIC_SUPPORT(sc)) {
16953        REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
16954        REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
16955        REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
16956        REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
16957        REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
16958        REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
16959        REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
16960        REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
16961        REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
16962        REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
16963    }
16964    REG_WR(sc, SRC_REG_SOFT_RST, 0);
16965
16966    if (sizeof(union cdu_context) != 1024) {
16967        /* we currently assume that a context is 1024 bytes */
16968        BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
16969              (long)sizeof(union cdu_context));
16970    }
16971
16972    ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
16973    val = (4 << 24) + (0 << 12) + 1024;
16974    REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
16975
16976    ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
16977
16978    REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
16979    /* enable context validation interrupt from CFC */
16980    REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16981
16982    /* set the thresholds to prevent CFC/CDU race */
16983    REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
16984    ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
16985
16986    if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
16987        REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
16988    }
16989
16990    ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
16991    ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
16992
16993    /* Reset PCIE errors for debug */
16994    REG_WR(sc, 0x2814, 0xffffffff);
16995    REG_WR(sc, 0x3820, 0xffffffff);
16996
16997    if (!CHIP_IS_E1x(sc)) {
16998        REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
16999               (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17000                PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17001        REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17002               (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17003                PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17004                PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17005        REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17006               (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17007                PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17008                PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17009    }
17010
17011    ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17012
17013    if (!CHIP_IS_E1(sc)) {
17014        /* in E3 this done in per-port section */
17015        if (!CHIP_IS_E3(sc))
17016            REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17017    }
17018
17019    if (CHIP_IS_E1H(sc)) {
17020        /* not applicable for E2 (and above ...) */
17021        REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17022    }
17023
17024    if (CHIP_REV_IS_SLOW(sc)) {
17025        DELAY(200000);
17026    }
17027
17028    /* finish CFC init */
17029    val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17030    if (val != 1) {
17031        BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17032        return (-1);
17033    }
17034    val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17035    if (val != 1) {
17036        BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17037        return (-1);
17038    }
17039    val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17040    if (val != 1) {
17041        BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17042        return (-1);
17043    }
17044    REG_WR(sc, CFC_REG_DEBUG0, 0);
17045
17046    if (CHIP_IS_E1(sc)) {
17047        /* read NIG statistic to see if this is our first up since powerup */
17048        bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17049        val = *BXE_SP(sc, wb_data[0]);
17050
17051        /* do internal memory self test */
17052        if ((val == 0) && bxe_int_mem_test(sc)) {
17053            BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17054            return (-1);
17055        }
17056    }
17057
17058    bxe_setup_fan_failure_detection(sc);
17059
17060    /* clear PXP2 attentions */
17061    REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17062
17063    bxe_enable_blocks_attention(sc);
17064
17065    if (!CHIP_REV_IS_SLOW(sc)) {
17066        ecore_enable_blocks_parity(sc);
17067    }
17068
17069    if (!BXE_NOMCP(sc)) {
17070        if (CHIP_IS_E1x(sc)) {
17071            bxe_common_init_phy(sc);
17072        }
17073    }
17074
17075    return (0);
17076}
17077
17078/**
17079 * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17080 *
17081 * @sc:     driver handle
17082 */
17083static int
17084bxe_init_hw_common_chip(struct bxe_softc *sc)
17085{
17086    int rc = bxe_init_hw_common(sc);
17087
17088    if (rc) {
17089        BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17090        return (rc);
17091    }
17092
17093    /* In E2 2-PORT mode, same ext phy is used for the two paths */
17094    if (!BXE_NOMCP(sc)) {
17095        bxe_common_init_phy(sc);
17096    }
17097
17098    return (0);
17099}
17100
17101static int
17102bxe_init_hw_port(struct bxe_softc *sc)
17103{
17104    int port = SC_PORT(sc);
17105    int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17106    uint32_t low, high;
17107    uint32_t val;
17108
17109    BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17110
17111    REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17112
17113    ecore_init_block(sc, BLOCK_MISC, init_phase);
17114    ecore_init_block(sc, BLOCK_PXP, init_phase);
17115    ecore_init_block(sc, BLOCK_PXP2, init_phase);
17116
17117    /*
17118     * Timers bug workaround: disables the pf_master bit in pglue at
17119     * common phase, we need to enable it here before any dmae access are
17120     * attempted. Therefore we manually added the enable-master to the
17121     * port phase (it also happens in the function phase)
17122     */
17123    if (!CHIP_IS_E1x(sc)) {
17124        REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17125    }
17126
17127    ecore_init_block(sc, BLOCK_ATC, init_phase);
17128    ecore_init_block(sc, BLOCK_DMAE, init_phase);
17129    ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17130    ecore_init_block(sc, BLOCK_QM, init_phase);
17131
17132    ecore_init_block(sc, BLOCK_TCM, init_phase);
17133    ecore_init_block(sc, BLOCK_UCM, init_phase);
17134    ecore_init_block(sc, BLOCK_CCM, init_phase);
17135    ecore_init_block(sc, BLOCK_XCM, init_phase);
17136
17137    /* QM cid (connection) count */
17138    ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17139
17140    if (CNIC_SUPPORT(sc)) {
17141        ecore_init_block(sc, BLOCK_TM, init_phase);
17142        REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17143        REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17144    }
17145
17146    ecore_init_block(sc, BLOCK_DORQ, init_phase);
17147
17148    ecore_init_block(sc, BLOCK_BRB1, init_phase);
17149
17150    if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17151        if (IS_MF(sc)) {
17152            low = (BXE_ONE_PORT(sc) ? 160 : 246);
17153        } else if (sc->mtu > 4096) {
17154            if (BXE_ONE_PORT(sc)) {
17155                low = 160;
17156            } else {
17157                val = sc->mtu;
17158                /* (24*1024 + val*4)/256 */
17159                low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17160            }
17161        } else {
17162            low = (BXE_ONE_PORT(sc) ? 80 : 160);
17163        }
17164        high = (low + 56); /* 14*1024/256 */
17165        REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17166        REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17167    }
17168
17169    if (CHIP_IS_MODE_4_PORT(sc)) {
17170        REG_WR(sc, SC_PORT(sc) ?
17171               BRB1_REG_MAC_GUARANTIED_1 :
17172               BRB1_REG_MAC_GUARANTIED_0, 40);
17173    }
17174
17175    ecore_init_block(sc, BLOCK_PRS, init_phase);
17176    if (CHIP_IS_E3B0(sc)) {
17177        if (IS_MF_AFEX(sc)) {
17178            /* configure headers for AFEX mode */
17179            REG_WR(sc, SC_PORT(sc) ?
17180                   PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17181                   PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17182            REG_WR(sc, SC_PORT(sc) ?
17183                   PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17184                   PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17185            REG_WR(sc, SC_PORT(sc) ?
17186                   PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17187                   PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17188        } else {
17189            /* Ovlan exists only if we are in multi-function +
17190             * switch-dependent mode, in switch-independent there
17191             * is no ovlan headers
17192             */
17193            REG_WR(sc, SC_PORT(sc) ?
17194                   PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17195                   PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17196                   (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17197        }
17198    }
17199
17200    ecore_init_block(sc, BLOCK_TSDM, init_phase);
17201    ecore_init_block(sc, BLOCK_CSDM, init_phase);
17202    ecore_init_block(sc, BLOCK_USDM, init_phase);
17203    ecore_init_block(sc, BLOCK_XSDM, init_phase);
17204
17205    ecore_init_block(sc, BLOCK_TSEM, init_phase);
17206    ecore_init_block(sc, BLOCK_USEM, init_phase);
17207    ecore_init_block(sc, BLOCK_CSEM, init_phase);
17208    ecore_init_block(sc, BLOCK_XSEM, init_phase);
17209
17210    ecore_init_block(sc, BLOCK_UPB, init_phase);
17211    ecore_init_block(sc, BLOCK_XPB, init_phase);
17212
17213    ecore_init_block(sc, BLOCK_PBF, init_phase);
17214
17215    if (CHIP_IS_E1x(sc)) {
17216        /* configure PBF to work without PAUSE mtu 9000 */
17217        REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17218
17219        /* update threshold */
17220        REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17221        /* update init credit */
17222        REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17223
17224        /* probe changes */
17225        REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17226        DELAY(50);
17227        REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17228    }
17229
17230    if (CNIC_SUPPORT(sc)) {
17231        ecore_init_block(sc, BLOCK_SRC, init_phase);
17232    }
17233
17234    ecore_init_block(sc, BLOCK_CDU, init_phase);
17235    ecore_init_block(sc, BLOCK_CFC, init_phase);
17236
17237    if (CHIP_IS_E1(sc)) {
17238        REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17239        REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17240    }
17241    ecore_init_block(sc, BLOCK_HC, init_phase);
17242
17243    ecore_init_block(sc, BLOCK_IGU, init_phase);
17244
17245    ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17246    /* init aeu_mask_attn_func_0/1:
17247     *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17248     *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17249     *             bits 4-7 are used for "per vn group attention" */
17250    val = IS_MF(sc) ? 0xF7 : 0x7;
17251    /* Enable DCBX attention for all but E1 */
17252    val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17253    REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17254
17255    ecore_init_block(sc, BLOCK_NIG, init_phase);
17256
17257    if (!CHIP_IS_E1x(sc)) {
17258        /* Bit-map indicating which L2 hdrs may appear after the
17259         * basic Ethernet header
17260         */
17261        if (IS_MF_AFEX(sc)) {
17262            REG_WR(sc, SC_PORT(sc) ?
17263                   NIG_REG_P1_HDRS_AFTER_BASIC :
17264                   NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17265        } else {
17266            REG_WR(sc, SC_PORT(sc) ?
17267                   NIG_REG_P1_HDRS_AFTER_BASIC :
17268                   NIG_REG_P0_HDRS_AFTER_BASIC,
17269                   IS_MF_SD(sc) ? 7 : 6);
17270        }
17271
17272        if (CHIP_IS_E3(sc)) {
17273            REG_WR(sc, SC_PORT(sc) ?
17274                   NIG_REG_LLH1_MF_MODE :
17275                   NIG_REG_LLH_MF_MODE, IS_MF(sc));
17276        }
17277    }
17278    if (!CHIP_IS_E3(sc)) {
17279        REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17280    }
17281
17282    if (!CHIP_IS_E1(sc)) {
17283        /* 0x2 disable mf_ov, 0x1 enable */
17284        REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17285               (IS_MF_SD(sc) ? 0x1 : 0x2));
17286
17287        if (!CHIP_IS_E1x(sc)) {
17288            val = 0;
17289            switch (sc->devinfo.mf_info.mf_mode) {
17290            case MULTI_FUNCTION_SD:
17291                val = 1;
17292                break;
17293            case MULTI_FUNCTION_SI:
17294            case MULTI_FUNCTION_AFEX:
17295                val = 2;
17296                break;
17297            }
17298
17299            REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17300                        NIG_REG_LLH0_CLS_TYPE), val);
17301        }
17302        REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17303        REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17304        REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17305    }
17306
17307    /* If SPIO5 is set to generate interrupts, enable it for this port */
17308    val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17309    if (val & MISC_SPIO_SPIO5) {
17310        uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17311                                    MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17312        val = REG_RD(sc, reg_addr);
17313        val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17314        REG_WR(sc, reg_addr, val);
17315    }
17316
17317    return (0);
17318}
17319
17320static uint32_t
17321bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17322                       uint32_t         reg,
17323                       uint32_t         expected,
17324                       uint32_t         poll_count)
17325{
17326    uint32_t cur_cnt = poll_count;
17327    uint32_t val;
17328
17329    while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17330        DELAY(FLR_WAIT_INTERVAL);
17331    }
17332
17333    return (val);
17334}
17335
17336static int
17337bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17338                              uint32_t         reg,
17339                              char             *msg,
17340                              uint32_t         poll_cnt)
17341{
17342    uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17343
17344    if (val != 0) {
17345        BLOGE(sc, "%s usage count=%d\n", msg, val);
17346        return (1);
17347    }
17348
17349    return (0);
17350}
17351
17352/* Common routines with VF FLR cleanup */
17353static uint32_t
17354bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17355{
17356    /* adjust polling timeout */
17357    if (CHIP_REV_IS_EMUL(sc)) {
17358        return (FLR_POLL_CNT * 2000);
17359    }
17360
17361    if (CHIP_REV_IS_FPGA(sc)) {
17362        return (FLR_POLL_CNT * 120);
17363    }
17364
17365    return (FLR_POLL_CNT);
17366}
17367
17368static int
17369bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17370                           uint32_t         poll_cnt)
17371{
17372    /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17373    if (bxe_flr_clnup_poll_hw_counter(sc,
17374                                      CFC_REG_NUM_LCIDS_INSIDE_PF,
17375                                      "CFC PF usage counter timed out",
17376                                      poll_cnt)) {
17377        return (1);
17378    }
17379
17380    /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17381    if (bxe_flr_clnup_poll_hw_counter(sc,
17382                                      DORQ_REG_PF_USAGE_CNT,
17383                                      "DQ PF usage counter timed out",
17384                                      poll_cnt)) {
17385        return (1);
17386    }
17387
17388    /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17389    if (bxe_flr_clnup_poll_hw_counter(sc,
17390                                      QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17391                                      "QM PF usage counter timed out",
17392                                      poll_cnt)) {
17393        return (1);
17394    }
17395
17396    /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17397    if (bxe_flr_clnup_poll_hw_counter(sc,
17398                                      TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17399                                      "Timers VNIC usage counter timed out",
17400                                      poll_cnt)) {
17401        return (1);
17402    }
17403
17404    if (bxe_flr_clnup_poll_hw_counter(sc,
17405                                      TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17406                                      "Timers NUM_SCANS usage counter timed out",
17407                                      poll_cnt)) {
17408        return (1);
17409    }
17410
17411    /* Wait DMAE PF usage counter to zero */
17412    if (bxe_flr_clnup_poll_hw_counter(sc,
17413                                      dmae_reg_go_c[INIT_DMAE_C(sc)],
17414                                      "DMAE dommand register timed out",
17415                                      poll_cnt)) {
17416        return (1);
17417    }
17418
17419    return (0);
17420}
17421
17422#define OP_GEN_PARAM(param)                                            \
17423    (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17424#define OP_GEN_TYPE(type)                                           \
17425    (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17426#define OP_GEN_AGG_VECT(index)                                             \
17427    (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17428
17429static int
17430bxe_send_final_clnup(struct bxe_softc *sc,
17431                     uint8_t          clnup_func,
17432                     uint32_t         poll_cnt)
17433{
17434    uint32_t op_gen_command = 0;
17435    uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17436                          CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17437    int ret = 0;
17438
17439    if (REG_RD(sc, comp_addr)) {
17440        BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17441        return (1);
17442    }
17443
17444    op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17445    op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17446    op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17447    op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17448
17449    BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17450    REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17451
17452    if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17453        BLOGE(sc, "FW final cleanup did not succeed\n");
17454        BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17455              (REG_RD(sc, comp_addr)));
17456        bxe_panic(sc, ("FLR cleanup failed\n"));
17457        return (1);
17458    }
17459
17460    /* Zero completion for nxt FLR */
17461    REG_WR(sc, comp_addr, 0);
17462
17463    return (ret);
17464}
17465
17466static void
17467bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17468                       struct pbf_pN_buf_regs *regs,
17469                       uint32_t               poll_count)
17470{
17471    uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17472    uint32_t cur_cnt = poll_count;
17473
17474    crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17475    crd = crd_start = REG_RD(sc, regs->crd);
17476    init_crd = REG_RD(sc, regs->init_crd);
17477
17478    BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17479    BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17480    BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17481
17482    while ((crd != init_crd) &&
17483           ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17484            (init_crd - crd_start))) {
17485        if (cur_cnt--) {
17486            DELAY(FLR_WAIT_INTERVAL);
17487            crd = REG_RD(sc, regs->crd);
17488            crd_freed = REG_RD(sc, regs->crd_freed);
17489        } else {
17490            BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17491            BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17492            BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17493            break;
17494        }
17495    }
17496
17497    BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17498          poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17499}
17500
17501static void
17502bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17503                       struct pbf_pN_cmd_regs *regs,
17504                       uint32_t               poll_count)
17505{
17506    uint32_t occup, to_free, freed, freed_start;
17507    uint32_t cur_cnt = poll_count;
17508
17509    occup = to_free = REG_RD(sc, regs->lines_occup);
17510    freed = freed_start = REG_RD(sc, regs->lines_freed);
17511
17512    BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17513    BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17514
17515    while (occup &&
17516           ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17517        if (cur_cnt--) {
17518            DELAY(FLR_WAIT_INTERVAL);
17519            occup = REG_RD(sc, regs->lines_occup);
17520            freed = REG_RD(sc, regs->lines_freed);
17521        } else {
17522            BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17523            BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17524            BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17525            break;
17526        }
17527    }
17528
17529    BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17530          poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17531}
17532
17533static void
17534bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17535{
17536    struct pbf_pN_cmd_regs cmd_regs[] = {
17537        {0, (CHIP_IS_E3B0(sc)) ?
17538            PBF_REG_TQ_OCCUPANCY_Q0 :
17539            PBF_REG_P0_TQ_OCCUPANCY,
17540            (CHIP_IS_E3B0(sc)) ?
17541            PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17542            PBF_REG_P0_TQ_LINES_FREED_CNT},
17543        {1, (CHIP_IS_E3B0(sc)) ?
17544            PBF_REG_TQ_OCCUPANCY_Q1 :
17545            PBF_REG_P1_TQ_OCCUPANCY,
17546            (CHIP_IS_E3B0(sc)) ?
17547            PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17548            PBF_REG_P1_TQ_LINES_FREED_CNT},
17549        {4, (CHIP_IS_E3B0(sc)) ?
17550            PBF_REG_TQ_OCCUPANCY_LB_Q :
17551            PBF_REG_P4_TQ_OCCUPANCY,
17552            (CHIP_IS_E3B0(sc)) ?
17553            PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17554            PBF_REG_P4_TQ_LINES_FREED_CNT}
17555    };
17556
17557    struct pbf_pN_buf_regs buf_regs[] = {
17558        {0, (CHIP_IS_E3B0(sc)) ?
17559            PBF_REG_INIT_CRD_Q0 :
17560            PBF_REG_P0_INIT_CRD ,
17561            (CHIP_IS_E3B0(sc)) ?
17562            PBF_REG_CREDIT_Q0 :
17563            PBF_REG_P0_CREDIT,
17564            (CHIP_IS_E3B0(sc)) ?
17565            PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17566            PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17567        {1, (CHIP_IS_E3B0(sc)) ?
17568            PBF_REG_INIT_CRD_Q1 :
17569            PBF_REG_P1_INIT_CRD,
17570            (CHIP_IS_E3B0(sc)) ?
17571            PBF_REG_CREDIT_Q1 :
17572            PBF_REG_P1_CREDIT,
17573            (CHIP_IS_E3B0(sc)) ?
17574            PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17575            PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17576        {4, (CHIP_IS_E3B0(sc)) ?
17577            PBF_REG_INIT_CRD_LB_Q :
17578            PBF_REG_P4_INIT_CRD,
17579            (CHIP_IS_E3B0(sc)) ?
17580            PBF_REG_CREDIT_LB_Q :
17581            PBF_REG_P4_CREDIT,
17582            (CHIP_IS_E3B0(sc)) ?
17583            PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17584            PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17585    };
17586
17587    int i;
17588
17589    /* Verify the command queues are flushed P0, P1, P4 */
17590    for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17591        bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17592    }
17593
17594    /* Verify the transmission buffers are flushed P0, P1, P4 */
17595    for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17596        bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17597    }
17598}
17599
17600static void
17601bxe_hw_enable_status(struct bxe_softc *sc)
17602{
17603    uint32_t val;
17604
17605    val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17606    BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17607
17608    val = REG_RD(sc, PBF_REG_DISABLE_PF);
17609    BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17610
17611    val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17612    BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17613
17614    val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17615    BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17616
17617    val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17618    BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17619
17620    val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17621    BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17622
17623    val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17624    BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17625
17626    val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17627    BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17628}
17629
17630static int
17631bxe_pf_flr_clnup(struct bxe_softc *sc)
17632{
17633    uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17634
17635    BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17636
17637    /* Re-enable PF target read access */
17638    REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17639
17640    /* Poll HW usage counters */
17641    BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17642    if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17643        return (-1);
17644    }
17645
17646    /* Zero the igu 'trailing edge' and 'leading edge' */
17647
17648    /* Send the FW cleanup command */
17649    if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17650        return (-1);
17651    }
17652
17653    /* ATC cleanup */
17654
17655    /* Verify TX hw is flushed */
17656    bxe_tx_hw_flushed(sc, poll_cnt);
17657
17658    /* Wait 100ms (not adjusted according to platform) */
17659    DELAY(100000);
17660
17661    /* Verify no pending pci transactions */
17662    if (bxe_is_pcie_pending(sc)) {
17663        BLOGE(sc, "PCIE Transactions still pending\n");
17664    }
17665
17666    /* Debug */
17667    bxe_hw_enable_status(sc);
17668
17669    /*
17670     * Master enable - Due to WB DMAE writes performed before this
17671     * register is re-initialized as part of the regular function init
17672     */
17673    REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17674
17675    return (0);
17676}
17677
17678static int
17679bxe_init_hw_func(struct bxe_softc *sc)
17680{
17681    int port = SC_PORT(sc);
17682    int func = SC_FUNC(sc);
17683    int init_phase = PHASE_PF0 + func;
17684    struct ecore_ilt *ilt = sc->ilt;
17685    uint16_t cdu_ilt_start;
17686    uint32_t addr, val;
17687    uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17688    int i, main_mem_width, rc;
17689
17690    BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17691
17692    /* FLR cleanup */
17693    if (!CHIP_IS_E1x(sc)) {
17694        rc = bxe_pf_flr_clnup(sc);
17695        if (rc) {
17696            BLOGE(sc, "FLR cleanup failed!\n");
17697            // XXX bxe_fw_dump(sc);
17698            // XXX bxe_idle_chk(sc);
17699            return (rc);
17700        }
17701    }
17702
17703    /* set MSI reconfigure capability */
17704    if (sc->devinfo.int_block == INT_BLOCK_HC) {
17705        addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17706        val = REG_RD(sc, addr);
17707        val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17708        REG_WR(sc, addr, val);
17709    }
17710
17711    ecore_init_block(sc, BLOCK_PXP, init_phase);
17712    ecore_init_block(sc, BLOCK_PXP2, init_phase);
17713
17714    ilt = sc->ilt;
17715    cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17716
17717    for (i = 0; i < L2_ILT_LINES(sc); i++) {
17718        ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17719        ilt->lines[cdu_ilt_start + i].page_mapping =
17720            sc->context[i].vcxt_dma.paddr;
17721        ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17722    }
17723    ecore_ilt_init_op(sc, INITOP_SET);
17724
17725    /* Set NIC mode */
17726    REG_WR(sc, PRS_REG_NIC_MODE, 1);
17727    BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17728
17729    if (!CHIP_IS_E1x(sc)) {
17730        uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17731
17732        /* Turn on a single ISR mode in IGU if driver is going to use
17733         * INT#x or MSI
17734         */
17735        if (sc->interrupt_mode != INTR_MODE_MSIX) {
17736            pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17737        }
17738
17739        /*
17740         * Timers workaround bug: function init part.
17741         * Need to wait 20msec after initializing ILT,
17742         * needed to make sure there are no requests in
17743         * one of the PXP internal queues with "old" ILT addresses
17744         */
17745        DELAY(20000);
17746
17747        /*
17748         * Master enable - Due to WB DMAE writes performed before this
17749         * register is re-initialized as part of the regular function
17750         * init
17751         */
17752        REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17753        /* Enable the function in IGU */
17754        REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17755    }
17756
17757    sc->dmae_ready = 1;
17758
17759    ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17760
17761    if (!CHIP_IS_E1x(sc))
17762        REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17763
17764    ecore_init_block(sc, BLOCK_ATC, init_phase);
17765    ecore_init_block(sc, BLOCK_DMAE, init_phase);
17766    ecore_init_block(sc, BLOCK_NIG, init_phase);
17767    ecore_init_block(sc, BLOCK_SRC, init_phase);
17768    ecore_init_block(sc, BLOCK_MISC, init_phase);
17769    ecore_init_block(sc, BLOCK_TCM, init_phase);
17770    ecore_init_block(sc, BLOCK_UCM, init_phase);
17771    ecore_init_block(sc, BLOCK_CCM, init_phase);
17772    ecore_init_block(sc, BLOCK_XCM, init_phase);
17773    ecore_init_block(sc, BLOCK_TSEM, init_phase);
17774    ecore_init_block(sc, BLOCK_USEM, init_phase);
17775    ecore_init_block(sc, BLOCK_CSEM, init_phase);
17776    ecore_init_block(sc, BLOCK_XSEM, init_phase);
17777
17778    if (!CHIP_IS_E1x(sc))
17779        REG_WR(sc, QM_REG_PF_EN, 1);
17780
17781    if (!CHIP_IS_E1x(sc)) {
17782        REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17783        REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17784        REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17785        REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17786    }
17787    ecore_init_block(sc, BLOCK_QM, init_phase);
17788
17789    ecore_init_block(sc, BLOCK_TM, init_phase);
17790    ecore_init_block(sc, BLOCK_DORQ, init_phase);
17791
17792    bxe_iov_init_dq(sc);
17793
17794    ecore_init_block(sc, BLOCK_BRB1, init_phase);
17795    ecore_init_block(sc, BLOCK_PRS, init_phase);
17796    ecore_init_block(sc, BLOCK_TSDM, init_phase);
17797    ecore_init_block(sc, BLOCK_CSDM, init_phase);
17798    ecore_init_block(sc, BLOCK_USDM, init_phase);
17799    ecore_init_block(sc, BLOCK_XSDM, init_phase);
17800    ecore_init_block(sc, BLOCK_UPB, init_phase);
17801    ecore_init_block(sc, BLOCK_XPB, init_phase);
17802    ecore_init_block(sc, BLOCK_PBF, init_phase);
17803    if (!CHIP_IS_E1x(sc))
17804        REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17805
17806    ecore_init_block(sc, BLOCK_CDU, init_phase);
17807
17808    ecore_init_block(sc, BLOCK_CFC, init_phase);
17809
17810    if (!CHIP_IS_E1x(sc))
17811        REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
17812
17813    if (IS_MF(sc)) {
17814        REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
17815        REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
17816    }
17817
17818    ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17819
17820    /* HC init per function */
17821    if (sc->devinfo.int_block == INT_BLOCK_HC) {
17822        if (CHIP_IS_E1H(sc)) {
17823            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17824
17825            REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17826            REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17827        }
17828        ecore_init_block(sc, BLOCK_HC, init_phase);
17829
17830    } else {
17831        int num_segs, sb_idx, prod_offset;
17832
17833        REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17834
17835        if (!CHIP_IS_E1x(sc)) {
17836            REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
17837            REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
17838        }
17839
17840        ecore_init_block(sc, BLOCK_IGU, init_phase);
17841
17842        if (!CHIP_IS_E1x(sc)) {
17843            int dsb_idx = 0;
17844            /**
17845             * Producer memory:
17846             * E2 mode: address 0-135 match to the mapping memory;
17847             * 136 - PF0 default prod; 137 - PF1 default prod;
17848             * 138 - PF2 default prod; 139 - PF3 default prod;
17849             * 140 - PF0 attn prod;    141 - PF1 attn prod;
17850             * 142 - PF2 attn prod;    143 - PF3 attn prod;
17851             * 144-147 reserved.
17852             *
17853             * E1.5 mode - In backward compatible mode;
17854             * for non default SB; each even line in the memory
17855             * holds the U producer and each odd line hold
17856             * the C producer. The first 128 producers are for
17857             * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
17858             * producers are for the DSB for each PF.
17859             * Each PF has five segments: (the order inside each
17860             * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
17861             * 132-135 C prods; 136-139 X prods; 140-143 T prods;
17862             * 144-147 attn prods;
17863             */
17864            /* non-default-status-blocks */
17865            num_segs = CHIP_INT_MODE_IS_BC(sc) ?
17866                IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
17867            for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
17868                prod_offset = (sc->igu_base_sb + sb_idx) *
17869                    num_segs;
17870
17871                for (i = 0; i < num_segs; i++) {
17872                    addr = IGU_REG_PROD_CONS_MEMORY +
17873                            (prod_offset + i) * 4;
17874                    REG_WR(sc, addr, 0);
17875                }
17876                /* send consumer update with value 0 */
17877                bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
17878                           USTORM_ID, 0, IGU_INT_NOP, 1);
17879                bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
17880            }
17881
17882            /* default-status-blocks */
17883            num_segs = CHIP_INT_MODE_IS_BC(sc) ?
17884                IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
17885
17886            if (CHIP_IS_MODE_4_PORT(sc))
17887                dsb_idx = SC_FUNC(sc);
17888            else
17889                dsb_idx = SC_VN(sc);
17890
17891            prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
17892                       IGU_BC_BASE_DSB_PROD + dsb_idx :
17893                       IGU_NORM_BASE_DSB_PROD + dsb_idx);
17894
17895            /*
17896             * igu prods come in chunks of E1HVN_MAX (4) -
17897             * does not matters what is the current chip mode
17898             */
17899            for (i = 0; i < (num_segs * E1HVN_MAX);
17900                 i += E1HVN_MAX) {
17901                addr = IGU_REG_PROD_CONS_MEMORY +
17902                            (prod_offset + i)*4;
17903                REG_WR(sc, addr, 0);
17904            }
17905            /* send consumer update with 0 */
17906            if (CHIP_INT_MODE_IS_BC(sc)) {
17907                bxe_ack_sb(sc, sc->igu_dsb_id,
17908                           USTORM_ID, 0, IGU_INT_NOP, 1);
17909                bxe_ack_sb(sc, sc->igu_dsb_id,
17910                           CSTORM_ID, 0, IGU_INT_NOP, 1);
17911                bxe_ack_sb(sc, sc->igu_dsb_id,
17912                           XSTORM_ID, 0, IGU_INT_NOP, 1);
17913                bxe_ack_sb(sc, sc->igu_dsb_id,
17914                           TSTORM_ID, 0, IGU_INT_NOP, 1);
17915                bxe_ack_sb(sc, sc->igu_dsb_id,
17916                           ATTENTION_ID, 0, IGU_INT_NOP, 1);
17917            } else {
17918                bxe_ack_sb(sc, sc->igu_dsb_id,
17919                           USTORM_ID, 0, IGU_INT_NOP, 1);
17920                bxe_ack_sb(sc, sc->igu_dsb_id,
17921                           ATTENTION_ID, 0, IGU_INT_NOP, 1);
17922            }
17923            bxe_igu_clear_sb(sc, sc->igu_dsb_id);
17924
17925            /* !!! these should become driver const once
17926               rf-tool supports split-68 const */
17927            REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
17928            REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
17929            REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
17930            REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
17931            REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
17932            REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
17933        }
17934    }
17935
17936    /* Reset PCIE errors for debug */
17937    REG_WR(sc, 0x2114, 0xffffffff);
17938    REG_WR(sc, 0x2120, 0xffffffff);
17939
17940    if (CHIP_IS_E1x(sc)) {
17941        main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
17942        main_mem_base = HC_REG_MAIN_MEMORY +
17943                SC_PORT(sc) * (main_mem_size * 4);
17944        main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
17945        main_mem_width = 8;
17946
17947        val = REG_RD(sc, main_mem_prty_clr);
17948        if (val) {
17949            BLOGD(sc, DBG_LOAD,
17950                  "Parity errors in HC block during function init (0x%x)!\n",
17951                  val);
17952        }
17953
17954        /* Clear "false" parity errors in MSI-X table */
17955        for (i = main_mem_base;
17956             i < main_mem_base + main_mem_size * 4;
17957             i += main_mem_width) {
17958            bxe_read_dmae(sc, i, main_mem_width / 4);
17959            bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
17960                           i, main_mem_width / 4);
17961        }
17962        /* Clear HC parity attention */
17963        REG_RD(sc, main_mem_prty_clr);
17964    }
17965
17966#if 1
17967    /* Enable STORMs SP logging */
17968    REG_WR8(sc, BAR_USTRORM_INTMEM +
17969           USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17970    REG_WR8(sc, BAR_TSTRORM_INTMEM +
17971           TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17972    REG_WR8(sc, BAR_CSTRORM_INTMEM +
17973           CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17974    REG_WR8(sc, BAR_XSTRORM_INTMEM +
17975           XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17976#endif
17977
17978    elink_phy_probe(&sc->link_params);
17979
17980    return (0);
17981}
17982
17983static void
17984bxe_link_reset(struct bxe_softc *sc)
17985{
17986    if (!BXE_NOMCP(sc)) {
17987	bxe_acquire_phy_lock(sc);
17988        elink_lfa_reset(&sc->link_params, &sc->link_vars);
17989	bxe_release_phy_lock(sc);
17990    } else {
17991        if (!CHIP_REV_IS_SLOW(sc)) {
17992            BLOGW(sc, "Bootcode is missing - cannot reset link\n");
17993        }
17994    }
17995}
17996
17997static void
17998bxe_reset_port(struct bxe_softc *sc)
17999{
18000    int port = SC_PORT(sc);
18001    uint32_t val;
18002
18003    /* reset physical Link */
18004    bxe_link_reset(sc);
18005
18006    REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18007
18008    /* Do not rcv packets to BRB */
18009    REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18010    /* Do not direct rcv packets that are not for MCP to the BRB */
18011    REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18012               NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18013
18014    /* Configure AEU */
18015    REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18016
18017    DELAY(100000);
18018
18019    /* Check for BRB port occupancy */
18020    val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18021    if (val) {
18022        BLOGD(sc, DBG_LOAD,
18023              "BRB1 is not empty, %d blocks are occupied\n", val);
18024    }
18025
18026    /* TODO: Close Doorbell port? */
18027}
18028
18029static void
18030bxe_ilt_wr(struct bxe_softc *sc,
18031           uint32_t         index,
18032           bus_addr_t       addr)
18033{
18034    int reg;
18035    uint32_t wb_write[2];
18036
18037    if (CHIP_IS_E1(sc)) {
18038        reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18039    } else {
18040        reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18041    }
18042
18043    wb_write[0] = ONCHIP_ADDR1(addr);
18044    wb_write[1] = ONCHIP_ADDR2(addr);
18045    REG_WR_DMAE(sc, reg, wb_write, 2);
18046}
18047
18048static void
18049bxe_clear_func_ilt(struct bxe_softc *sc,
18050                   uint32_t         func)
18051{
18052    uint32_t i, base = FUNC_ILT_BASE(func);
18053    for (i = base; i < base + ILT_PER_FUNC; i++) {
18054        bxe_ilt_wr(sc, i, 0);
18055    }
18056}
18057
18058static void
18059bxe_reset_func(struct bxe_softc *sc)
18060{
18061    struct bxe_fastpath *fp;
18062    int port = SC_PORT(sc);
18063    int func = SC_FUNC(sc);
18064    int i;
18065
18066    /* Disable the function in the FW */
18067    REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18068    REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18069    REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18070    REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18071
18072    /* FP SBs */
18073    FOR_EACH_ETH_QUEUE(sc, i) {
18074        fp = &sc->fp[i];
18075        REG_WR8(sc, BAR_CSTRORM_INTMEM +
18076                CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18077                SB_DISABLED);
18078    }
18079
18080    /* SP SB */
18081    REG_WR8(sc, BAR_CSTRORM_INTMEM +
18082            CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18083            SB_DISABLED);
18084
18085    for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18086        REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18087    }
18088
18089    /* Configure IGU */
18090    if (sc->devinfo.int_block == INT_BLOCK_HC) {
18091        REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18092        REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18093    } else {
18094        REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18095        REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18096    }
18097
18098    if (CNIC_LOADED(sc)) {
18099        /* Disable Timer scan */
18100        REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18101        /*
18102         * Wait for at least 10ms and up to 2 second for the timers
18103         * scan to complete
18104         */
18105        for (i = 0; i < 200; i++) {
18106            DELAY(10000);
18107            if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18108                break;
18109        }
18110    }
18111
18112    /* Clear ILT */
18113    bxe_clear_func_ilt(sc, func);
18114
18115    /*
18116     * Timers workaround bug for E2: if this is vnic-3,
18117     * we need to set the entire ilt range for this timers.
18118     */
18119    if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18120        struct ilt_client_info ilt_cli;
18121        /* use dummy TM client */
18122        memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18123        ilt_cli.start = 0;
18124        ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18125        ilt_cli.client_num = ILT_CLIENT_TM;
18126
18127        ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18128    }
18129
18130    /* this assumes that reset_port() called before reset_func()*/
18131    if (!CHIP_IS_E1x(sc)) {
18132        bxe_pf_disable(sc);
18133    }
18134
18135    sc->dmae_ready = 0;
18136}
18137
18138static int
18139bxe_gunzip_init(struct bxe_softc *sc)
18140{
18141    return (0);
18142}
18143
18144static void
18145bxe_gunzip_end(struct bxe_softc *sc)
18146{
18147    return;
18148}
18149
18150static int
18151bxe_init_firmware(struct bxe_softc *sc)
18152{
18153    if (CHIP_IS_E1(sc)) {
18154        ecore_init_e1_firmware(sc);
18155        sc->iro_array = e1_iro_arr;
18156    } else if (CHIP_IS_E1H(sc)) {
18157        ecore_init_e1h_firmware(sc);
18158        sc->iro_array = e1h_iro_arr;
18159    } else if (!CHIP_IS_E1x(sc)) {
18160        ecore_init_e2_firmware(sc);
18161        sc->iro_array = e2_iro_arr;
18162    } else {
18163        BLOGE(sc, "Unsupported chip revision\n");
18164        return (-1);
18165    }
18166
18167    return (0);
18168}
18169
18170static void
18171bxe_release_firmware(struct bxe_softc *sc)
18172{
18173    /* Do nothing */
18174    return;
18175}
18176
18177static int
18178ecore_gunzip(struct bxe_softc *sc,
18179             const uint8_t    *zbuf,
18180             int              len)
18181{
18182    /* XXX : Implement... */
18183    BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18184    return (FALSE);
18185}
18186
18187static void
18188ecore_reg_wr_ind(struct bxe_softc *sc,
18189                 uint32_t         addr,
18190                 uint32_t         val)
18191{
18192    bxe_reg_wr_ind(sc, addr, val);
18193}
18194
18195static void
18196ecore_write_dmae_phys_len(struct bxe_softc *sc,
18197                          bus_addr_t       phys_addr,
18198                          uint32_t         addr,
18199                          uint32_t         len)
18200{
18201    bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18202}
18203
18204void
18205ecore_storm_memset_struct(struct bxe_softc *sc,
18206                          uint32_t         addr,
18207                          size_t           size,
18208                          uint32_t         *data)
18209{
18210    uint8_t i;
18211    for (i = 0; i < size/4; i++) {
18212        REG_WR(sc, addr + (i * 4), data[i]);
18213    }
18214}
18215
18216
18217/*
18218 * character device - ioctl interface definitions
18219 */
18220
18221
18222#include "bxe_dump.h"
18223#include "bxe_ioctl.h"
18224#include <sys/conf.h>
18225
18226static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18227                struct thread *td);
18228
18229static struct cdevsw bxe_cdevsw = {
18230    .d_version = D_VERSION,
18231    .d_ioctl = bxe_eioctl,
18232    .d_name = "bxecnic",
18233};
18234
18235#define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18236
18237
18238#define DUMP_ALL_PRESETS        0x1FFF
18239#define DUMP_MAX_PRESETS        13
18240#define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18241#define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18242#define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18243#define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18244#define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18245
18246#define IS_REG_IN_PRESET(presets, idx)  \
18247                ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18248
18249
18250static int
18251bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18252{
18253    if (CHIP_IS_E1(sc))
18254        return dump_num_registers[0][preset-1];
18255    else if (CHIP_IS_E1H(sc))
18256        return dump_num_registers[1][preset-1];
18257    else if (CHIP_IS_E2(sc))
18258        return dump_num_registers[2][preset-1];
18259    else if (CHIP_IS_E3A0(sc))
18260        return dump_num_registers[3][preset-1];
18261    else if (CHIP_IS_E3B0(sc))
18262        return dump_num_registers[4][preset-1];
18263    else
18264        return 0;
18265}
18266
18267static int
18268bxe_get_total_regs_len32(struct bxe_softc *sc)
18269{
18270    uint32_t preset_idx;
18271    int regdump_len32 = 0;
18272
18273
18274    /* Calculate the total preset regs length */
18275    for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18276        regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18277    }
18278
18279    return regdump_len32;
18280}
18281
18282static const uint32_t *
18283__bxe_get_page_addr_ar(struct bxe_softc *sc)
18284{
18285    if (CHIP_IS_E2(sc))
18286        return page_vals_e2;
18287    else if (CHIP_IS_E3(sc))
18288        return page_vals_e3;
18289    else
18290        return NULL;
18291}
18292
18293static uint32_t
18294__bxe_get_page_reg_num(struct bxe_softc *sc)
18295{
18296    if (CHIP_IS_E2(sc))
18297        return PAGE_MODE_VALUES_E2;
18298    else if (CHIP_IS_E3(sc))
18299        return PAGE_MODE_VALUES_E3;
18300    else
18301        return 0;
18302}
18303
18304static const uint32_t *
18305__bxe_get_page_write_ar(struct bxe_softc *sc)
18306{
18307    if (CHIP_IS_E2(sc))
18308        return page_write_regs_e2;
18309    else if (CHIP_IS_E3(sc))
18310        return page_write_regs_e3;
18311    else
18312        return NULL;
18313}
18314
18315static uint32_t
18316__bxe_get_page_write_num(struct bxe_softc *sc)
18317{
18318    if (CHIP_IS_E2(sc))
18319        return PAGE_WRITE_REGS_E2;
18320    else if (CHIP_IS_E3(sc))
18321        return PAGE_WRITE_REGS_E3;
18322    else
18323        return 0;
18324}
18325
18326static const struct reg_addr *
18327__bxe_get_page_read_ar(struct bxe_softc *sc)
18328{
18329    if (CHIP_IS_E2(sc))
18330        return page_read_regs_e2;
18331    else if (CHIP_IS_E3(sc))
18332        return page_read_regs_e3;
18333    else
18334        return NULL;
18335}
18336
18337static uint32_t
18338__bxe_get_page_read_num(struct bxe_softc *sc)
18339{
18340    if (CHIP_IS_E2(sc))
18341        return PAGE_READ_REGS_E2;
18342    else if (CHIP_IS_E3(sc))
18343        return PAGE_READ_REGS_E3;
18344    else
18345        return 0;
18346}
18347
18348static bool
18349bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18350{
18351    if (CHIP_IS_E1(sc))
18352        return IS_E1_REG(reg_info->chips);
18353    else if (CHIP_IS_E1H(sc))
18354        return IS_E1H_REG(reg_info->chips);
18355    else if (CHIP_IS_E2(sc))
18356        return IS_E2_REG(reg_info->chips);
18357    else if (CHIP_IS_E3A0(sc))
18358        return IS_E3A0_REG(reg_info->chips);
18359    else if (CHIP_IS_E3B0(sc))
18360        return IS_E3B0_REG(reg_info->chips);
18361    else
18362        return 0;
18363}
18364
18365static bool
18366bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18367{
18368    if (CHIP_IS_E1(sc))
18369        return IS_E1_REG(wreg_info->chips);
18370    else if (CHIP_IS_E1H(sc))
18371        return IS_E1H_REG(wreg_info->chips);
18372    else if (CHIP_IS_E2(sc))
18373        return IS_E2_REG(wreg_info->chips);
18374    else if (CHIP_IS_E3A0(sc))
18375        return IS_E3A0_REG(wreg_info->chips);
18376    else if (CHIP_IS_E3B0(sc))
18377        return IS_E3B0_REG(wreg_info->chips);
18378    else
18379        return 0;
18380}
18381
18382/**
18383 * bxe_read_pages_regs - read "paged" registers
18384 *
18385 * @bp          device handle
18386 * @p           output buffer
18387 *
18388 * Reads "paged" memories: memories that may only be read by first writing to a
18389 * specific address ("write address") and then reading from a specific address
18390 * ("read address"). There may be more than one write address per "page" and
18391 * more than one read address per write address.
18392 */
18393static void
18394bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18395{
18396    uint32_t i, j, k, n;
18397
18398    /* addresses of the paged registers */
18399    const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18400    /* number of paged registers */
18401    int num_pages = __bxe_get_page_reg_num(sc);
18402    /* write addresses */
18403    const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18404    /* number of write addresses */
18405    int write_num = __bxe_get_page_write_num(sc);
18406    /* read addresses info */
18407    const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18408    /* number of read addresses */
18409    int read_num = __bxe_get_page_read_num(sc);
18410    uint32_t addr, size;
18411
18412    for (i = 0; i < num_pages; i++) {
18413        for (j = 0; j < write_num; j++) {
18414            REG_WR(sc, write_addr[j], page_addr[i]);
18415
18416            for (k = 0; k < read_num; k++) {
18417                if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18418                    size = read_addr[k].size;
18419                    for (n = 0; n < size; n++) {
18420                        addr = read_addr[k].addr + n*4;
18421                        *p++ = REG_RD(sc, addr);
18422                    }
18423                }
18424            }
18425        }
18426    }
18427    return;
18428}
18429
18430
18431static int
18432bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18433{
18434    uint32_t i, j, addr;
18435    const struct wreg_addr *wreg_addr_p = NULL;
18436
18437    if (CHIP_IS_E1(sc))
18438        wreg_addr_p = &wreg_addr_e1;
18439    else if (CHIP_IS_E1H(sc))
18440        wreg_addr_p = &wreg_addr_e1h;
18441    else if (CHIP_IS_E2(sc))
18442        wreg_addr_p = &wreg_addr_e2;
18443    else if (CHIP_IS_E3A0(sc))
18444        wreg_addr_p = &wreg_addr_e3;
18445    else if (CHIP_IS_E3B0(sc))
18446        wreg_addr_p = &wreg_addr_e3b0;
18447    else
18448        return (-1);
18449
18450    /* Read the idle_chk registers */
18451    for (i = 0; i < IDLE_REGS_COUNT; i++) {
18452        if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18453            IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18454            for (j = 0; j < idle_reg_addrs[i].size; j++)
18455                *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18456        }
18457    }
18458
18459    /* Read the regular registers */
18460    for (i = 0; i < REGS_COUNT; i++) {
18461        if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18462            IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18463            for (j = 0; j < reg_addrs[i].size; j++)
18464                *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18465        }
18466    }
18467
18468    /* Read the CAM registers */
18469    if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18470        IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18471        for (i = 0; i < wreg_addr_p->size; i++) {
18472            *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18473
18474            /* In case of wreg_addr register, read additional
18475               registers from read_regs array
18476             */
18477            for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18478                addr = *(wreg_addr_p->read_regs);
18479                *p++ = REG_RD(sc, addr + j*4);
18480            }
18481        }
18482    }
18483
18484    /* Paged registers are supported in E2 & E3 only */
18485    if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18486        /* Read "paged" registers */
18487        bxe_read_pages_regs(sc, p, preset);
18488    }
18489
18490    return 0;
18491}
18492
18493int
18494bxe_grc_dump(struct bxe_softc *sc)
18495{
18496    int rval = 0;
18497    uint32_t preset_idx;
18498    uint8_t *buf;
18499    uint32_t size;
18500    struct  dump_header *d_hdr;
18501    uint32_t i;
18502    uint32_t reg_val;
18503    uint32_t reg_addr;
18504    uint32_t cmd_offset;
18505    int context_size;
18506    int allocated;
18507    struct ecore_ilt *ilt = SC_ILT(sc);
18508    struct bxe_fastpath *fp;
18509    struct ilt_client_info *ilt_cli;
18510    int grc_dump_size;
18511
18512
18513    if (sc->grcdump_done || sc->grcdump_started)
18514	return (rval);
18515
18516    sc->grcdump_started = 1;
18517    BLOGI(sc, "Started collecting grcdump\n");
18518
18519    grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18520                sizeof(struct  dump_header);
18521
18522    sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18523
18524    if (sc->grc_dump == NULL) {
18525        BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
18526        return(ENOMEM);
18527    }
18528
18529
18530
18531    /* Disable parity attentions as long as following dump may
18532     * cause false alarms by reading never written registers. We
18533     * will re-enable parity attentions right after the dump.
18534     */
18535
18536    /* Disable parity on path 0 */
18537    bxe_pretend_func(sc, 0);
18538
18539    ecore_disable_blocks_parity(sc);
18540
18541    /* Disable parity on path 1 */
18542    bxe_pretend_func(sc, 1);
18543    ecore_disable_blocks_parity(sc);
18544
18545    /* Return to current function */
18546    bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18547
18548    buf = sc->grc_dump;
18549    d_hdr = sc->grc_dump;
18550
18551    d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18552    d_hdr->version = BNX2X_DUMP_VERSION;
18553    d_hdr->preset = DUMP_ALL_PRESETS;
18554
18555    if (CHIP_IS_E1(sc)) {
18556        d_hdr->dump_meta_data = DUMP_CHIP_E1;
18557    } else if (CHIP_IS_E1H(sc)) {
18558        d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18559    } else if (CHIP_IS_E2(sc)) {
18560        d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18561                (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18562    } else if (CHIP_IS_E3A0(sc)) {
18563        d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18564                (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18565    } else if (CHIP_IS_E3B0(sc)) {
18566        d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18567                (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18568    }
18569
18570    buf += sizeof(struct  dump_header);
18571
18572    for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18573
18574        /* Skip presets with IOR */
18575        if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18576            (preset_idx == 11))
18577            continue;
18578
18579        rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
18580
18581	if (rval)
18582            break;
18583
18584        size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18585
18586        buf += size;
18587    }
18588
18589    bxe_pretend_func(sc, 0);
18590    ecore_clear_blocks_parity(sc);
18591    ecore_enable_blocks_parity(sc);
18592
18593    bxe_pretend_func(sc, 1);
18594    ecore_clear_blocks_parity(sc);
18595    ecore_enable_blocks_parity(sc);
18596
18597    /* Return to current function */
18598    bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18599
18600
18601    context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
18602    for (i = 0, allocated = 0; allocated < context_size; i++) {
18603
18604        BLOGI(sc, "cdu_context i %d paddr %#jx vaddr %p size 0x%zx\n", i,
18605            (uintmax_t)sc->context[i].vcxt_dma.paddr,
18606            sc->context[i].vcxt_dma.vaddr,
18607            sc->context[i].size);
18608        allocated += sc->context[i].size;
18609    }
18610    BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
18611        (uintmax_t)sc->fw_stats_req_mapping,
18612        (uintmax_t)sc->fw_stats_data_mapping,
18613        sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
18614    BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
18615        (void *)sc->def_sb_dma.paddr, sc->def_sb,
18616        sizeof(struct host_sp_status_block));
18617    BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
18618        (uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
18619    BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
18620        (uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
18621        sizeof(struct bxe_slowpath));
18622    BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
18623        (uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
18624    BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
18625        (uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
18626        FW_BUF_SIZE);
18627    for (i = 0; i < sc->num_queues; i++) {
18628        fp = &sc->fp[i];
18629        BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18630            (uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
18631            sizeof(union bxe_host_hc_status_block));
18632        BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18633            (uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
18634            (BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
18635        BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18636            (uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
18637            (BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
18638        BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18639            (uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
18640            (BCM_PAGE_SIZE * RCQ_NUM_PAGES));
18641        BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18642            (uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
18643            (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
18644    }
18645
18646    ilt_cli = &ilt->clients[1];
18647    for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
18648        BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
18649            (uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
18650            ((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
18651    }
18652
18653
18654    cmd_offset = DMAE_REG_CMD_MEM;
18655    for (i = 0; i < 224; i++) {
18656        reg_addr = (cmd_offset +(i * 4));
18657        reg_val = REG_RD(sc, reg_addr);
18658        BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
18659            reg_addr, reg_val);
18660    }
18661
18662
18663    BLOGI(sc, "Collection of grcdump done\n");
18664    sc->grcdump_done = 1;
18665    return(rval);
18666}
18667
18668static int
18669bxe_add_cdev(struct bxe_softc *sc)
18670{
18671    sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
18672
18673    if (sc->eeprom == NULL) {
18674        BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
18675        return (-1);
18676    }
18677
18678    sc->ioctl_dev = make_dev(&bxe_cdevsw,
18679                            sc->ifp->if_dunit,
18680                            UID_ROOT,
18681                            GID_WHEEL,
18682                            0600,
18683                            "%s",
18684                            if_name(sc->ifp));
18685
18686    if (sc->ioctl_dev == NULL) {
18687        free(sc->eeprom, M_DEVBUF);
18688        sc->eeprom = NULL;
18689        return (-1);
18690    }
18691
18692    sc->ioctl_dev->si_drv1 = sc;
18693
18694    return (0);
18695}
18696
18697static void
18698bxe_del_cdev(struct bxe_softc *sc)
18699{
18700    if (sc->ioctl_dev != NULL)
18701        destroy_dev(sc->ioctl_dev);
18702
18703    if (sc->eeprom != NULL) {
18704        free(sc->eeprom, M_DEVBUF);
18705        sc->eeprom = NULL;
18706    }
18707    sc->ioctl_dev = NULL;
18708
18709    return;
18710}
18711
18712static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
18713{
18714
18715    if ((if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) == 0)
18716        return FALSE;
18717
18718    return TRUE;
18719}
18720
18721
18722static int
18723bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18724{
18725    int rval = 0;
18726
18727    if(!bxe_is_nvram_accessible(sc)) {
18728        BLOGW(sc, "Cannot access eeprom when interface is down\n");
18729        return (-EAGAIN);
18730    }
18731    rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
18732
18733
18734   return (rval);
18735}
18736
18737static int
18738bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18739{
18740    int rval = 0;
18741
18742    if(!bxe_is_nvram_accessible(sc)) {
18743        BLOGW(sc, "Cannot access eeprom when interface is down\n");
18744        return (-EAGAIN);
18745    }
18746    rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
18747
18748   return (rval);
18749}
18750
18751static int
18752bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
18753{
18754    int rval = 0;
18755
18756    switch (eeprom->eeprom_cmd) {
18757
18758    case BXE_EEPROM_CMD_SET_EEPROM:
18759
18760        rval = copyin(eeprom->eeprom_data, sc->eeprom,
18761                       eeprom->eeprom_data_len);
18762
18763        if (rval)
18764            break;
18765
18766        rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18767                       eeprom->eeprom_data_len);
18768        break;
18769
18770    case BXE_EEPROM_CMD_GET_EEPROM:
18771
18772        rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18773                       eeprom->eeprom_data_len);
18774
18775        if (rval) {
18776            break;
18777        }
18778
18779        rval = copyout(sc->eeprom, eeprom->eeprom_data,
18780                       eeprom->eeprom_data_len);
18781        break;
18782
18783    default:
18784            rval = EINVAL;
18785            break;
18786    }
18787
18788    if (rval) {
18789        BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
18790    }
18791
18792    return (rval);
18793}
18794
18795static int
18796bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
18797{
18798    uint32_t ext_phy_config;
18799    int port = SC_PORT(sc);
18800    int cfg_idx = bxe_get_link_cfg_idx(sc);
18801
18802    dev_p->supported = sc->port.supported[cfg_idx] |
18803            (sc->port.supported[cfg_idx ^ 1] &
18804            (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
18805    dev_p->advertising = sc->port.advertising[cfg_idx];
18806    if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
18807        ELINK_ETH_PHY_SFP_1G_FIBER) {
18808        dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
18809        dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
18810    }
18811    if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
18812        !(sc->flags & BXE_MF_FUNC_DIS)) {
18813        dev_p->duplex = sc->link_vars.duplex;
18814        if (IS_MF(sc) && !BXE_NOMCP(sc))
18815            dev_p->speed = bxe_get_mf_speed(sc);
18816        else
18817            dev_p->speed = sc->link_vars.line_speed;
18818    } else {
18819        dev_p->duplex = DUPLEX_UNKNOWN;
18820        dev_p->speed = SPEED_UNKNOWN;
18821    }
18822
18823    dev_p->port = bxe_media_detect(sc);
18824
18825    ext_phy_config = SHMEM_RD(sc,
18826                         dev_info.port_hw_config[port].external_phy_config);
18827    if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
18828        PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
18829        dev_p->phy_address =  sc->port.phy_addr;
18830    else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18831            PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
18832        ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18833            PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
18834        dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
18835    else
18836        dev_p->phy_address = 0;
18837
18838    if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
18839        dev_p->autoneg = AUTONEG_ENABLE;
18840    else
18841       dev_p->autoneg = AUTONEG_DISABLE;
18842
18843
18844    return 0;
18845}
18846
18847static int
18848bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18849        struct thread *td)
18850{
18851    struct bxe_softc    *sc;
18852    int                 rval = 0;
18853    device_t            pci_dev;
18854    bxe_grcdump_t       *dump = NULL;
18855    int grc_dump_size;
18856    bxe_drvinfo_t   *drv_infop = NULL;
18857    bxe_dev_setting_t  *dev_p;
18858    bxe_dev_setting_t  dev_set;
18859    bxe_get_regs_t  *reg_p;
18860    bxe_reg_rdw_t *reg_rdw_p;
18861    bxe_pcicfg_rdw_t *cfg_rdw_p;
18862    bxe_perm_mac_addr_t *mac_addr_p;
18863
18864
18865    if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
18866        return ENXIO;
18867
18868    pci_dev= sc->dev;
18869
18870    dump = (bxe_grcdump_t *)data;
18871
18872    switch(cmd) {
18873
18874        case BXE_GRC_DUMP_SIZE:
18875            dump->pci_func = sc->pcie_func;
18876            dump->grcdump_size =
18877                (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18878                     sizeof(struct  dump_header);
18879            break;
18880
18881        case BXE_GRC_DUMP:
18882
18883            grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18884                                sizeof(struct  dump_header);
18885            if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
18886                (dump->grcdump_size < grc_dump_size)) {
18887                rval = EINVAL;
18888                break;
18889            }
18890
18891            if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
18892                (!sc->grcdump_started)) {
18893                rval =  bxe_grc_dump(sc);
18894            }
18895
18896            if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
18897                (sc->grc_dump != NULL))  {
18898                dump->grcdump_dwords = grc_dump_size >> 2;
18899                rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
18900                free(sc->grc_dump, M_DEVBUF);
18901                sc->grc_dump = NULL;
18902                sc->grcdump_started = 0;
18903                sc->grcdump_done = 0;
18904            }
18905
18906            break;
18907
18908        case BXE_DRV_INFO:
18909            drv_infop = (bxe_drvinfo_t *)data;
18910            snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
18911            snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
18912                BXE_DRIVER_VERSION);
18913            snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
18914                sc->devinfo.bc_ver_str);
18915            snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
18916                "%s", sc->fw_ver_str);
18917            drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
18918            drv_infop->reg_dump_len =
18919                (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
18920                    + sizeof(struct  dump_header);
18921            snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
18922                sc->pcie_bus, sc->pcie_device, sc->pcie_func);
18923            break;
18924
18925        case BXE_DEV_SETTING:
18926            dev_p = (bxe_dev_setting_t *)data;
18927            bxe_get_settings(sc, &dev_set);
18928            dev_p->supported = dev_set.supported;
18929            dev_p->advertising = dev_set.advertising;
18930            dev_p->speed = dev_set.speed;
18931            dev_p->duplex = dev_set.duplex;
18932            dev_p->port = dev_set.port;
18933            dev_p->phy_address = dev_set.phy_address;
18934            dev_p->autoneg = dev_set.autoneg;
18935
18936            break;
18937
18938        case BXE_GET_REGS:
18939
18940            reg_p = (bxe_get_regs_t *)data;
18941            grc_dump_size = reg_p->reg_buf_len;
18942
18943            if((!sc->grcdump_done) && (!sc->grcdump_started)) {
18944                bxe_grc_dump(sc);
18945            }
18946            if((sc->grcdump_done) && (sc->grcdump_started) &&
18947                (sc->grc_dump != NULL))  {
18948                rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
18949                free(sc->grc_dump, M_DEVBUF);
18950                sc->grc_dump = NULL;
18951                sc->grcdump_started = 0;
18952                sc->grcdump_done = 0;
18953            }
18954
18955            break;
18956
18957        case BXE_RDW_REG:
18958            reg_rdw_p = (bxe_reg_rdw_t *)data;
18959            if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
18960                (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
18961                reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
18962
18963            if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
18964                (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
18965                REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
18966
18967            break;
18968
18969        case BXE_RDW_PCICFG:
18970            cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
18971            if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
18972
18973                cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
18974                                         cfg_rdw_p->cfg_width);
18975
18976            } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
18977                pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
18978                            cfg_rdw_p->cfg_width);
18979            } else {
18980                BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
18981            }
18982            break;
18983
18984        case BXE_MAC_ADDR:
18985            mac_addr_p = (bxe_perm_mac_addr_t *)data;
18986            snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
18987                sc->mac_addr_str);
18988            break;
18989
18990        case BXE_EEPROM:
18991            rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
18992            break;
18993
18994
18995        default:
18996            break;
18997    }
18998
18999    return (rval);
19000}
19001