1/*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2007-2014 QLogic Corporation. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS'
17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26 * THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD$");
31
32#define BXE_DRIVER_VERSION "1.78.91"
33
34#include "bxe.h"
35#include "ecore_sp.h"
36#include "ecore_init.h"
37#include "ecore_init_ops.h"
38
39#include "57710_int_offsets.h"
40#include "57711_int_offsets.h"
41#include "57712_int_offsets.h"
42
43/*
44 * CTLTYPE_U64 and sysctl_handle_64 were added in r217616. Define these
45 * explicitly here for older kernels that don't include this changeset.
46 */
47#ifndef CTLTYPE_U64
48#define CTLTYPE_U64      CTLTYPE_QUAD
49#define sysctl_handle_64 sysctl_handle_quad
50#endif
51
52/*
53 * CSUM_TCP_IPV6 and CSUM_UDP_IPV6 were added in r236170. Define these
54 * here as zero(0) for older kernels that don't include this changeset
55 * thereby masking the functionality.
56 */
57#ifndef CSUM_TCP_IPV6
58#define CSUM_TCP_IPV6 0
59#define CSUM_UDP_IPV6 0
60#endif
61
62/*
63 * pci_find_cap was added in r219865. Re-define this at pci_find_extcap
64 * for older kernels that don't include this changeset.
65 */
66#if __FreeBSD_version < 900035
67#define pci_find_cap pci_find_extcap
68#endif
69
70#define BXE_DEF_SB_ATT_IDX 0x0001
71#define BXE_DEF_SB_IDX     0x0002
72
73/*
74 * FLR Support - bxe_pf_flr_clnup() is called during nic_load in the per
75 * function HW initialization.
76 */
77#define FLR_WAIT_USEC     10000 /* 10 msecs */
78#define FLR_WAIT_INTERVAL 50    /* usecs */
79#define FLR_POLL_CNT      (FLR_WAIT_USEC / FLR_WAIT_INTERVAL) /* 200 */
80
81struct pbf_pN_buf_regs {
82    int pN;
83    uint32_t init_crd;
84    uint32_t crd;
85    uint32_t crd_freed;
86};
87
88struct pbf_pN_cmd_regs {
89    int pN;
90    uint32_t lines_occup;
91    uint32_t lines_freed;
92};
93
94/*
95 * PCI Device ID Table used by bxe_probe().
96 */
97#define BXE_DEVDESC_MAX 64
98static struct bxe_device_type bxe_devs[] = {
99    {
100        BRCM_VENDORID,
101        CHIP_NUM_57710,
102        PCI_ANY_ID, PCI_ANY_ID,
103        "QLogic NetXtreme II BCM57710 10GbE"
104    },
105    {
106        BRCM_VENDORID,
107        CHIP_NUM_57711,
108        PCI_ANY_ID, PCI_ANY_ID,
109        "QLogic NetXtreme II BCM57711 10GbE"
110    },
111    {
112        BRCM_VENDORID,
113        CHIP_NUM_57711E,
114        PCI_ANY_ID, PCI_ANY_ID,
115        "QLogic NetXtreme II BCM57711E 10GbE"
116    },
117    {
118        BRCM_VENDORID,
119        CHIP_NUM_57712,
120        PCI_ANY_ID, PCI_ANY_ID,
121        "QLogic NetXtreme II BCM57712 10GbE"
122    },
123    {
124        BRCM_VENDORID,
125        CHIP_NUM_57712_MF,
126        PCI_ANY_ID, PCI_ANY_ID,
127        "QLogic NetXtreme II BCM57712 MF 10GbE"
128    },
129    {
130        BRCM_VENDORID,
131        CHIP_NUM_57800,
132        PCI_ANY_ID, PCI_ANY_ID,
133        "QLogic NetXtreme II BCM57800 10GbE"
134    },
135    {
136        BRCM_VENDORID,
137        CHIP_NUM_57800_MF,
138        PCI_ANY_ID, PCI_ANY_ID,
139        "QLogic NetXtreme II BCM57800 MF 10GbE"
140    },
141    {
142        BRCM_VENDORID,
143        CHIP_NUM_57810,
144        PCI_ANY_ID, PCI_ANY_ID,
145        "QLogic NetXtreme II BCM57810 10GbE"
146    },
147    {
148        BRCM_VENDORID,
149        CHIP_NUM_57810_MF,
150        PCI_ANY_ID, PCI_ANY_ID,
151        "QLogic NetXtreme II BCM57810 MF 10GbE"
152    },
153    {
154        BRCM_VENDORID,
155        CHIP_NUM_57811,
156        PCI_ANY_ID, PCI_ANY_ID,
157        "QLogic NetXtreme II BCM57811 10GbE"
158    },
159    {
160        BRCM_VENDORID,
161        CHIP_NUM_57811_MF,
162        PCI_ANY_ID, PCI_ANY_ID,
163        "QLogic NetXtreme II BCM57811 MF 10GbE"
164    },
165    {
166        BRCM_VENDORID,
167        CHIP_NUM_57840_4_10,
168        PCI_ANY_ID, PCI_ANY_ID,
169        "QLogic NetXtreme II BCM57840 4x10GbE"
170    },
171    {
172        QLOGIC_VENDORID,
173        CHIP_NUM_57840_4_10,
174        PCI_ANY_ID, PCI_ANY_ID,
175        "QLogic NetXtreme II BCM57840 4x10GbE"
176    },
177    {
178        BRCM_VENDORID,
179        CHIP_NUM_57840_2_20,
180        PCI_ANY_ID, PCI_ANY_ID,
181        "QLogic NetXtreme II BCM57840 2x20GbE"
182    },
183    {
184        BRCM_VENDORID,
185        CHIP_NUM_57840_MF,
186        PCI_ANY_ID, PCI_ANY_ID,
187        "QLogic NetXtreme II BCM57840 MF 10GbE"
188    },
189    {
190        0, 0, 0, 0, NULL
191    }
192};
193
194MALLOC_DECLARE(M_BXE_ILT);
195MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
196
197/*
198 * FreeBSD device entry points.
199 */
200static int bxe_probe(device_t);
201static int bxe_attach(device_t);
202static int bxe_detach(device_t);
203static int bxe_shutdown(device_t);
204
205
206/*
207 * FreeBSD KLD module/device interface event handler method.
208 */
209static device_method_t bxe_methods[] = {
210    /* Device interface (device_if.h) */
211    DEVMETHOD(device_probe,     bxe_probe),
212    DEVMETHOD(device_attach,    bxe_attach),
213    DEVMETHOD(device_detach,    bxe_detach),
214    DEVMETHOD(device_shutdown,  bxe_shutdown),
215    /* Bus interface (bus_if.h) */
216    DEVMETHOD(bus_print_child,  bus_generic_print_child),
217    DEVMETHOD(bus_driver_added, bus_generic_driver_added),
218    KOBJMETHOD_END
219};
220
221/*
222 * FreeBSD KLD Module data declaration
223 */
224static driver_t bxe_driver = {
225    "bxe",                   /* module name */
226    bxe_methods,             /* event handler */
227    sizeof(struct bxe_softc) /* extra data */
228};
229
230/*
231 * FreeBSD dev class is needed to manage dev instances and
232 * to associate with a bus type
233 */
234static devclass_t bxe_devclass;
235
236MODULE_DEPEND(bxe, pci, 1, 1, 1);
237MODULE_DEPEND(bxe, ether, 1, 1, 1);
238DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
239
240NETDUMP_DEFINE(bxe);
241
242/* resources needed for unloading a previously loaded device */
243
244#define BXE_PREV_WAIT_NEEDED 1
245struct mtx bxe_prev_mtx;
246MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
247struct bxe_prev_list_node {
248    LIST_ENTRY(bxe_prev_list_node) node;
249    uint8_t bus;
250    uint8_t slot;
251    uint8_t path;
252    uint8_t aer; /* XXX automatic error recovery */
253    uint8_t undi;
254};
255static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
256
257static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
258
259/* Tunable device values... */
260
261SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
262
263/* Debug */
264unsigned long bxe_debug = 0;
265SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, CTLFLAG_RDTUN,
266             &bxe_debug, 0, "Debug logging mode");
267
268/* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
269static int bxe_interrupt_mode = INTR_MODE_MSIX;
270SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
271           &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
272
273/* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
274static int bxe_queue_count = 4;
275SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
276           &bxe_queue_count, 0, "Multi-Queue queue count");
277
278/* max number of buffers per queue (default RX_BD_USABLE) */
279static int bxe_max_rx_bufs = 0;
280SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
281           &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
282
283/* Host interrupt coalescing RX tick timer (usecs) */
284static int bxe_hc_rx_ticks = 25;
285SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
286           &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
287
288/* Host interrupt coalescing TX tick timer (usecs) */
289static int bxe_hc_tx_ticks = 50;
290SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
291           &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
292
293/* Maximum number of Rx packets to process at a time */
294static int bxe_rx_budget = 0xffffffff;
295SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
296           &bxe_rx_budget, 0, "Rx processing budget");
297
298/* Maximum LRO aggregation size */
299static int bxe_max_aggregation_size = 0;
300SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
301           &bxe_max_aggregation_size, 0, "max aggregation size");
302
303/* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
304static int bxe_mrrs = -1;
305SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
306           &bxe_mrrs, 0, "PCIe maximum read request size");
307
308/* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
309static int bxe_autogreeen = 0;
310SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
311           &bxe_autogreeen, 0, "AutoGrEEEn support");
312
313/* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
314static int bxe_udp_rss = 0;
315SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
316           &bxe_udp_rss, 0, "UDP RSS support");
317
318
319#define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
320
321#define STATS_OFFSET32(stat_name)                   \
322    (offsetof(struct bxe_eth_stats, stat_name) / 4)
323
324#define Q_STATS_OFFSET32(stat_name)                   \
325    (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
326
327static const struct {
328    uint32_t offset;
329    uint32_t size;
330    uint32_t flags;
331#define STATS_FLAGS_PORT  1
332#define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
333#define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
334    char string[STAT_NAME_LEN];
335} bxe_eth_stats_arr[] = {
336    { STATS_OFFSET32(total_bytes_received_hi),
337                8, STATS_FLAGS_BOTH, "rx_bytes" },
338    { STATS_OFFSET32(error_bytes_received_hi),
339                8, STATS_FLAGS_BOTH, "rx_error_bytes" },
340    { STATS_OFFSET32(total_unicast_packets_received_hi),
341                8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
342    { STATS_OFFSET32(total_multicast_packets_received_hi),
343                8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
344    { STATS_OFFSET32(total_broadcast_packets_received_hi),
345                8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
346    { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
347                8, STATS_FLAGS_PORT, "rx_crc_errors" },
348    { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
349                8, STATS_FLAGS_PORT, "rx_align_errors" },
350    { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
351                8, STATS_FLAGS_PORT, "rx_undersize_packets" },
352    { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
353                8, STATS_FLAGS_PORT, "rx_oversize_packets" },
354    { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
355                8, STATS_FLAGS_PORT, "rx_fragments" },
356    { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
357                8, STATS_FLAGS_PORT, "rx_jabbers" },
358    { STATS_OFFSET32(no_buff_discard_hi),
359                8, STATS_FLAGS_BOTH, "rx_discards" },
360    { STATS_OFFSET32(mac_filter_discard),
361                4, STATS_FLAGS_PORT, "rx_filtered_packets" },
362    { STATS_OFFSET32(mf_tag_discard),
363                4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
364    { STATS_OFFSET32(pfc_frames_received_hi),
365                8, STATS_FLAGS_PORT, "pfc_frames_received" },
366    { STATS_OFFSET32(pfc_frames_sent_hi),
367                8, STATS_FLAGS_PORT, "pfc_frames_sent" },
368    { STATS_OFFSET32(brb_drop_hi),
369                8, STATS_FLAGS_PORT, "rx_brb_discard" },
370    { STATS_OFFSET32(brb_truncate_hi),
371                8, STATS_FLAGS_PORT, "rx_brb_truncate" },
372    { STATS_OFFSET32(pause_frames_received_hi),
373                8, STATS_FLAGS_PORT, "rx_pause_frames" },
374    { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
375                8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
376    { STATS_OFFSET32(nig_timer_max),
377                4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
378    { STATS_OFFSET32(total_bytes_transmitted_hi),
379                8, STATS_FLAGS_BOTH, "tx_bytes" },
380    { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
381                8, STATS_FLAGS_PORT, "tx_error_bytes" },
382    { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
383                8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
384    { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
385                8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
386    { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
387                8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
388    { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
389                8, STATS_FLAGS_PORT, "tx_mac_errors" },
390    { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
391                8, STATS_FLAGS_PORT, "tx_carrier_errors" },
392    { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
393                8, STATS_FLAGS_PORT, "tx_single_collisions" },
394    { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
395                8, STATS_FLAGS_PORT, "tx_multi_collisions" },
396    { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
397                8, STATS_FLAGS_PORT, "tx_deferred" },
398    { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
399                8, STATS_FLAGS_PORT, "tx_excess_collisions" },
400    { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
401                8, STATS_FLAGS_PORT, "tx_late_collisions" },
402    { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
403                8, STATS_FLAGS_PORT, "tx_total_collisions" },
404    { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
405                8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
406    { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
407                8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
408    { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
409                8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
410    { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
411                8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
412    { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
413                8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
414    { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
415                8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
416    { STATS_OFFSET32(etherstatspktsover1522octets_hi),
417                8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
418    { STATS_OFFSET32(pause_frames_sent_hi),
419                8, STATS_FLAGS_PORT, "tx_pause_frames" },
420    { STATS_OFFSET32(total_tpa_aggregations_hi),
421                8, STATS_FLAGS_FUNC, "tpa_aggregations" },
422    { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
423                8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
424    { STATS_OFFSET32(total_tpa_bytes_hi),
425                8, STATS_FLAGS_FUNC, "tpa_bytes"},
426    { STATS_OFFSET32(eee_tx_lpi),
427                4, STATS_FLAGS_PORT, "eee_tx_lpi"},
428    { STATS_OFFSET32(rx_calls),
429                4, STATS_FLAGS_FUNC, "rx_calls"},
430    { STATS_OFFSET32(rx_pkts),
431                4, STATS_FLAGS_FUNC, "rx_pkts"},
432    { STATS_OFFSET32(rx_tpa_pkts),
433                4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
434    { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
435                4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
436    { STATS_OFFSET32(rx_bxe_service_rxsgl),
437                4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
438    { STATS_OFFSET32(rx_jumbo_sge_pkts),
439                4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
440    { STATS_OFFSET32(rx_soft_errors),
441                4, STATS_FLAGS_FUNC, "rx_soft_errors"},
442    { STATS_OFFSET32(rx_hw_csum_errors),
443                4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
444    { STATS_OFFSET32(rx_ofld_frames_csum_ip),
445                4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
446    { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
447                4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
448    { STATS_OFFSET32(rx_budget_reached),
449                4, STATS_FLAGS_FUNC, "rx_budget_reached"},
450    { STATS_OFFSET32(tx_pkts),
451                4, STATS_FLAGS_FUNC, "tx_pkts"},
452    { STATS_OFFSET32(tx_soft_errors),
453                4, STATS_FLAGS_FUNC, "tx_soft_errors"},
454    { STATS_OFFSET32(tx_ofld_frames_csum_ip),
455                4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
456    { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
457                4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
458    { STATS_OFFSET32(tx_ofld_frames_csum_udp),
459                4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
460    { STATS_OFFSET32(tx_ofld_frames_lso),
461                4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
462    { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
463                4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
464    { STATS_OFFSET32(tx_encap_failures),
465                4, STATS_FLAGS_FUNC, "tx_encap_failures"},
466    { STATS_OFFSET32(tx_hw_queue_full),
467                4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
468    { STATS_OFFSET32(tx_hw_max_queue_depth),
469                4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
470    { STATS_OFFSET32(tx_dma_mapping_failure),
471                4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
472    { STATS_OFFSET32(tx_max_drbr_queue_depth),
473                4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
474    { STATS_OFFSET32(tx_window_violation_std),
475                4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
476    { STATS_OFFSET32(tx_window_violation_tso),
477                4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
478    { STATS_OFFSET32(tx_chain_lost_mbuf),
479                4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
480    { STATS_OFFSET32(tx_frames_deferred),
481                4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
482    { STATS_OFFSET32(tx_queue_xoff),
483                4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
484    { STATS_OFFSET32(mbuf_defrag_attempts),
485                4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
486    { STATS_OFFSET32(mbuf_defrag_failures),
487                4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
488    { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
489                4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
490    { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
491                4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
492    { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
493                4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
494    { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
495                4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
496    { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
497                4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
498    { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
499                4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
500    { STATS_OFFSET32(mbuf_alloc_tx),
501                4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
502    { STATS_OFFSET32(mbuf_alloc_rx),
503                4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
504    { STATS_OFFSET32(mbuf_alloc_sge),
505                4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
506    { STATS_OFFSET32(mbuf_alloc_tpa),
507                4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"},
508    { STATS_OFFSET32(tx_queue_full_return),
509                4, STATS_FLAGS_FUNC, "tx_queue_full_return"},
510    { STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
511                4, STATS_FLAGS_FUNC, "bxe_tx_mq_sc_state_failures"},
512    { STATS_OFFSET32(tx_request_link_down_failures),
513                4, STATS_FLAGS_FUNC, "tx_request_link_down_failures"},
514    { STATS_OFFSET32(bd_avail_too_less_failures),
515                4, STATS_FLAGS_FUNC, "bd_avail_too_less_failures"},
516    { STATS_OFFSET32(tx_mq_not_empty),
517                4, STATS_FLAGS_FUNC, "tx_mq_not_empty"},
518    { STATS_OFFSET32(nsegs_path1_errors),
519                4, STATS_FLAGS_FUNC, "nsegs_path1_errors"},
520    { STATS_OFFSET32(nsegs_path2_errors),
521                4, STATS_FLAGS_FUNC, "nsegs_path2_errors"}
522
523
524};
525
526static const struct {
527    uint32_t offset;
528    uint32_t size;
529    char string[STAT_NAME_LEN];
530} bxe_eth_q_stats_arr[] = {
531    { Q_STATS_OFFSET32(total_bytes_received_hi),
532                8, "rx_bytes" },
533    { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
534                8, "rx_ucast_packets" },
535    { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
536                8, "rx_mcast_packets" },
537    { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
538                8, "rx_bcast_packets" },
539    { Q_STATS_OFFSET32(no_buff_discard_hi),
540                8, "rx_discards" },
541    { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
542                8, "tx_bytes" },
543    { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
544                8, "tx_ucast_packets" },
545    { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
546                8, "tx_mcast_packets" },
547    { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
548                8, "tx_bcast_packets" },
549    { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
550                8, "tpa_aggregations" },
551    { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
552                8, "tpa_aggregated_frames"},
553    { Q_STATS_OFFSET32(total_tpa_bytes_hi),
554                8, "tpa_bytes"},
555    { Q_STATS_OFFSET32(rx_calls),
556                4, "rx_calls"},
557    { Q_STATS_OFFSET32(rx_pkts),
558                4, "rx_pkts"},
559    { Q_STATS_OFFSET32(rx_tpa_pkts),
560                4, "rx_tpa_pkts"},
561    { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
562                4, "rx_erroneous_jumbo_sge_pkts"},
563    { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
564                4, "rx_bxe_service_rxsgl"},
565    { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
566                4, "rx_jumbo_sge_pkts"},
567    { Q_STATS_OFFSET32(rx_soft_errors),
568                4, "rx_soft_errors"},
569    { Q_STATS_OFFSET32(rx_hw_csum_errors),
570                4, "rx_hw_csum_errors"},
571    { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
572                4, "rx_ofld_frames_csum_ip"},
573    { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
574                4, "rx_ofld_frames_csum_tcp_udp"},
575    { Q_STATS_OFFSET32(rx_budget_reached),
576                4, "rx_budget_reached"},
577    { Q_STATS_OFFSET32(tx_pkts),
578                4, "tx_pkts"},
579    { Q_STATS_OFFSET32(tx_soft_errors),
580                4, "tx_soft_errors"},
581    { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
582                4, "tx_ofld_frames_csum_ip"},
583    { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
584                4, "tx_ofld_frames_csum_tcp"},
585    { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
586                4, "tx_ofld_frames_csum_udp"},
587    { Q_STATS_OFFSET32(tx_ofld_frames_lso),
588                4, "tx_ofld_frames_lso"},
589    { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
590                4, "tx_ofld_frames_lso_hdr_splits"},
591    { Q_STATS_OFFSET32(tx_encap_failures),
592                4, "tx_encap_failures"},
593    { Q_STATS_OFFSET32(tx_hw_queue_full),
594                4, "tx_hw_queue_full"},
595    { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
596                4, "tx_hw_max_queue_depth"},
597    { Q_STATS_OFFSET32(tx_dma_mapping_failure),
598                4, "tx_dma_mapping_failure"},
599    { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
600                4, "tx_max_drbr_queue_depth"},
601    { Q_STATS_OFFSET32(tx_window_violation_std),
602                4, "tx_window_violation_std"},
603    { Q_STATS_OFFSET32(tx_window_violation_tso),
604                4, "tx_window_violation_tso"},
605    { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
606                4, "tx_chain_lost_mbuf"},
607    { Q_STATS_OFFSET32(tx_frames_deferred),
608                4, "tx_frames_deferred"},
609    { Q_STATS_OFFSET32(tx_queue_xoff),
610                4, "tx_queue_xoff"},
611    { Q_STATS_OFFSET32(mbuf_defrag_attempts),
612                4, "mbuf_defrag_attempts"},
613    { Q_STATS_OFFSET32(mbuf_defrag_failures),
614                4, "mbuf_defrag_failures"},
615    { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
616                4, "mbuf_rx_bd_alloc_failed"},
617    { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
618                4, "mbuf_rx_bd_mapping_failed"},
619    { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
620                4, "mbuf_rx_tpa_alloc_failed"},
621    { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
622                4, "mbuf_rx_tpa_mapping_failed"},
623    { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
624                4, "mbuf_rx_sge_alloc_failed"},
625    { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
626                4, "mbuf_rx_sge_mapping_failed"},
627    { Q_STATS_OFFSET32(mbuf_alloc_tx),
628                4, "mbuf_alloc_tx"},
629    { Q_STATS_OFFSET32(mbuf_alloc_rx),
630                4, "mbuf_alloc_rx"},
631    { Q_STATS_OFFSET32(mbuf_alloc_sge),
632                4, "mbuf_alloc_sge"},
633    { Q_STATS_OFFSET32(mbuf_alloc_tpa),
634                4, "mbuf_alloc_tpa"},
635    { Q_STATS_OFFSET32(tx_queue_full_return),
636                4, "tx_queue_full_return"},
637    { Q_STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
638                4, "bxe_tx_mq_sc_state_failures"},
639    { Q_STATS_OFFSET32(tx_request_link_down_failures),
640                4, "tx_request_link_down_failures"},
641    { Q_STATS_OFFSET32(bd_avail_too_less_failures),
642                4, "bd_avail_too_less_failures"},
643    { Q_STATS_OFFSET32(tx_mq_not_empty),
644                4, "tx_mq_not_empty"},
645    { Q_STATS_OFFSET32(nsegs_path1_errors),
646                4, "nsegs_path1_errors"},
647    { Q_STATS_OFFSET32(nsegs_path2_errors),
648                4, "nsegs_path2_errors"}
649
650
651};
652
653#define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
654#define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
655
656
657static void    bxe_cmng_fns_init(struct bxe_softc *sc,
658                                 uint8_t          read_cfg,
659                                 uint8_t          cmng_type);
660static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
661static void    storm_memset_cmng(struct bxe_softc *sc,
662                                 struct cmng_init *cmng,
663                                 uint8_t          port);
664static void    bxe_set_reset_global(struct bxe_softc *sc);
665static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
666static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
667                                 int              engine);
668static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
669static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
670                                   uint8_t          *global,
671                                   uint8_t          print);
672static void    bxe_int_disable(struct bxe_softc *sc);
673static int     bxe_release_leader_lock(struct bxe_softc *sc);
674static void    bxe_pf_disable(struct bxe_softc *sc);
675static void    bxe_free_fp_buffers(struct bxe_softc *sc);
676static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
677                                      struct bxe_fastpath *fp,
678                                      uint16_t            rx_bd_prod,
679                                      uint16_t            rx_cq_prod,
680                                      uint16_t            rx_sge_prod);
681static void    bxe_link_report_locked(struct bxe_softc *sc);
682static void    bxe_link_report(struct bxe_softc *sc);
683static void    bxe_link_status_update(struct bxe_softc *sc);
684static void    bxe_periodic_callout_func(void *xsc);
685static void    bxe_periodic_start(struct bxe_softc *sc);
686static void    bxe_periodic_stop(struct bxe_softc *sc);
687static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
688                                    uint16_t prev_index,
689                                    uint16_t index);
690static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
691                                     int                 queue);
692static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
693                                     uint16_t            index);
694static uint8_t bxe_txeof(struct bxe_softc *sc,
695                         struct bxe_fastpath *fp);
696static void    bxe_task_fp(struct bxe_fastpath *fp);
697static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
698                                     struct mbuf      *m,
699                                     uint8_t          contents);
700static int     bxe_alloc_mem(struct bxe_softc *sc);
701static void    bxe_free_mem(struct bxe_softc *sc);
702static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
703static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
704static int     bxe_interrupt_attach(struct bxe_softc *sc);
705static void    bxe_interrupt_detach(struct bxe_softc *sc);
706static void    bxe_set_rx_mode(struct bxe_softc *sc);
707static int     bxe_init_locked(struct bxe_softc *sc);
708static int     bxe_stop_locked(struct bxe_softc *sc);
709static void    bxe_sp_err_timeout_task(void *arg, int pending);
710void           bxe_parity_recover(struct bxe_softc *sc);
711void           bxe_handle_error(struct bxe_softc *sc);
712static __noinline int bxe_nic_load(struct bxe_softc *sc,
713                                   int              load_mode);
714static __noinline int bxe_nic_unload(struct bxe_softc *sc,
715                                     uint32_t         unload_mode,
716                                     uint8_t          keep_link);
717
718static void bxe_handle_sp_tq(void *context, int pending);
719static void bxe_handle_fp_tq(void *context, int pending);
720
721static int bxe_add_cdev(struct bxe_softc *sc);
722static void bxe_del_cdev(struct bxe_softc *sc);
723int bxe_grc_dump(struct bxe_softc *sc);
724static int bxe_alloc_buf_rings(struct bxe_softc *sc);
725static void bxe_free_buf_rings(struct bxe_softc *sc);
726
727/* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
728uint32_t
729calc_crc32(uint8_t  *crc32_packet,
730           uint32_t crc32_length,
731           uint32_t crc32_seed,
732           uint8_t  complement)
733{
734   uint32_t byte         = 0;
735   uint32_t bit          = 0;
736   uint8_t  msb          = 0;
737   uint32_t temp         = 0;
738   uint32_t shft         = 0;
739   uint8_t  current_byte = 0;
740   uint32_t crc32_result = crc32_seed;
741   const uint32_t CRC32_POLY = 0x1edc6f41;
742
743   if ((crc32_packet == NULL) ||
744       (crc32_length == 0) ||
745       ((crc32_length % 8) != 0))
746    {
747        return (crc32_result);
748    }
749
750    for (byte = 0; byte < crc32_length; byte = byte + 1)
751    {
752        current_byte = crc32_packet[byte];
753        for (bit = 0; bit < 8; bit = bit + 1)
754        {
755            /* msb = crc32_result[31]; */
756            msb = (uint8_t)(crc32_result >> 31);
757
758            crc32_result = crc32_result << 1;
759
760            /* it (msb != current_byte[bit]) */
761            if (msb != (0x1 & (current_byte >> bit)))
762            {
763                crc32_result = crc32_result ^ CRC32_POLY;
764                /* crc32_result[0] = 1 */
765                crc32_result |= 1;
766            }
767        }
768    }
769
770    /* Last step is to:
771     * 1. "mirror" every bit
772     * 2. swap the 4 bytes
773     * 3. complement each bit
774     */
775
776    /* Mirror */
777    temp = crc32_result;
778    shft = sizeof(crc32_result) * 8 - 1;
779
780    for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
781    {
782        temp <<= 1;
783        temp |= crc32_result & 1;
784        shft-- ;
785    }
786
787    /* temp[31-bit] = crc32_result[bit] */
788    temp <<= shft;
789
790    /* Swap */
791    /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
792    {
793        uint32_t t0, t1, t2, t3;
794        t0 = (0x000000ff & (temp >> 24));
795        t1 = (0x0000ff00 & (temp >> 8));
796        t2 = (0x00ff0000 & (temp << 8));
797        t3 = (0xff000000 & (temp << 24));
798        crc32_result = t0 | t1 | t2 | t3;
799    }
800
801    /* Complement */
802    if (complement)
803    {
804        crc32_result = ~crc32_result;
805    }
806
807    return (crc32_result);
808}
809
810int
811bxe_test_bit(int                    nr,
812             volatile unsigned long *addr)
813{
814    return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
815}
816
817void
818bxe_set_bit(unsigned int           nr,
819            volatile unsigned long *addr)
820{
821    atomic_set_acq_long(addr, (1 << nr));
822}
823
824void
825bxe_clear_bit(int                    nr,
826              volatile unsigned long *addr)
827{
828    atomic_clear_acq_long(addr, (1 << nr));
829}
830
831int
832bxe_test_and_set_bit(int                    nr,
833                       volatile unsigned long *addr)
834{
835    unsigned long x;
836    nr = (1 << nr);
837    do {
838        x = *addr;
839    } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
840    // if (x & nr) bit_was_set; else bit_was_not_set;
841    return (x & nr);
842}
843
844int
845bxe_test_and_clear_bit(int                    nr,
846                       volatile unsigned long *addr)
847{
848    unsigned long x;
849    nr = (1 << nr);
850    do {
851        x = *addr;
852    } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
853    // if (x & nr) bit_was_set; else bit_was_not_set;
854    return (x & nr);
855}
856
857int
858bxe_cmpxchg(volatile int *addr,
859            int          old,
860            int          new)
861{
862    int x;
863    do {
864        x = *addr;
865    } while (atomic_cmpset_acq_int(addr, old, new) == 0);
866    return (x);
867}
868
869/*
870 * Get DMA memory from the OS.
871 *
872 * Validates that the OS has provided DMA buffers in response to a
873 * bus_dmamap_load call and saves the physical address of those buffers.
874 * When the callback is used the OS will return 0 for the mapping function
875 * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
876 * failures back to the caller.
877 *
878 * Returns:
879 *   Nothing.
880 */
881static void
882bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
883{
884    struct bxe_dma *dma = arg;
885
886    if (error) {
887        dma->paddr = 0;
888        dma->nseg  = 0;
889        BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
890    } else {
891        dma->paddr = segs->ds_addr;
892        dma->nseg  = nseg;
893    }
894}
895
896/*
897 * Allocate a block of memory and map it for DMA. No partial completions
898 * allowed and release any resources acquired if we can't acquire all
899 * resources.
900 *
901 * Returns:
902 *   0 = Success, !0 = Failure
903 */
904int
905bxe_dma_alloc(struct bxe_softc *sc,
906              bus_size_t       size,
907              struct bxe_dma   *dma,
908              const char       *msg)
909{
910    int rc;
911
912    if (dma->size > 0) {
913        BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
914              (unsigned long)dma->size);
915        return (1);
916    }
917
918    memset(dma, 0, sizeof(*dma)); /* sanity */
919    dma->sc   = sc;
920    dma->size = size;
921    snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
922
923    rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
924                            BCM_PAGE_SIZE,      /* alignment */
925                            0,                  /* boundary limit */
926                            BUS_SPACE_MAXADDR,  /* restricted low */
927                            BUS_SPACE_MAXADDR,  /* restricted hi */
928                            NULL,               /* addr filter() */
929                            NULL,               /* addr filter() arg */
930                            size,               /* max map size */
931                            1,                  /* num discontinuous */
932                            size,               /* max seg size */
933                            BUS_DMA_ALLOCNOW,   /* flags */
934                            NULL,               /* lock() */
935                            NULL,               /* lock() arg */
936                            &dma->tag);         /* returned dma tag */
937    if (rc != 0) {
938        BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
939        memset(dma, 0, sizeof(*dma));
940        return (1);
941    }
942
943    rc = bus_dmamem_alloc(dma->tag,
944                          (void **)&dma->vaddr,
945                          (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
946                          &dma->map);
947    if (rc != 0) {
948        BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
949        bus_dma_tag_destroy(dma->tag);
950        memset(dma, 0, sizeof(*dma));
951        return (1);
952    }
953
954    rc = bus_dmamap_load(dma->tag,
955                         dma->map,
956                         dma->vaddr,
957                         size,
958                         bxe_dma_map_addr, /* BLOGD in here */
959                         dma,
960                         BUS_DMA_NOWAIT);
961    if (rc != 0) {
962        BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
963        bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
964        bus_dma_tag_destroy(dma->tag);
965        memset(dma, 0, sizeof(*dma));
966        return (1);
967    }
968
969    return (0);
970}
971
972void
973bxe_dma_free(struct bxe_softc *sc,
974             struct bxe_dma   *dma)
975{
976    if (dma->size > 0) {
977        DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
978
979        bus_dmamap_sync(dma->tag, dma->map,
980                        (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
981        bus_dmamap_unload(dma->tag, dma->map);
982        bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
983        bus_dma_tag_destroy(dma->tag);
984    }
985
986    memset(dma, 0, sizeof(*dma));
987}
988
989/*
990 * These indirect read and write routines are only during init.
991 * The locking is handled by the MCP.
992 */
993
994void
995bxe_reg_wr_ind(struct bxe_softc *sc,
996               uint32_t         addr,
997               uint32_t         val)
998{
999    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1000    pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
1001    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1002}
1003
1004uint32_t
1005bxe_reg_rd_ind(struct bxe_softc *sc,
1006               uint32_t         addr)
1007{
1008    uint32_t val;
1009
1010    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1011    val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
1012    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1013
1014    return (val);
1015}
1016
1017static int
1018bxe_acquire_hw_lock(struct bxe_softc *sc,
1019                    uint32_t         resource)
1020{
1021    uint32_t lock_status;
1022    uint32_t resource_bit = (1 << resource);
1023    int func = SC_FUNC(sc);
1024    uint32_t hw_lock_control_reg;
1025    int cnt;
1026
1027    /* validate the resource is within range */
1028    if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1029        BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1030            " resource_bit 0x%x\n", resource, resource_bit);
1031        return (-1);
1032    }
1033
1034    if (func <= 5) {
1035        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1036    } else {
1037        hw_lock_control_reg =
1038                (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1039    }
1040
1041    /* validate the resource is not already taken */
1042    lock_status = REG_RD(sc, hw_lock_control_reg);
1043    if (lock_status & resource_bit) {
1044        BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1045              resource, lock_status, resource_bit);
1046        return (-1);
1047    }
1048
1049    /* try every 5ms for 5 seconds */
1050    for (cnt = 0; cnt < 1000; cnt++) {
1051        REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1052        lock_status = REG_RD(sc, hw_lock_control_reg);
1053        if (lock_status & resource_bit) {
1054            return (0);
1055        }
1056        DELAY(5000);
1057    }
1058
1059    BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1060        resource, resource_bit);
1061    return (-1);
1062}
1063
1064static int
1065bxe_release_hw_lock(struct bxe_softc *sc,
1066                    uint32_t         resource)
1067{
1068    uint32_t lock_status;
1069    uint32_t resource_bit = (1 << resource);
1070    int func = SC_FUNC(sc);
1071    uint32_t hw_lock_control_reg;
1072
1073    /* validate the resource is within range */
1074    if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1075        BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1076            " resource_bit 0x%x\n", resource, resource_bit);
1077        return (-1);
1078    }
1079
1080    if (func <= 5) {
1081        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1082    } else {
1083        hw_lock_control_reg =
1084                (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1085    }
1086
1087    /* validate the resource is currently taken */
1088    lock_status = REG_RD(sc, hw_lock_control_reg);
1089    if (!(lock_status & resource_bit)) {
1090        BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1091              resource, lock_status, resource_bit);
1092        return (-1);
1093    }
1094
1095    REG_WR(sc, hw_lock_control_reg, resource_bit);
1096    return (0);
1097}
1098static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1099{
1100	BXE_PHY_LOCK(sc);
1101	bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1102}
1103
1104static void bxe_release_phy_lock(struct bxe_softc *sc)
1105{
1106	bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1107	BXE_PHY_UNLOCK(sc);
1108}
1109/*
1110 * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1111 * had we done things the other way around, if two pfs from the same port
1112 * would attempt to access nvram at the same time, we could run into a
1113 * scenario such as:
1114 * pf A takes the port lock.
1115 * pf B succeeds in taking the same lock since they are from the same port.
1116 * pf A takes the per pf misc lock. Performs eeprom access.
1117 * pf A finishes. Unlocks the per pf misc lock.
1118 * Pf B takes the lock and proceeds to perform it's own access.
1119 * pf A unlocks the per port lock, while pf B is still working (!).
1120 * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1121 * access corrupted by pf B).*
1122 */
1123static int
1124bxe_acquire_nvram_lock(struct bxe_softc *sc)
1125{
1126    int port = SC_PORT(sc);
1127    int count, i;
1128    uint32_t val = 0;
1129
1130    /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1131    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1132
1133    /* adjust timeout for emulation/FPGA */
1134    count = NVRAM_TIMEOUT_COUNT;
1135    if (CHIP_REV_IS_SLOW(sc)) {
1136        count *= 100;
1137    }
1138
1139    /* request access to nvram interface */
1140    REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1141           (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1142
1143    for (i = 0; i < count*10; i++) {
1144        val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1145        if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1146            break;
1147        }
1148
1149        DELAY(5);
1150    }
1151
1152    if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1153        BLOGE(sc, "Cannot get access to nvram interface "
1154            "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1155            port, val);
1156        return (-1);
1157    }
1158
1159    return (0);
1160}
1161
1162static int
1163bxe_release_nvram_lock(struct bxe_softc *sc)
1164{
1165    int port = SC_PORT(sc);
1166    int count, i;
1167    uint32_t val = 0;
1168
1169    /* adjust timeout for emulation/FPGA */
1170    count = NVRAM_TIMEOUT_COUNT;
1171    if (CHIP_REV_IS_SLOW(sc)) {
1172        count *= 100;
1173    }
1174
1175    /* relinquish nvram interface */
1176    REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1177           (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1178
1179    for (i = 0; i < count*10; i++) {
1180        val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1181        if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1182            break;
1183        }
1184
1185        DELAY(5);
1186    }
1187
1188    if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1189        BLOGE(sc, "Cannot free access to nvram interface "
1190            "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1191            port, val);
1192        return (-1);
1193    }
1194
1195    /* release HW lock: protect against other PFs in PF Direct Assignment */
1196    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1197
1198    return (0);
1199}
1200
1201static void
1202bxe_enable_nvram_access(struct bxe_softc *sc)
1203{
1204    uint32_t val;
1205
1206    val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1207
1208    /* enable both bits, even on read */
1209    REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1210           (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1211}
1212
1213static void
1214bxe_disable_nvram_access(struct bxe_softc *sc)
1215{
1216    uint32_t val;
1217
1218    val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1219
1220    /* disable both bits, even after read */
1221    REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1222           (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1223                    MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1224}
1225
1226static int
1227bxe_nvram_read_dword(struct bxe_softc *sc,
1228                     uint32_t         offset,
1229                     uint32_t         *ret_val,
1230                     uint32_t         cmd_flags)
1231{
1232    int count, i, rc;
1233    uint32_t val;
1234
1235    /* build the command word */
1236    cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1237
1238    /* need to clear DONE bit separately */
1239    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1240
1241    /* address of the NVRAM to read from */
1242    REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1243           (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1244
1245    /* issue a read command */
1246    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1247
1248    /* adjust timeout for emulation/FPGA */
1249    count = NVRAM_TIMEOUT_COUNT;
1250    if (CHIP_REV_IS_SLOW(sc)) {
1251        count *= 100;
1252    }
1253
1254    /* wait for completion */
1255    *ret_val = 0;
1256    rc = -1;
1257    for (i = 0; i < count; i++) {
1258        DELAY(5);
1259        val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1260
1261        if (val & MCPR_NVM_COMMAND_DONE) {
1262            val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1263            /* we read nvram data in cpu order
1264             * but ethtool sees it as an array of bytes
1265             * converting to big-endian will do the work
1266             */
1267            *ret_val = htobe32(val);
1268            rc = 0;
1269            break;
1270        }
1271    }
1272
1273    if (rc == -1) {
1274        BLOGE(sc, "nvram read timeout expired "
1275            "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1276            offset, cmd_flags, val);
1277    }
1278
1279    return (rc);
1280}
1281
1282static int
1283bxe_nvram_read(struct bxe_softc *sc,
1284               uint32_t         offset,
1285               uint8_t          *ret_buf,
1286               int              buf_size)
1287{
1288    uint32_t cmd_flags;
1289    uint32_t val;
1290    int rc;
1291
1292    if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1293        BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1294              offset, buf_size);
1295        return (-1);
1296    }
1297
1298    if ((offset + buf_size) > sc->devinfo.flash_size) {
1299        BLOGE(sc, "Invalid parameter, "
1300                  "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1301              offset, buf_size, sc->devinfo.flash_size);
1302        return (-1);
1303    }
1304
1305    /* request access to nvram interface */
1306    rc = bxe_acquire_nvram_lock(sc);
1307    if (rc) {
1308        return (rc);
1309    }
1310
1311    /* enable access to nvram interface */
1312    bxe_enable_nvram_access(sc);
1313
1314    /* read the first word(s) */
1315    cmd_flags = MCPR_NVM_COMMAND_FIRST;
1316    while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1317        rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1318        memcpy(ret_buf, &val, 4);
1319
1320        /* advance to the next dword */
1321        offset += sizeof(uint32_t);
1322        ret_buf += sizeof(uint32_t);
1323        buf_size -= sizeof(uint32_t);
1324        cmd_flags = 0;
1325    }
1326
1327    if (rc == 0) {
1328        cmd_flags |= MCPR_NVM_COMMAND_LAST;
1329        rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1330        memcpy(ret_buf, &val, 4);
1331    }
1332
1333    /* disable access to nvram interface */
1334    bxe_disable_nvram_access(sc);
1335    bxe_release_nvram_lock(sc);
1336
1337    return (rc);
1338}
1339
1340static int
1341bxe_nvram_write_dword(struct bxe_softc *sc,
1342                      uint32_t         offset,
1343                      uint32_t         val,
1344                      uint32_t         cmd_flags)
1345{
1346    int count, i, rc;
1347
1348    /* build the command word */
1349    cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1350
1351    /* need to clear DONE bit separately */
1352    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1353
1354    /* write the data */
1355    REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1356
1357    /* address of the NVRAM to write to */
1358    REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1359           (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1360
1361    /* issue the write command */
1362    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1363
1364    /* adjust timeout for emulation/FPGA */
1365    count = NVRAM_TIMEOUT_COUNT;
1366    if (CHIP_REV_IS_SLOW(sc)) {
1367        count *= 100;
1368    }
1369
1370    /* wait for completion */
1371    rc = -1;
1372    for (i = 0; i < count; i++) {
1373        DELAY(5);
1374        val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1375        if (val & MCPR_NVM_COMMAND_DONE) {
1376            rc = 0;
1377            break;
1378        }
1379    }
1380
1381    if (rc == -1) {
1382        BLOGE(sc, "nvram write timeout expired "
1383            "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1384            offset, cmd_flags, val);
1385    }
1386
1387    return (rc);
1388}
1389
1390#define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1391
1392static int
1393bxe_nvram_write1(struct bxe_softc *sc,
1394                 uint32_t         offset,
1395                 uint8_t          *data_buf,
1396                 int              buf_size)
1397{
1398    uint32_t cmd_flags;
1399    uint32_t align_offset;
1400    uint32_t val;
1401    int rc;
1402
1403    if ((offset + buf_size) > sc->devinfo.flash_size) {
1404        BLOGE(sc, "Invalid parameter, "
1405                  "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1406              offset, buf_size, sc->devinfo.flash_size);
1407        return (-1);
1408    }
1409
1410    /* request access to nvram interface */
1411    rc = bxe_acquire_nvram_lock(sc);
1412    if (rc) {
1413        return (rc);
1414    }
1415
1416    /* enable access to nvram interface */
1417    bxe_enable_nvram_access(sc);
1418
1419    cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1420    align_offset = (offset & ~0x03);
1421    rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1422
1423    if (rc == 0) {
1424        val &= ~(0xff << BYTE_OFFSET(offset));
1425        val |= (*data_buf << BYTE_OFFSET(offset));
1426
1427        /* nvram data is returned as an array of bytes
1428         * convert it back to cpu order
1429         */
1430        val = be32toh(val);
1431
1432        rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1433    }
1434
1435    /* disable access to nvram interface */
1436    bxe_disable_nvram_access(sc);
1437    bxe_release_nvram_lock(sc);
1438
1439    return (rc);
1440}
1441
1442static int
1443bxe_nvram_write(struct bxe_softc *sc,
1444                uint32_t         offset,
1445                uint8_t          *data_buf,
1446                int              buf_size)
1447{
1448    uint32_t cmd_flags;
1449    uint32_t val;
1450    uint32_t written_so_far;
1451    int rc;
1452
1453    if (buf_size == 1) {
1454        return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1455    }
1456
1457    if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1458        BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1459              offset, buf_size);
1460        return (-1);
1461    }
1462
1463    if (buf_size == 0) {
1464        return (0); /* nothing to do */
1465    }
1466
1467    if ((offset + buf_size) > sc->devinfo.flash_size) {
1468        BLOGE(sc, "Invalid parameter, "
1469                  "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1470              offset, buf_size, sc->devinfo.flash_size);
1471        return (-1);
1472    }
1473
1474    /* request access to nvram interface */
1475    rc = bxe_acquire_nvram_lock(sc);
1476    if (rc) {
1477        return (rc);
1478    }
1479
1480    /* enable access to nvram interface */
1481    bxe_enable_nvram_access(sc);
1482
1483    written_so_far = 0;
1484    cmd_flags = MCPR_NVM_COMMAND_FIRST;
1485    while ((written_so_far < buf_size) && (rc == 0)) {
1486        if (written_so_far == (buf_size - sizeof(uint32_t))) {
1487            cmd_flags |= MCPR_NVM_COMMAND_LAST;
1488        } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1489            cmd_flags |= MCPR_NVM_COMMAND_LAST;
1490        } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1491            cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1492        }
1493
1494        memcpy(&val, data_buf, 4);
1495
1496        rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1497
1498        /* advance to the next dword */
1499        offset += sizeof(uint32_t);
1500        data_buf += sizeof(uint32_t);
1501        written_so_far += sizeof(uint32_t);
1502        cmd_flags = 0;
1503    }
1504
1505    /* disable access to nvram interface */
1506    bxe_disable_nvram_access(sc);
1507    bxe_release_nvram_lock(sc);
1508
1509    return (rc);
1510}
1511
1512/* copy command into DMAE command memory and set DMAE command Go */
1513void
1514bxe_post_dmae(struct bxe_softc    *sc,
1515              struct dmae_cmd *dmae,
1516              int                 idx)
1517{
1518    uint32_t cmd_offset;
1519    int i;
1520
1521    cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1522    for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1523        REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1524    }
1525
1526    REG_WR(sc, dmae_reg_go_c[idx], 1);
1527}
1528
1529uint32_t
1530bxe_dmae_opcode_add_comp(uint32_t opcode,
1531                         uint8_t  comp_type)
1532{
1533    return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1534                      DMAE_CMD_C_TYPE_ENABLE));
1535}
1536
1537uint32_t
1538bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1539{
1540    return (opcode & ~DMAE_CMD_SRC_RESET);
1541}
1542
1543uint32_t
1544bxe_dmae_opcode(struct bxe_softc *sc,
1545                uint8_t          src_type,
1546                uint8_t          dst_type,
1547                uint8_t          with_comp,
1548                uint8_t          comp_type)
1549{
1550    uint32_t opcode = 0;
1551
1552    opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1553               (dst_type << DMAE_CMD_DST_SHIFT));
1554
1555    opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1556
1557    opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1558
1559    opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1560               (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1561
1562    opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1563
1564#ifdef __BIG_ENDIAN
1565    opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1566#else
1567    opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1568#endif
1569
1570    if (with_comp) {
1571        opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1572    }
1573
1574    return (opcode);
1575}
1576
1577static void
1578bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1579                        struct dmae_cmd *dmae,
1580                        uint8_t             src_type,
1581                        uint8_t             dst_type)
1582{
1583    memset(dmae, 0, sizeof(struct dmae_cmd));
1584
1585    /* set the opcode */
1586    dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1587                                   TRUE, DMAE_COMP_PCI);
1588
1589    /* fill in the completion parameters */
1590    dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1591    dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1592    dmae->comp_val     = DMAE_COMP_VAL;
1593}
1594
1595/* issue a DMAE command over the init channel and wait for completion */
1596static int
1597bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1598                         struct dmae_cmd *dmae)
1599{
1600    uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1601    int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1602
1603    BXE_DMAE_LOCK(sc);
1604
1605    /* reset completion */
1606    *wb_comp = 0;
1607
1608    /* post the command on the channel used for initializations */
1609    bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1610
1611    /* wait for completion */
1612    DELAY(5);
1613
1614    while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1615        if (!timeout ||
1616            (sc->recovery_state != BXE_RECOVERY_DONE &&
1617             sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1618            BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1619                *wb_comp, sc->recovery_state);
1620            BXE_DMAE_UNLOCK(sc);
1621            return (DMAE_TIMEOUT);
1622        }
1623
1624        timeout--;
1625        DELAY(50);
1626    }
1627
1628    if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1629        BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1630                *wb_comp, sc->recovery_state);
1631        BXE_DMAE_UNLOCK(sc);
1632        return (DMAE_PCI_ERROR);
1633    }
1634
1635    BXE_DMAE_UNLOCK(sc);
1636    return (0);
1637}
1638
1639void
1640bxe_read_dmae(struct bxe_softc *sc,
1641              uint32_t         src_addr,
1642              uint32_t         len32)
1643{
1644    struct dmae_cmd dmae;
1645    uint32_t *data;
1646    int i, rc;
1647
1648    DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1649
1650    if (!sc->dmae_ready) {
1651        data = BXE_SP(sc, wb_data[0]);
1652
1653        for (i = 0; i < len32; i++) {
1654            data[i] = (CHIP_IS_E1(sc)) ?
1655                          bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1656                          REG_RD(sc, (src_addr + (i * 4)));
1657        }
1658
1659        return;
1660    }
1661
1662    /* set opcode and fixed command fields */
1663    bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1664
1665    /* fill in addresses and len */
1666    dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1667    dmae.src_addr_hi = 0;
1668    dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1669    dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1670    dmae.len         = len32;
1671
1672    /* issue the command and wait for completion */
1673    if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1674        bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1675    }
1676}
1677
1678void
1679bxe_write_dmae(struct bxe_softc *sc,
1680               bus_addr_t       dma_addr,
1681               uint32_t         dst_addr,
1682               uint32_t         len32)
1683{
1684    struct dmae_cmd dmae;
1685    int rc;
1686
1687    if (!sc->dmae_ready) {
1688        DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1689
1690        if (CHIP_IS_E1(sc)) {
1691            ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1692        } else {
1693            ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1694        }
1695
1696        return;
1697    }
1698
1699    /* set opcode and fixed command fields */
1700    bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1701
1702    /* fill in addresses and len */
1703    dmae.src_addr_lo = U64_LO(dma_addr);
1704    dmae.src_addr_hi = U64_HI(dma_addr);
1705    dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1706    dmae.dst_addr_hi = 0;
1707    dmae.len         = len32;
1708
1709    /* issue the command and wait for completion */
1710    if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1711        bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1712    }
1713}
1714
1715void
1716bxe_write_dmae_phys_len(struct bxe_softc *sc,
1717                        bus_addr_t       phys_addr,
1718                        uint32_t         addr,
1719                        uint32_t         len)
1720{
1721    int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1722    int offset = 0;
1723
1724    while (len > dmae_wr_max) {
1725        bxe_write_dmae(sc,
1726                       (phys_addr + offset), /* src DMA address */
1727                       (addr + offset),      /* dst GRC address */
1728                       dmae_wr_max);
1729        offset += (dmae_wr_max * 4);
1730        len -= dmae_wr_max;
1731    }
1732
1733    bxe_write_dmae(sc,
1734                   (phys_addr + offset), /* src DMA address */
1735                   (addr + offset),      /* dst GRC address */
1736                   len);
1737}
1738
1739void
1740bxe_set_ctx_validation(struct bxe_softc   *sc,
1741                       struct eth_context *cxt,
1742                       uint32_t           cid)
1743{
1744    /* ustorm cxt validation */
1745    cxt->ustorm_ag_context.cdu_usage =
1746        CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1747            CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1748    /* xcontext validation */
1749    cxt->xstorm_ag_context.cdu_reserved =
1750        CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1751            CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1752}
1753
1754static void
1755bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1756                            uint8_t          port,
1757                            uint8_t          fw_sb_id,
1758                            uint8_t          sb_index,
1759                            uint8_t          ticks)
1760{
1761    uint32_t addr =
1762        (BAR_CSTRORM_INTMEM +
1763         CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1764
1765    REG_WR8(sc, addr, ticks);
1766
1767    BLOGD(sc, DBG_LOAD,
1768          "port %d fw_sb_id %d sb_index %d ticks %d\n",
1769          port, fw_sb_id, sb_index, ticks);
1770}
1771
1772static void
1773bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1774                            uint8_t          port,
1775                            uint16_t         fw_sb_id,
1776                            uint8_t          sb_index,
1777                            uint8_t          disable)
1778{
1779    uint32_t enable_flag =
1780        (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1781    uint32_t addr =
1782        (BAR_CSTRORM_INTMEM +
1783         CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1784    uint8_t flags;
1785
1786    /* clear and set */
1787    flags = REG_RD8(sc, addr);
1788    flags &= ~HC_INDEX_DATA_HC_ENABLED;
1789    flags |= enable_flag;
1790    REG_WR8(sc, addr, flags);
1791
1792    BLOGD(sc, DBG_LOAD,
1793          "port %d fw_sb_id %d sb_index %d disable %d\n",
1794          port, fw_sb_id, sb_index, disable);
1795}
1796
1797void
1798bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1799                             uint8_t          fw_sb_id,
1800                             uint8_t          sb_index,
1801                             uint8_t          disable,
1802                             uint16_t         usec)
1803{
1804    int port = SC_PORT(sc);
1805    uint8_t ticks = (usec / 4); /* XXX ??? */
1806
1807    bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1808
1809    disable = (disable) ? 1 : ((usec) ? 0 : 1);
1810    bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1811}
1812
1813void
1814elink_cb_udelay(struct bxe_softc *sc,
1815                uint32_t         usecs)
1816{
1817    DELAY(usecs);
1818}
1819
1820uint32_t
1821elink_cb_reg_read(struct bxe_softc *sc,
1822                  uint32_t         reg_addr)
1823{
1824    return (REG_RD(sc, reg_addr));
1825}
1826
1827void
1828elink_cb_reg_write(struct bxe_softc *sc,
1829                   uint32_t         reg_addr,
1830                   uint32_t         val)
1831{
1832    REG_WR(sc, reg_addr, val);
1833}
1834
1835void
1836elink_cb_reg_wb_write(struct bxe_softc *sc,
1837                      uint32_t         offset,
1838                      uint32_t         *wb_write,
1839                      uint16_t         len)
1840{
1841    REG_WR_DMAE(sc, offset, wb_write, len);
1842}
1843
1844void
1845elink_cb_reg_wb_read(struct bxe_softc *sc,
1846                     uint32_t         offset,
1847                     uint32_t         *wb_write,
1848                     uint16_t         len)
1849{
1850    REG_RD_DMAE(sc, offset, wb_write, len);
1851}
1852
1853uint8_t
1854elink_cb_path_id(struct bxe_softc *sc)
1855{
1856    return (SC_PATH(sc));
1857}
1858
1859void
1860elink_cb_event_log(struct bxe_softc     *sc,
1861                   const elink_log_id_t elink_log_id,
1862                   ...)
1863{
1864    /* XXX */
1865    BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1866}
1867
1868static int
1869bxe_set_spio(struct bxe_softc *sc,
1870             int              spio,
1871             uint32_t         mode)
1872{
1873    uint32_t spio_reg;
1874
1875    /* Only 2 SPIOs are configurable */
1876    if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1877        BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1878        return (-1);
1879    }
1880
1881    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1882
1883    /* read SPIO and mask except the float bits */
1884    spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1885
1886    switch (mode) {
1887    case MISC_SPIO_OUTPUT_LOW:
1888        BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1889        /* clear FLOAT and set CLR */
1890        spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1891        spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1892        break;
1893
1894    case MISC_SPIO_OUTPUT_HIGH:
1895        BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1896        /* clear FLOAT and set SET */
1897        spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1898        spio_reg |=  (spio << MISC_SPIO_SET_POS);
1899        break;
1900
1901    case MISC_SPIO_INPUT_HI_Z:
1902        BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1903        /* set FLOAT */
1904        spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1905        break;
1906
1907    default:
1908        break;
1909    }
1910
1911    REG_WR(sc, MISC_REG_SPIO, spio_reg);
1912    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1913
1914    return (0);
1915}
1916
1917static int
1918bxe_gpio_read(struct bxe_softc *sc,
1919              int              gpio_num,
1920              uint8_t          port)
1921{
1922    /* The GPIO should be swapped if swap register is set and active */
1923    int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1924                      REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1925    int gpio_shift = (gpio_num +
1926                      (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1927    uint32_t gpio_mask = (1 << gpio_shift);
1928    uint32_t gpio_reg;
1929
1930    if (gpio_num > MISC_REGISTERS_GPIO_3) {
1931        BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1932            " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1933            gpio_mask);
1934        return (-1);
1935    }
1936
1937    /* read GPIO value */
1938    gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1939
1940    /* get the requested pin value */
1941    return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1942}
1943
1944static int
1945bxe_gpio_write(struct bxe_softc *sc,
1946               int              gpio_num,
1947               uint32_t         mode,
1948               uint8_t          port)
1949{
1950    /* The GPIO should be swapped if swap register is set and active */
1951    int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1952                      REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1953    int gpio_shift = (gpio_num +
1954                      (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1955    uint32_t gpio_mask = (1 << gpio_shift);
1956    uint32_t gpio_reg;
1957
1958    if (gpio_num > MISC_REGISTERS_GPIO_3) {
1959        BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1960            " gpio_shift %d gpio_mask 0x%x\n",
1961            gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1962        return (-1);
1963    }
1964
1965    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1966
1967    /* read GPIO and mask except the float bits */
1968    gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1969
1970    switch (mode) {
1971    case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1972        BLOGD(sc, DBG_PHY,
1973              "Set GPIO %d (shift %d) -> output low\n",
1974              gpio_num, gpio_shift);
1975        /* clear FLOAT and set CLR */
1976        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1977        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1978        break;
1979
1980    case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1981        BLOGD(sc, DBG_PHY,
1982              "Set GPIO %d (shift %d) -> output high\n",
1983              gpio_num, gpio_shift);
1984        /* clear FLOAT and set SET */
1985        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1986        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1987        break;
1988
1989    case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1990        BLOGD(sc, DBG_PHY,
1991              "Set GPIO %d (shift %d) -> input\n",
1992              gpio_num, gpio_shift);
1993        /* set FLOAT */
1994        gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1995        break;
1996
1997    default:
1998        break;
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_mult_write(struct bxe_softc *sc,
2009                    uint8_t          pins,
2010                    uint32_t         mode)
2011{
2012    uint32_t gpio_reg;
2013
2014    /* any port swapping should be handled by caller */
2015
2016    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2017
2018    /* read GPIO and mask except the float bits */
2019    gpio_reg = REG_RD(sc, MISC_REG_GPIO);
2020    gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2021    gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
2022    gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
2023
2024    switch (mode) {
2025    case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2026        BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
2027        /* set CLR */
2028        gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
2029        break;
2030
2031    case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2032        BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
2033        /* set SET */
2034        gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2035        break;
2036
2037    case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2038        BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2039        /* set FLOAT */
2040        gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2041        break;
2042
2043    default:
2044        BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2045            " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2046        bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2047        return (-1);
2048    }
2049
2050    REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2051    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2052
2053    return (0);
2054}
2055
2056static int
2057bxe_gpio_int_write(struct bxe_softc *sc,
2058                   int              gpio_num,
2059                   uint32_t         mode,
2060                   uint8_t          port)
2061{
2062    /* The GPIO should be swapped if swap register is set and active */
2063    int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2064                      REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2065    int gpio_shift = (gpio_num +
2066                      (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2067    uint32_t gpio_mask = (1 << gpio_shift);
2068    uint32_t gpio_reg;
2069
2070    if (gpio_num > MISC_REGISTERS_GPIO_3) {
2071        BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2072            " gpio_shift %d gpio_mask 0x%x\n",
2073            gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2074        return (-1);
2075    }
2076
2077    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2078
2079    /* read GPIO int */
2080    gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2081
2082    switch (mode) {
2083    case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2084        BLOGD(sc, DBG_PHY,
2085              "Clear GPIO INT %d (shift %d) -> output low\n",
2086              gpio_num, gpio_shift);
2087        /* clear SET and set CLR */
2088        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2089        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2090        break;
2091
2092    case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2093        BLOGD(sc, DBG_PHY,
2094              "Set GPIO INT %d (shift %d) -> output high\n",
2095              gpio_num, gpio_shift);
2096        /* clear CLR and set SET */
2097        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2098        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2099        break;
2100
2101    default:
2102        break;
2103    }
2104
2105    REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2106    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2107
2108    return (0);
2109}
2110
2111uint32_t
2112elink_cb_gpio_read(struct bxe_softc *sc,
2113                   uint16_t         gpio_num,
2114                   uint8_t          port)
2115{
2116    return (bxe_gpio_read(sc, gpio_num, port));
2117}
2118
2119uint8_t
2120elink_cb_gpio_write(struct bxe_softc *sc,
2121                    uint16_t         gpio_num,
2122                    uint8_t          mode, /* 0=low 1=high */
2123                    uint8_t          port)
2124{
2125    return (bxe_gpio_write(sc, gpio_num, mode, port));
2126}
2127
2128uint8_t
2129elink_cb_gpio_mult_write(struct bxe_softc *sc,
2130                         uint8_t          pins,
2131                         uint8_t          mode) /* 0=low 1=high */
2132{
2133    return (bxe_gpio_mult_write(sc, pins, mode));
2134}
2135
2136uint8_t
2137elink_cb_gpio_int_write(struct bxe_softc *sc,
2138                        uint16_t         gpio_num,
2139                        uint8_t          mode, /* 0=low 1=high */
2140                        uint8_t          port)
2141{
2142    return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2143}
2144
2145void
2146elink_cb_notify_link_changed(struct bxe_softc *sc)
2147{
2148    REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2149                (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2150}
2151
2152/* send the MCP a request, block until there is a reply */
2153uint32_t
2154elink_cb_fw_command(struct bxe_softc *sc,
2155                    uint32_t         command,
2156                    uint32_t         param)
2157{
2158    int mb_idx = SC_FW_MB_IDX(sc);
2159    uint32_t seq;
2160    uint32_t rc = 0;
2161    uint32_t cnt = 1;
2162    uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2163
2164    BXE_FWMB_LOCK(sc);
2165
2166    seq = ++sc->fw_seq;
2167    SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2168    SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2169
2170    BLOGD(sc, DBG_PHY,
2171          "wrote command 0x%08x to FW MB param 0x%08x\n",
2172          (command | seq), param);
2173
2174    /* Let the FW do it's magic. GIve it up to 5 seconds... */
2175    do {
2176        DELAY(delay * 1000);
2177        rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2178    } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2179
2180    BLOGD(sc, DBG_PHY,
2181          "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2182          cnt*delay, rc, seq);
2183
2184    /* is this a reply to our command? */
2185    if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2186        rc &= FW_MSG_CODE_MASK;
2187    } else {
2188        /* Ruh-roh! */
2189        BLOGE(sc, "FW failed to respond!\n");
2190        // XXX bxe_fw_dump(sc);
2191        rc = 0;
2192    }
2193
2194    BXE_FWMB_UNLOCK(sc);
2195    return (rc);
2196}
2197
2198static uint32_t
2199bxe_fw_command(struct bxe_softc *sc,
2200               uint32_t         command,
2201               uint32_t         param)
2202{
2203    return (elink_cb_fw_command(sc, command, param));
2204}
2205
2206static void
2207__storm_memset_dma_mapping(struct bxe_softc *sc,
2208                           uint32_t         addr,
2209                           bus_addr_t       mapping)
2210{
2211    REG_WR(sc, addr, U64_LO(mapping));
2212    REG_WR(sc, (addr + 4), U64_HI(mapping));
2213}
2214
2215static void
2216storm_memset_spq_addr(struct bxe_softc *sc,
2217                      bus_addr_t       mapping,
2218                      uint16_t         abs_fid)
2219{
2220    uint32_t addr = (XSEM_REG_FAST_MEMORY +
2221                     XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2222    __storm_memset_dma_mapping(sc, addr, mapping);
2223}
2224
2225static void
2226storm_memset_vf_to_pf(struct bxe_softc *sc,
2227                      uint16_t         abs_fid,
2228                      uint16_t         pf_id)
2229{
2230    REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2231    REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2232    REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2233    REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2234}
2235
2236static void
2237storm_memset_func_en(struct bxe_softc *sc,
2238                     uint16_t         abs_fid,
2239                     uint8_t          enable)
2240{
2241    REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2242    REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2243    REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2244    REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2245}
2246
2247static void
2248storm_memset_eq_data(struct bxe_softc       *sc,
2249                     struct event_ring_data *eq_data,
2250                     uint16_t               pfid)
2251{
2252    uint32_t addr;
2253    size_t size;
2254
2255    addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2256    size = sizeof(struct event_ring_data);
2257    ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2258}
2259
2260static void
2261storm_memset_eq_prod(struct bxe_softc *sc,
2262                     uint16_t         eq_prod,
2263                     uint16_t         pfid)
2264{
2265    uint32_t addr = (BAR_CSTRORM_INTMEM +
2266                     CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2267    REG_WR16(sc, addr, eq_prod);
2268}
2269
2270/*
2271 * Post a slowpath command.
2272 *
2273 * A slowpath command is used to propagate a configuration change through
2274 * the controller in a controlled manner, allowing each STORM processor and
2275 * other H/W blocks to phase in the change.  The commands sent on the
2276 * slowpath are referred to as ramrods.  Depending on the ramrod used the
2277 * completion of the ramrod will occur in different ways.  Here's a
2278 * breakdown of ramrods and how they complete:
2279 *
2280 * RAMROD_CMD_ID_ETH_PORT_SETUP
2281 *   Used to setup the leading connection on a port.  Completes on the
2282 *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2283 *
2284 * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2285 *   Used to setup an additional connection on a port.  Completes on the
2286 *   RCQ of the multi-queue/RSS connection being initialized.
2287 *
2288 * RAMROD_CMD_ID_ETH_STAT_QUERY
2289 *   Used to force the storm processors to update the statistics database
2290 *   in host memory.  This ramrod is send on the leading connection CID and
2291 *   completes as an index increment of the CSTORM on the default status
2292 *   block.
2293 *
2294 * RAMROD_CMD_ID_ETH_UPDATE
2295 *   Used to update the state of the leading connection, usually to udpate
2296 *   the RSS indirection table.  Completes on the RCQ of the leading
2297 *   connection. (Not currently used under FreeBSD until OS support becomes
2298 *   available.)
2299 *
2300 * RAMROD_CMD_ID_ETH_HALT
2301 *   Used when tearing down a connection prior to driver unload.  Completes
2302 *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2303 *   use this on the leading connection.
2304 *
2305 * RAMROD_CMD_ID_ETH_SET_MAC
2306 *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2307 *   the RCQ of the leading connection.
2308 *
2309 * RAMROD_CMD_ID_ETH_CFC_DEL
2310 *   Used when tearing down a conneciton prior to driver unload.  Completes
2311 *   on the RCQ of the leading connection (since the current connection
2312 *   has been completely removed from controller memory).
2313 *
2314 * RAMROD_CMD_ID_ETH_PORT_DEL
2315 *   Used to tear down the leading connection prior to driver unload,
2316 *   typically fp[0].  Completes as an index increment of the CSTORM on the
2317 *   default status block.
2318 *
2319 * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2320 *   Used for connection offload.  Completes on the RCQ of the multi-queue
2321 *   RSS connection that is being offloaded.  (Not currently used under
2322 *   FreeBSD.)
2323 *
2324 * There can only be one command pending per function.
2325 *
2326 * Returns:
2327 *   0 = Success, !0 = Failure.
2328 */
2329
2330/* must be called under the spq lock */
2331static inline
2332struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2333{
2334    struct eth_spe *next_spe = sc->spq_prod_bd;
2335
2336    if (sc->spq_prod_bd == sc->spq_last_bd) {
2337        /* wrap back to the first eth_spq */
2338        sc->spq_prod_bd = sc->spq;
2339        sc->spq_prod_idx = 0;
2340    } else {
2341        sc->spq_prod_bd++;
2342        sc->spq_prod_idx++;
2343    }
2344
2345    return (next_spe);
2346}
2347
2348/* must be called under the spq lock */
2349static inline
2350void bxe_sp_prod_update(struct bxe_softc *sc)
2351{
2352    int func = SC_FUNC(sc);
2353
2354    /*
2355     * Make sure that BD data is updated before writing the producer.
2356     * BD data is written to the memory, the producer is read from the
2357     * memory, thus we need a full memory barrier to ensure the ordering.
2358     */
2359    mb();
2360
2361    REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2362             sc->spq_prod_idx);
2363
2364    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2365                      BUS_SPACE_BARRIER_WRITE);
2366}
2367
2368/**
2369 * bxe_is_contextless_ramrod - check if the current command ends on EQ
2370 *
2371 * @cmd:      command to check
2372 * @cmd_type: command type
2373 */
2374static inline
2375int bxe_is_contextless_ramrod(int cmd,
2376                              int cmd_type)
2377{
2378    if ((cmd_type == NONE_CONNECTION_TYPE) ||
2379        (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2380        (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2381        (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2382        (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2383        (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2384        (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2385        return (TRUE);
2386    } else {
2387        return (FALSE);
2388    }
2389}
2390
2391/**
2392 * bxe_sp_post - place a single command on an SP ring
2393 *
2394 * @sc:         driver handle
2395 * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2396 * @cid:        SW CID the command is related to
2397 * @data_hi:    command private data address (high 32 bits)
2398 * @data_lo:    command private data address (low 32 bits)
2399 * @cmd_type:   command type (e.g. NONE, ETH)
2400 *
2401 * SP data is handled as if it's always an address pair, thus data fields are
2402 * not swapped to little endian in upper functions. Instead this function swaps
2403 * data as if it's two uint32 fields.
2404 */
2405int
2406bxe_sp_post(struct bxe_softc *sc,
2407            int              command,
2408            int              cid,
2409            uint32_t         data_hi,
2410            uint32_t         data_lo,
2411            int              cmd_type)
2412{
2413    struct eth_spe *spe;
2414    uint16_t type;
2415    int common;
2416
2417    common = bxe_is_contextless_ramrod(command, cmd_type);
2418
2419    BXE_SP_LOCK(sc);
2420
2421    if (common) {
2422        if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2423            BLOGE(sc, "EQ ring is full!\n");
2424            BXE_SP_UNLOCK(sc);
2425            return (-1);
2426        }
2427    } else {
2428        if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2429            BLOGE(sc, "SPQ ring is full!\n");
2430            BXE_SP_UNLOCK(sc);
2431            return (-1);
2432        }
2433    }
2434
2435    spe = bxe_sp_get_next(sc);
2436
2437    /* CID needs port number to be encoded int it */
2438    spe->hdr.conn_and_cmd_data =
2439        htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2440
2441    type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2442
2443    /* TBD: Check if it works for VFs */
2444    type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2445             SPE_HDR_T_FUNCTION_ID);
2446
2447    spe->hdr.type = htole16(type);
2448
2449    spe->data.update_data_addr.hi = htole32(data_hi);
2450    spe->data.update_data_addr.lo = htole32(data_lo);
2451
2452    /*
2453     * It's ok if the actual decrement is issued towards the memory
2454     * somewhere between the lock and unlock. Thus no more explict
2455     * memory barrier is needed.
2456     */
2457    if (common) {
2458        atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2459    } else {
2460        atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2461    }
2462
2463    BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2464    BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2465          BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2466    BLOGD(sc, DBG_SP,
2467          "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2468          sc->spq_prod_idx,
2469          (uint32_t)U64_HI(sc->spq_dma.paddr),
2470          (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2471          command,
2472          common,
2473          HW_CID(sc, cid),
2474          data_hi,
2475          data_lo,
2476          type,
2477          atomic_load_acq_long(&sc->cq_spq_left),
2478          atomic_load_acq_long(&sc->eq_spq_left));
2479
2480    bxe_sp_prod_update(sc);
2481
2482    BXE_SP_UNLOCK(sc);
2483    return (0);
2484}
2485
2486/**
2487 * bxe_debug_print_ind_table - prints the indirection table configuration.
2488 *
2489 * @sc: driver hanlde
2490 * @p:  pointer to rss configuration
2491 */
2492
2493/*
2494 * FreeBSD Device probe function.
2495 *
2496 * Compares the device found to the driver's list of supported devices and
2497 * reports back to the bsd loader whether this is the right driver for the device.
2498 * This is the driver entry function called from the "kldload" command.
2499 *
2500 * Returns:
2501 *   BUS_PROBE_DEFAULT on success, positive value on failure.
2502 */
2503static int
2504bxe_probe(device_t dev)
2505{
2506    struct bxe_device_type *t;
2507    char *descbuf;
2508    uint16_t did, sdid, svid, vid;
2509
2510    /* Find our device structure */
2511    t = bxe_devs;
2512
2513    /* Get the data for the device to be probed. */
2514    vid  = pci_get_vendor(dev);
2515    did  = pci_get_device(dev);
2516    svid = pci_get_subvendor(dev);
2517    sdid = pci_get_subdevice(dev);
2518
2519    /* Look through the list of known devices for a match. */
2520    while (t->bxe_name != NULL) {
2521        if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2522            ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2523            ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2524            descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2525            if (descbuf == NULL)
2526                return (ENOMEM);
2527
2528            /* Print out the device identity. */
2529            snprintf(descbuf, BXE_DEVDESC_MAX,
2530                     "%s (%c%d) BXE v:%s\n", t->bxe_name,
2531                     (((pci_read_config(dev, PCIR_REVID, 4) &
2532                        0xf0) >> 4) + 'A'),
2533                     (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2534                     BXE_DRIVER_VERSION);
2535
2536            device_set_desc_copy(dev, descbuf);
2537            free(descbuf, M_TEMP);
2538            return (BUS_PROBE_DEFAULT);
2539        }
2540        t++;
2541    }
2542
2543    return (ENXIO);
2544}
2545
2546static void
2547bxe_init_mutexes(struct bxe_softc *sc)
2548{
2549#ifdef BXE_CORE_LOCK_SX
2550    snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2551             "bxe%d_core_lock", sc->unit);
2552    sx_init(&sc->core_sx, sc->core_sx_name);
2553#else
2554    snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2555             "bxe%d_core_lock", sc->unit);
2556    mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2557#endif
2558
2559    snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2560             "bxe%d_sp_lock", sc->unit);
2561    mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2562
2563    snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2564             "bxe%d_dmae_lock", sc->unit);
2565    mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2566
2567    snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2568             "bxe%d_phy_lock", sc->unit);
2569    mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2570
2571    snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2572             "bxe%d_fwmb_lock", sc->unit);
2573    mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2574
2575    snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2576             "bxe%d_print_lock", sc->unit);
2577    mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2578
2579    snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2580             "bxe%d_stats_lock", sc->unit);
2581    mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2582
2583    snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2584             "bxe%d_mcast_lock", sc->unit);
2585    mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2586}
2587
2588static void
2589bxe_release_mutexes(struct bxe_softc *sc)
2590{
2591#ifdef BXE_CORE_LOCK_SX
2592    sx_destroy(&sc->core_sx);
2593#else
2594    if (mtx_initialized(&sc->core_mtx)) {
2595        mtx_destroy(&sc->core_mtx);
2596    }
2597#endif
2598
2599    if (mtx_initialized(&sc->sp_mtx)) {
2600        mtx_destroy(&sc->sp_mtx);
2601    }
2602
2603    if (mtx_initialized(&sc->dmae_mtx)) {
2604        mtx_destroy(&sc->dmae_mtx);
2605    }
2606
2607    if (mtx_initialized(&sc->port.phy_mtx)) {
2608        mtx_destroy(&sc->port.phy_mtx);
2609    }
2610
2611    if (mtx_initialized(&sc->fwmb_mtx)) {
2612        mtx_destroy(&sc->fwmb_mtx);
2613    }
2614
2615    if (mtx_initialized(&sc->print_mtx)) {
2616        mtx_destroy(&sc->print_mtx);
2617    }
2618
2619    if (mtx_initialized(&sc->stats_mtx)) {
2620        mtx_destroy(&sc->stats_mtx);
2621    }
2622
2623    if (mtx_initialized(&sc->mcast_mtx)) {
2624        mtx_destroy(&sc->mcast_mtx);
2625    }
2626}
2627
2628static void
2629bxe_tx_disable(struct bxe_softc* sc)
2630{
2631    if_t ifp = sc->ifp;
2632
2633    /* tell the stack the driver is stopped and TX queue is full */
2634    if (ifp !=  NULL) {
2635        if_setdrvflags(ifp, 0);
2636    }
2637}
2638
2639static void
2640bxe_drv_pulse(struct bxe_softc *sc)
2641{
2642    SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2643             sc->fw_drv_pulse_wr_seq);
2644}
2645
2646static inline uint16_t
2647bxe_tx_avail(struct bxe_softc *sc,
2648             struct bxe_fastpath *fp)
2649{
2650    int16_t  used;
2651    uint16_t prod;
2652    uint16_t cons;
2653
2654    prod = fp->tx_bd_prod;
2655    cons = fp->tx_bd_cons;
2656
2657    used = SUB_S16(prod, cons);
2658
2659    return (int16_t)(sc->tx_ring_size) - used;
2660}
2661
2662static inline int
2663bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2664{
2665    uint16_t hw_cons;
2666
2667    mb(); /* status block fields can change */
2668    hw_cons = le16toh(*fp->tx_cons_sb);
2669    return (hw_cons != fp->tx_pkt_cons);
2670}
2671
2672static inline uint8_t
2673bxe_has_tx_work(struct bxe_fastpath *fp)
2674{
2675    /* expand this for multi-cos if ever supported */
2676    return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2677}
2678
2679static inline int
2680bxe_has_rx_work(struct bxe_fastpath *fp)
2681{
2682    uint16_t rx_cq_cons_sb;
2683
2684    mb(); /* status block fields can change */
2685    rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2686    if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2687        rx_cq_cons_sb++;
2688    return (fp->rx_cq_cons != rx_cq_cons_sb);
2689}
2690
2691static void
2692bxe_sp_event(struct bxe_softc    *sc,
2693             struct bxe_fastpath *fp,
2694             union eth_rx_cqe    *rr_cqe)
2695{
2696    int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2697    int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2698    enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2699    struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2700
2701    BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2702          fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2703
2704    switch (command) {
2705    case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2706        BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2707        drv_cmd = ECORE_Q_CMD_UPDATE;
2708        break;
2709
2710    case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2711        BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2712        drv_cmd = ECORE_Q_CMD_SETUP;
2713        break;
2714
2715    case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2716        BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2717        drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2718        break;
2719
2720    case (RAMROD_CMD_ID_ETH_HALT):
2721        BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2722        drv_cmd = ECORE_Q_CMD_HALT;
2723        break;
2724
2725    case (RAMROD_CMD_ID_ETH_TERMINATE):
2726        BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2727        drv_cmd = ECORE_Q_CMD_TERMINATE;
2728        break;
2729
2730    case (RAMROD_CMD_ID_ETH_EMPTY):
2731        BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2732        drv_cmd = ECORE_Q_CMD_EMPTY;
2733        break;
2734
2735    default:
2736        BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2737              command, fp->index);
2738        return;
2739    }
2740
2741    if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2742        q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2743        /*
2744         * q_obj->complete_cmd() failure means that this was
2745         * an unexpected completion.
2746         *
2747         * In this case we don't want to increase the sc->spq_left
2748         * because apparently we haven't sent this command the first
2749         * place.
2750         */
2751        // bxe_panic(sc, ("Unexpected SP completion\n"));
2752        return;
2753    }
2754
2755    atomic_add_acq_long(&sc->cq_spq_left, 1);
2756
2757    BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2758          atomic_load_acq_long(&sc->cq_spq_left));
2759}
2760
2761/*
2762 * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2763 * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2764 * the current aggregation queue as in-progress.
2765 */
2766static void
2767bxe_tpa_start(struct bxe_softc            *sc,
2768              struct bxe_fastpath         *fp,
2769              uint16_t                    queue,
2770              uint16_t                    cons,
2771              uint16_t                    prod,
2772              struct eth_fast_path_rx_cqe *cqe)
2773{
2774    struct bxe_sw_rx_bd tmp_bd;
2775    struct bxe_sw_rx_bd *rx_buf;
2776    struct eth_rx_bd *rx_bd;
2777    int max_agg_queues;
2778    struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2779    uint16_t index;
2780
2781    BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2782                       "cons=%d prod=%d\n",
2783          fp->index, queue, cons, prod);
2784
2785    max_agg_queues = MAX_AGG_QS(sc);
2786
2787    KASSERT((queue < max_agg_queues),
2788            ("fp[%02d] invalid aggr queue (%d >= %d)!",
2789             fp->index, queue, max_agg_queues));
2790
2791    KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2792            ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2793             fp->index, queue));
2794
2795    /* copy the existing mbuf and mapping from the TPA pool */
2796    tmp_bd = tpa_info->bd;
2797
2798    if (tmp_bd.m == NULL) {
2799        uint32_t *tmp;
2800
2801        tmp = (uint32_t *)cqe;
2802
2803        BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2804              fp->index, queue, cons, prod);
2805        BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2806            *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2807
2808        /* XXX Error handling? */
2809        return;
2810    }
2811
2812    /* change the TPA queue to the start state */
2813    tpa_info->state            = BXE_TPA_STATE_START;
2814    tpa_info->placement_offset = cqe->placement_offset;
2815    tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2816    tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2817    tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2818
2819    fp->rx_tpa_queue_used |= (1 << queue);
2820
2821    /*
2822     * If all the buffer descriptors are filled with mbufs then fill in
2823     * the current consumer index with a new BD. Else if a maximum Rx
2824     * buffer limit is imposed then fill in the next producer index.
2825     */
2826    index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2827                prod : cons;
2828
2829    /* move the received mbuf and mapping to TPA pool */
2830    tpa_info->bd = fp->rx_mbuf_chain[cons];
2831
2832    /* release any existing RX BD mbuf mappings */
2833    if (cons != index) {
2834        rx_buf = &fp->rx_mbuf_chain[cons];
2835
2836        if (rx_buf->m_map != NULL) {
2837            bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2838                            BUS_DMASYNC_POSTREAD);
2839            bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2840        }
2841
2842        /*
2843         * We get here when the maximum number of rx buffers is less than
2844         * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2845         * it out here without concern of a memory leak.
2846         */
2847        fp->rx_mbuf_chain[cons].m = NULL;
2848    }
2849
2850    /* update the Rx SW BD with the mbuf info from the TPA pool */
2851    fp->rx_mbuf_chain[index] = tmp_bd;
2852
2853    /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2854    rx_bd = &fp->rx_chain[index];
2855    rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2856    rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2857}
2858
2859/*
2860 * When a TPA aggregation is completed, loop through the individual mbufs
2861 * of the aggregation, combining them into a single mbuf which will be sent
2862 * up the stack. Refill all freed SGEs with mbufs as we go along.
2863 */
2864static int
2865bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2866                   struct bxe_fastpath       *fp,
2867                   struct bxe_sw_tpa_info    *tpa_info,
2868                   uint16_t                  queue,
2869                   uint16_t                  pages,
2870                   struct mbuf               *m,
2871			       struct eth_end_agg_rx_cqe *cqe,
2872                   uint16_t                  cqe_idx)
2873{
2874    struct mbuf *m_frag;
2875    uint32_t frag_len, frag_size, i;
2876    uint16_t sge_idx;
2877    int rc = 0;
2878    int j;
2879
2880    frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2881
2882    BLOGD(sc, DBG_LRO,
2883          "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2884          fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2885
2886    /* make sure the aggregated frame is not too big to handle */
2887    if (pages > 8 * PAGES_PER_SGE) {
2888
2889        uint32_t *tmp = (uint32_t *)cqe;
2890
2891        BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2892                  "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2893              fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2894              tpa_info->len_on_bd, frag_size);
2895
2896        BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2897            *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2898
2899        bxe_panic(sc, ("sge page count error\n"));
2900        return (EINVAL);
2901    }
2902
2903    /*
2904     * Scan through the scatter gather list pulling individual mbufs into a
2905     * single mbuf for the host stack.
2906     */
2907    for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2908        sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2909
2910        /*
2911         * Firmware gives the indices of the SGE as if the ring is an array
2912         * (meaning that the "next" element will consume 2 indices).
2913         */
2914        frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2915
2916        BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2917                           "sge_idx=%d frag_size=%d frag_len=%d\n",
2918              fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2919
2920        m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2921
2922        /* allocate a new mbuf for the SGE */
2923        rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2924        if (rc) {
2925            /* Leave all remaining SGEs in the ring! */
2926            return (rc);
2927        }
2928
2929        /* update the fragment length */
2930        m_frag->m_len = frag_len;
2931
2932        /* concatenate the fragment to the head mbuf */
2933        m_cat(m, m_frag);
2934        fp->eth_q_stats.mbuf_alloc_sge--;
2935
2936        /* update the TPA mbuf size and remaining fragment size */
2937        m->m_pkthdr.len += frag_len;
2938        frag_size -= frag_len;
2939    }
2940
2941    BLOGD(sc, DBG_LRO,
2942          "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2943          fp->index, queue, frag_size);
2944
2945    return (rc);
2946}
2947
2948static inline void
2949bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2950{
2951    int i, j;
2952
2953    for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2954        int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2955
2956        for (j = 0; j < 2; j++) {
2957            BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2958            idx--;
2959        }
2960    }
2961}
2962
2963static inline void
2964bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2965{
2966    /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2967    memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2968
2969    /*
2970     * Clear the two last indices in the page to 1. These are the indices that
2971     * correspond to the "next" element, hence will never be indicated and
2972     * should be removed from the calculations.
2973     */
2974    bxe_clear_sge_mask_next_elems(fp);
2975}
2976
2977static inline void
2978bxe_update_last_max_sge(struct bxe_fastpath *fp,
2979                        uint16_t            idx)
2980{
2981    uint16_t last_max = fp->last_max_sge;
2982
2983    if (SUB_S16(idx, last_max) > 0) {
2984        fp->last_max_sge = idx;
2985    }
2986}
2987
2988static inline void
2989bxe_update_sge_prod(struct bxe_softc          *sc,
2990                    struct bxe_fastpath       *fp,
2991                    uint16_t                  sge_len,
2992                    union eth_sgl_or_raw_data *cqe)
2993{
2994    uint16_t last_max, last_elem, first_elem;
2995    uint16_t delta = 0;
2996    uint16_t i;
2997
2998    if (!sge_len) {
2999        return;
3000    }
3001
3002    /* first mark all used pages */
3003    for (i = 0; i < sge_len; i++) {
3004        BIT_VEC64_CLEAR_BIT(fp->sge_mask,
3005                            RX_SGE(le16toh(cqe->sgl[i])));
3006    }
3007
3008    BLOGD(sc, DBG_LRO,
3009          "fp[%02d] fp_cqe->sgl[%d] = %d\n",
3010          fp->index, sge_len - 1,
3011          le16toh(cqe->sgl[sge_len - 1]));
3012
3013    /* assume that the last SGE index is the biggest */
3014    bxe_update_last_max_sge(fp,
3015                            le16toh(cqe->sgl[sge_len - 1]));
3016
3017    last_max = RX_SGE(fp->last_max_sge);
3018    last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
3019    first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
3020
3021    /* if ring is not full */
3022    if (last_elem + 1 != first_elem) {
3023        last_elem++;
3024    }
3025
3026    /* now update the prod */
3027    for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
3028        if (__predict_true(fp->sge_mask[i])) {
3029            break;
3030        }
3031
3032        fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3033        delta += BIT_VEC64_ELEM_SZ;
3034    }
3035
3036    if (delta > 0) {
3037        fp->rx_sge_prod += delta;
3038        /* clear page-end entries */
3039        bxe_clear_sge_mask_next_elems(fp);
3040    }
3041
3042    BLOGD(sc, DBG_LRO,
3043          "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3044          fp->index, fp->last_max_sge, fp->rx_sge_prod);
3045}
3046
3047/*
3048 * The aggregation on the current TPA queue has completed. Pull the individual
3049 * mbuf fragments together into a single mbuf, perform all necessary checksum
3050 * calculations, and send the resuting mbuf to the stack.
3051 */
3052static void
3053bxe_tpa_stop(struct bxe_softc          *sc,
3054             struct bxe_fastpath       *fp,
3055             struct bxe_sw_tpa_info    *tpa_info,
3056             uint16_t                  queue,
3057             uint16_t                  pages,
3058			 struct eth_end_agg_rx_cqe *cqe,
3059             uint16_t                  cqe_idx)
3060{
3061    if_t ifp = sc->ifp;
3062    struct mbuf *m;
3063    int rc = 0;
3064
3065    BLOGD(sc, DBG_LRO,
3066          "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3067          fp->index, queue, tpa_info->placement_offset,
3068          le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3069
3070    m = tpa_info->bd.m;
3071
3072    /* allocate a replacement before modifying existing mbuf */
3073    rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3074    if (rc) {
3075        /* drop the frame and log an error */
3076        fp->eth_q_stats.rx_soft_errors++;
3077        goto bxe_tpa_stop_exit;
3078    }
3079
3080    /* we have a replacement, fixup the current mbuf */
3081    m_adj(m, tpa_info->placement_offset);
3082    m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3083
3084    /* mark the checksums valid (taken care of by the firmware) */
3085    fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3086    fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3087    m->m_pkthdr.csum_data = 0xffff;
3088    m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3089                               CSUM_IP_VALID   |
3090                               CSUM_DATA_VALID |
3091                               CSUM_PSEUDO_HDR);
3092
3093    /* aggregate all of the SGEs into a single mbuf */
3094    rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3095    if (rc) {
3096        /* drop the packet and log an error */
3097        fp->eth_q_stats.rx_soft_errors++;
3098        m_freem(m);
3099    } else {
3100        if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3101            m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3102            m->m_flags |= M_VLANTAG;
3103        }
3104
3105        /* assign packet to this interface interface */
3106        if_setrcvif(m, ifp);
3107
3108#if __FreeBSD_version >= 800000
3109        /* specify what RSS queue was used for this flow */
3110        m->m_pkthdr.flowid = fp->index;
3111        BXE_SET_FLOWID(m);
3112#endif
3113
3114        if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3115        fp->eth_q_stats.rx_tpa_pkts++;
3116
3117        /* pass the frame to the stack */
3118        if_input(ifp, m);
3119    }
3120
3121    /* we passed an mbuf up the stack or dropped the frame */
3122    fp->eth_q_stats.mbuf_alloc_tpa--;
3123
3124bxe_tpa_stop_exit:
3125
3126    fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3127    fp->rx_tpa_queue_used &= ~(1 << queue);
3128}
3129
3130static uint8_t
3131bxe_service_rxsgl(
3132                 struct bxe_fastpath *fp,
3133                 uint16_t len,
3134                 uint16_t lenonbd,
3135                 struct mbuf *m,
3136                 struct eth_fast_path_rx_cqe *cqe_fp)
3137{
3138    struct mbuf *m_frag;
3139    uint16_t frags, frag_len;
3140    uint16_t sge_idx = 0;
3141    uint16_t j;
3142    uint8_t i, rc = 0;
3143    uint32_t frag_size;
3144
3145    /* adjust the mbuf */
3146    m->m_len = lenonbd;
3147
3148    frag_size =  len - lenonbd;
3149    frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3150
3151    for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3152        sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3153
3154        m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3155        frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3156        m_frag->m_len = frag_len;
3157
3158       /* allocate a new mbuf for the SGE */
3159        rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3160        if (rc) {
3161            /* Leave all remaining SGEs in the ring! */
3162            return (rc);
3163        }
3164        fp->eth_q_stats.mbuf_alloc_sge--;
3165
3166        /* concatenate the fragment to the head mbuf */
3167        m_cat(m, m_frag);
3168
3169        frag_size -= frag_len;
3170    }
3171
3172    bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3173
3174    return rc;
3175}
3176
3177static uint8_t
3178bxe_rxeof(struct bxe_softc    *sc,
3179          struct bxe_fastpath *fp)
3180{
3181    if_t ifp = sc->ifp;
3182    uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3183    uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3184    int rx_pkts = 0;
3185    int rc = 0;
3186
3187    BXE_FP_RX_LOCK(fp);
3188
3189    /* CQ "next element" is of the size of the regular element */
3190    hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3191    if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3192        hw_cq_cons++;
3193    }
3194
3195    bd_cons = fp->rx_bd_cons;
3196    bd_prod = fp->rx_bd_prod;
3197    bd_prod_fw = bd_prod;
3198    sw_cq_cons = fp->rx_cq_cons;
3199    sw_cq_prod = fp->rx_cq_prod;
3200
3201    /*
3202     * Memory barrier necessary as speculative reads of the rx
3203     * buffer can be ahead of the index in the status block
3204     */
3205    rmb();
3206
3207    BLOGD(sc, DBG_RX,
3208          "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3209          fp->index, hw_cq_cons, sw_cq_cons);
3210
3211    while (sw_cq_cons != hw_cq_cons) {
3212        struct bxe_sw_rx_bd *rx_buf = NULL;
3213        union eth_rx_cqe *cqe;
3214        struct eth_fast_path_rx_cqe *cqe_fp;
3215        uint8_t cqe_fp_flags;
3216        enum eth_rx_cqe_type cqe_fp_type;
3217        uint16_t len, lenonbd,  pad;
3218        struct mbuf *m = NULL;
3219
3220        comp_ring_cons = RCQ(sw_cq_cons);
3221        bd_prod = RX_BD(bd_prod);
3222        bd_cons = RX_BD(bd_cons);
3223
3224        cqe          = &fp->rcq_chain[comp_ring_cons];
3225        cqe_fp       = &cqe->fast_path_cqe;
3226        cqe_fp_flags = cqe_fp->type_error_flags;
3227        cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3228
3229        BLOGD(sc, DBG_RX,
3230              "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3231              "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3232              "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3233              fp->index,
3234              hw_cq_cons,
3235              sw_cq_cons,
3236              bd_prod,
3237              bd_cons,
3238              CQE_TYPE(cqe_fp_flags),
3239              cqe_fp_flags,
3240              cqe_fp->status_flags,
3241              le32toh(cqe_fp->rss_hash_result),
3242              le16toh(cqe_fp->vlan_tag),
3243              le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3244              le16toh(cqe_fp->len_on_bd));
3245
3246        /* is this a slowpath msg? */
3247        if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3248            bxe_sp_event(sc, fp, cqe);
3249            goto next_cqe;
3250        }
3251
3252        rx_buf = &fp->rx_mbuf_chain[bd_cons];
3253
3254        if (!CQE_TYPE_FAST(cqe_fp_type)) {
3255            struct bxe_sw_tpa_info *tpa_info;
3256            uint16_t frag_size, pages;
3257            uint8_t queue;
3258
3259            if (CQE_TYPE_START(cqe_fp_type)) {
3260                bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3261                              bd_cons, bd_prod, cqe_fp);
3262                m = NULL; /* packet not ready yet */
3263                goto next_rx;
3264            }
3265
3266            KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3267                    ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3268
3269            queue = cqe->end_agg_cqe.queue_index;
3270            tpa_info = &fp->rx_tpa_info[queue];
3271
3272            BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3273                  fp->index, queue);
3274
3275            frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3276                         tpa_info->len_on_bd);
3277            pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3278
3279            bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3280                         &cqe->end_agg_cqe, comp_ring_cons);
3281
3282            bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3283
3284            goto next_cqe;
3285        }
3286
3287        /* non TPA */
3288
3289        /* is this an error packet? */
3290        if (__predict_false(cqe_fp_flags &
3291                            ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3292            BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3293            fp->eth_q_stats.rx_soft_errors++;
3294            goto next_rx;
3295        }
3296
3297        len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3298        lenonbd = le16toh(cqe_fp->len_on_bd);
3299        pad = cqe_fp->placement_offset;
3300
3301        m = rx_buf->m;
3302
3303        if (__predict_false(m == NULL)) {
3304            BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3305                  bd_cons, fp->index);
3306            goto next_rx;
3307        }
3308
3309        /* XXX double copy if packet length under a threshold */
3310
3311        /*
3312         * If all the buffer descriptors are filled with mbufs then fill in
3313         * the current consumer index with a new BD. Else if a maximum Rx
3314         * buffer limit is imposed then fill in the next producer index.
3315         */
3316        rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3317                                  (sc->max_rx_bufs != RX_BD_USABLE) ?
3318                                      bd_prod : bd_cons);
3319        if (rc != 0) {
3320
3321            /* we simply reuse the received mbuf and don't post it to the stack */
3322            m = NULL;
3323
3324            BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3325                  fp->index, rc);
3326            fp->eth_q_stats.rx_soft_errors++;
3327
3328            if (sc->max_rx_bufs != RX_BD_USABLE) {
3329                /* copy this consumer index to the producer index */
3330                memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3331                       sizeof(struct bxe_sw_rx_bd));
3332                memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3333            }
3334
3335            goto next_rx;
3336        }
3337
3338        /* current mbuf was detached from the bd */
3339        fp->eth_q_stats.mbuf_alloc_rx--;
3340
3341        /* we allocated a replacement mbuf, fixup the current one */
3342        m_adj(m, pad);
3343        m->m_pkthdr.len = m->m_len = len;
3344
3345        if ((len > 60) && (len > lenonbd)) {
3346            fp->eth_q_stats.rx_bxe_service_rxsgl++;
3347            rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3348            if (rc)
3349                break;
3350            fp->eth_q_stats.rx_jumbo_sge_pkts++;
3351        } else if (lenonbd < len) {
3352            fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3353        }
3354
3355        /* assign packet to this interface interface */
3356	if_setrcvif(m, ifp);
3357
3358        /* assume no hardware checksum has complated */
3359        m->m_pkthdr.csum_flags = 0;
3360
3361        /* validate checksum if offload enabled */
3362        if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
3363            /* check for a valid IP frame */
3364            if (!(cqe->fast_path_cqe.status_flags &
3365                  ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3366                m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3367                if (__predict_false(cqe_fp_flags &
3368                                    ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3369                    fp->eth_q_stats.rx_hw_csum_errors++;
3370                } else {
3371                    fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3372                    m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3373                }
3374            }
3375
3376            /* check for a valid TCP/UDP frame */
3377            if (!(cqe->fast_path_cqe.status_flags &
3378                  ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3379                if (__predict_false(cqe_fp_flags &
3380                                    ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3381                    fp->eth_q_stats.rx_hw_csum_errors++;
3382                } else {
3383                    fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3384                    m->m_pkthdr.csum_data = 0xFFFF;
3385                    m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3386                                               CSUM_PSEUDO_HDR);
3387                }
3388            }
3389        }
3390
3391        /* if there is a VLAN tag then flag that info */
3392        if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3393            m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3394            m->m_flags |= M_VLANTAG;
3395        }
3396
3397#if __FreeBSD_version >= 800000
3398        /* specify what RSS queue was used for this flow */
3399        m->m_pkthdr.flowid = fp->index;
3400        BXE_SET_FLOWID(m);
3401#endif
3402
3403next_rx:
3404
3405        bd_cons    = RX_BD_NEXT(bd_cons);
3406        bd_prod    = RX_BD_NEXT(bd_prod);
3407        bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3408
3409        /* pass the frame to the stack */
3410        if (__predict_true(m != NULL)) {
3411            if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3412            rx_pkts++;
3413            if_input(ifp, m);
3414        }
3415
3416next_cqe:
3417
3418        sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3419        sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3420
3421        /* limit spinning on the queue */
3422        if (rc != 0)
3423            break;
3424
3425        if (rx_pkts == sc->rx_budget) {
3426            fp->eth_q_stats.rx_budget_reached++;
3427            break;
3428        }
3429    } /* while work to do */
3430
3431    fp->rx_bd_cons = bd_cons;
3432    fp->rx_bd_prod = bd_prod_fw;
3433    fp->rx_cq_cons = sw_cq_cons;
3434    fp->rx_cq_prod = sw_cq_prod;
3435
3436    /* Update producers */
3437    bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3438
3439    fp->eth_q_stats.rx_pkts += rx_pkts;
3440    fp->eth_q_stats.rx_calls++;
3441
3442    BXE_FP_RX_UNLOCK(fp);
3443
3444    return (sw_cq_cons != hw_cq_cons);
3445}
3446
3447static uint16_t
3448bxe_free_tx_pkt(struct bxe_softc    *sc,
3449                struct bxe_fastpath *fp,
3450                uint16_t            idx)
3451{
3452    struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3453    struct eth_tx_start_bd *tx_start_bd;
3454    uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3455    uint16_t new_cons;
3456    int nbd;
3457
3458    /* unmap the mbuf from non-paged memory */
3459    bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3460
3461    tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3462    nbd = le16toh(tx_start_bd->nbd) - 1;
3463
3464    new_cons = (tx_buf->first_bd + nbd);
3465
3466    /* free the mbuf */
3467    if (__predict_true(tx_buf->m != NULL)) {
3468        m_freem(tx_buf->m);
3469        fp->eth_q_stats.mbuf_alloc_tx--;
3470    } else {
3471        fp->eth_q_stats.tx_chain_lost_mbuf++;
3472    }
3473
3474    tx_buf->m = NULL;
3475    tx_buf->first_bd = 0;
3476
3477    return (new_cons);
3478}
3479
3480/* transmit timeout watchdog */
3481static int
3482bxe_watchdog(struct bxe_softc    *sc,
3483             struct bxe_fastpath *fp)
3484{
3485    BXE_FP_TX_LOCK(fp);
3486
3487    if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3488        BXE_FP_TX_UNLOCK(fp);
3489        return (0);
3490    }
3491
3492    BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3493
3494    BXE_FP_TX_UNLOCK(fp);
3495    BXE_SET_ERROR_BIT(sc, BXE_ERR_TXQ_STUCK);
3496    taskqueue_enqueue_timeout(taskqueue_thread,
3497        &sc->sp_err_timeout_task, hz/10);
3498
3499    return (-1);
3500}
3501
3502/* processes transmit completions */
3503static uint8_t
3504bxe_txeof(struct bxe_softc    *sc,
3505          struct bxe_fastpath *fp)
3506{
3507    if_t ifp = sc->ifp;
3508    uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3509    uint16_t tx_bd_avail;
3510
3511    BXE_FP_TX_LOCK_ASSERT(fp);
3512
3513    bd_cons = fp->tx_bd_cons;
3514    hw_cons = le16toh(*fp->tx_cons_sb);
3515    sw_cons = fp->tx_pkt_cons;
3516
3517    while (sw_cons != hw_cons) {
3518        pkt_cons = TX_BD(sw_cons);
3519
3520        BLOGD(sc, DBG_TX,
3521              "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3522              fp->index, hw_cons, sw_cons, pkt_cons);
3523
3524        bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3525
3526        sw_cons++;
3527    }
3528
3529    fp->tx_pkt_cons = sw_cons;
3530    fp->tx_bd_cons  = bd_cons;
3531
3532    BLOGD(sc, DBG_TX,
3533          "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3534          fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3535
3536    mb();
3537
3538    tx_bd_avail = bxe_tx_avail(sc, fp);
3539
3540    if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3541        if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
3542    } else {
3543        if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
3544    }
3545
3546    if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3547        /* reset the watchdog timer if there are pending transmits */
3548        fp->watchdog_timer = BXE_TX_TIMEOUT;
3549        return (TRUE);
3550    } else {
3551        /* clear watchdog when there are no pending transmits */
3552        fp->watchdog_timer = 0;
3553        return (FALSE);
3554    }
3555}
3556
3557static void
3558bxe_drain_tx_queues(struct bxe_softc *sc)
3559{
3560    struct bxe_fastpath *fp;
3561    int i, count;
3562
3563    /* wait until all TX fastpath tasks have completed */
3564    for (i = 0; i < sc->num_queues; i++) {
3565        fp = &sc->fp[i];
3566
3567        count = 1000;
3568
3569        while (bxe_has_tx_work(fp)) {
3570
3571            BXE_FP_TX_LOCK(fp);
3572            bxe_txeof(sc, fp);
3573            BXE_FP_TX_UNLOCK(fp);
3574
3575            if (count == 0) {
3576                BLOGE(sc, "Timeout waiting for fp[%d] "
3577                          "transmits to complete!\n", i);
3578                bxe_panic(sc, ("tx drain failure\n"));
3579                return;
3580            }
3581
3582            count--;
3583            DELAY(1000);
3584            rmb();
3585        }
3586    }
3587
3588    return;
3589}
3590
3591static int
3592bxe_del_all_macs(struct bxe_softc          *sc,
3593                 struct ecore_vlan_mac_obj *mac_obj,
3594                 int                       mac_type,
3595                 uint8_t                   wait_for_comp)
3596{
3597    unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3598    int rc;
3599
3600    /* wait for completion of requested */
3601    if (wait_for_comp) {
3602        bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3603    }
3604
3605    /* Set the mac type of addresses we want to clear */
3606    bxe_set_bit(mac_type, &vlan_mac_flags);
3607
3608    rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3609    if (rc < 0) {
3610        BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3611            rc, mac_type, wait_for_comp);
3612    }
3613
3614    return (rc);
3615}
3616
3617static int
3618bxe_fill_accept_flags(struct bxe_softc *sc,
3619                      uint32_t         rx_mode,
3620                      unsigned long    *rx_accept_flags,
3621                      unsigned long    *tx_accept_flags)
3622{
3623    /* Clear the flags first */
3624    *rx_accept_flags = 0;
3625    *tx_accept_flags = 0;
3626
3627    switch (rx_mode) {
3628    case BXE_RX_MODE_NONE:
3629        /*
3630         * 'drop all' supersedes any accept flags that may have been
3631         * passed to the function.
3632         */
3633        break;
3634
3635    case BXE_RX_MODE_NORMAL:
3636        bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3637        bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3638        bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3639
3640        /* internal switching mode */
3641        bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3642        bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3643        bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3644
3645        break;
3646
3647    case BXE_RX_MODE_ALLMULTI:
3648        bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3649        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3650        bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3651
3652        /* internal switching mode */
3653        bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3654        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3655        bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3656
3657        break;
3658
3659    case BXE_RX_MODE_PROMISC:
3660        /*
3661         * According to deffinition of SI mode, iface in promisc mode
3662         * should receive matched and unmatched (in resolution of port)
3663         * unicast packets.
3664         */
3665        bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3666        bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3667        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3668        bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3669
3670        /* internal switching mode */
3671        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3672        bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3673
3674        if (IS_MF_SI(sc)) {
3675            bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3676        } else {
3677            bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3678        }
3679
3680        break;
3681
3682    default:
3683        BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3684        return (-1);
3685    }
3686
3687    /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3688    if (rx_mode != BXE_RX_MODE_NONE) {
3689        bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3690        bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3691    }
3692
3693    return (0);
3694}
3695
3696static int
3697bxe_set_q_rx_mode(struct bxe_softc *sc,
3698                  uint8_t          cl_id,
3699                  unsigned long    rx_mode_flags,
3700                  unsigned long    rx_accept_flags,
3701                  unsigned long    tx_accept_flags,
3702                  unsigned long    ramrod_flags)
3703{
3704    struct ecore_rx_mode_ramrod_params ramrod_param;
3705    int rc;
3706
3707    memset(&ramrod_param, 0, sizeof(ramrod_param));
3708
3709    /* Prepare ramrod parameters */
3710    ramrod_param.cid = 0;
3711    ramrod_param.cl_id = cl_id;
3712    ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3713    ramrod_param.func_id = SC_FUNC(sc);
3714
3715    ramrod_param.pstate = &sc->sp_state;
3716    ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3717
3718    ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3719    ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3720
3721    bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3722
3723    ramrod_param.ramrod_flags = ramrod_flags;
3724    ramrod_param.rx_mode_flags = rx_mode_flags;
3725
3726    ramrod_param.rx_accept_flags = rx_accept_flags;
3727    ramrod_param.tx_accept_flags = tx_accept_flags;
3728
3729    rc = ecore_config_rx_mode(sc, &ramrod_param);
3730    if (rc < 0) {
3731        BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3732            "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3733            "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3734            (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3735            (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3736        return (rc);
3737    }
3738
3739    return (0);
3740}
3741
3742static int
3743bxe_set_storm_rx_mode(struct bxe_softc *sc)
3744{
3745    unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3746    unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3747    int rc;
3748
3749    rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3750                               &tx_accept_flags);
3751    if (rc) {
3752        return (rc);
3753    }
3754
3755    bxe_set_bit(RAMROD_RX, &ramrod_flags);
3756    bxe_set_bit(RAMROD_TX, &ramrod_flags);
3757
3758    /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3759    return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3760                              rx_accept_flags, tx_accept_flags,
3761                              ramrod_flags));
3762}
3763
3764/* returns the "mcp load_code" according to global load_count array */
3765static int
3766bxe_nic_load_no_mcp(struct bxe_softc *sc)
3767{
3768    int path = SC_PATH(sc);
3769    int port = SC_PORT(sc);
3770
3771    BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3772          path, load_count[path][0], load_count[path][1],
3773          load_count[path][2]);
3774    load_count[path][0]++;
3775    load_count[path][1 + port]++;
3776    BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3777          path, load_count[path][0], load_count[path][1],
3778          load_count[path][2]);
3779    if (load_count[path][0] == 1) {
3780        return (FW_MSG_CODE_DRV_LOAD_COMMON);
3781    } else if (load_count[path][1 + port] == 1) {
3782        return (FW_MSG_CODE_DRV_LOAD_PORT);
3783    } else {
3784        return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3785    }
3786}
3787
3788/* returns the "mcp load_code" according to global load_count array */
3789static int
3790bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3791{
3792    int port = SC_PORT(sc);
3793    int path = SC_PATH(sc);
3794
3795    BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3796          path, load_count[path][0], load_count[path][1],
3797          load_count[path][2]);
3798    load_count[path][0]--;
3799    load_count[path][1 + port]--;
3800    BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3801          path, load_count[path][0], load_count[path][1],
3802          load_count[path][2]);
3803    if (load_count[path][0] == 0) {
3804        return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3805    } else if (load_count[path][1 + port] == 0) {
3806        return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3807    } else {
3808        return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3809    }
3810}
3811
3812/* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3813static uint32_t
3814bxe_send_unload_req(struct bxe_softc *sc,
3815                    int              unload_mode)
3816{
3817    uint32_t reset_code = 0;
3818
3819    /* Select the UNLOAD request mode */
3820    if (unload_mode == UNLOAD_NORMAL) {
3821        reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3822    } else {
3823        reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3824    }
3825
3826    /* Send the request to the MCP */
3827    if (!BXE_NOMCP(sc)) {
3828        reset_code = bxe_fw_command(sc, reset_code, 0);
3829    } else {
3830        reset_code = bxe_nic_unload_no_mcp(sc);
3831    }
3832
3833    return (reset_code);
3834}
3835
3836/* send UNLOAD_DONE command to the MCP */
3837static void
3838bxe_send_unload_done(struct bxe_softc *sc,
3839                     uint8_t          keep_link)
3840{
3841    uint32_t reset_param =
3842        keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3843
3844    /* Report UNLOAD_DONE to MCP */
3845    if (!BXE_NOMCP(sc)) {
3846        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3847    }
3848}
3849
3850static int
3851bxe_func_wait_started(struct bxe_softc *sc)
3852{
3853    int tout = 50;
3854
3855    if (!sc->port.pmf) {
3856        return (0);
3857    }
3858
3859    /*
3860     * (assumption: No Attention from MCP at this stage)
3861     * PMF probably in the middle of TX disable/enable transaction
3862     * 1. Sync IRS for default SB
3863     * 2. Sync SP queue - this guarantees us that attention handling started
3864     * 3. Wait, that TX disable/enable transaction completes
3865     *
3866     * 1+2 guarantee that if DCBX attention was scheduled it already changed
3867     * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3868     * received completion for the transaction the state is TX_STOPPED.
3869     * State will return to STARTED after completion of TX_STOPPED-->STARTED
3870     * transaction.
3871     */
3872
3873    /* XXX make sure default SB ISR is done */
3874    /* need a way to synchronize an irq (intr_mtx?) */
3875
3876    /* XXX flush any work queues */
3877
3878    while (ecore_func_get_state(sc, &sc->func_obj) !=
3879           ECORE_F_STATE_STARTED && tout--) {
3880        DELAY(20000);
3881    }
3882
3883    if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3884        /*
3885         * Failed to complete the transaction in a "good way"
3886         * Force both transactions with CLR bit.
3887         */
3888        struct ecore_func_state_params func_params = { NULL };
3889
3890        BLOGE(sc, "Unexpected function state! "
3891                  "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3892
3893        func_params.f_obj = &sc->func_obj;
3894        bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3895
3896        /* STARTED-->TX_STOPPED */
3897        func_params.cmd = ECORE_F_CMD_TX_STOP;
3898        ecore_func_state_change(sc, &func_params);
3899
3900        /* TX_STOPPED-->STARTED */
3901        func_params.cmd = ECORE_F_CMD_TX_START;
3902        return (ecore_func_state_change(sc, &func_params));
3903    }
3904
3905    return (0);
3906}
3907
3908static int
3909bxe_stop_queue(struct bxe_softc *sc,
3910               int              index)
3911{
3912    struct bxe_fastpath *fp = &sc->fp[index];
3913    struct ecore_queue_state_params q_params = { NULL };
3914    int rc;
3915
3916    BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3917
3918    q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3919    /* We want to wait for completion in this context */
3920    bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3921
3922    /* Stop the primary connection: */
3923
3924    /* ...halt the connection */
3925    q_params.cmd = ECORE_Q_CMD_HALT;
3926    rc = ecore_queue_state_change(sc, &q_params);
3927    if (rc) {
3928        return (rc);
3929    }
3930
3931    /* ...terminate the connection */
3932    q_params.cmd = ECORE_Q_CMD_TERMINATE;
3933    memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3934    q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3935    rc = ecore_queue_state_change(sc, &q_params);
3936    if (rc) {
3937        return (rc);
3938    }
3939
3940    /* ...delete cfc entry */
3941    q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3942    memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3943    q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3944    return (ecore_queue_state_change(sc, &q_params));
3945}
3946
3947/* wait for the outstanding SP commands */
3948static inline uint8_t
3949bxe_wait_sp_comp(struct bxe_softc *sc,
3950                 unsigned long    mask)
3951{
3952    unsigned long tmp;
3953    int tout = 5000; /* wait for 5 secs tops */
3954
3955    while (tout--) {
3956        mb();
3957        if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3958            return (TRUE);
3959        }
3960
3961        DELAY(1000);
3962    }
3963
3964    mb();
3965
3966    tmp = atomic_load_acq_long(&sc->sp_state);
3967    if (tmp & mask) {
3968        BLOGE(sc, "Filtering completion timed out: "
3969                  "sp_state 0x%lx, mask 0x%lx\n",
3970              tmp, mask);
3971        return (FALSE);
3972    }
3973
3974    return (FALSE);
3975}
3976
3977static int
3978bxe_func_stop(struct bxe_softc *sc)
3979{
3980    struct ecore_func_state_params func_params = { NULL };
3981    int rc;
3982
3983    /* prepare parameters for function state transitions */
3984    bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3985    func_params.f_obj = &sc->func_obj;
3986    func_params.cmd = ECORE_F_CMD_STOP;
3987
3988    /*
3989     * Try to stop the function the 'good way'. If it fails (in case
3990     * of a parity error during bxe_chip_cleanup()) and we are
3991     * not in a debug mode, perform a state transaction in order to
3992     * enable further HW_RESET transaction.
3993     */
3994    rc = ecore_func_state_change(sc, &func_params);
3995    if (rc) {
3996        BLOGE(sc, "FUNC_STOP ramrod failed. "
3997                  "Running a dry transaction (%d)\n", rc);
3998        bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3999        return (ecore_func_state_change(sc, &func_params));
4000    }
4001
4002    return (0);
4003}
4004
4005static int
4006bxe_reset_hw(struct bxe_softc *sc,
4007             uint32_t         load_code)
4008{
4009    struct ecore_func_state_params func_params = { NULL };
4010
4011    /* Prepare parameters for function state transitions */
4012    bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4013
4014    func_params.f_obj = &sc->func_obj;
4015    func_params.cmd = ECORE_F_CMD_HW_RESET;
4016
4017    func_params.params.hw_init.load_phase = load_code;
4018
4019    return (ecore_func_state_change(sc, &func_params));
4020}
4021
4022static void
4023bxe_int_disable_sync(struct bxe_softc *sc,
4024                     int              disable_hw)
4025{
4026    if (disable_hw) {
4027        /* prevent the HW from sending interrupts */
4028        bxe_int_disable(sc);
4029    }
4030
4031    /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4032    /* make sure all ISRs are done */
4033
4034    /* XXX make sure sp_task is not running */
4035    /* cancel and flush work queues */
4036}
4037
4038static void
4039bxe_chip_cleanup(struct bxe_softc *sc,
4040                 uint32_t         unload_mode,
4041                 uint8_t          keep_link)
4042{
4043    int port = SC_PORT(sc);
4044    struct ecore_mcast_ramrod_params rparam = { NULL };
4045    uint32_t reset_code;
4046    int i, rc = 0;
4047
4048    bxe_drain_tx_queues(sc);
4049
4050    /* give HW time to discard old tx messages */
4051    DELAY(1000);
4052
4053    /* Clean all ETH MACs */
4054    rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4055    if (rc < 0) {
4056        BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4057    }
4058
4059    /* Clean up UC list  */
4060    rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4061    if (rc < 0) {
4062        BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4063    }
4064
4065    /* Disable LLH */
4066    if (!CHIP_IS_E1(sc)) {
4067        REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4068    }
4069
4070    /* Set "drop all" to stop Rx */
4071
4072    /*
4073     * We need to take the BXE_MCAST_LOCK() here in order to prevent
4074     * a race between the completion code and this code.
4075     */
4076    BXE_MCAST_LOCK(sc);
4077
4078    if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4079        bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4080    } else {
4081        bxe_set_storm_rx_mode(sc);
4082    }
4083
4084    /* Clean up multicast configuration */
4085    rparam.mcast_obj = &sc->mcast_obj;
4086    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4087    if (rc < 0) {
4088        BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4089    }
4090
4091    BXE_MCAST_UNLOCK(sc);
4092
4093    // XXX bxe_iov_chip_cleanup(sc);
4094
4095    /*
4096     * Send the UNLOAD_REQUEST to the MCP. This will return if
4097     * this function should perform FUNCTION, PORT, or COMMON HW
4098     * reset.
4099     */
4100    reset_code = bxe_send_unload_req(sc, unload_mode);
4101
4102    /*
4103     * (assumption: No Attention from MCP at this stage)
4104     * PMF probably in the middle of TX disable/enable transaction
4105     */
4106    rc = bxe_func_wait_started(sc);
4107    if (rc) {
4108        BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4109    }
4110
4111    /*
4112     * Close multi and leading connections
4113     * Completions for ramrods are collected in a synchronous way
4114     */
4115    for (i = 0; i < sc->num_queues; i++) {
4116        if (bxe_stop_queue(sc, i)) {
4117            goto unload_error;
4118        }
4119    }
4120
4121    /*
4122     * If SP settings didn't get completed so far - something
4123     * very wrong has happen.
4124     */
4125    if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4126        BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4127    }
4128
4129unload_error:
4130
4131    rc = bxe_func_stop(sc);
4132    if (rc) {
4133        BLOGE(sc, "Function stop failed!(%d)\n", rc);
4134    }
4135
4136    /* disable HW interrupts */
4137    bxe_int_disable_sync(sc, TRUE);
4138
4139    /* detach interrupts */
4140    bxe_interrupt_detach(sc);
4141
4142    /* Reset the chip */
4143    rc = bxe_reset_hw(sc, reset_code);
4144    if (rc) {
4145        BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4146    }
4147
4148    /* Report UNLOAD_DONE to MCP */
4149    bxe_send_unload_done(sc, keep_link);
4150}
4151
4152static void
4153bxe_disable_close_the_gate(struct bxe_softc *sc)
4154{
4155    uint32_t val;
4156    int port = SC_PORT(sc);
4157
4158    BLOGD(sc, DBG_LOAD,
4159          "Disabling 'close the gates'\n");
4160
4161    if (CHIP_IS_E1(sc)) {
4162        uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4163                               MISC_REG_AEU_MASK_ATTN_FUNC_0;
4164        val = REG_RD(sc, addr);
4165        val &= ~(0x300);
4166        REG_WR(sc, addr, val);
4167    } else {
4168        val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4169        val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4170                 MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4171        REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4172    }
4173}
4174
4175/*
4176 * Cleans the object that have internal lists without sending
4177 * ramrods. Should be run when interrutps are disabled.
4178 */
4179static void
4180bxe_squeeze_objects(struct bxe_softc *sc)
4181{
4182    unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4183    struct ecore_mcast_ramrod_params rparam = { NULL };
4184    struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4185    int rc;
4186
4187    /* Cleanup MACs' object first... */
4188
4189    /* Wait for completion of requested */
4190    bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4191    /* Perform a dry cleanup */
4192    bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4193
4194    /* Clean ETH primary MAC */
4195    bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4196    rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4197                             &ramrod_flags);
4198    if (rc != 0) {
4199        BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4200    }
4201
4202    /* Cleanup UC list */
4203    vlan_mac_flags = 0;
4204    bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4205    rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4206                             &ramrod_flags);
4207    if (rc != 0) {
4208        BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4209    }
4210
4211    /* Now clean mcast object... */
4212
4213    rparam.mcast_obj = &sc->mcast_obj;
4214    bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4215
4216    /* Add a DEL command... */
4217    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4218    if (rc < 0) {
4219        BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4220    }
4221
4222    /* now wait until all pending commands are cleared */
4223
4224    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4225    while (rc != 0) {
4226        if (rc < 0) {
4227            BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4228            return;
4229        }
4230
4231        rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4232    }
4233}
4234
4235/* stop the controller */
4236static __noinline int
4237bxe_nic_unload(struct bxe_softc *sc,
4238               uint32_t         unload_mode,
4239               uint8_t          keep_link)
4240{
4241    uint8_t global = FALSE;
4242    uint32_t val;
4243    int i;
4244
4245    BXE_CORE_LOCK_ASSERT(sc);
4246
4247    if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
4248
4249    for (i = 0; i < sc->num_queues; i++) {
4250        struct bxe_fastpath *fp;
4251
4252        fp = &sc->fp[i];
4253	fp->watchdog_timer = 0;
4254        BXE_FP_TX_LOCK(fp);
4255        BXE_FP_TX_UNLOCK(fp);
4256    }
4257
4258    BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4259
4260    /* mark driver as unloaded in shmem2 */
4261    if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4262        val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4263        SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4264                  val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4265    }
4266
4267    if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4268        (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4269
4270	if(CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
4271            /*
4272             * We can get here if the driver has been unloaded
4273             * during parity error recovery and is either waiting for a
4274             * leader to complete or for other functions to unload and
4275             * then ifconfig down has been issued. In this case we want to
4276             * unload and let other functions to complete a recovery
4277             * process.
4278             */
4279            sc->recovery_state = BXE_RECOVERY_DONE;
4280            sc->is_leader = 0;
4281            bxe_release_leader_lock(sc);
4282            mb();
4283            BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4284	}
4285        BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4286            " state = 0x%x\n", sc->recovery_state, sc->state);
4287        return (-1);
4288    }
4289
4290    /*
4291     * Nothing to do during unload if previous bxe_nic_load()
4292     * did not completed successfully - all resourses are released.
4293     */
4294    if ((sc->state == BXE_STATE_CLOSED) ||
4295        (sc->state == BXE_STATE_ERROR)) {
4296        return (0);
4297    }
4298
4299    sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4300    mb();
4301
4302    /* stop tx */
4303    bxe_tx_disable(sc);
4304
4305    sc->rx_mode = BXE_RX_MODE_NONE;
4306    /* XXX set rx mode ??? */
4307
4308    if (IS_PF(sc) && !sc->grcdump_done) {
4309        /* set ALWAYS_ALIVE bit in shmem */
4310        sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4311
4312        bxe_drv_pulse(sc);
4313
4314        bxe_stats_handle(sc, STATS_EVENT_STOP);
4315        bxe_save_statistics(sc);
4316    }
4317
4318    /* wait till consumers catch up with producers in all queues */
4319    bxe_drain_tx_queues(sc);
4320
4321    /* if VF indicate to PF this function is going down (PF will delete sp
4322     * elements and clear initializations
4323     */
4324    if (IS_VF(sc)) {
4325        ; /* bxe_vfpf_close_vf(sc); */
4326    } else if (unload_mode != UNLOAD_RECOVERY) {
4327        /* if this is a normal/close unload need to clean up chip */
4328        if (!sc->grcdump_done)
4329            bxe_chip_cleanup(sc, unload_mode, keep_link);
4330    } else {
4331        /* Send the UNLOAD_REQUEST to the MCP */
4332        bxe_send_unload_req(sc, unload_mode);
4333
4334        /*
4335         * Prevent transactions to host from the functions on the
4336         * engine that doesn't reset global blocks in case of global
4337         * attention once gloabl blocks are reset and gates are opened
4338         * (the engine which leader will perform the recovery
4339         * last).
4340         */
4341        if (!CHIP_IS_E1x(sc)) {
4342            bxe_pf_disable(sc);
4343        }
4344
4345        /* disable HW interrupts */
4346        bxe_int_disable_sync(sc, TRUE);
4347
4348        /* detach interrupts */
4349        bxe_interrupt_detach(sc);
4350
4351        /* Report UNLOAD_DONE to MCP */
4352        bxe_send_unload_done(sc, FALSE);
4353    }
4354
4355    /*
4356     * At this stage no more interrupts will arrive so we may safely clean
4357     * the queue'able objects here in case they failed to get cleaned so far.
4358     */
4359    if (IS_PF(sc)) {
4360        bxe_squeeze_objects(sc);
4361    }
4362
4363    /* There should be no more pending SP commands at this stage */
4364    sc->sp_state = 0;
4365
4366    sc->port.pmf = 0;
4367
4368    bxe_free_fp_buffers(sc);
4369
4370    if (IS_PF(sc)) {
4371        bxe_free_mem(sc);
4372    }
4373
4374    bxe_free_fw_stats_mem(sc);
4375
4376    sc->state = BXE_STATE_CLOSED;
4377
4378    /*
4379     * Check if there are pending parity attentions. If there are - set
4380     * RECOVERY_IN_PROGRESS.
4381     */
4382    if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4383        bxe_set_reset_in_progress(sc);
4384
4385        /* Set RESET_IS_GLOBAL if needed */
4386        if (global) {
4387            bxe_set_reset_global(sc);
4388        }
4389    }
4390
4391    /*
4392     * The last driver must disable a "close the gate" if there is no
4393     * parity attention or "process kill" pending.
4394     */
4395    if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4396        bxe_reset_is_done(sc, SC_PATH(sc))) {
4397        bxe_disable_close_the_gate(sc);
4398    }
4399
4400    BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4401
4402    bxe_link_report(sc);
4403
4404    return (0);
4405}
4406
4407/*
4408 * Called by the OS to set various media options (i.e. link, speed, etc.) when
4409 * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4410 */
4411static int
4412bxe_ifmedia_update(struct ifnet  *ifp)
4413{
4414    struct bxe_softc *sc = (struct bxe_softc *)if_getsoftc(ifp);
4415    struct ifmedia *ifm;
4416
4417    ifm = &sc->ifmedia;
4418
4419    /* We only support Ethernet media type. */
4420    if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4421        return (EINVAL);
4422    }
4423
4424    switch (IFM_SUBTYPE(ifm->ifm_media)) {
4425    case IFM_AUTO:
4426         break;
4427    case IFM_10G_CX4:
4428    case IFM_10G_SR:
4429    case IFM_10G_T:
4430    case IFM_10G_TWINAX:
4431    default:
4432        /* We don't support changing the media type. */
4433        BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4434              IFM_SUBTYPE(ifm->ifm_media));
4435        return (EINVAL);
4436    }
4437
4438    return (0);
4439}
4440
4441/*
4442 * Called by the OS to get the current media status (i.e. link, speed, etc.).
4443 */
4444static void
4445bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4446{
4447    struct bxe_softc *sc = if_getsoftc(ifp);
4448
4449    /* Bug 165447: the 'ifconfig' tool skips printing of the "status: ..."
4450       line if the IFM_AVALID flag is *NOT* set. So we need to set this
4451       flag unconditionally (irrespective of the admininistrative
4452       'up/down' state of the interface) to ensure that that line is always
4453       displayed.
4454    */
4455    ifmr->ifm_status = IFM_AVALID;
4456
4457    /* Setup the default interface info. */
4458    ifmr->ifm_active = IFM_ETHER;
4459
4460    /* Report link down if the driver isn't running. */
4461    if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4462        ifmr->ifm_active |= IFM_NONE;
4463        BLOGD(sc, DBG_PHY, "in %s : nic still not loaded fully\n", __func__);
4464        BLOGD(sc, DBG_PHY, "in %s : link_up (1) : %d\n",
4465                __func__, sc->link_vars.link_up);
4466        return;
4467    }
4468
4469
4470    if (sc->link_vars.link_up) {
4471        ifmr->ifm_status |= IFM_ACTIVE;
4472        ifmr->ifm_active |= IFM_FDX;
4473    } else {
4474        ifmr->ifm_active |= IFM_NONE;
4475        BLOGD(sc, DBG_PHY, "in %s : setting IFM_NONE\n",
4476                __func__);
4477        return;
4478    }
4479
4480    ifmr->ifm_active |= sc->media;
4481    return;
4482}
4483
4484static void
4485bxe_handle_chip_tq(void *context,
4486                   int  pending)
4487{
4488    struct bxe_softc *sc = (struct bxe_softc *)context;
4489    long work = atomic_load_acq_long(&sc->chip_tq_flags);
4490
4491    switch (work)
4492    {
4493
4494    case CHIP_TQ_REINIT:
4495        if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
4496            /* restart the interface */
4497            BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4498            bxe_periodic_stop(sc);
4499            BXE_CORE_LOCK(sc);
4500            bxe_stop_locked(sc);
4501            bxe_init_locked(sc);
4502            BXE_CORE_UNLOCK(sc);
4503        }
4504        break;
4505
4506    default:
4507        break;
4508    }
4509}
4510
4511/*
4512 * Handles any IOCTL calls from the operating system.
4513 *
4514 * Returns:
4515 *   0 = Success, >0 Failure
4516 */
4517static int
4518bxe_ioctl(if_t ifp,
4519          u_long       command,
4520          caddr_t      data)
4521{
4522    struct bxe_softc *sc = if_getsoftc(ifp);
4523    struct ifreq *ifr = (struct ifreq *)data;
4524    int mask = 0;
4525    int reinit = 0;
4526    int error = 0;
4527
4528    int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4529    int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4530
4531    switch (command)
4532    {
4533    case SIOCSIFMTU:
4534        BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4535              ifr->ifr_mtu);
4536
4537        if (sc->mtu == ifr->ifr_mtu) {
4538            /* nothing to change */
4539            break;
4540        }
4541
4542        if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4543            BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4544                  ifr->ifr_mtu, mtu_min, mtu_max);
4545            error = EINVAL;
4546            break;
4547        }
4548
4549        atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4550                             (unsigned long)ifr->ifr_mtu);
4551	/*
4552        atomic_store_rel_long((volatile unsigned long *)&if_getmtu(ifp),
4553                              (unsigned long)ifr->ifr_mtu);
4554	XXX - Not sure why it needs to be atomic
4555	*/
4556	if_setmtu(ifp, ifr->ifr_mtu);
4557        reinit = 1;
4558        break;
4559
4560    case SIOCSIFFLAGS:
4561        /* toggle the interface state up or down */
4562        BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4563
4564	BXE_CORE_LOCK(sc);
4565        /* check if the interface is up */
4566        if (if_getflags(ifp) & IFF_UP) {
4567            if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4568                /* set the receive mode flags */
4569                bxe_set_rx_mode(sc);
4570            } else if(sc->state != BXE_STATE_DISABLED) {
4571		bxe_init_locked(sc);
4572            }
4573        } else {
4574            if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4575		bxe_periodic_stop(sc);
4576		bxe_stop_locked(sc);
4577            }
4578        }
4579	BXE_CORE_UNLOCK(sc);
4580
4581        break;
4582
4583    case SIOCADDMULTI:
4584    case SIOCDELMULTI:
4585        /* add/delete multicast addresses */
4586        BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4587
4588        /* check if the interface is up */
4589        if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4590            /* set the receive mode flags */
4591	    BXE_CORE_LOCK(sc);
4592            bxe_set_rx_mode(sc);
4593	    BXE_CORE_UNLOCK(sc);
4594        }
4595
4596        break;
4597
4598    case SIOCSIFCAP:
4599        /* find out which capabilities have changed */
4600        mask = (ifr->ifr_reqcap ^ if_getcapenable(ifp));
4601
4602        BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4603              mask);
4604
4605        /* toggle the LRO capabilites enable flag */
4606        if (mask & IFCAP_LRO) {
4607	    if_togglecapenable(ifp, IFCAP_LRO);
4608            BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4609                  (if_getcapenable(ifp) & IFCAP_LRO) ? "ON" : "OFF");
4610            reinit = 1;
4611        }
4612
4613        /* toggle the TXCSUM checksum capabilites enable flag */
4614        if (mask & IFCAP_TXCSUM) {
4615	    if_togglecapenable(ifp, IFCAP_TXCSUM);
4616            BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4617                  (if_getcapenable(ifp) & IFCAP_TXCSUM) ? "ON" : "OFF");
4618            if (if_getcapenable(ifp) & IFCAP_TXCSUM) {
4619                if_sethwassistbits(ifp, (CSUM_IP      |
4620                                    CSUM_TCP      |
4621                                    CSUM_UDP      |
4622                                    CSUM_TSO      |
4623                                    CSUM_TCP_IPV6 |
4624                                    CSUM_UDP_IPV6), 0);
4625            } else {
4626		if_clearhwassist(ifp); /* XXX */
4627            }
4628        }
4629
4630        /* toggle the RXCSUM checksum capabilities enable flag */
4631        if (mask & IFCAP_RXCSUM) {
4632	    if_togglecapenable(ifp, IFCAP_RXCSUM);
4633            BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4634                  (if_getcapenable(ifp) & IFCAP_RXCSUM) ? "ON" : "OFF");
4635            if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
4636                if_sethwassistbits(ifp, (CSUM_IP      |
4637                                    CSUM_TCP      |
4638                                    CSUM_UDP      |
4639                                    CSUM_TSO      |
4640                                    CSUM_TCP_IPV6 |
4641                                    CSUM_UDP_IPV6), 0);
4642            } else {
4643		if_clearhwassist(ifp); /* XXX */
4644            }
4645        }
4646
4647        /* toggle TSO4 capabilities enabled flag */
4648        if (mask & IFCAP_TSO4) {
4649            if_togglecapenable(ifp, IFCAP_TSO4);
4650            BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4651                  (if_getcapenable(ifp) & IFCAP_TSO4) ? "ON" : "OFF");
4652        }
4653
4654        /* toggle TSO6 capabilities enabled flag */
4655        if (mask & IFCAP_TSO6) {
4656	    if_togglecapenable(ifp, IFCAP_TSO6);
4657            BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4658                  (if_getcapenable(ifp) & IFCAP_TSO6) ? "ON" : "OFF");
4659        }
4660
4661        /* toggle VLAN_HWTSO capabilities enabled flag */
4662        if (mask & IFCAP_VLAN_HWTSO) {
4663
4664	    if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
4665            BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4666                  (if_getcapenable(ifp) & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4667        }
4668
4669        /* toggle VLAN_HWCSUM capabilities enabled flag */
4670        if (mask & IFCAP_VLAN_HWCSUM) {
4671            /* XXX investigate this... */
4672            BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4673            error = EINVAL;
4674        }
4675
4676        /* toggle VLAN_MTU capabilities enable flag */
4677        if (mask & IFCAP_VLAN_MTU) {
4678            /* XXX investigate this... */
4679            BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4680            error = EINVAL;
4681        }
4682
4683        /* toggle VLAN_HWTAGGING capabilities enabled flag */
4684        if (mask & IFCAP_VLAN_HWTAGGING) {
4685            /* XXX investigate this... */
4686            BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4687            error = EINVAL;
4688        }
4689
4690        /* toggle VLAN_HWFILTER capabilities enabled flag */
4691        if (mask & IFCAP_VLAN_HWFILTER) {
4692            /* XXX investigate this... */
4693            BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4694            error = EINVAL;
4695        }
4696
4697        /* XXX not yet...
4698         * IFCAP_WOL_MAGIC
4699         */
4700
4701        break;
4702
4703    case SIOCSIFMEDIA:
4704    case SIOCGIFMEDIA:
4705        /* set/get interface media */
4706        BLOGD(sc, DBG_IOCTL,
4707              "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4708              (command & 0xff));
4709        error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4710        break;
4711
4712    default:
4713        BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4714              (command & 0xff));
4715        error = ether_ioctl(ifp, command, data);
4716        break;
4717    }
4718
4719    if (reinit && (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4720        BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4721              "Re-initializing hardware from IOCTL change\n");
4722	bxe_periodic_stop(sc);
4723	BXE_CORE_LOCK(sc);
4724	bxe_stop_locked(sc);
4725	bxe_init_locked(sc);
4726	BXE_CORE_UNLOCK(sc);
4727    }
4728
4729    return (error);
4730}
4731
4732static __noinline void
4733bxe_dump_mbuf(struct bxe_softc *sc,
4734              struct mbuf      *m,
4735              uint8_t          contents)
4736{
4737    char * type;
4738    int i = 0;
4739
4740    if (!(sc->debug & DBG_MBUF)) {
4741        return;
4742    }
4743
4744    if (m == NULL) {
4745        BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4746        return;
4747    }
4748
4749    while (m) {
4750
4751#if __FreeBSD_version >= 1000000
4752        BLOGD(sc, DBG_MBUF,
4753              "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4754              i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4755
4756        if (m->m_flags & M_PKTHDR) {
4757             BLOGD(sc, DBG_MBUF,
4758                   "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4759                   i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4760                   (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4761        }
4762#else
4763        BLOGD(sc, DBG_MBUF,
4764              "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4765              i, m, m->m_len, m->m_flags,
4766              "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4767
4768        if (m->m_flags & M_PKTHDR) {
4769             BLOGD(sc, DBG_MBUF,
4770                   "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4771                   i, m->m_pkthdr.len, m->m_flags,
4772                   "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4773                   "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4774                   "\22M_PROMISC\23M_NOFREE",
4775                   (int)m->m_pkthdr.csum_flags,
4776                   "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4777                   "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4778                   "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4779                   "\14CSUM_PSEUDO_HDR");
4780        }
4781#endif /* #if __FreeBSD_version >= 1000000 */
4782
4783        if (m->m_flags & M_EXT) {
4784            switch (m->m_ext.ext_type) {
4785            case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4786            case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4787            case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4788            case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4789            case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4790            case EXT_PACKET:     type = "EXT_PACKET";     break;
4791            case EXT_MBUF:       type = "EXT_MBUF";       break;
4792            case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4793            case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4794            case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4795            case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4796            default:             type = "UNKNOWN";        break;
4797            }
4798
4799            BLOGD(sc, DBG_MBUF,
4800                  "%02d: - m_ext: %p ext_size=%d type=%s\n",
4801                  i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4802        }
4803
4804        if (contents) {
4805            bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4806        }
4807
4808        m = m->m_next;
4809        i++;
4810    }
4811}
4812
4813/*
4814 * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4815 * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4816 * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4817 * The headers comes in a separate bd in FreeBSD so 13-3=10.
4818 * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4819 */
4820static int
4821bxe_chktso_window(struct bxe_softc  *sc,
4822                  int               nsegs,
4823                  bus_dma_segment_t *segs,
4824                  struct mbuf       *m)
4825{
4826    uint32_t num_wnds, wnd_size, wnd_sum;
4827    int32_t frag_idx, wnd_idx;
4828    unsigned short lso_mss;
4829    int defrag;
4830
4831    defrag = 0;
4832    wnd_sum = 0;
4833    wnd_size = 10;
4834    num_wnds = nsegs - wnd_size;
4835    lso_mss = htole16(m->m_pkthdr.tso_segsz);
4836
4837    /*
4838     * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4839     * first window sum of data while skipping the first assuming it is the
4840     * header in FreeBSD.
4841     */
4842    for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4843        wnd_sum += htole16(segs[frag_idx].ds_len);
4844    }
4845
4846    /* check the first 10 bd window size */
4847    if (wnd_sum < lso_mss) {
4848        return (1);
4849    }
4850
4851    /* run through the windows */
4852    for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4853        /* subtract the first mbuf->m_len of the last wndw(-header) */
4854        wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4855        /* add the next mbuf len to the len of our new window */
4856        wnd_sum += htole16(segs[frag_idx].ds_len);
4857        if (wnd_sum < lso_mss) {
4858            return (1);
4859        }
4860    }
4861
4862    return (0);
4863}
4864
4865static uint8_t
4866bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4867                    struct mbuf         *m,
4868                    uint32_t            *parsing_data)
4869{
4870    struct ether_vlan_header *eh = NULL;
4871    struct ip *ip4 = NULL;
4872    struct ip6_hdr *ip6 = NULL;
4873    caddr_t ip = NULL;
4874    struct tcphdr *th = NULL;
4875    int e_hlen, ip_hlen, l4_off;
4876    uint16_t proto;
4877
4878    if (m->m_pkthdr.csum_flags == CSUM_IP) {
4879        /* no L4 checksum offload needed */
4880        return (0);
4881    }
4882
4883    /* get the Ethernet header */
4884    eh = mtod(m, struct ether_vlan_header *);
4885
4886    /* handle VLAN encapsulation if present */
4887    if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4888        e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4889        proto  = ntohs(eh->evl_proto);
4890    } else {
4891        e_hlen = ETHER_HDR_LEN;
4892        proto  = ntohs(eh->evl_encap_proto);
4893    }
4894
4895    switch (proto) {
4896    case ETHERTYPE_IP:
4897        /* get the IP header, if mbuf len < 20 then header in next mbuf */
4898        ip4 = (m->m_len < sizeof(struct ip)) ?
4899                  (struct ip *)m->m_next->m_data :
4900                  (struct ip *)(m->m_data + e_hlen);
4901        /* ip_hl is number of 32-bit words */
4902        ip_hlen = (ip4->ip_hl << 2);
4903        ip = (caddr_t)ip4;
4904        break;
4905    case ETHERTYPE_IPV6:
4906        /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4907        ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4908                  (struct ip6_hdr *)m->m_next->m_data :
4909                  (struct ip6_hdr *)(m->m_data + e_hlen);
4910        /* XXX cannot support offload with IPv6 extensions */
4911        ip_hlen = sizeof(struct ip6_hdr);
4912        ip = (caddr_t)ip6;
4913        break;
4914    default:
4915        /* We can't offload in this case... */
4916        /* XXX error stat ??? */
4917        return (0);
4918    }
4919
4920    /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4921    l4_off = (e_hlen + ip_hlen);
4922
4923    *parsing_data |=
4924        (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4925         ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4926
4927    if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4928                                  CSUM_TSO |
4929                                  CSUM_TCP_IPV6)) {
4930        fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4931        th = (struct tcphdr *)(ip + ip_hlen);
4932        /* th_off is number of 32-bit words */
4933        *parsing_data |= ((th->th_off <<
4934                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4935                          ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4936        return (l4_off + (th->th_off << 2)); /* entire header length */
4937    } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4938                                         CSUM_UDP_IPV6)) {
4939        fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4940        return (l4_off + sizeof(struct udphdr)); /* entire header length */
4941    } else {
4942        /* XXX error stat ??? */
4943        return (0);
4944    }
4945}
4946
4947static uint8_t
4948bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4949                 struct mbuf                *m,
4950                 struct eth_tx_parse_bd_e1x *pbd)
4951{
4952    struct ether_vlan_header *eh = NULL;
4953    struct ip *ip4 = NULL;
4954    struct ip6_hdr *ip6 = NULL;
4955    caddr_t ip = NULL;
4956    struct tcphdr *th = NULL;
4957    struct udphdr *uh = NULL;
4958    int e_hlen, ip_hlen;
4959    uint16_t proto;
4960    uint8_t hlen;
4961    uint16_t tmp_csum;
4962    uint32_t *tmp_uh;
4963
4964    /* get the Ethernet header */
4965    eh = mtod(m, struct ether_vlan_header *);
4966
4967    /* handle VLAN encapsulation if present */
4968    if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4969        e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4970        proto  = ntohs(eh->evl_proto);
4971    } else {
4972        e_hlen = ETHER_HDR_LEN;
4973        proto  = ntohs(eh->evl_encap_proto);
4974    }
4975
4976    switch (proto) {
4977    case ETHERTYPE_IP:
4978        /* get the IP header, if mbuf len < 20 then header in next mbuf */
4979        ip4 = (m->m_len < sizeof(struct ip)) ?
4980                  (struct ip *)m->m_next->m_data :
4981                  (struct ip *)(m->m_data + e_hlen);
4982        /* ip_hl is number of 32-bit words */
4983        ip_hlen = (ip4->ip_hl << 1);
4984        ip = (caddr_t)ip4;
4985        break;
4986    case ETHERTYPE_IPV6:
4987        /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4988        ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4989                  (struct ip6_hdr *)m->m_next->m_data :
4990                  (struct ip6_hdr *)(m->m_data + e_hlen);
4991        /* XXX cannot support offload with IPv6 extensions */
4992        ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4993        ip = (caddr_t)ip6;
4994        break;
4995    default:
4996        /* We can't offload in this case... */
4997        /* XXX error stat ??? */
4998        return (0);
4999    }
5000
5001    hlen = (e_hlen >> 1);
5002
5003    /* note that rest of global_data is indirectly zeroed here */
5004    if (m->m_flags & M_VLANTAG) {
5005        pbd->global_data =
5006            htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
5007    } else {
5008        pbd->global_data = htole16(hlen);
5009    }
5010
5011    pbd->ip_hlen_w = ip_hlen;
5012
5013    hlen += pbd->ip_hlen_w;
5014
5015    /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5016
5017    if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5018                                  CSUM_TSO |
5019                                  CSUM_TCP_IPV6)) {
5020        th = (struct tcphdr *)(ip + (ip_hlen << 1));
5021        /* th_off is number of 32-bit words */
5022        hlen += (uint16_t)(th->th_off << 1);
5023    } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5024                                         CSUM_UDP_IPV6)) {
5025        uh = (struct udphdr *)(ip + (ip_hlen << 1));
5026        hlen += (sizeof(struct udphdr) / 2);
5027    } else {
5028        /* valid case as only CSUM_IP was set */
5029        return (0);
5030    }
5031
5032    pbd->total_hlen_w = htole16(hlen);
5033
5034    if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5035                                  CSUM_TSO |
5036                                  CSUM_TCP_IPV6)) {
5037        fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5038        pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5039    } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5040                                         CSUM_UDP_IPV6)) {
5041        fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5042
5043        /*
5044         * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5045         * checksums and does not know anything about the UDP header and where
5046         * the checksum field is located. It only knows about TCP. Therefore
5047         * we "lie" to the hardware for outgoing UDP packets w/ checksum
5048         * offload. Since the checksum field offset for TCP is 16 bytes and
5049         * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5050         * bytes less than the start of the UDP header. This allows the
5051         * hardware to write the checksum in the correct spot. But the
5052         * hardware will compute a checksum which includes the last 10 bytes
5053         * of the IP header. To correct this we tweak the stack computed
5054         * pseudo checksum by folding in the calculation of the inverse
5055         * checksum for those final 10 bytes of the IP header. This allows
5056         * the correct checksum to be computed by the hardware.
5057         */
5058
5059        /* set pointer 10 bytes before UDP header */
5060        tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5061
5062        /* calculate a pseudo header checksum over the first 10 bytes */
5063        tmp_csum = in_pseudo(*tmp_uh,
5064                             *(tmp_uh + 1),
5065                             *(uint16_t *)(tmp_uh + 2));
5066
5067        pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5068    }
5069
5070    return (hlen * 2); /* entire header length, number of bytes */
5071}
5072
5073static void
5074bxe_set_pbd_lso_e2(struct mbuf *m,
5075                   uint32_t    *parsing_data)
5076{
5077    *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5078                       ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5079                      ETH_TX_PARSE_BD_E2_LSO_MSS);
5080
5081    /* XXX test for IPv6 with extension header... */
5082}
5083
5084static void
5085bxe_set_pbd_lso(struct mbuf                *m,
5086                struct eth_tx_parse_bd_e1x *pbd)
5087{
5088    struct ether_vlan_header *eh = NULL;
5089    struct ip *ip = NULL;
5090    struct tcphdr *th = NULL;
5091    int e_hlen;
5092
5093    /* get the Ethernet header */
5094    eh = mtod(m, struct ether_vlan_header *);
5095
5096    /* handle VLAN encapsulation if present */
5097    e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5098                 (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5099
5100    /* get the IP and TCP header, with LSO entire header in first mbuf */
5101    /* XXX assuming IPv4 */
5102    ip = (struct ip *)(m->m_data + e_hlen);
5103    th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5104
5105    pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5106    pbd->tcp_send_seq = ntohl(th->th_seq);
5107    pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5108
5109#if 1
5110        /* XXX IPv4 */
5111        pbd->ip_id = ntohs(ip->ip_id);
5112        pbd->tcp_pseudo_csum =
5113            ntohs(in_pseudo(ip->ip_src.s_addr,
5114                            ip->ip_dst.s_addr,
5115                            htons(IPPROTO_TCP)));
5116#else
5117        /* XXX IPv6 */
5118        pbd->tcp_pseudo_csum =
5119            ntohs(in_pseudo(&ip6->ip6_src,
5120                            &ip6->ip6_dst,
5121                            htons(IPPROTO_TCP)));
5122#endif
5123
5124    pbd->global_data |=
5125        htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5126}
5127
5128/*
5129 * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5130 * visible to the controller.
5131 *
5132 * If an mbuf is submitted to this routine and cannot be given to the
5133 * controller (e.g. it has too many fragments) then the function may free
5134 * the mbuf and return to the caller.
5135 *
5136 * Returns:
5137 *   0 = Success, !0 = Failure
5138 *   Note the side effect that an mbuf may be freed if it causes a problem.
5139 */
5140static int
5141bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5142{
5143    bus_dma_segment_t segs[32];
5144    struct mbuf *m0;
5145    struct bxe_sw_tx_bd *tx_buf;
5146    struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5147    struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5148    /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5149    struct eth_tx_bd *tx_data_bd;
5150    struct eth_tx_bd *tx_total_pkt_size_bd;
5151    struct eth_tx_start_bd *tx_start_bd;
5152    uint16_t bd_prod, pkt_prod, total_pkt_size;
5153    uint8_t mac_type;
5154    int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5155    struct bxe_softc *sc;
5156    uint16_t tx_bd_avail;
5157    struct ether_vlan_header *eh;
5158    uint32_t pbd_e2_parsing_data = 0;
5159    uint8_t hlen = 0;
5160    int tmp_bd;
5161    int i;
5162
5163    sc = fp->sc;
5164
5165#if __FreeBSD_version >= 800000
5166    M_ASSERTPKTHDR(*m_head);
5167#endif /* #if __FreeBSD_version >= 800000 */
5168
5169    m0 = *m_head;
5170    rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5171    tx_start_bd = NULL;
5172    tx_data_bd = NULL;
5173    tx_total_pkt_size_bd = NULL;
5174
5175    /* get the H/W pointer for packets and BDs */
5176    pkt_prod = fp->tx_pkt_prod;
5177    bd_prod = fp->tx_bd_prod;
5178
5179    mac_type = UNICAST_ADDRESS;
5180
5181    /* map the mbuf into the next open DMAable memory */
5182    tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5183    error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5184                                    tx_buf->m_map, m0,
5185                                    segs, &nsegs, BUS_DMA_NOWAIT);
5186
5187    /* mapping errors */
5188    if(__predict_false(error != 0)) {
5189        fp->eth_q_stats.tx_dma_mapping_failure++;
5190        if (error == ENOMEM) {
5191            /* resource issue, try again later */
5192            rc = ENOMEM;
5193        } else if (error == EFBIG) {
5194            /* possibly recoverable with defragmentation */
5195            fp->eth_q_stats.mbuf_defrag_attempts++;
5196            m0 = m_defrag(*m_head, M_NOWAIT);
5197            if (m0 == NULL) {
5198                fp->eth_q_stats.mbuf_defrag_failures++;
5199                rc = ENOBUFS;
5200            } else {
5201                /* defrag successful, try mapping again */
5202                *m_head = m0;
5203                error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5204                                                tx_buf->m_map, m0,
5205                                                segs, &nsegs, BUS_DMA_NOWAIT);
5206                if (error) {
5207                    fp->eth_q_stats.tx_dma_mapping_failure++;
5208                    rc = error;
5209                }
5210            }
5211        } else {
5212            /* unknown, unrecoverable mapping error */
5213            BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5214            bxe_dump_mbuf(sc, m0, FALSE);
5215            rc = error;
5216        }
5217
5218        goto bxe_tx_encap_continue;
5219    }
5220
5221    tx_bd_avail = bxe_tx_avail(sc, fp);
5222
5223    /* make sure there is enough room in the send queue */
5224    if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5225        /* Recoverable, try again later. */
5226        fp->eth_q_stats.tx_hw_queue_full++;
5227        bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5228        rc = ENOMEM;
5229        goto bxe_tx_encap_continue;
5230    }
5231
5232    /* capture the current H/W TX chain high watermark */
5233    if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5234                        (TX_BD_USABLE - tx_bd_avail))) {
5235        fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5236    }
5237
5238    /* make sure it fits in the packet window */
5239    if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5240        /*
5241         * The mbuf may be to big for the controller to handle. If the frame
5242         * is a TSO frame we'll need to do an additional check.
5243         */
5244        if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5245            if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5246                goto bxe_tx_encap_continue; /* OK to send */
5247            } else {
5248                fp->eth_q_stats.tx_window_violation_tso++;
5249            }
5250        } else {
5251            fp->eth_q_stats.tx_window_violation_std++;
5252        }
5253
5254        /* lets try to defragment this mbuf and remap it */
5255        fp->eth_q_stats.mbuf_defrag_attempts++;
5256        bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5257
5258        m0 = m_defrag(*m_head, M_NOWAIT);
5259        if (m0 == NULL) {
5260            fp->eth_q_stats.mbuf_defrag_failures++;
5261            /* Ugh, just drop the frame... :( */
5262            rc = ENOBUFS;
5263        } else {
5264            /* defrag successful, try mapping again */
5265            *m_head = m0;
5266            error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5267                                            tx_buf->m_map, m0,
5268                                            segs, &nsegs, BUS_DMA_NOWAIT);
5269            if (error) {
5270                fp->eth_q_stats.tx_dma_mapping_failure++;
5271                /* No sense in trying to defrag/copy chain, drop it. :( */
5272                rc = error;
5273            } else {
5274               /* if the chain is still too long then drop it */
5275                if(m0->m_pkthdr.csum_flags & CSUM_TSO) {
5276                    /*
5277                     * in case TSO is enabled nsegs should be checked against
5278                     * BXE_TSO_MAX_SEGMENTS
5279                     */
5280                    if (__predict_false(nsegs > BXE_TSO_MAX_SEGMENTS)) {
5281                        bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5282                        fp->eth_q_stats.nsegs_path1_errors++;
5283                        rc = ENODEV;
5284                    }
5285                } else {
5286                    if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5287                        bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5288                        fp->eth_q_stats.nsegs_path2_errors++;
5289                        rc = ENODEV;
5290                    }
5291                }
5292            }
5293        }
5294    }
5295
5296bxe_tx_encap_continue:
5297
5298    /* Check for errors */
5299    if (rc) {
5300        if (rc == ENOMEM) {
5301            /* recoverable try again later  */
5302        } else {
5303            fp->eth_q_stats.tx_soft_errors++;
5304            fp->eth_q_stats.mbuf_alloc_tx--;
5305            m_freem(*m_head);
5306            *m_head = NULL;
5307        }
5308
5309        return (rc);
5310    }
5311
5312    /* set flag according to packet type (UNICAST_ADDRESS is default) */
5313    if (m0->m_flags & M_BCAST) {
5314        mac_type = BROADCAST_ADDRESS;
5315    } else if (m0->m_flags & M_MCAST) {
5316        mac_type = MULTICAST_ADDRESS;
5317    }
5318
5319    /* store the mbuf into the mbuf ring */
5320    tx_buf->m        = m0;
5321    tx_buf->first_bd = fp->tx_bd_prod;
5322    tx_buf->flags    = 0;
5323
5324    /* prepare the first transmit (start) BD for the mbuf */
5325    tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5326
5327    BLOGD(sc, DBG_TX,
5328          "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5329          pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5330
5331    tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5332    tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5333    tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5334    total_pkt_size += tx_start_bd->nbytes;
5335    tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5336
5337    tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5338
5339    /* all frames have at least Start BD + Parsing BD */
5340    nbds = nsegs + 1;
5341    tx_start_bd->nbd = htole16(nbds);
5342
5343    if (m0->m_flags & M_VLANTAG) {
5344        tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5345        tx_start_bd->bd_flags.as_bitfield |=
5346            (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5347    } else {
5348        /* vf tx, start bd must hold the ethertype for fw to enforce it */
5349        if (IS_VF(sc)) {
5350            /* map ethernet header to find type and header length */
5351            eh = mtod(m0, struct ether_vlan_header *);
5352            tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5353        } else {
5354            /* used by FW for packet accounting */
5355            tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5356        }
5357    }
5358
5359    /*
5360     * add a parsing BD from the chain. The parsing BD is always added
5361     * though it is only used for TSO and chksum
5362     */
5363    bd_prod = TX_BD_NEXT(bd_prod);
5364
5365    if (m0->m_pkthdr.csum_flags) {
5366        if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5367            fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5368            tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5369        }
5370
5371        if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5372            tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5373                                                  ETH_TX_BD_FLAGS_L4_CSUM);
5374        } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5375            tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5376                                                  ETH_TX_BD_FLAGS_IS_UDP |
5377                                                  ETH_TX_BD_FLAGS_L4_CSUM);
5378        } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5379                   (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5380            tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5381        } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5382            tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5383                                                  ETH_TX_BD_FLAGS_IS_UDP);
5384        }
5385    }
5386
5387    if (!CHIP_IS_E1x(sc)) {
5388        pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5389        memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5390
5391        if (m0->m_pkthdr.csum_flags) {
5392            hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5393        }
5394
5395        SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5396                 mac_type);
5397    } else {
5398        uint16_t global_data = 0;
5399
5400        pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5401        memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5402
5403        if (m0->m_pkthdr.csum_flags) {
5404            hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5405        }
5406
5407        SET_FLAG(global_data,
5408                 ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5409        pbd_e1x->global_data |= htole16(global_data);
5410    }
5411
5412    /* setup the parsing BD with TSO specific info */
5413    if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5414        fp->eth_q_stats.tx_ofld_frames_lso++;
5415        tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5416
5417        if (__predict_false(tx_start_bd->nbytes > hlen)) {
5418            fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5419
5420            /* split the first BD into header/data making the fw job easy */
5421            nbds++;
5422            tx_start_bd->nbd = htole16(nbds);
5423            tx_start_bd->nbytes = htole16(hlen);
5424
5425            bd_prod = TX_BD_NEXT(bd_prod);
5426
5427            /* new transmit BD after the tx_parse_bd */
5428            tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5429            tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5430            tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5431            tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5432            if (tx_total_pkt_size_bd == NULL) {
5433                tx_total_pkt_size_bd = tx_data_bd;
5434            }
5435
5436            BLOGD(sc, DBG_TX,
5437                  "TSO split header size is %d (%x:%x) nbds %d\n",
5438                  le16toh(tx_start_bd->nbytes),
5439                  le32toh(tx_start_bd->addr_hi),
5440                  le32toh(tx_start_bd->addr_lo),
5441                  nbds);
5442        }
5443
5444        if (!CHIP_IS_E1x(sc)) {
5445            bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5446        } else {
5447            bxe_set_pbd_lso(m0, pbd_e1x);
5448        }
5449    }
5450
5451    if (pbd_e2_parsing_data) {
5452        pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5453    }
5454
5455    /* prepare remaining BDs, start tx bd contains first seg/frag */
5456    for (i = 1; i < nsegs ; i++) {
5457        bd_prod = TX_BD_NEXT(bd_prod);
5458        tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5459        tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5460        tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5461        tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5462        if (tx_total_pkt_size_bd == NULL) {
5463            tx_total_pkt_size_bd = tx_data_bd;
5464        }
5465        total_pkt_size += tx_data_bd->nbytes;
5466    }
5467
5468    BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5469
5470    if (tx_total_pkt_size_bd != NULL) {
5471        tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5472    }
5473
5474    if (__predict_false(sc->debug & DBG_TX)) {
5475        tmp_bd = tx_buf->first_bd;
5476        for (i = 0; i < nbds; i++)
5477        {
5478            if (i == 0) {
5479                BLOGD(sc, DBG_TX,
5480                      "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5481                      "bd_flags=0x%x hdr_nbds=%d\n",
5482                      tx_start_bd,
5483                      tmp_bd,
5484                      le16toh(tx_start_bd->nbd),
5485                      le16toh(tx_start_bd->vlan_or_ethertype),
5486                      tx_start_bd->bd_flags.as_bitfield,
5487                      (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5488            } else if (i == 1) {
5489                if (pbd_e1x) {
5490                    BLOGD(sc, DBG_TX,
5491                          "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5492                          "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5493                          "tcp_seq=%u total_hlen_w=%u\n",
5494                          pbd_e1x,
5495                          tmp_bd,
5496                          pbd_e1x->global_data,
5497                          pbd_e1x->ip_hlen_w,
5498                          pbd_e1x->ip_id,
5499                          pbd_e1x->lso_mss,
5500                          pbd_e1x->tcp_flags,
5501                          pbd_e1x->tcp_pseudo_csum,
5502                          pbd_e1x->tcp_send_seq,
5503                          le16toh(pbd_e1x->total_hlen_w));
5504                } else { /* if (pbd_e2) */
5505                    BLOGD(sc, DBG_TX,
5506                          "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5507                          "src=%02x:%02x:%02x parsing_data=0x%x\n",
5508                          pbd_e2,
5509                          tmp_bd,
5510                          pbd_e2->data.mac_addr.dst_hi,
5511                          pbd_e2->data.mac_addr.dst_mid,
5512                          pbd_e2->data.mac_addr.dst_lo,
5513                          pbd_e2->data.mac_addr.src_hi,
5514                          pbd_e2->data.mac_addr.src_mid,
5515                          pbd_e2->data.mac_addr.src_lo,
5516                          pbd_e2->parsing_data);
5517                }
5518            }
5519
5520            if (i != 1) { /* skip parse db as it doesn't hold data */
5521                tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5522                BLOGD(sc, DBG_TX,
5523                      "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5524                      tx_data_bd,
5525                      tmp_bd,
5526                      le16toh(tx_data_bd->nbytes),
5527                      le32toh(tx_data_bd->addr_hi),
5528                      le32toh(tx_data_bd->addr_lo));
5529            }
5530
5531            tmp_bd = TX_BD_NEXT(tmp_bd);
5532        }
5533    }
5534
5535    BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5536
5537    /* update TX BD producer index value for next TX */
5538    bd_prod = TX_BD_NEXT(bd_prod);
5539
5540    /*
5541     * If the chain of tx_bd's describing this frame is adjacent to or spans
5542     * an eth_tx_next_bd element then we need to increment the nbds value.
5543     */
5544    if (TX_BD_IDX(bd_prod) < nbds) {
5545        nbds++;
5546    }
5547
5548    /* don't allow reordering of writes for nbd and packets */
5549    mb();
5550
5551    fp->tx_db.data.prod += nbds;
5552
5553    /* producer points to the next free tx_bd at this point */
5554    fp->tx_pkt_prod++;
5555    fp->tx_bd_prod = bd_prod;
5556
5557    DOORBELL(sc, fp->index, fp->tx_db.raw);
5558
5559    fp->eth_q_stats.tx_pkts++;
5560
5561    /* Prevent speculative reads from getting ahead of the status block. */
5562    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5563                      0, 0, BUS_SPACE_BARRIER_READ);
5564
5565    /* Prevent speculative reads from getting ahead of the doorbell. */
5566    bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5567                      0, 0, BUS_SPACE_BARRIER_READ);
5568
5569    return (0);
5570}
5571
5572static void
5573bxe_tx_start_locked(struct bxe_softc *sc,
5574                    if_t ifp,
5575                    struct bxe_fastpath *fp)
5576{
5577    struct mbuf *m = NULL;
5578    int tx_count = 0;
5579    uint16_t tx_bd_avail;
5580
5581    BXE_FP_TX_LOCK_ASSERT(fp);
5582
5583    /* keep adding entries while there are frames to send */
5584    while (!if_sendq_empty(ifp)) {
5585
5586        /*
5587         * check for any frames to send
5588         * dequeue can still be NULL even if queue is not empty
5589         */
5590        m = if_dequeue(ifp);
5591        if (__predict_false(m == NULL)) {
5592            break;
5593        }
5594
5595        /* the mbuf now belongs to us */
5596        fp->eth_q_stats.mbuf_alloc_tx++;
5597
5598        /*
5599         * Put the frame into the transmit ring. If we don't have room,
5600         * place the mbuf back at the head of the TX queue, set the
5601         * OACTIVE flag, and wait for the NIC to drain the chain.
5602         */
5603        if (__predict_false(bxe_tx_encap(fp, &m))) {
5604            fp->eth_q_stats.tx_encap_failures++;
5605            if (m != NULL) {
5606                /* mark the TX queue as full and return the frame */
5607                if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5608		if_sendq_prepend(ifp, m);
5609                fp->eth_q_stats.mbuf_alloc_tx--;
5610                fp->eth_q_stats.tx_queue_xoff++;
5611            }
5612
5613            /* stop looking for more work */
5614            break;
5615        }
5616
5617        /* the frame was enqueued successfully */
5618        tx_count++;
5619
5620        /* send a copy of the frame to any BPF listeners. */
5621        if_etherbpfmtap(ifp, m);
5622
5623        tx_bd_avail = bxe_tx_avail(sc, fp);
5624
5625        /* handle any completions if we're running low */
5626        if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5627            /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5628            bxe_txeof(sc, fp);
5629            if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5630                break;
5631            }
5632        }
5633    }
5634
5635    /* all TX packets were dequeued and/or the tx ring is full */
5636    if (tx_count > 0) {
5637        /* reset the TX watchdog timeout timer */
5638        fp->watchdog_timer = BXE_TX_TIMEOUT;
5639    }
5640}
5641
5642/* Legacy (non-RSS) dispatch routine */
5643static void
5644bxe_tx_start(if_t ifp)
5645{
5646    struct bxe_softc *sc;
5647    struct bxe_fastpath *fp;
5648
5649    sc = if_getsoftc(ifp);
5650
5651    if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5652        BLOGW(sc, "Interface not running, ignoring transmit request\n");
5653        return;
5654    }
5655
5656    if (!sc->link_vars.link_up) {
5657        BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5658        return;
5659    }
5660
5661    fp = &sc->fp[0];
5662
5663    if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5664        fp->eth_q_stats.tx_queue_full_return++;
5665        return;
5666    }
5667
5668    BXE_FP_TX_LOCK(fp);
5669    bxe_tx_start_locked(sc, ifp, fp);
5670    BXE_FP_TX_UNLOCK(fp);
5671}
5672
5673#if __FreeBSD_version >= 901504
5674
5675static int
5676bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5677                       if_t                ifp,
5678                       struct bxe_fastpath *fp,
5679                       struct mbuf         *m)
5680{
5681    struct buf_ring *tx_br = fp->tx_br;
5682    struct mbuf *next;
5683    int depth, rc, tx_count;
5684    uint16_t tx_bd_avail;
5685
5686    rc = tx_count = 0;
5687
5688    BXE_FP_TX_LOCK_ASSERT(fp);
5689
5690    if (sc->state != BXE_STATE_OPEN)  {
5691        fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5692        return ENETDOWN;
5693    }
5694
5695    if (!tx_br) {
5696        BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5697        return (EINVAL);
5698    }
5699
5700    if (m != NULL) {
5701        rc = drbr_enqueue(ifp, tx_br, m);
5702        if (rc != 0) {
5703            fp->eth_q_stats.tx_soft_errors++;
5704            goto bxe_tx_mq_start_locked_exit;
5705        }
5706    }
5707
5708    if (!sc->link_vars.link_up || !(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5709        fp->eth_q_stats.tx_request_link_down_failures++;
5710        goto bxe_tx_mq_start_locked_exit;
5711    }
5712
5713    /* fetch the depth of the driver queue */
5714    depth = drbr_inuse_drv(ifp, tx_br);
5715    if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5716        fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5717    }
5718
5719    /* keep adding entries while there are frames to send */
5720    while ((next = drbr_peek(ifp, tx_br)) != NULL) {
5721        /* handle any completions if we're running low */
5722        tx_bd_avail = bxe_tx_avail(sc, fp);
5723        if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5724            /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5725            bxe_txeof(sc, fp);
5726            tx_bd_avail = bxe_tx_avail(sc, fp);
5727            if (tx_bd_avail < (BXE_TSO_MAX_SEGMENTS + 1)) {
5728                fp->eth_q_stats.bd_avail_too_less_failures++;
5729                m_freem(next);
5730                drbr_advance(ifp, tx_br);
5731                rc = ENOBUFS;
5732                break;
5733            }
5734        }
5735
5736        /* the mbuf now belongs to us */
5737        fp->eth_q_stats.mbuf_alloc_tx++;
5738
5739        /*
5740         * Put the frame into the transmit ring. If we don't have room,
5741         * place the mbuf back at the head of the TX queue, set the
5742         * OACTIVE flag, and wait for the NIC to drain the chain.
5743         */
5744        rc = bxe_tx_encap(fp, &next);
5745        if (__predict_false(rc != 0)) {
5746            fp->eth_q_stats.tx_encap_failures++;
5747            if (next != NULL) {
5748                /* mark the TX queue as full and save the frame */
5749                if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5750                drbr_putback(ifp, tx_br, next);
5751                fp->eth_q_stats.mbuf_alloc_tx--;
5752                fp->eth_q_stats.tx_frames_deferred++;
5753            } else
5754                drbr_advance(ifp, tx_br);
5755
5756            /* stop looking for more work */
5757            break;
5758        }
5759
5760        /* the transmit frame was enqueued successfully */
5761        tx_count++;
5762
5763        /* send a copy of the frame to any BPF listeners */
5764	if_etherbpfmtap(ifp, next);
5765
5766        drbr_advance(ifp, tx_br);
5767    }
5768
5769    /* all TX packets were dequeued and/or the tx ring is full */
5770    if (tx_count > 0) {
5771        /* reset the TX watchdog timeout timer */
5772        fp->watchdog_timer = BXE_TX_TIMEOUT;
5773    }
5774
5775bxe_tx_mq_start_locked_exit:
5776    /* If we didn't drain the drbr, enqueue a task in the future to do it. */
5777    if (!drbr_empty(ifp, tx_br)) {
5778        fp->eth_q_stats.tx_mq_not_empty++;
5779        taskqueue_enqueue_timeout(fp->tq, &fp->tx_timeout_task, 1);
5780    }
5781
5782    return (rc);
5783}
5784
5785static void
5786bxe_tx_mq_start_deferred(void *arg,
5787                         int pending)
5788{
5789    struct bxe_fastpath *fp = (struct bxe_fastpath *)arg;
5790    struct bxe_softc *sc = fp->sc;
5791    if_t ifp = sc->ifp;
5792
5793    BXE_FP_TX_LOCK(fp);
5794    bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
5795    BXE_FP_TX_UNLOCK(fp);
5796}
5797
5798/* Multiqueue (TSS) dispatch routine. */
5799static int
5800bxe_tx_mq_start(struct ifnet *ifp,
5801                struct mbuf  *m)
5802{
5803    struct bxe_softc *sc = if_getsoftc(ifp);
5804    struct bxe_fastpath *fp;
5805    int fp_index, rc;
5806
5807    fp_index = 0; /* default is the first queue */
5808
5809    /* check if flowid is set */
5810
5811    if (BXE_VALID_FLOWID(m))
5812        fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5813
5814    fp = &sc->fp[fp_index];
5815
5816    if (sc->state != BXE_STATE_OPEN)  {
5817        fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5818        return ENETDOWN;
5819    }
5820
5821    if (BXE_FP_TX_TRYLOCK(fp)) {
5822        rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5823        BXE_FP_TX_UNLOCK(fp);
5824    } else {
5825        rc = drbr_enqueue(ifp, fp->tx_br, m);
5826        taskqueue_enqueue(fp->tq, &fp->tx_task);
5827    }
5828
5829    return (rc);
5830}
5831
5832static void
5833bxe_mq_flush(struct ifnet *ifp)
5834{
5835    struct bxe_softc *sc = if_getsoftc(ifp);
5836    struct bxe_fastpath *fp;
5837    struct mbuf *m;
5838    int i;
5839
5840    for (i = 0; i < sc->num_queues; i++) {
5841        fp = &sc->fp[i];
5842
5843        if (fp->state != BXE_FP_STATE_IRQ) {
5844            BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5845                  fp->index, fp->state);
5846            continue;
5847        }
5848
5849        if (fp->tx_br != NULL) {
5850            BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5851            BXE_FP_TX_LOCK(fp);
5852            while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5853                m_freem(m);
5854            }
5855            BXE_FP_TX_UNLOCK(fp);
5856        }
5857    }
5858
5859    if_qflush(ifp);
5860}
5861
5862#endif /* FreeBSD_version >= 901504 */
5863
5864static uint16_t
5865bxe_cid_ilt_lines(struct bxe_softc *sc)
5866{
5867    if (IS_SRIOV(sc)) {
5868        return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5869    }
5870    return (L2_ILT_LINES(sc));
5871}
5872
5873static void
5874bxe_ilt_set_info(struct bxe_softc *sc)
5875{
5876    struct ilt_client_info *ilt_client;
5877    struct ecore_ilt *ilt = sc->ilt;
5878    uint16_t line = 0;
5879
5880    ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5881    BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5882
5883    /* CDU */
5884    ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5885    ilt_client->client_num = ILT_CLIENT_CDU;
5886    ilt_client->page_size = CDU_ILT_PAGE_SZ;
5887    ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5888    ilt_client->start = line;
5889    line += bxe_cid_ilt_lines(sc);
5890
5891    if (CNIC_SUPPORT(sc)) {
5892        line += CNIC_ILT_LINES;
5893    }
5894
5895    ilt_client->end = (line - 1);
5896
5897    BLOGD(sc, DBG_LOAD,
5898          "ilt client[CDU]: start %d, end %d, "
5899          "psz 0x%x, flags 0x%x, hw psz %d\n",
5900          ilt_client->start, ilt_client->end,
5901          ilt_client->page_size,
5902          ilt_client->flags,
5903          ilog2(ilt_client->page_size >> 12));
5904
5905    /* QM */
5906    if (QM_INIT(sc->qm_cid_count)) {
5907        ilt_client = &ilt->clients[ILT_CLIENT_QM];
5908        ilt_client->client_num = ILT_CLIENT_QM;
5909        ilt_client->page_size = QM_ILT_PAGE_SZ;
5910        ilt_client->flags = 0;
5911        ilt_client->start = line;
5912
5913        /* 4 bytes for each cid */
5914        line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5915                             QM_ILT_PAGE_SZ);
5916
5917        ilt_client->end = (line - 1);
5918
5919        BLOGD(sc, DBG_LOAD,
5920              "ilt client[QM]: start %d, end %d, "
5921              "psz 0x%x, flags 0x%x, hw psz %d\n",
5922              ilt_client->start, ilt_client->end,
5923              ilt_client->page_size, ilt_client->flags,
5924              ilog2(ilt_client->page_size >> 12));
5925    }
5926
5927    if (CNIC_SUPPORT(sc)) {
5928        /* SRC */
5929        ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5930        ilt_client->client_num = ILT_CLIENT_SRC;
5931        ilt_client->page_size = SRC_ILT_PAGE_SZ;
5932        ilt_client->flags = 0;
5933        ilt_client->start = line;
5934        line += SRC_ILT_LINES;
5935        ilt_client->end = (line - 1);
5936
5937        BLOGD(sc, DBG_LOAD,
5938              "ilt client[SRC]: start %d, end %d, "
5939              "psz 0x%x, flags 0x%x, hw psz %d\n",
5940              ilt_client->start, ilt_client->end,
5941              ilt_client->page_size, ilt_client->flags,
5942              ilog2(ilt_client->page_size >> 12));
5943
5944        /* TM */
5945        ilt_client = &ilt->clients[ILT_CLIENT_TM];
5946        ilt_client->client_num = ILT_CLIENT_TM;
5947        ilt_client->page_size = TM_ILT_PAGE_SZ;
5948        ilt_client->flags = 0;
5949        ilt_client->start = line;
5950        line += TM_ILT_LINES;
5951        ilt_client->end = (line - 1);
5952
5953        BLOGD(sc, DBG_LOAD,
5954              "ilt client[TM]: start %d, end %d, "
5955              "psz 0x%x, flags 0x%x, hw psz %d\n",
5956              ilt_client->start, ilt_client->end,
5957              ilt_client->page_size, ilt_client->flags,
5958              ilog2(ilt_client->page_size >> 12));
5959    }
5960
5961    KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5962}
5963
5964static void
5965bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5966{
5967    int i;
5968    uint32_t rx_buf_size;
5969
5970    rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5971
5972    for (i = 0; i < sc->num_queues; i++) {
5973        if(rx_buf_size <= MCLBYTES){
5974            sc->fp[i].rx_buf_size = rx_buf_size;
5975            sc->fp[i].mbuf_alloc_size = MCLBYTES;
5976        }else if (rx_buf_size <= MJUMPAGESIZE){
5977            sc->fp[i].rx_buf_size = rx_buf_size;
5978            sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5979        }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5980            sc->fp[i].rx_buf_size = MCLBYTES;
5981            sc->fp[i].mbuf_alloc_size = MCLBYTES;
5982        }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5983            sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5984            sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5985        }else {
5986            sc->fp[i].rx_buf_size = MCLBYTES;
5987            sc->fp[i].mbuf_alloc_size = MCLBYTES;
5988        }
5989    }
5990}
5991
5992static int
5993bxe_alloc_ilt_mem(struct bxe_softc *sc)
5994{
5995    int rc = 0;
5996
5997    if ((sc->ilt =
5998         (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
5999                                    M_BXE_ILT,
6000                                    (M_NOWAIT | M_ZERO))) == NULL) {
6001        rc = 1;
6002    }
6003
6004    return (rc);
6005}
6006
6007static int
6008bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
6009{
6010    int rc = 0;
6011
6012    if ((sc->ilt->lines =
6013         (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6014                                    M_BXE_ILT,
6015                                    (M_NOWAIT | M_ZERO))) == NULL) {
6016        rc = 1;
6017    }
6018
6019    return (rc);
6020}
6021
6022static void
6023bxe_free_ilt_mem(struct bxe_softc *sc)
6024{
6025    if (sc->ilt != NULL) {
6026        free(sc->ilt, M_BXE_ILT);
6027        sc->ilt = NULL;
6028    }
6029}
6030
6031static void
6032bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6033{
6034    if (sc->ilt->lines != NULL) {
6035        free(sc->ilt->lines, M_BXE_ILT);
6036        sc->ilt->lines = NULL;
6037    }
6038}
6039
6040static void
6041bxe_free_mem(struct bxe_softc *sc)
6042{
6043    int i;
6044
6045    for (i = 0; i < L2_ILT_LINES(sc); i++) {
6046        bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6047        sc->context[i].vcxt = NULL;
6048        sc->context[i].size = 0;
6049    }
6050
6051    ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6052
6053    bxe_free_ilt_lines_mem(sc);
6054
6055}
6056
6057static int
6058bxe_alloc_mem(struct bxe_softc *sc)
6059{
6060
6061    int context_size;
6062    int allocated;
6063    int i;
6064
6065    /*
6066     * Allocate memory for CDU context:
6067     * This memory is allocated separately and not in the generic ILT
6068     * functions because CDU differs in few aspects:
6069     * 1. There can be multiple entities allocating memory for context -
6070     * regular L2, CNIC, and SRIOV drivers. Each separately controls
6071     * its own ILT lines.
6072     * 2. Since CDU page-size is not a single 4KB page (which is the case
6073     * for the other ILT clients), to be efficient we want to support
6074     * allocation of sub-page-size in the last entry.
6075     * 3. Context pointers are used by the driver to pass to FW / update
6076     * the context (for the other ILT clients the pointers are used just to
6077     * free the memory during unload).
6078     */
6079    context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6080    for (i = 0, allocated = 0; allocated < context_size; i++) {
6081        sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6082                                  (context_size - allocated));
6083
6084        if (bxe_dma_alloc(sc, sc->context[i].size,
6085                          &sc->context[i].vcxt_dma,
6086                          "cdu context") != 0) {
6087            bxe_free_mem(sc);
6088            return (-1);
6089        }
6090
6091        sc->context[i].vcxt =
6092            (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6093
6094        allocated += sc->context[i].size;
6095    }
6096
6097    bxe_alloc_ilt_lines_mem(sc);
6098
6099    BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6100          sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6101    {
6102        for (i = 0; i < 4; i++) {
6103            BLOGD(sc, DBG_LOAD,
6104                  "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6105                  i,
6106                  sc->ilt->clients[i].page_size,
6107                  sc->ilt->clients[i].start,
6108                  sc->ilt->clients[i].end,
6109                  sc->ilt->clients[i].client_num,
6110                  sc->ilt->clients[i].flags);
6111        }
6112    }
6113    if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6114        BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6115        bxe_free_mem(sc);
6116        return (-1);
6117    }
6118
6119    return (0);
6120}
6121
6122static void
6123bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6124{
6125    struct bxe_softc *sc;
6126    int i;
6127
6128    sc = fp->sc;
6129
6130    if (fp->rx_mbuf_tag == NULL) {
6131        return;
6132    }
6133
6134    /* free all mbufs and unload all maps */
6135    for (i = 0; i < RX_BD_TOTAL; i++) {
6136        if (fp->rx_mbuf_chain[i].m_map != NULL) {
6137            bus_dmamap_sync(fp->rx_mbuf_tag,
6138                            fp->rx_mbuf_chain[i].m_map,
6139                            BUS_DMASYNC_POSTREAD);
6140            bus_dmamap_unload(fp->rx_mbuf_tag,
6141                              fp->rx_mbuf_chain[i].m_map);
6142        }
6143
6144        if (fp->rx_mbuf_chain[i].m != NULL) {
6145            m_freem(fp->rx_mbuf_chain[i].m);
6146            fp->rx_mbuf_chain[i].m = NULL;
6147            fp->eth_q_stats.mbuf_alloc_rx--;
6148        }
6149    }
6150}
6151
6152static void
6153bxe_free_tpa_pool(struct bxe_fastpath *fp)
6154{
6155    struct bxe_softc *sc;
6156    int i, max_agg_queues;
6157
6158    sc = fp->sc;
6159
6160    if (fp->rx_mbuf_tag == NULL) {
6161        return;
6162    }
6163
6164    max_agg_queues = MAX_AGG_QS(sc);
6165
6166    /* release all mbufs and unload all DMA maps in the TPA pool */
6167    for (i = 0; i < max_agg_queues; i++) {
6168        if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6169            bus_dmamap_sync(fp->rx_mbuf_tag,
6170                            fp->rx_tpa_info[i].bd.m_map,
6171                            BUS_DMASYNC_POSTREAD);
6172            bus_dmamap_unload(fp->rx_mbuf_tag,
6173                              fp->rx_tpa_info[i].bd.m_map);
6174        }
6175
6176        if (fp->rx_tpa_info[i].bd.m != NULL) {
6177            m_freem(fp->rx_tpa_info[i].bd.m);
6178            fp->rx_tpa_info[i].bd.m = NULL;
6179            fp->eth_q_stats.mbuf_alloc_tpa--;
6180        }
6181    }
6182}
6183
6184static void
6185bxe_free_sge_chain(struct bxe_fastpath *fp)
6186{
6187    struct bxe_softc *sc;
6188    int i;
6189
6190    sc = fp->sc;
6191
6192    if (fp->rx_sge_mbuf_tag == NULL) {
6193        return;
6194    }
6195
6196    /* rree all mbufs and unload all maps */
6197    for (i = 0; i < RX_SGE_TOTAL; i++) {
6198        if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6199            bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6200                            fp->rx_sge_mbuf_chain[i].m_map,
6201                            BUS_DMASYNC_POSTREAD);
6202            bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6203                              fp->rx_sge_mbuf_chain[i].m_map);
6204        }
6205
6206        if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6207            m_freem(fp->rx_sge_mbuf_chain[i].m);
6208            fp->rx_sge_mbuf_chain[i].m = NULL;
6209            fp->eth_q_stats.mbuf_alloc_sge--;
6210        }
6211    }
6212}
6213
6214static void
6215bxe_free_fp_buffers(struct bxe_softc *sc)
6216{
6217    struct bxe_fastpath *fp;
6218    int i;
6219
6220    for (i = 0; i < sc->num_queues; i++) {
6221        fp = &sc->fp[i];
6222
6223#if __FreeBSD_version >= 901504
6224        if (fp->tx_br != NULL) {
6225            /* just in case bxe_mq_flush() wasn't called */
6226            if (mtx_initialized(&fp->tx_mtx)) {
6227                struct mbuf *m;
6228
6229                BXE_FP_TX_LOCK(fp);
6230                while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6231                    m_freem(m);
6232                BXE_FP_TX_UNLOCK(fp);
6233            }
6234        }
6235#endif
6236
6237        /* free all RX buffers */
6238        bxe_free_rx_bd_chain(fp);
6239        bxe_free_tpa_pool(fp);
6240        bxe_free_sge_chain(fp);
6241
6242        if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6243            BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6244                  fp->eth_q_stats.mbuf_alloc_rx);
6245        }
6246
6247        if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6248            BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6249                  fp->eth_q_stats.mbuf_alloc_sge);
6250        }
6251
6252        if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6253            BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6254                  fp->eth_q_stats.mbuf_alloc_tpa);
6255        }
6256
6257        if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6258            BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6259                  fp->eth_q_stats.mbuf_alloc_tx);
6260        }
6261
6262        /* XXX verify all mbufs were reclaimed */
6263    }
6264}
6265
6266static int
6267bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6268                     uint16_t            prev_index,
6269                     uint16_t            index)
6270{
6271    struct bxe_sw_rx_bd *rx_buf;
6272    struct eth_rx_bd *rx_bd;
6273    bus_dma_segment_t segs[1];
6274    bus_dmamap_t map;
6275    struct mbuf *m;
6276    int nsegs, rc;
6277
6278    rc = 0;
6279
6280    /* allocate the new RX BD mbuf */
6281    m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6282    if (__predict_false(m == NULL)) {
6283        fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6284        return (ENOBUFS);
6285    }
6286
6287    fp->eth_q_stats.mbuf_alloc_rx++;
6288
6289    /* initialize the mbuf buffer length */
6290    m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6291
6292    /* map the mbuf into non-paged pool */
6293    rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6294                                 fp->rx_mbuf_spare_map,
6295                                 m, segs, &nsegs, BUS_DMA_NOWAIT);
6296    if (__predict_false(rc != 0)) {
6297        fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6298        m_freem(m);
6299        fp->eth_q_stats.mbuf_alloc_rx--;
6300        return (rc);
6301    }
6302
6303    /* all mbufs must map to a single segment */
6304    KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6305
6306    /* release any existing RX BD mbuf mappings */
6307
6308    if (prev_index != index) {
6309        rx_buf = &fp->rx_mbuf_chain[prev_index];
6310
6311        if (rx_buf->m_map != NULL) {
6312            bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6313                            BUS_DMASYNC_POSTREAD);
6314            bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6315        }
6316
6317        /*
6318         * We only get here from bxe_rxeof() when the maximum number
6319         * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6320         * holds the mbuf in the prev_index so it's OK to NULL it out
6321         * here without concern of a memory leak.
6322         */
6323        fp->rx_mbuf_chain[prev_index].m = NULL;
6324    }
6325
6326    rx_buf = &fp->rx_mbuf_chain[index];
6327
6328    if (rx_buf->m_map != NULL) {
6329        bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6330                        BUS_DMASYNC_POSTREAD);
6331        bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6332    }
6333
6334    /* save the mbuf and mapping info for a future packet */
6335    map = (prev_index != index) ?
6336              fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6337    rx_buf->m_map = fp->rx_mbuf_spare_map;
6338    fp->rx_mbuf_spare_map = map;
6339    bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6340                    BUS_DMASYNC_PREREAD);
6341    rx_buf->m = m;
6342
6343    rx_bd = &fp->rx_chain[index];
6344    rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6345    rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6346
6347    return (rc);
6348}
6349
6350static int
6351bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6352                      int                 queue)
6353{
6354    struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6355    bus_dma_segment_t segs[1];
6356    bus_dmamap_t map;
6357    struct mbuf *m;
6358    int nsegs;
6359    int rc = 0;
6360
6361    /* allocate the new TPA mbuf */
6362    m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6363    if (__predict_false(m == NULL)) {
6364        fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6365        return (ENOBUFS);
6366    }
6367
6368    fp->eth_q_stats.mbuf_alloc_tpa++;
6369
6370    /* initialize the mbuf buffer length */
6371    m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6372
6373    /* map the mbuf into non-paged pool */
6374    rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6375                                 fp->rx_tpa_info_mbuf_spare_map,
6376                                 m, segs, &nsegs, BUS_DMA_NOWAIT);
6377    if (__predict_false(rc != 0)) {
6378        fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6379        m_free(m);
6380        fp->eth_q_stats.mbuf_alloc_tpa--;
6381        return (rc);
6382    }
6383
6384    /* all mbufs must map to a single segment */
6385    KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6386
6387    /* release any existing TPA mbuf mapping */
6388    if (tpa_info->bd.m_map != NULL) {
6389        bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6390                        BUS_DMASYNC_POSTREAD);
6391        bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6392    }
6393
6394    /* save the mbuf and mapping info for the TPA mbuf */
6395    map = tpa_info->bd.m_map;
6396    tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6397    fp->rx_tpa_info_mbuf_spare_map = map;
6398    bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6399                    BUS_DMASYNC_PREREAD);
6400    tpa_info->bd.m = m;
6401    tpa_info->seg = segs[0];
6402
6403    return (rc);
6404}
6405
6406/*
6407 * Allocate an mbuf and assign it to the receive scatter gather chain. The
6408 * caller must take care to save a copy of the existing mbuf in the SG mbuf
6409 * chain.
6410 */
6411static int
6412bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6413                      uint16_t            index)
6414{
6415    struct bxe_sw_rx_bd *sge_buf;
6416    struct eth_rx_sge *sge;
6417    bus_dma_segment_t segs[1];
6418    bus_dmamap_t map;
6419    struct mbuf *m;
6420    int nsegs;
6421    int rc = 0;
6422
6423    /* allocate a new SGE mbuf */
6424    m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6425    if (__predict_false(m == NULL)) {
6426        fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6427        return (ENOMEM);
6428    }
6429
6430    fp->eth_q_stats.mbuf_alloc_sge++;
6431
6432    /* initialize the mbuf buffer length */
6433    m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6434
6435    /* map the SGE mbuf into non-paged pool */
6436    rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6437                                 fp->rx_sge_mbuf_spare_map,
6438                                 m, segs, &nsegs, BUS_DMA_NOWAIT);
6439    if (__predict_false(rc != 0)) {
6440        fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6441        m_freem(m);
6442        fp->eth_q_stats.mbuf_alloc_sge--;
6443        return (rc);
6444    }
6445
6446    /* all mbufs must map to a single segment */
6447    KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6448
6449    sge_buf = &fp->rx_sge_mbuf_chain[index];
6450
6451    /* release any existing SGE mbuf mapping */
6452    if (sge_buf->m_map != NULL) {
6453        bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6454                        BUS_DMASYNC_POSTREAD);
6455        bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6456    }
6457
6458    /* save the mbuf and mapping info for a future packet */
6459    map = sge_buf->m_map;
6460    sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6461    fp->rx_sge_mbuf_spare_map = map;
6462    bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6463                    BUS_DMASYNC_PREREAD);
6464    sge_buf->m = m;
6465
6466    sge = &fp->rx_sge_chain[index];
6467    sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6468    sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6469
6470    return (rc);
6471}
6472
6473static __noinline int
6474bxe_alloc_fp_buffers(struct bxe_softc *sc)
6475{
6476    struct bxe_fastpath *fp;
6477    int i, j, rc = 0;
6478    int ring_prod, cqe_ring_prod;
6479    int max_agg_queues;
6480
6481    for (i = 0; i < sc->num_queues; i++) {
6482        fp = &sc->fp[i];
6483
6484        ring_prod = cqe_ring_prod = 0;
6485        fp->rx_bd_cons = 0;
6486        fp->rx_cq_cons = 0;
6487
6488        /* allocate buffers for the RX BDs in RX BD chain */
6489        for (j = 0; j < sc->max_rx_bufs; j++) {
6490            rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6491            if (rc != 0) {
6492                BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6493                      i, rc);
6494                goto bxe_alloc_fp_buffers_error;
6495            }
6496
6497            ring_prod     = RX_BD_NEXT(ring_prod);
6498            cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6499        }
6500
6501        fp->rx_bd_prod = ring_prod;
6502        fp->rx_cq_prod = cqe_ring_prod;
6503        fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6504
6505        max_agg_queues = MAX_AGG_QS(sc);
6506
6507        fp->tpa_enable = TRUE;
6508
6509        /* fill the TPA pool */
6510        for (j = 0; j < max_agg_queues; j++) {
6511            rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6512            if (rc != 0) {
6513                BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6514                          i, j);
6515                fp->tpa_enable = FALSE;
6516                goto bxe_alloc_fp_buffers_error;
6517            }
6518
6519            fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6520        }
6521
6522        if (fp->tpa_enable) {
6523            /* fill the RX SGE chain */
6524            ring_prod = 0;
6525            for (j = 0; j < RX_SGE_USABLE; j++) {
6526                rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6527                if (rc != 0) {
6528                    BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6529                              i, ring_prod);
6530                    fp->tpa_enable = FALSE;
6531                    ring_prod = 0;
6532                    goto bxe_alloc_fp_buffers_error;
6533                }
6534
6535                ring_prod = RX_SGE_NEXT(ring_prod);
6536            }
6537
6538            fp->rx_sge_prod = ring_prod;
6539        }
6540    }
6541
6542    return (0);
6543
6544bxe_alloc_fp_buffers_error:
6545
6546    /* unwind what was already allocated */
6547    bxe_free_rx_bd_chain(fp);
6548    bxe_free_tpa_pool(fp);
6549    bxe_free_sge_chain(fp);
6550
6551    return (ENOBUFS);
6552}
6553
6554static void
6555bxe_free_fw_stats_mem(struct bxe_softc *sc)
6556{
6557    bxe_dma_free(sc, &sc->fw_stats_dma);
6558
6559    sc->fw_stats_num = 0;
6560
6561    sc->fw_stats_req_size = 0;
6562    sc->fw_stats_req = NULL;
6563    sc->fw_stats_req_mapping = 0;
6564
6565    sc->fw_stats_data_size = 0;
6566    sc->fw_stats_data = NULL;
6567    sc->fw_stats_data_mapping = 0;
6568}
6569
6570static int
6571bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6572{
6573    uint8_t num_queue_stats;
6574    int num_groups;
6575
6576    /* number of queues for statistics is number of eth queues */
6577    num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6578
6579    /*
6580     * Total number of FW statistics requests =
6581     *   1 for port stats + 1 for PF stats + num of queues
6582     */
6583    sc->fw_stats_num = (2 + num_queue_stats);
6584
6585    /*
6586     * Request is built from stats_query_header and an array of
6587     * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6588     * rules. The real number or requests is configured in the
6589     * stats_query_header.
6590     */
6591    num_groups =
6592        ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6593         ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6594
6595    BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6596          sc->fw_stats_num, num_groups);
6597
6598    sc->fw_stats_req_size =
6599        (sizeof(struct stats_query_header) +
6600         (num_groups * sizeof(struct stats_query_cmd_group)));
6601
6602    /*
6603     * Data for statistics requests + stats_counter.
6604     * stats_counter holds per-STORM counters that are incremented when
6605     * STORM has finished with the current request. Memory for FCoE
6606     * offloaded statistics are counted anyway, even if they will not be sent.
6607     * VF stats are not accounted for here as the data of VF stats is stored
6608     * in memory allocated by the VF, not here.
6609     */
6610    sc->fw_stats_data_size =
6611        (sizeof(struct stats_counter) +
6612         sizeof(struct per_port_stats) +
6613         sizeof(struct per_pf_stats) +
6614         /* sizeof(struct fcoe_statistics_params) + */
6615         (sizeof(struct per_queue_stats) * num_queue_stats));
6616
6617    if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6618                      &sc->fw_stats_dma, "fw stats") != 0) {
6619        bxe_free_fw_stats_mem(sc);
6620        return (-1);
6621    }
6622
6623    /* set up the shortcuts */
6624
6625    sc->fw_stats_req =
6626        (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6627    sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6628
6629    sc->fw_stats_data =
6630        (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6631                                     sc->fw_stats_req_size);
6632    sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6633                                 sc->fw_stats_req_size);
6634
6635    BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6636          (uintmax_t)sc->fw_stats_req_mapping);
6637
6638    BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6639          (uintmax_t)sc->fw_stats_data_mapping);
6640
6641    return (0);
6642}
6643
6644/*
6645 * Bits map:
6646 * 0-7  - Engine0 load counter.
6647 * 8-15 - Engine1 load counter.
6648 * 16   - Engine0 RESET_IN_PROGRESS bit.
6649 * 17   - Engine1 RESET_IN_PROGRESS bit.
6650 * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6651 *        function on the engine
6652 * 19   - Engine1 ONE_IS_LOADED.
6653 * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6654 *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6655 *        for just the one belonging to its engine).
6656 */
6657#define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6658#define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6659#define BXE_PATH0_LOAD_CNT_SHIFT  0
6660#define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6661#define BXE_PATH1_LOAD_CNT_SHIFT  8
6662#define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6663#define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6664#define BXE_GLOBAL_RESET_BIT      0x00040000
6665
6666/* set the GLOBAL_RESET bit, should be run under rtnl lock */
6667static void
6668bxe_set_reset_global(struct bxe_softc *sc)
6669{
6670    uint32_t val;
6671    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6672    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6673    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6674    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6675}
6676
6677/* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6678static void
6679bxe_clear_reset_global(struct bxe_softc *sc)
6680{
6681    uint32_t val;
6682    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6683    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6684    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6685    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6686}
6687
6688/* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6689static uint8_t
6690bxe_reset_is_global(struct bxe_softc *sc)
6691{
6692    uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6693    BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6694    return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6695}
6696
6697/* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6698static void
6699bxe_set_reset_done(struct bxe_softc *sc)
6700{
6701    uint32_t val;
6702    uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6703                                 BXE_PATH0_RST_IN_PROG_BIT;
6704
6705    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6706
6707    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6708    /* Clear the bit */
6709    val &= ~bit;
6710    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6711
6712    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6713}
6714
6715/* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6716static void
6717bxe_set_reset_in_progress(struct bxe_softc *sc)
6718{
6719    uint32_t val;
6720    uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6721                                 BXE_PATH0_RST_IN_PROG_BIT;
6722
6723    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6724
6725    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6726    /* Set the bit */
6727    val |= bit;
6728    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6729
6730    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6731}
6732
6733/* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6734static uint8_t
6735bxe_reset_is_done(struct bxe_softc *sc,
6736                  int              engine)
6737{
6738    uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6739    uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6740                            BXE_PATH0_RST_IN_PROG_BIT;
6741
6742    /* return false if bit is set */
6743    return (val & bit) ? FALSE : TRUE;
6744}
6745
6746/* get the load status for an engine, should be run under rtnl lock */
6747static uint8_t
6748bxe_get_load_status(struct bxe_softc *sc,
6749                    int              engine)
6750{
6751    uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6752                             BXE_PATH0_LOAD_CNT_MASK;
6753    uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6754                              BXE_PATH0_LOAD_CNT_SHIFT;
6755    uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6756
6757    BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6758
6759    val = ((val & mask) >> shift);
6760
6761    BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6762
6763    return (val != 0);
6764}
6765
6766/* set pf load mark */
6767/* XXX needs to be under rtnl lock */
6768static void
6769bxe_set_pf_load(struct bxe_softc *sc)
6770{
6771    uint32_t val;
6772    uint32_t val1;
6773    uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6774                                  BXE_PATH0_LOAD_CNT_MASK;
6775    uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6776                                   BXE_PATH0_LOAD_CNT_SHIFT;
6777
6778    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6779
6780    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6781    BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6782
6783    /* get the current counter value */
6784    val1 = ((val & mask) >> shift);
6785
6786    /* set bit of this PF */
6787    val1 |= (1 << SC_ABS_FUNC(sc));
6788
6789    /* clear the old value */
6790    val &= ~mask;
6791
6792    /* set the new one */
6793    val |= ((val1 << shift) & mask);
6794
6795    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6796
6797    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6798}
6799
6800/* clear pf load mark */
6801/* XXX needs to be under rtnl lock */
6802static uint8_t
6803bxe_clear_pf_load(struct bxe_softc *sc)
6804{
6805    uint32_t val1, val;
6806    uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6807                                  BXE_PATH0_LOAD_CNT_MASK;
6808    uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6809                                   BXE_PATH0_LOAD_CNT_SHIFT;
6810
6811    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6812    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6813    BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6814
6815    /* get the current counter value */
6816    val1 = (val & mask) >> shift;
6817
6818    /* clear bit of that PF */
6819    val1 &= ~(1 << SC_ABS_FUNC(sc));
6820
6821    /* clear the old value */
6822    val &= ~mask;
6823
6824    /* set the new one */
6825    val |= ((val1 << shift) & mask);
6826
6827    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6828    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6829    return (val1 != 0);
6830}
6831
6832/* send load requrest to mcp and analyze response */
6833static int
6834bxe_nic_load_request(struct bxe_softc *sc,
6835                     uint32_t         *load_code)
6836{
6837    /* init fw_seq */
6838    sc->fw_seq =
6839        (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6840         DRV_MSG_SEQ_NUMBER_MASK);
6841
6842    BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6843
6844    /* get the current FW pulse sequence */
6845    sc->fw_drv_pulse_wr_seq =
6846        (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6847         DRV_PULSE_SEQ_MASK);
6848
6849    BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6850          sc->fw_drv_pulse_wr_seq);
6851
6852    /* load request */
6853    (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6854                                  DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6855
6856    /* if the MCP fails to respond we must abort */
6857    if (!(*load_code)) {
6858        BLOGE(sc, "MCP response failure!\n");
6859        return (-1);
6860    }
6861
6862    /* if MCP refused then must abort */
6863    if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6864        BLOGE(sc, "MCP refused load request\n");
6865        return (-1);
6866    }
6867
6868    return (0);
6869}
6870
6871/*
6872 * Check whether another PF has already loaded FW to chip. In virtualized
6873 * environments a pf from anoth VM may have already initialized the device
6874 * including loading FW.
6875 */
6876static int
6877bxe_nic_load_analyze_req(struct bxe_softc *sc,
6878                         uint32_t         load_code)
6879{
6880    uint32_t my_fw, loaded_fw;
6881
6882    /* is another pf loaded on this engine? */
6883    if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6884        (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6885        /* build my FW version dword */
6886        my_fw = (BCM_5710_FW_MAJOR_VERSION +
6887                 (BCM_5710_FW_MINOR_VERSION << 8 ) +
6888                 (BCM_5710_FW_REVISION_VERSION << 16) +
6889                 (BCM_5710_FW_ENGINEERING_VERSION << 24));
6890
6891        /* read loaded FW from chip */
6892        loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6893        BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6894              loaded_fw, my_fw);
6895
6896        /* abort nic load if version mismatch */
6897        if (my_fw != loaded_fw) {
6898            BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6899                  loaded_fw, my_fw);
6900            return (-1);
6901        }
6902    }
6903
6904    return (0);
6905}
6906
6907/* mark PMF if applicable */
6908static void
6909bxe_nic_load_pmf(struct bxe_softc *sc,
6910                 uint32_t         load_code)
6911{
6912    uint32_t ncsi_oem_data_addr;
6913
6914    if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6915        (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6916        (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6917        /*
6918         * Barrier here for ordering between the writing to sc->port.pmf here
6919         * and reading it from the periodic task.
6920         */
6921        sc->port.pmf = 1;
6922        mb();
6923    } else {
6924        sc->port.pmf = 0;
6925    }
6926
6927    BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6928
6929    /* XXX needed? */
6930    if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6931        if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6932            ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6933            if (ncsi_oem_data_addr) {
6934                REG_WR(sc,
6935                       (ncsi_oem_data_addr +
6936                        offsetof(struct glob_ncsi_oem_data, driver_version)),
6937                       0);
6938            }
6939        }
6940    }
6941}
6942
6943static void
6944bxe_read_mf_cfg(struct bxe_softc *sc)
6945{
6946    int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6947    int abs_func;
6948    int vn;
6949
6950    if (BXE_NOMCP(sc)) {
6951        return; /* what should be the default bvalue in this case */
6952    }
6953
6954    /*
6955     * The formula for computing the absolute function number is...
6956     * For 2 port configuration (4 functions per port):
6957     *   abs_func = 2 * vn + SC_PORT + SC_PATH
6958     * For 4 port configuration (2 functions per port):
6959     *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6960     */
6961    for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6962        abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6963        if (abs_func >= E1H_FUNC_MAX) {
6964            break;
6965        }
6966        sc->devinfo.mf_info.mf_config[vn] =
6967            MFCFG_RD(sc, func_mf_config[abs_func].config);
6968    }
6969
6970    if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6971        FUNC_MF_CFG_FUNC_DISABLED) {
6972        BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6973        sc->flags |= BXE_MF_FUNC_DIS;
6974    } else {
6975        BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6976        sc->flags &= ~BXE_MF_FUNC_DIS;
6977    }
6978}
6979
6980/* acquire split MCP access lock register */
6981static int bxe_acquire_alr(struct bxe_softc *sc)
6982{
6983    uint32_t j, val;
6984
6985    for (j = 0; j < 1000; j++) {
6986        val = (1UL << 31);
6987        REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6988        val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6989        if (val & (1L << 31))
6990            break;
6991
6992        DELAY(5000);
6993    }
6994
6995    if (!(val & (1L << 31))) {
6996        BLOGE(sc, "Cannot acquire MCP access lock register\n");
6997        return (-1);
6998    }
6999
7000    return (0);
7001}
7002
7003/* release split MCP access lock register */
7004static void bxe_release_alr(struct bxe_softc *sc)
7005{
7006    REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
7007}
7008
7009static void
7010bxe_fan_failure(struct bxe_softc *sc)
7011{
7012    int port = SC_PORT(sc);
7013    uint32_t ext_phy_config;
7014
7015    /* mark the failure */
7016    ext_phy_config =
7017        SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7018
7019    ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7020    ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7021    SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7022             ext_phy_config);
7023
7024    /* log the failure */
7025    BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7026              "the card to prevent permanent damage. "
7027              "Please contact OEM Support for assistance\n");
7028
7029    /* XXX */
7030#if 1
7031    bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7032#else
7033    /*
7034     * Schedule device reset (unload)
7035     * This is due to some boards consuming sufficient power when driver is
7036     * up to overheat if fan fails.
7037     */
7038    bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7039    schedule_delayed_work(&sc->sp_rtnl_task, 0);
7040#endif
7041}
7042
7043/* this function is called upon a link interrupt */
7044static void
7045bxe_link_attn(struct bxe_softc *sc)
7046{
7047    uint32_t pause_enabled = 0;
7048    struct host_port_stats *pstats;
7049    int cmng_fns;
7050    struct bxe_fastpath *fp;
7051    int i;
7052
7053    /* Make sure that we are synced with the current statistics */
7054    bxe_stats_handle(sc, STATS_EVENT_STOP);
7055    BLOGD(sc, DBG_LOAD, "link_vars phy_flags : %x\n", sc->link_vars.phy_flags);
7056    elink_link_update(&sc->link_params, &sc->link_vars);
7057
7058    if (sc->link_vars.link_up) {
7059
7060        /* dropless flow control */
7061        if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7062            pause_enabled = 0;
7063
7064            if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7065                pause_enabled = 1;
7066            }
7067
7068            REG_WR(sc,
7069                   (BAR_USTRORM_INTMEM +
7070                    USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7071                   pause_enabled);
7072        }
7073
7074        if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7075            pstats = BXE_SP(sc, port_stats);
7076            /* reset old mac stats */
7077            memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7078        }
7079
7080        if (sc->state == BXE_STATE_OPEN) {
7081            bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7082	    /* Restart tx when the link comes back. */
7083	    FOR_EACH_ETH_QUEUE(sc, i) {
7084		fp = &sc->fp[i];
7085		taskqueue_enqueue(fp->tq, &fp->tx_task);
7086	    }
7087        }
7088
7089    }
7090
7091    if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7092        cmng_fns = bxe_get_cmng_fns_mode(sc);
7093
7094        if (cmng_fns != CMNG_FNS_NONE) {
7095            bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7096            storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7097        } else {
7098            /* rate shaping and fairness are disabled */
7099            BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7100        }
7101    }
7102
7103    bxe_link_report_locked(sc);
7104
7105    if (IS_MF(sc)) {
7106        ; // XXX bxe_link_sync_notify(sc);
7107    }
7108}
7109
7110static void
7111bxe_attn_int_asserted(struct bxe_softc *sc,
7112                      uint32_t         asserted)
7113{
7114    int port = SC_PORT(sc);
7115    uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7116                               MISC_REG_AEU_MASK_ATTN_FUNC_0;
7117    uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7118                                        NIG_REG_MASK_INTERRUPT_PORT0;
7119    uint32_t aeu_mask;
7120    uint32_t nig_mask = 0;
7121    uint32_t reg_addr;
7122    uint32_t igu_acked;
7123    uint32_t cnt;
7124
7125    if (sc->attn_state & asserted) {
7126        BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7127    }
7128
7129    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7130
7131    aeu_mask = REG_RD(sc, aeu_addr);
7132
7133    BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7134          aeu_mask, asserted);
7135
7136    aeu_mask &= ~(asserted & 0x3ff);
7137
7138    BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7139
7140    REG_WR(sc, aeu_addr, aeu_mask);
7141
7142    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7143
7144    BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7145    sc->attn_state |= asserted;
7146    BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7147
7148    if (asserted & ATTN_HARD_WIRED_MASK) {
7149        if (asserted & ATTN_NIG_FOR_FUNC) {
7150
7151	    bxe_acquire_phy_lock(sc);
7152            /* save nig interrupt mask */
7153            nig_mask = REG_RD(sc, nig_int_mask_addr);
7154
7155            /* If nig_mask is not set, no need to call the update function */
7156            if (nig_mask) {
7157                REG_WR(sc, nig_int_mask_addr, 0);
7158
7159                bxe_link_attn(sc);
7160            }
7161
7162            /* handle unicore attn? */
7163        }
7164
7165        if (asserted & ATTN_SW_TIMER_4_FUNC) {
7166            BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7167        }
7168
7169        if (asserted & GPIO_2_FUNC) {
7170            BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7171        }
7172
7173        if (asserted & GPIO_3_FUNC) {
7174            BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7175        }
7176
7177        if (asserted & GPIO_4_FUNC) {
7178            BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7179        }
7180
7181        if (port == 0) {
7182            if (asserted & ATTN_GENERAL_ATTN_1) {
7183                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7184                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7185            }
7186            if (asserted & ATTN_GENERAL_ATTN_2) {
7187                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7188                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7189            }
7190            if (asserted & ATTN_GENERAL_ATTN_3) {
7191                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7192                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7193            }
7194        } else {
7195            if (asserted & ATTN_GENERAL_ATTN_4) {
7196                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7197                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7198            }
7199            if (asserted & ATTN_GENERAL_ATTN_5) {
7200                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7201                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7202            }
7203            if (asserted & ATTN_GENERAL_ATTN_6) {
7204                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7205                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7206            }
7207        }
7208    } /* hardwired */
7209
7210    if (sc->devinfo.int_block == INT_BLOCK_HC) {
7211        reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7212    } else {
7213        reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7214    }
7215
7216    BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7217          asserted,
7218          (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7219    REG_WR(sc, reg_addr, asserted);
7220
7221    /* now set back the mask */
7222    if (asserted & ATTN_NIG_FOR_FUNC) {
7223        /*
7224         * Verify that IGU ack through BAR was written before restoring
7225         * NIG mask. This loop should exit after 2-3 iterations max.
7226         */
7227        if (sc->devinfo.int_block != INT_BLOCK_HC) {
7228            cnt = 0;
7229
7230            do {
7231                igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7232            } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7233                     (++cnt < MAX_IGU_ATTN_ACK_TO));
7234
7235            if (!igu_acked) {
7236                BLOGE(sc, "Failed to verify IGU ack on time\n");
7237            }
7238
7239            mb();
7240        }
7241
7242        REG_WR(sc, nig_int_mask_addr, nig_mask);
7243
7244	bxe_release_phy_lock(sc);
7245    }
7246}
7247
7248static void
7249bxe_print_next_block(struct bxe_softc *sc,
7250                     int              idx,
7251                     const char       *blk)
7252{
7253    BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7254}
7255
7256static int
7257bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7258                              uint32_t         sig,
7259                              int              par_num,
7260                              uint8_t          print)
7261{
7262    uint32_t cur_bit = 0;
7263    int i = 0;
7264
7265    for (i = 0; sig; i++) {
7266        cur_bit = ((uint32_t)0x1 << i);
7267        if (sig & cur_bit) {
7268            switch (cur_bit) {
7269            case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7270                if (print)
7271                    bxe_print_next_block(sc, par_num++, "BRB");
7272                break;
7273            case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7274                if (print)
7275                    bxe_print_next_block(sc, par_num++, "PARSER");
7276                break;
7277            case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7278                if (print)
7279                    bxe_print_next_block(sc, par_num++, "TSDM");
7280                break;
7281            case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7282                if (print)
7283                    bxe_print_next_block(sc, par_num++, "SEARCHER");
7284                break;
7285            case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7286                if (print)
7287                    bxe_print_next_block(sc, par_num++, "TCM");
7288                break;
7289            case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7290                if (print)
7291                    bxe_print_next_block(sc, par_num++, "TSEMI");
7292                break;
7293            case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7294                if (print)
7295                    bxe_print_next_block(sc, par_num++, "XPB");
7296                break;
7297            }
7298
7299            /* Clear the bit */
7300            sig &= ~cur_bit;
7301        }
7302    }
7303
7304    return (par_num);
7305}
7306
7307static int
7308bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7309                              uint32_t         sig,
7310                              int              par_num,
7311                              uint8_t          *global,
7312                              uint8_t          print)
7313{
7314    int i = 0;
7315    uint32_t cur_bit = 0;
7316    for (i = 0; sig; i++) {
7317        cur_bit = ((uint32_t)0x1 << i);
7318        if (sig & cur_bit) {
7319            switch (cur_bit) {
7320            case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7321                if (print)
7322                    bxe_print_next_block(sc, par_num++, "PBF");
7323                break;
7324            case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7325                if (print)
7326                    bxe_print_next_block(sc, par_num++, "QM");
7327                break;
7328            case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7329                if (print)
7330                    bxe_print_next_block(sc, par_num++, "TM");
7331                break;
7332            case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7333                if (print)
7334                    bxe_print_next_block(sc, par_num++, "XSDM");
7335                break;
7336            case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7337                if (print)
7338                    bxe_print_next_block(sc, par_num++, "XCM");
7339                break;
7340            case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7341                if (print)
7342                    bxe_print_next_block(sc, par_num++, "XSEMI");
7343                break;
7344            case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7345                if (print)
7346                    bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7347                break;
7348            case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7349                if (print)
7350                    bxe_print_next_block(sc, par_num++, "NIG");
7351                break;
7352            case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7353                if (print)
7354                    bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7355                *global = TRUE;
7356                break;
7357            case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7358                if (print)
7359                    bxe_print_next_block(sc, par_num++, "DEBUG");
7360                break;
7361            case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7362                if (print)
7363                    bxe_print_next_block(sc, par_num++, "USDM");
7364                break;
7365            case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7366                if (print)
7367                    bxe_print_next_block(sc, par_num++, "UCM");
7368                break;
7369            case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7370                if (print)
7371                    bxe_print_next_block(sc, par_num++, "USEMI");
7372                break;
7373            case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7374                if (print)
7375                    bxe_print_next_block(sc, par_num++, "UPB");
7376                break;
7377            case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7378                if (print)
7379                    bxe_print_next_block(sc, par_num++, "CSDM");
7380                break;
7381            case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7382                if (print)
7383                    bxe_print_next_block(sc, par_num++, "CCM");
7384                break;
7385            }
7386
7387            /* Clear the bit */
7388            sig &= ~cur_bit;
7389        }
7390    }
7391
7392    return (par_num);
7393}
7394
7395static int
7396bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7397                              uint32_t         sig,
7398                              int              par_num,
7399                              uint8_t          print)
7400{
7401    uint32_t cur_bit = 0;
7402    int i = 0;
7403
7404    for (i = 0; sig; i++) {
7405        cur_bit = ((uint32_t)0x1 << i);
7406        if (sig & cur_bit) {
7407            switch (cur_bit) {
7408            case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7409                if (print)
7410                    bxe_print_next_block(sc, par_num++, "CSEMI");
7411                break;
7412            case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7413                if (print)
7414                    bxe_print_next_block(sc, par_num++, "PXP");
7415                break;
7416            case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7417                if (print)
7418                    bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7419                break;
7420            case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7421                if (print)
7422                    bxe_print_next_block(sc, par_num++, "CFC");
7423                break;
7424            case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7425                if (print)
7426                    bxe_print_next_block(sc, par_num++, "CDU");
7427                break;
7428            case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7429                if (print)
7430                    bxe_print_next_block(sc, par_num++, "DMAE");
7431                break;
7432            case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7433                if (print)
7434                    bxe_print_next_block(sc, par_num++, "IGU");
7435                break;
7436            case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7437                if (print)
7438                    bxe_print_next_block(sc, par_num++, "MISC");
7439                break;
7440            }
7441
7442            /* Clear the bit */
7443            sig &= ~cur_bit;
7444        }
7445    }
7446
7447    return (par_num);
7448}
7449
7450static int
7451bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7452                              uint32_t         sig,
7453                              int              par_num,
7454                              uint8_t          *global,
7455                              uint8_t          print)
7456{
7457    uint32_t cur_bit = 0;
7458    int i = 0;
7459
7460    for (i = 0; sig; i++) {
7461        cur_bit = ((uint32_t)0x1 << i);
7462        if (sig & cur_bit) {
7463            switch (cur_bit) {
7464            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7465                if (print)
7466                    bxe_print_next_block(sc, par_num++, "MCP ROM");
7467                *global = TRUE;
7468                break;
7469            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7470                if (print)
7471                    bxe_print_next_block(sc, par_num++,
7472                              "MCP UMP RX");
7473                *global = TRUE;
7474                break;
7475            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7476                if (print)
7477                    bxe_print_next_block(sc, par_num++,
7478                              "MCP UMP TX");
7479                *global = TRUE;
7480                break;
7481            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7482                if (print)
7483                    bxe_print_next_block(sc, par_num++,
7484                              "MCP SCPAD");
7485                *global = TRUE;
7486                break;
7487            }
7488
7489            /* Clear the bit */
7490            sig &= ~cur_bit;
7491        }
7492    }
7493
7494    return (par_num);
7495}
7496
7497static int
7498bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7499                              uint32_t         sig,
7500                              int              par_num,
7501                              uint8_t          print)
7502{
7503    uint32_t cur_bit = 0;
7504    int i = 0;
7505
7506    for (i = 0; sig; i++) {
7507        cur_bit = ((uint32_t)0x1 << i);
7508        if (sig & cur_bit) {
7509            switch (cur_bit) {
7510            case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7511                if (print)
7512                    bxe_print_next_block(sc, par_num++, "PGLUE_B");
7513                break;
7514            case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7515                if (print)
7516                    bxe_print_next_block(sc, par_num++, "ATC");
7517                break;
7518            }
7519
7520            /* Clear the bit */
7521            sig &= ~cur_bit;
7522        }
7523    }
7524
7525    return (par_num);
7526}
7527
7528static uint8_t
7529bxe_parity_attn(struct bxe_softc *sc,
7530                uint8_t          *global,
7531                uint8_t          print,
7532                uint32_t         *sig)
7533{
7534    int par_num = 0;
7535
7536    if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7537        (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7538        (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7539        (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7540        (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7541        BLOGE(sc, "Parity error: HW block parity attention:\n"
7542                  "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7543              (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7544              (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7545              (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7546              (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7547              (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7548
7549        if (print)
7550            BLOGI(sc, "Parity errors detected in blocks: ");
7551
7552        par_num =
7553            bxe_check_blocks_with_parity0(sc, sig[0] &
7554                                          HW_PRTY_ASSERT_SET_0,
7555                                          par_num, print);
7556        par_num =
7557            bxe_check_blocks_with_parity1(sc, sig[1] &
7558                                          HW_PRTY_ASSERT_SET_1,
7559                                          par_num, global, print);
7560        par_num =
7561            bxe_check_blocks_with_parity2(sc, sig[2] &
7562                                          HW_PRTY_ASSERT_SET_2,
7563                                          par_num, print);
7564        par_num =
7565            bxe_check_blocks_with_parity3(sc, sig[3] &
7566                                          HW_PRTY_ASSERT_SET_3,
7567                                          par_num, global, print);
7568        par_num =
7569            bxe_check_blocks_with_parity4(sc, sig[4] &
7570                                          HW_PRTY_ASSERT_SET_4,
7571                                          par_num, print);
7572
7573        if (print)
7574            BLOGI(sc, "\n");
7575
7576	if( *global == TRUE ) {
7577                BXE_SET_ERROR_BIT(sc, BXE_ERR_GLOBAL);
7578        }
7579
7580        return (TRUE);
7581    }
7582
7583    return (FALSE);
7584}
7585
7586static uint8_t
7587bxe_chk_parity_attn(struct bxe_softc *sc,
7588                    uint8_t          *global,
7589                    uint8_t          print)
7590{
7591    struct attn_route attn = { {0} };
7592    int port = SC_PORT(sc);
7593
7594    if(sc->state != BXE_STATE_OPEN)
7595        return FALSE;
7596
7597    attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7598    attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7599    attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7600    attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7601
7602    /*
7603     * Since MCP attentions can't be disabled inside the block, we need to
7604     * read AEU registers to see whether they're currently disabled
7605     */
7606    attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7607                                      : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7608                         MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7609                        ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7610
7611
7612    if (!CHIP_IS_E1x(sc))
7613        attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7614
7615    return (bxe_parity_attn(sc, global, print, attn.sig));
7616}
7617
7618static void
7619bxe_attn_int_deasserted4(struct bxe_softc *sc,
7620                         uint32_t         attn)
7621{
7622    uint32_t val;
7623    boolean_t err_flg = FALSE;
7624
7625    if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7626        val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7627        BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7628        err_flg = TRUE;
7629        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7630            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7631        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7632            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7633        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7634            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7635        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7636            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7637        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7638            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7639        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7640            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7641        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7642            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7643        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7644            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7645        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7646            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7647    }
7648
7649    if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7650        val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7651        BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7652	err_flg = TRUE;
7653        if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7654            BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7655        if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7656            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7657        if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7658            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7659        if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7660            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7661        if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7662            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7663        if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7664            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7665    }
7666
7667    if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7668                AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7669        BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7670              (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7671                                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7672	err_flg = TRUE;
7673    }
7674    if (err_flg) {
7675	BXE_SET_ERROR_BIT(sc, BXE_ERR_MISC);
7676	taskqueue_enqueue_timeout(taskqueue_thread,
7677	    &sc->sp_err_timeout_task, hz/10);
7678    }
7679
7680}
7681
7682static void
7683bxe_e1h_disable(struct bxe_softc *sc)
7684{
7685    int port = SC_PORT(sc);
7686
7687    bxe_tx_disable(sc);
7688
7689    REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7690}
7691
7692static void
7693bxe_e1h_enable(struct bxe_softc *sc)
7694{
7695    int port = SC_PORT(sc);
7696
7697    REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7698
7699    // XXX bxe_tx_enable(sc);
7700}
7701
7702/*
7703 * called due to MCP event (on pmf):
7704 *   reread new bandwidth configuration
7705 *   configure FW
7706 *   notify others function about the change
7707 */
7708static void
7709bxe_config_mf_bw(struct bxe_softc *sc)
7710{
7711    if (sc->link_vars.link_up) {
7712        bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7713        // XXX bxe_link_sync_notify(sc);
7714    }
7715
7716    storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7717}
7718
7719static void
7720bxe_set_mf_bw(struct bxe_softc *sc)
7721{
7722    bxe_config_mf_bw(sc);
7723    bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7724}
7725
7726static void
7727bxe_handle_eee_event(struct bxe_softc *sc)
7728{
7729    BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7730    bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7731}
7732
7733#define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7734
7735static void
7736bxe_drv_info_ether_stat(struct bxe_softc *sc)
7737{
7738    struct eth_stats_info *ether_stat =
7739        &sc->sp->drv_info_to_mcp.ether_stat;
7740
7741    strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7742            ETH_STAT_INFO_VERSION_LEN);
7743
7744    /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7745    sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7746                                          DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7747                                          ether_stat->mac_local + MAC_PAD,
7748                                          MAC_PAD, ETH_ALEN);
7749
7750    ether_stat->mtu_size = sc->mtu;
7751
7752    ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7753    if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
7754        ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7755    }
7756
7757    // XXX ether_stat->feature_flags |= ???;
7758
7759    ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7760
7761    ether_stat->txq_size = sc->tx_ring_size;
7762    ether_stat->rxq_size = sc->rx_ring_size;
7763}
7764
7765static void
7766bxe_handle_drv_info_req(struct bxe_softc *sc)
7767{
7768    enum drv_info_opcode op_code;
7769    uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7770
7771    /* if drv_info version supported by MFW doesn't match - send NACK */
7772    if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7773        bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7774        return;
7775    }
7776
7777    op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7778               DRV_INFO_CONTROL_OP_CODE_SHIFT);
7779
7780    memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7781
7782    switch (op_code) {
7783    case ETH_STATS_OPCODE:
7784        bxe_drv_info_ether_stat(sc);
7785        break;
7786    case FCOE_STATS_OPCODE:
7787    case ISCSI_STATS_OPCODE:
7788    default:
7789        /* if op code isn't supported - send NACK */
7790        bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7791        return;
7792    }
7793
7794    /*
7795     * If we got drv_info attn from MFW then these fields are defined in
7796     * shmem2 for sure
7797     */
7798    SHMEM2_WR(sc, drv_info_host_addr_lo,
7799              U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7800    SHMEM2_WR(sc, drv_info_host_addr_hi,
7801              U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7802
7803    bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7804}
7805
7806static void
7807bxe_dcc_event(struct bxe_softc *sc,
7808              uint32_t         dcc_event)
7809{
7810    BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7811
7812    if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7813        /*
7814         * This is the only place besides the function initialization
7815         * where the sc->flags can change so it is done without any
7816         * locks
7817         */
7818        if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7819            BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7820            sc->flags |= BXE_MF_FUNC_DIS;
7821            bxe_e1h_disable(sc);
7822        } else {
7823            BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7824            sc->flags &= ~BXE_MF_FUNC_DIS;
7825            bxe_e1h_enable(sc);
7826        }
7827        dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7828    }
7829
7830    if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7831        bxe_config_mf_bw(sc);
7832        dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7833    }
7834
7835    /* Report results to MCP */
7836    if (dcc_event)
7837        bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7838    else
7839        bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7840}
7841
7842static void
7843bxe_pmf_update(struct bxe_softc *sc)
7844{
7845    int port = SC_PORT(sc);
7846    uint32_t val;
7847
7848    sc->port.pmf = 1;
7849    BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7850
7851    /*
7852     * We need the mb() to ensure the ordering between the writing to
7853     * sc->port.pmf here and reading it from the bxe_periodic_task().
7854     */
7855    mb();
7856
7857    /* queue a periodic task */
7858    // XXX schedule task...
7859
7860    // XXX bxe_dcbx_pmf_update(sc);
7861
7862    /* enable nig attention */
7863    val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7864    if (sc->devinfo.int_block == INT_BLOCK_HC) {
7865        REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7866        REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7867    } else if (!CHIP_IS_E1x(sc)) {
7868        REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7869        REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7870    }
7871
7872    bxe_stats_handle(sc, STATS_EVENT_PMF);
7873}
7874
7875static int
7876bxe_mc_assert(struct bxe_softc *sc)
7877{
7878    char last_idx;
7879    int i, rc = 0;
7880    uint32_t row0, row1, row2, row3;
7881
7882    /* XSTORM */
7883    last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7884    if (last_idx)
7885        BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7886
7887    /* print the asserts */
7888    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7889
7890        row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7891        row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7892        row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7893        row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7894
7895        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7896            BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7897                  i, row3, row2, row1, row0);
7898            rc++;
7899        } else {
7900            break;
7901        }
7902    }
7903
7904    /* TSTORM */
7905    last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7906    if (last_idx) {
7907        BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7908    }
7909
7910    /* print the asserts */
7911    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7912
7913        row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7914        row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7915        row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7916        row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7917
7918        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7919            BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7920                  i, row3, row2, row1, row0);
7921            rc++;
7922        } else {
7923            break;
7924        }
7925    }
7926
7927    /* CSTORM */
7928    last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7929    if (last_idx) {
7930        BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7931    }
7932
7933    /* print the asserts */
7934    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7935
7936        row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7937        row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7938        row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7939        row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7940
7941        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7942            BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7943                  i, row3, row2, row1, row0);
7944            rc++;
7945        } else {
7946            break;
7947        }
7948    }
7949
7950    /* USTORM */
7951    last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7952    if (last_idx) {
7953        BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7954    }
7955
7956    /* print the asserts */
7957    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7958
7959        row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7960        row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7961        row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7962        row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7963
7964        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7965            BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7966                  i, row3, row2, row1, row0);
7967            rc++;
7968        } else {
7969            break;
7970        }
7971    }
7972
7973    return (rc);
7974}
7975
7976static void
7977bxe_attn_int_deasserted3(struct bxe_softc *sc,
7978                         uint32_t         attn)
7979{
7980    int func = SC_FUNC(sc);
7981    uint32_t val;
7982
7983    if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7984
7985        if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7986
7987            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7988            bxe_read_mf_cfg(sc);
7989            sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7990                MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7991            val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7992
7993            if (val & DRV_STATUS_DCC_EVENT_MASK)
7994                bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7995
7996            if (val & DRV_STATUS_SET_MF_BW)
7997                bxe_set_mf_bw(sc);
7998
7999            if (val & DRV_STATUS_DRV_INFO_REQ)
8000                bxe_handle_drv_info_req(sc);
8001
8002            if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
8003                bxe_pmf_update(sc);
8004
8005            if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
8006                bxe_handle_eee_event(sc);
8007
8008            if (sc->link_vars.periodic_flags &
8009                ELINK_PERIODIC_FLAGS_LINK_EVENT) {
8010                /* sync with link */
8011		bxe_acquire_phy_lock(sc);
8012                sc->link_vars.periodic_flags &=
8013                    ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
8014		bxe_release_phy_lock(sc);
8015                if (IS_MF(sc))
8016                    ; // XXX bxe_link_sync_notify(sc);
8017                bxe_link_report(sc);
8018            }
8019
8020            /*
8021             * Always call it here: bxe_link_report() will
8022             * prevent the link indication duplication.
8023             */
8024            bxe_link_status_update(sc);
8025
8026        } else if (attn & BXE_MC_ASSERT_BITS) {
8027
8028            BLOGE(sc, "MC assert!\n");
8029            bxe_mc_assert(sc);
8030            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8031            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8032            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8033            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8034            bxe_int_disable(sc);
8035            BXE_SET_ERROR_BIT(sc, BXE_ERR_MC_ASSERT);
8036            taskqueue_enqueue_timeout(taskqueue_thread,
8037                &sc->sp_err_timeout_task, hz/10);
8038
8039        } else if (attn & BXE_MCP_ASSERT) {
8040
8041            BLOGE(sc, "MCP assert!\n");
8042            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8043            BXE_SET_ERROR_BIT(sc, BXE_ERR_MCP_ASSERT);
8044            taskqueue_enqueue_timeout(taskqueue_thread,
8045                &sc->sp_err_timeout_task, hz/10);
8046            bxe_int_disable(sc);  /*avoid repetive assert alert */
8047
8048
8049        } else {
8050            BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8051        }
8052    }
8053
8054    if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8055        BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8056        if (attn & BXE_GRC_TIMEOUT) {
8057            val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8058            BLOGE(sc, "GRC time-out 0x%08x\n", val);
8059        }
8060        if (attn & BXE_GRC_RSV) {
8061            val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8062            BLOGE(sc, "GRC reserved 0x%08x\n", val);
8063        }
8064        REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8065    }
8066}
8067
8068static void
8069bxe_attn_int_deasserted2(struct bxe_softc *sc,
8070                         uint32_t         attn)
8071{
8072    int port = SC_PORT(sc);
8073    int reg_offset;
8074    uint32_t val0, mask0, val1, mask1;
8075    uint32_t val;
8076    boolean_t err_flg = FALSE;
8077
8078    if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8079        val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8080        BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8081        /* CFC error attention */
8082        if (val & 0x2) {
8083            BLOGE(sc, "FATAL error from CFC\n");
8084	    err_flg = TRUE;
8085        }
8086    }
8087
8088    if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8089        val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8090        BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8091        /* RQ_USDMDP_FIFO_OVERFLOW */
8092        if (val & 0x18000) {
8093            BLOGE(sc, "FATAL error from PXP\n");
8094	    err_flg = TRUE;
8095        }
8096
8097        if (!CHIP_IS_E1x(sc)) {
8098            val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8099            BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8100	    err_flg = TRUE;
8101        }
8102    }
8103
8104#define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8105#define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8106
8107    if (attn & AEU_PXP2_HW_INT_BIT) {
8108        /*  CQ47854 workaround do not panic on
8109         *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8110         */
8111        if (!CHIP_IS_E1x(sc)) {
8112            mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8113            val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8114            mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8115            val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8116            /*
8117             * If the only PXP2_EOP_ERROR_BIT is set in
8118             * STS0 and STS1 - clear it
8119             *
8120             * probably we lose additional attentions between
8121             * STS0 and STS_CLR0, in this case user will not
8122             * be notified about them
8123             */
8124            if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8125                !(val1 & mask1))
8126                val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8127
8128            /* print the register, since no one can restore it */
8129            BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8130
8131            /*
8132             * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8133             * then notify
8134             */
8135            if (val0 & PXP2_EOP_ERROR_BIT) {
8136                BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8137		err_flg = TRUE;
8138
8139                /*
8140                 * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8141                 * set then clear attention from PXP2 block without panic
8142                 */
8143                if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8144                    ((val1 & mask1) == 0))
8145                    attn &= ~AEU_PXP2_HW_INT_BIT;
8146            }
8147        }
8148    }
8149
8150    if (attn & HW_INTERRUT_ASSERT_SET_2) {
8151        reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8152                             MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8153
8154        val = REG_RD(sc, reg_offset);
8155        val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8156        REG_WR(sc, reg_offset, val);
8157
8158        BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8159              (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8160	err_flg = TRUE;
8161        bxe_panic(sc, ("HW block attention set2\n"));
8162    }
8163    if(err_flg) {
8164        BXE_SET_ERROR_BIT(sc, BXE_ERR_GLOBAL);
8165        taskqueue_enqueue_timeout(taskqueue_thread,
8166           &sc->sp_err_timeout_task, hz/10);
8167    }
8168
8169}
8170
8171static void
8172bxe_attn_int_deasserted1(struct bxe_softc *sc,
8173                         uint32_t         attn)
8174{
8175    int port = SC_PORT(sc);
8176    int reg_offset;
8177    uint32_t val;
8178    boolean_t err_flg = FALSE;
8179
8180    if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8181        val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8182        BLOGE(sc, "DB hw attention 0x%08x\n", val);
8183        /* DORQ discard attention */
8184        if (val & 0x2) {
8185            BLOGE(sc, "FATAL error from DORQ\n");
8186	    err_flg = TRUE;
8187        }
8188    }
8189
8190    if (attn & HW_INTERRUT_ASSERT_SET_1) {
8191        reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8192                             MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8193
8194        val = REG_RD(sc, reg_offset);
8195        val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8196        REG_WR(sc, reg_offset, val);
8197
8198        BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8199              (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8200        err_flg = TRUE;
8201        bxe_panic(sc, ("HW block attention set1\n"));
8202    }
8203    if(err_flg) {
8204        BXE_SET_ERROR_BIT(sc, BXE_ERR_MISC);
8205        taskqueue_enqueue_timeout(taskqueue_thread,
8206           &sc->sp_err_timeout_task, hz/10);
8207    }
8208
8209}
8210
8211static void
8212bxe_attn_int_deasserted0(struct bxe_softc *sc,
8213                         uint32_t         attn)
8214{
8215    int port = SC_PORT(sc);
8216    int reg_offset;
8217    uint32_t val;
8218
8219    reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8220                          MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8221
8222    if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8223        val = REG_RD(sc, reg_offset);
8224        val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8225        REG_WR(sc, reg_offset, val);
8226
8227        BLOGW(sc, "SPIO5 hw attention\n");
8228
8229        /* Fan failure attention */
8230        elink_hw_reset_phy(&sc->link_params);
8231        bxe_fan_failure(sc);
8232    }
8233
8234    if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8235	bxe_acquire_phy_lock(sc);
8236        elink_handle_module_detect_int(&sc->link_params);
8237	bxe_release_phy_lock(sc);
8238    }
8239
8240    if (attn & HW_INTERRUT_ASSERT_SET_0) {
8241        val = REG_RD(sc, reg_offset);
8242        val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8243        REG_WR(sc, reg_offset, val);
8244
8245
8246        BXE_SET_ERROR_BIT(sc, BXE_ERR_MISC);
8247        taskqueue_enqueue_timeout(taskqueue_thread,
8248           &sc->sp_err_timeout_task, hz/10);
8249
8250        bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8251                       (attn & HW_INTERRUT_ASSERT_SET_0)));
8252    }
8253}
8254
8255static void
8256bxe_attn_int_deasserted(struct bxe_softc *sc,
8257                        uint32_t         deasserted)
8258{
8259    struct attn_route attn;
8260    struct attn_route *group_mask;
8261    int port = SC_PORT(sc);
8262    int index;
8263    uint32_t reg_addr;
8264    uint32_t val;
8265    uint32_t aeu_mask;
8266    uint8_t global = FALSE;
8267
8268    /*
8269     * Need to take HW lock because MCP or other port might also
8270     * try to handle this event.
8271     */
8272    bxe_acquire_alr(sc);
8273
8274    if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8275        /* XXX
8276         * In case of parity errors don't handle attentions so that
8277         * other function would "see" parity errors.
8278         */
8279        // XXX schedule a recovery task...
8280        /* disable HW interrupts */
8281        bxe_int_disable(sc);
8282        BXE_SET_ERROR_BIT(sc, BXE_ERR_PARITY);
8283        taskqueue_enqueue_timeout(taskqueue_thread,
8284           &sc->sp_err_timeout_task, hz/10);
8285        bxe_release_alr(sc);
8286        return;
8287    }
8288
8289    attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8290    attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8291    attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8292    attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8293    if (!CHIP_IS_E1x(sc)) {
8294        attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8295    } else {
8296        attn.sig[4] = 0;
8297    }
8298
8299    BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8300          attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8301
8302    for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8303        if (deasserted & (1 << index)) {
8304            group_mask = &sc->attn_group[index];
8305
8306            BLOGD(sc, DBG_INTR,
8307                  "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8308                  group_mask->sig[0], group_mask->sig[1],
8309                  group_mask->sig[2], group_mask->sig[3],
8310                  group_mask->sig[4]);
8311
8312            bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8313            bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8314            bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8315            bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8316            bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8317        }
8318    }
8319
8320    bxe_release_alr(sc);
8321
8322    if (sc->devinfo.int_block == INT_BLOCK_HC) {
8323        reg_addr = (HC_REG_COMMAND_REG + port*32 +
8324                    COMMAND_REG_ATTN_BITS_CLR);
8325    } else {
8326        reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8327    }
8328
8329    val = ~deasserted;
8330    BLOGD(sc, DBG_INTR,
8331          "about to mask 0x%08x at %s addr 0x%08x\n", val,
8332          (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8333    REG_WR(sc, reg_addr, val);
8334
8335    if (~sc->attn_state & deasserted) {
8336        BLOGE(sc, "IGU error\n");
8337    }
8338
8339    reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8340                      MISC_REG_AEU_MASK_ATTN_FUNC_0;
8341
8342    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8343
8344    aeu_mask = REG_RD(sc, reg_addr);
8345
8346    BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8347          aeu_mask, deasserted);
8348    aeu_mask |= (deasserted & 0x3ff);
8349    BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8350
8351    REG_WR(sc, reg_addr, aeu_mask);
8352    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8353
8354    BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8355    sc->attn_state &= ~deasserted;
8356    BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8357}
8358
8359static void
8360bxe_attn_int(struct bxe_softc *sc)
8361{
8362    /* read local copy of bits */
8363    uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8364    uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8365    uint32_t attn_state = sc->attn_state;
8366
8367    /* look for changed bits */
8368    uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8369    uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8370
8371    BLOGD(sc, DBG_INTR,
8372          "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8373          attn_bits, attn_ack, asserted, deasserted);
8374
8375    if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8376        BLOGE(sc, "BAD attention state\n");
8377    }
8378
8379    /* handle bits that were raised */
8380    if (asserted) {
8381        bxe_attn_int_asserted(sc, asserted);
8382    }
8383
8384    if (deasserted) {
8385        bxe_attn_int_deasserted(sc, deasserted);
8386    }
8387}
8388
8389static uint16_t
8390bxe_update_dsb_idx(struct bxe_softc *sc)
8391{
8392    struct host_sp_status_block *def_sb = sc->def_sb;
8393    uint16_t rc = 0;
8394
8395    mb(); /* status block is written to by the chip */
8396
8397    if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8398        sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8399        rc |= BXE_DEF_SB_ATT_IDX;
8400    }
8401
8402    if (sc->def_idx != def_sb->sp_sb.running_index) {
8403        sc->def_idx = def_sb->sp_sb.running_index;
8404        rc |= BXE_DEF_SB_IDX;
8405    }
8406
8407    mb();
8408
8409    return (rc);
8410}
8411
8412static inline struct ecore_queue_sp_obj *
8413bxe_cid_to_q_obj(struct bxe_softc *sc,
8414                 uint32_t         cid)
8415{
8416    BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8417    return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8418}
8419
8420static void
8421bxe_handle_mcast_eqe(struct bxe_softc *sc)
8422{
8423    struct ecore_mcast_ramrod_params rparam;
8424    int rc;
8425
8426    memset(&rparam, 0, sizeof(rparam));
8427
8428    rparam.mcast_obj = &sc->mcast_obj;
8429
8430    BXE_MCAST_LOCK(sc);
8431
8432    /* clear pending state for the last command */
8433    sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8434
8435    /* if there are pending mcast commands - send them */
8436    if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8437        rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8438        if (rc < 0) {
8439            BLOGD(sc, DBG_SP,
8440                "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8441        }
8442    }
8443
8444    BXE_MCAST_UNLOCK(sc);
8445}
8446
8447static void
8448bxe_handle_classification_eqe(struct bxe_softc      *sc,
8449                              union event_ring_elem *elem)
8450{
8451    unsigned long ramrod_flags = 0;
8452    int rc = 0;
8453    uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8454    struct ecore_vlan_mac_obj *vlan_mac_obj;
8455
8456    /* always push next commands out, don't wait here */
8457    bit_set(&ramrod_flags, RAMROD_CONT);
8458
8459    switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8460    case ECORE_FILTER_MAC_PENDING:
8461        BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8462        vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8463        break;
8464
8465    case ECORE_FILTER_MCAST_PENDING:
8466        BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8467        /*
8468         * This is only relevant for 57710 where multicast MACs are
8469         * configured as unicast MACs using the same ramrod.
8470         */
8471        bxe_handle_mcast_eqe(sc);
8472        return;
8473
8474    default:
8475        BLOGE(sc, "Unsupported classification command: %d\n",
8476              elem->message.data.eth_event.echo);
8477        return;
8478    }
8479
8480    rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8481
8482    if (rc < 0) {
8483        BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8484    } else if (rc > 0) {
8485        BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8486    }
8487}
8488
8489static void
8490bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8491                       union event_ring_elem *elem)
8492{
8493    bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8494
8495    /* send rx_mode command again if was requested */
8496    if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8497                               &sc->sp_state)) {
8498        bxe_set_storm_rx_mode(sc);
8499    }
8500}
8501
8502static void
8503bxe_update_eq_prod(struct bxe_softc *sc,
8504                   uint16_t         prod)
8505{
8506    storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8507    wmb(); /* keep prod updates ordered */
8508}
8509
8510static void
8511bxe_eq_int(struct bxe_softc *sc)
8512{
8513    uint16_t hw_cons, sw_cons, sw_prod;
8514    union event_ring_elem *elem;
8515    uint8_t echo;
8516    uint32_t cid;
8517    uint8_t opcode;
8518    int spqe_cnt = 0;
8519    struct ecore_queue_sp_obj *q_obj;
8520    struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8521    struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8522
8523    hw_cons = le16toh(*sc->eq_cons_sb);
8524
8525    /*
8526     * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8527     * when we get to the next-page we need to adjust so the loop
8528     * condition below will be met. The next element is the size of a
8529     * regular element and hence incrementing by 1
8530     */
8531    if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8532        hw_cons++;
8533    }
8534
8535    /*
8536     * This function may never run in parallel with itself for a
8537     * specific sc and no need for a read memory barrier here.
8538     */
8539    sw_cons = sc->eq_cons;
8540    sw_prod = sc->eq_prod;
8541
8542    BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8543          hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8544
8545    for (;
8546         sw_cons != hw_cons;
8547         sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8548
8549        elem = &sc->eq[EQ_DESC(sw_cons)];
8550
8551        /* elem CID originates from FW, actually LE */
8552        cid = SW_CID(elem->message.data.cfc_del_event.cid);
8553        opcode = elem->message.opcode;
8554
8555        /* handle eq element */
8556        switch (opcode) {
8557
8558        case EVENT_RING_OPCODE_STAT_QUERY:
8559            BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8560                  sc->stats_comp++);
8561            /* nothing to do with stats comp */
8562            goto next_spqe;
8563
8564        case EVENT_RING_OPCODE_CFC_DEL:
8565            /* handle according to cid range */
8566            /* we may want to verify here that the sc state is HALTING */
8567            BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8568            q_obj = bxe_cid_to_q_obj(sc, cid);
8569            if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8570                break;
8571            }
8572            goto next_spqe;
8573
8574        case EVENT_RING_OPCODE_STOP_TRAFFIC:
8575            BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8576            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8577                break;
8578            }
8579            // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8580            goto next_spqe;
8581
8582        case EVENT_RING_OPCODE_START_TRAFFIC:
8583            BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8584            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8585                break;
8586            }
8587            // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8588            goto next_spqe;
8589
8590        case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8591            echo = elem->message.data.function_update_event.echo;
8592            if (echo == SWITCH_UPDATE) {
8593                BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8594                if (f_obj->complete_cmd(sc, f_obj,
8595                                        ECORE_F_CMD_SWITCH_UPDATE)) {
8596                    break;
8597                }
8598            }
8599            else {
8600                BLOGD(sc, DBG_SP,
8601                      "AFEX: ramrod completed FUNCTION_UPDATE\n");
8602            }
8603            goto next_spqe;
8604
8605        case EVENT_RING_OPCODE_FORWARD_SETUP:
8606            q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8607            if (q_obj->complete_cmd(sc, q_obj,
8608                                    ECORE_Q_CMD_SETUP_TX_ONLY)) {
8609                break;
8610            }
8611            goto next_spqe;
8612
8613        case EVENT_RING_OPCODE_FUNCTION_START:
8614            BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8615            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8616                break;
8617            }
8618            goto next_spqe;
8619
8620        case EVENT_RING_OPCODE_FUNCTION_STOP:
8621            BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8622            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8623                break;
8624            }
8625            goto next_spqe;
8626        }
8627
8628        switch (opcode | sc->state) {
8629        case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8630        case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8631            cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8632            BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8633            rss_raw->clear_pending(rss_raw);
8634            break;
8635
8636        case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8637        case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8638        case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8639        case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8640        case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8641        case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8642            BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8643            bxe_handle_classification_eqe(sc, elem);
8644            break;
8645
8646        case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8647        case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8648        case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8649            BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8650            bxe_handle_mcast_eqe(sc);
8651            break;
8652
8653        case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8654        case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8655        case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8656            BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8657            bxe_handle_rx_mode_eqe(sc, elem);
8658            break;
8659
8660        default:
8661            /* unknown event log error and continue */
8662            BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8663                  elem->message.opcode, sc->state);
8664        }
8665
8666next_spqe:
8667        spqe_cnt++;
8668    } /* for */
8669
8670    mb();
8671    atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8672
8673    sc->eq_cons = sw_cons;
8674    sc->eq_prod = sw_prod;
8675
8676    /* make sure that above mem writes were issued towards the memory */
8677    wmb();
8678
8679    /* update producer */
8680    bxe_update_eq_prod(sc, sc->eq_prod);
8681}
8682
8683static void
8684bxe_handle_sp_tq(void *context,
8685                 int  pending)
8686{
8687    struct bxe_softc *sc = (struct bxe_softc *)context;
8688    uint16_t status;
8689
8690    BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8691
8692    /* what work needs to be performed? */
8693    status = bxe_update_dsb_idx(sc);
8694
8695    BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8696
8697    /* HW attentions */
8698    if (status & BXE_DEF_SB_ATT_IDX) {
8699        BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8700        bxe_attn_int(sc);
8701        status &= ~BXE_DEF_SB_ATT_IDX;
8702    }
8703
8704    /* SP events: STAT_QUERY and others */
8705    if (status & BXE_DEF_SB_IDX) {
8706        /* handle EQ completions */
8707        BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8708        bxe_eq_int(sc);
8709        bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8710                   le16toh(sc->def_idx), IGU_INT_NOP, 1);
8711        status &= ~BXE_DEF_SB_IDX;
8712    }
8713
8714    /* if status is non zero then something went wrong */
8715    if (__predict_false(status)) {
8716        BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8717    }
8718
8719    /* ack status block only if something was actually handled */
8720    bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8721               le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8722
8723    /*
8724     * Must be called after the EQ processing (since eq leads to sriov
8725     * ramrod completion flows).
8726     * This flow may have been scheduled by the arrival of a ramrod
8727     * completion, or by the sriov code rescheduling itself.
8728     */
8729    // XXX bxe_iov_sp_task(sc);
8730
8731}
8732
8733static void
8734bxe_handle_fp_tq(void *context,
8735                 int  pending)
8736{
8737    struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8738    struct bxe_softc *sc = fp->sc;
8739    uint8_t more_tx = FALSE;
8740    uint8_t more_rx = FALSE;
8741
8742    BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8743
8744    /* XXX
8745     * IFF_DRV_RUNNING state can't be checked here since we process
8746     * slowpath events on a client queue during setup. Instead
8747     * we need to add a "process/continue" flag here that the driver
8748     * can use to tell the task here not to do anything.
8749     */
8750#if 0
8751    if (!(if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
8752        return;
8753    }
8754#endif
8755
8756    /* update the fastpath index */
8757    bxe_update_fp_sb_idx(fp);
8758
8759    /* XXX add loop here if ever support multiple tx CoS */
8760    /* fp->txdata[cos] */
8761    if (bxe_has_tx_work(fp)) {
8762        BXE_FP_TX_LOCK(fp);
8763        more_tx = bxe_txeof(sc, fp);
8764        BXE_FP_TX_UNLOCK(fp);
8765    }
8766
8767    if (bxe_has_rx_work(fp)) {
8768        more_rx = bxe_rxeof(sc, fp);
8769    }
8770
8771    if (more_rx /*|| more_tx*/) {
8772        /* still more work to do */
8773        taskqueue_enqueue(fp->tq, &fp->tq_task);
8774        return;
8775    }
8776
8777    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8778               le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8779}
8780
8781static void
8782bxe_task_fp(struct bxe_fastpath *fp)
8783{
8784    struct bxe_softc *sc = fp->sc;
8785    uint8_t more_tx = FALSE;
8786    uint8_t more_rx = FALSE;
8787
8788    BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8789
8790    /* update the fastpath index */
8791    bxe_update_fp_sb_idx(fp);
8792
8793    /* XXX add loop here if ever support multiple tx CoS */
8794    /* fp->txdata[cos] */
8795    if (bxe_has_tx_work(fp)) {
8796        BXE_FP_TX_LOCK(fp);
8797        more_tx = bxe_txeof(sc, fp);
8798        BXE_FP_TX_UNLOCK(fp);
8799    }
8800
8801    if (bxe_has_rx_work(fp)) {
8802        more_rx = bxe_rxeof(sc, fp);
8803    }
8804
8805    if (more_rx /*|| more_tx*/) {
8806        /* still more work to do, bail out if this ISR and process later */
8807        taskqueue_enqueue(fp->tq, &fp->tq_task);
8808        return;
8809    }
8810
8811    /*
8812     * Here we write the fastpath index taken before doing any tx or rx work.
8813     * It is very well possible other hw events occurred up to this point and
8814     * they were actually processed accordingly above. Since we're going to
8815     * write an older fastpath index, an interrupt is coming which we might
8816     * not do any work in.
8817     */
8818    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8819               le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8820}
8821
8822/*
8823 * Legacy interrupt entry point.
8824 *
8825 * Verifies that the controller generated the interrupt and
8826 * then calls a separate routine to handle the various
8827 * interrupt causes: link, RX, and TX.
8828 */
8829static void
8830bxe_intr_legacy(void *xsc)
8831{
8832    struct bxe_softc *sc = (struct bxe_softc *)xsc;
8833    struct bxe_fastpath *fp;
8834    uint16_t status, mask;
8835    int i;
8836
8837    BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8838
8839    /*
8840     * 0 for ustorm, 1 for cstorm
8841     * the bits returned from ack_int() are 0-15
8842     * bit 0 = attention status block
8843     * bit 1 = fast path status block
8844     * a mask of 0x2 or more = tx/rx event
8845     * a mask of 1 = slow path event
8846     */
8847
8848    status = bxe_ack_int(sc);
8849
8850    /* the interrupt is not for us */
8851    if (__predict_false(status == 0)) {
8852        BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8853        return;
8854    }
8855
8856    BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8857
8858    FOR_EACH_ETH_QUEUE(sc, i) {
8859        fp = &sc->fp[i];
8860        mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8861        if (status & mask) {
8862            /* acknowledge and disable further fastpath interrupts */
8863            bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8864            bxe_task_fp(fp);
8865            status &= ~mask;
8866        }
8867    }
8868
8869    if (__predict_false(status & 0x1)) {
8870        /* acknowledge and disable further slowpath interrupts */
8871        bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8872
8873        /* schedule slowpath handler */
8874        taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8875
8876        status &= ~0x1;
8877    }
8878
8879    if (__predict_false(status)) {
8880        BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8881    }
8882}
8883
8884/* slowpath interrupt entry point */
8885static void
8886bxe_intr_sp(void *xsc)
8887{
8888    struct bxe_softc *sc = (struct bxe_softc *)xsc;
8889
8890    BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8891
8892    /* acknowledge and disable further slowpath interrupts */
8893    bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8894
8895    /* schedule slowpath handler */
8896    taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8897}
8898
8899/* fastpath interrupt entry point */
8900static void
8901bxe_intr_fp(void *xfp)
8902{
8903    struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8904    struct bxe_softc *sc = fp->sc;
8905
8906    BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8907
8908    BLOGD(sc, DBG_INTR,
8909          "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8910          curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8911
8912    /* acknowledge and disable further fastpath interrupts */
8913    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8914
8915    bxe_task_fp(fp);
8916}
8917
8918/* Release all interrupts allocated by the driver. */
8919static void
8920bxe_interrupt_free(struct bxe_softc *sc)
8921{
8922    int i;
8923
8924    switch (sc->interrupt_mode) {
8925    case INTR_MODE_INTX:
8926        BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8927        if (sc->intr[0].resource != NULL) {
8928            bus_release_resource(sc->dev,
8929                                 SYS_RES_IRQ,
8930                                 sc->intr[0].rid,
8931                                 sc->intr[0].resource);
8932        }
8933        break;
8934    case INTR_MODE_MSI:
8935        for (i = 0; i < sc->intr_count; i++) {
8936            BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8937            if (sc->intr[i].resource && sc->intr[i].rid) {
8938                bus_release_resource(sc->dev,
8939                                     SYS_RES_IRQ,
8940                                     sc->intr[i].rid,
8941                                     sc->intr[i].resource);
8942            }
8943        }
8944        pci_release_msi(sc->dev);
8945        break;
8946    case INTR_MODE_MSIX:
8947        for (i = 0; i < sc->intr_count; i++) {
8948            BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8949            if (sc->intr[i].resource && sc->intr[i].rid) {
8950                bus_release_resource(sc->dev,
8951                                     SYS_RES_IRQ,
8952                                     sc->intr[i].rid,
8953                                     sc->intr[i].resource);
8954            }
8955        }
8956        pci_release_msi(sc->dev);
8957        break;
8958    default:
8959        /* nothing to do as initial allocation failed */
8960        break;
8961    }
8962}
8963
8964/*
8965 * This function determines and allocates the appropriate
8966 * interrupt based on system capabilites and user request.
8967 *
8968 * The user may force a particular interrupt mode, specify
8969 * the number of receive queues, specify the method for
8970 * distribuitng received frames to receive queues, or use
8971 * the default settings which will automatically select the
8972 * best supported combination.  In addition, the OS may or
8973 * may not support certain combinations of these settings.
8974 * This routine attempts to reconcile the settings requested
8975 * by the user with the capabilites available from the system
8976 * to select the optimal combination of features.
8977 *
8978 * Returns:
8979 *   0 = Success, !0 = Failure.
8980 */
8981static int
8982bxe_interrupt_alloc(struct bxe_softc *sc)
8983{
8984    int msix_count = 0;
8985    int msi_count = 0;
8986    int num_requested = 0;
8987    int num_allocated = 0;
8988    int rid, i, j;
8989    int rc;
8990
8991    /* get the number of available MSI/MSI-X interrupts from the OS */
8992    if (sc->interrupt_mode > 0) {
8993        if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8994            msix_count = pci_msix_count(sc->dev);
8995        }
8996
8997        if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8998            msi_count = pci_msi_count(sc->dev);
8999        }
9000
9001        BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
9002              msi_count, msix_count);
9003    }
9004
9005    do { /* try allocating MSI-X interrupt resources (at least 2) */
9006        if (sc->interrupt_mode != INTR_MODE_MSIX) {
9007            break;
9008        }
9009
9010        if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
9011            (msix_count < 2)) {
9012            sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9013            break;
9014        }
9015
9016        /* ask for the necessary number of MSI-X vectors */
9017        num_requested = min((sc->num_queues + 1), msix_count);
9018
9019        BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
9020
9021        num_allocated = num_requested;
9022        if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
9023            BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
9024            sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9025            break;
9026        }
9027
9028        if (num_allocated < 2) { /* possible? */
9029            BLOGE(sc, "MSI-X allocation less than 2!\n");
9030            sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9031            pci_release_msi(sc->dev);
9032            break;
9033        }
9034
9035        BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
9036              num_requested, num_allocated);
9037
9038        /* best effort so use the number of vectors allocated to us */
9039        sc->intr_count = num_allocated;
9040        sc->num_queues = num_allocated - 1;
9041
9042        rid = 1; /* initial resource identifier */
9043
9044        /* allocate the MSI-X vectors */
9045        for (i = 0; i < num_allocated; i++) {
9046            sc->intr[i].rid = (rid + i);
9047
9048            if ((sc->intr[i].resource =
9049                 bus_alloc_resource_any(sc->dev,
9050                                        SYS_RES_IRQ,
9051                                        &sc->intr[i].rid,
9052                                        RF_ACTIVE)) == NULL) {
9053                BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
9054                      i, (rid + i));
9055
9056                for (j = (i - 1); j >= 0; j--) {
9057                    bus_release_resource(sc->dev,
9058                                         SYS_RES_IRQ,
9059                                         sc->intr[j].rid,
9060                                         sc->intr[j].resource);
9061                }
9062
9063                sc->intr_count = 0;
9064                sc->num_queues = 0;
9065                sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9066                pci_release_msi(sc->dev);
9067                break;
9068            }
9069
9070            BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9071        }
9072    } while (0);
9073
9074    do { /* try allocating MSI vector resources (at least 2) */
9075        if (sc->interrupt_mode != INTR_MODE_MSI) {
9076            break;
9077        }
9078
9079        if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9080            (msi_count < 1)) {
9081            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9082            break;
9083        }
9084
9085        /* ask for a single MSI vector */
9086        num_requested = 1;
9087
9088        BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9089
9090        num_allocated = num_requested;
9091        if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9092            BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9093            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9094            break;
9095        }
9096
9097        if (num_allocated != 1) { /* possible? */
9098            BLOGE(sc, "MSI allocation is not 1!\n");
9099            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9100            pci_release_msi(sc->dev);
9101            break;
9102        }
9103
9104        BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9105              num_requested, num_allocated);
9106
9107        /* best effort so use the number of vectors allocated to us */
9108        sc->intr_count = num_allocated;
9109        sc->num_queues = num_allocated;
9110
9111        rid = 1; /* initial resource identifier */
9112
9113        sc->intr[0].rid = rid;
9114
9115        if ((sc->intr[0].resource =
9116             bus_alloc_resource_any(sc->dev,
9117                                    SYS_RES_IRQ,
9118                                    &sc->intr[0].rid,
9119                                    RF_ACTIVE)) == NULL) {
9120            BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9121            sc->intr_count = 0;
9122            sc->num_queues = 0;
9123            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9124            pci_release_msi(sc->dev);
9125            break;
9126        }
9127
9128        BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9129    } while (0);
9130
9131    do { /* try allocating INTx vector resources */
9132        if (sc->interrupt_mode != INTR_MODE_INTX) {
9133            break;
9134        }
9135
9136        BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9137
9138        /* only one vector for INTx */
9139        sc->intr_count = 1;
9140        sc->num_queues = 1;
9141
9142        rid = 0; /* initial resource identifier */
9143
9144        sc->intr[0].rid = rid;
9145
9146        if ((sc->intr[0].resource =
9147             bus_alloc_resource_any(sc->dev,
9148                                    SYS_RES_IRQ,
9149                                    &sc->intr[0].rid,
9150                                    (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9151            BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9152            sc->intr_count = 0;
9153            sc->num_queues = 0;
9154            sc->interrupt_mode = -1; /* Failed! */
9155            break;
9156        }
9157
9158        BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9159    } while (0);
9160
9161    if (sc->interrupt_mode == -1) {
9162        BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9163        rc = 1;
9164    } else {
9165        BLOGD(sc, DBG_LOAD,
9166              "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9167              sc->interrupt_mode, sc->num_queues);
9168        rc = 0;
9169    }
9170
9171    return (rc);
9172}
9173
9174static void
9175bxe_interrupt_detach(struct bxe_softc *sc)
9176{
9177    struct bxe_fastpath *fp;
9178    int i;
9179
9180    /* release interrupt resources */
9181    for (i = 0; i < sc->intr_count; i++) {
9182        if (sc->intr[i].resource && sc->intr[i].tag) {
9183            BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9184            bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9185        }
9186    }
9187
9188    for (i = 0; i < sc->num_queues; i++) {
9189        fp = &sc->fp[i];
9190        if (fp->tq) {
9191            taskqueue_drain(fp->tq, &fp->tq_task);
9192            taskqueue_drain(fp->tq, &fp->tx_task);
9193            while (taskqueue_cancel_timeout(fp->tq, &fp->tx_timeout_task,
9194                NULL))
9195                taskqueue_drain_timeout(fp->tq, &fp->tx_timeout_task);
9196        }
9197
9198        for (i = 0; i < sc->num_queues; i++) {
9199            fp = &sc->fp[i];
9200            if (fp->tq != NULL) {
9201                taskqueue_free(fp->tq);
9202                fp->tq = NULL;
9203            }
9204        }
9205    }
9206
9207    if (sc->sp_tq) {
9208        taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9209        taskqueue_free(sc->sp_tq);
9210        sc->sp_tq = NULL;
9211    }
9212}
9213
9214/*
9215 * Enables interrupts and attach to the ISR.
9216 *
9217 * When using multiple MSI/MSI-X vectors the first vector
9218 * is used for slowpath operations while all remaining
9219 * vectors are used for fastpath operations.  If only a
9220 * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9221 * ISR must look for both slowpath and fastpath completions.
9222 */
9223static int
9224bxe_interrupt_attach(struct bxe_softc *sc)
9225{
9226    struct bxe_fastpath *fp;
9227    int rc = 0;
9228    int i;
9229
9230    snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9231             "bxe%d_sp_tq", sc->unit);
9232    TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9233    sc->sp_tq = taskqueue_create(sc->sp_tq_name, M_NOWAIT,
9234                                 taskqueue_thread_enqueue,
9235                                 &sc->sp_tq);
9236    taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9237                            "%s", sc->sp_tq_name);
9238
9239
9240    for (i = 0; i < sc->num_queues; i++) {
9241        fp = &sc->fp[i];
9242        snprintf(fp->tq_name, sizeof(fp->tq_name),
9243                 "bxe%d_fp%d_tq", sc->unit, i);
9244        TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9245        TASK_INIT(&fp->tx_task, 0, bxe_tx_mq_start_deferred, fp);
9246        fp->tq = taskqueue_create(fp->tq_name, M_NOWAIT,
9247                                  taskqueue_thread_enqueue,
9248                                  &fp->tq);
9249        TIMEOUT_TASK_INIT(fp->tq, &fp->tx_timeout_task, 0,
9250                          bxe_tx_mq_start_deferred, fp);
9251        taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9252                                "%s", fp->tq_name);
9253    }
9254
9255    /* setup interrupt handlers */
9256    if (sc->interrupt_mode == INTR_MODE_MSIX) {
9257        BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9258
9259        /*
9260         * Setup the interrupt handler. Note that we pass the driver instance
9261         * to the interrupt handler for the slowpath.
9262         */
9263        if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9264                                 (INTR_TYPE_NET | INTR_MPSAFE),
9265                                 NULL, bxe_intr_sp, sc,
9266                                 &sc->intr[0].tag)) != 0) {
9267            BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9268            goto bxe_interrupt_attach_exit;
9269        }
9270
9271        bus_describe_intr(sc->dev, sc->intr[0].resource,
9272                          sc->intr[0].tag, "sp");
9273
9274        /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9275
9276        /* initialize the fastpath vectors (note the first was used for sp) */
9277        for (i = 0; i < sc->num_queues; i++) {
9278            fp = &sc->fp[i];
9279            BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9280
9281            /*
9282             * Setup the interrupt handler. Note that we pass the
9283             * fastpath context to the interrupt handler in this
9284             * case.
9285             */
9286            if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9287                                     (INTR_TYPE_NET | INTR_MPSAFE),
9288                                     NULL, bxe_intr_fp, fp,
9289                                     &sc->intr[i + 1].tag)) != 0) {
9290                BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9291                      (i + 1), rc);
9292                goto bxe_interrupt_attach_exit;
9293            }
9294
9295            bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9296                              sc->intr[i + 1].tag, "fp%02d", i);
9297
9298            /* bind the fastpath instance to a cpu */
9299            if (sc->num_queues > 1) {
9300                bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9301            }
9302
9303            fp->state = BXE_FP_STATE_IRQ;
9304        }
9305    } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9306        BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9307
9308        /*
9309         * Setup the interrupt handler. Note that we pass the
9310         * driver instance to the interrupt handler which
9311         * will handle both the slowpath and fastpath.
9312         */
9313        if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9314                                 (INTR_TYPE_NET | INTR_MPSAFE),
9315                                 NULL, bxe_intr_legacy, sc,
9316                                 &sc->intr[0].tag)) != 0) {
9317            BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9318            goto bxe_interrupt_attach_exit;
9319        }
9320
9321    } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9322        BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9323
9324        /*
9325         * Setup the interrupt handler. Note that we pass the
9326         * driver instance to the interrupt handler which
9327         * will handle both the slowpath and fastpath.
9328         */
9329        if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9330                                 (INTR_TYPE_NET | INTR_MPSAFE),
9331                                 NULL, bxe_intr_legacy, sc,
9332                                 &sc->intr[0].tag)) != 0) {
9333            BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9334            goto bxe_interrupt_attach_exit;
9335        }
9336    }
9337
9338bxe_interrupt_attach_exit:
9339
9340    return (rc);
9341}
9342
9343static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9344static int  bxe_init_hw_common(struct bxe_softc *sc);
9345static int  bxe_init_hw_port(struct bxe_softc *sc);
9346static int  bxe_init_hw_func(struct bxe_softc *sc);
9347static void bxe_reset_common(struct bxe_softc *sc);
9348static void bxe_reset_port(struct bxe_softc *sc);
9349static void bxe_reset_func(struct bxe_softc *sc);
9350static int  bxe_gunzip_init(struct bxe_softc *sc);
9351static void bxe_gunzip_end(struct bxe_softc *sc);
9352static int  bxe_init_firmware(struct bxe_softc *sc);
9353static void bxe_release_firmware(struct bxe_softc *sc);
9354
9355static struct
9356ecore_func_sp_drv_ops bxe_func_sp_drv = {
9357    .init_hw_cmn_chip = bxe_init_hw_common_chip,
9358    .init_hw_cmn      = bxe_init_hw_common,
9359    .init_hw_port     = bxe_init_hw_port,
9360    .init_hw_func     = bxe_init_hw_func,
9361
9362    .reset_hw_cmn     = bxe_reset_common,
9363    .reset_hw_port    = bxe_reset_port,
9364    .reset_hw_func    = bxe_reset_func,
9365
9366    .gunzip_init      = bxe_gunzip_init,
9367    .gunzip_end       = bxe_gunzip_end,
9368
9369    .init_fw          = bxe_init_firmware,
9370    .release_fw       = bxe_release_firmware,
9371};
9372
9373static void
9374bxe_init_func_obj(struct bxe_softc *sc)
9375{
9376    sc->dmae_ready = 0;
9377
9378    ecore_init_func_obj(sc,
9379                        &sc->func_obj,
9380                        BXE_SP(sc, func_rdata),
9381                        BXE_SP_MAPPING(sc, func_rdata),
9382                        BXE_SP(sc, func_afex_rdata),
9383                        BXE_SP_MAPPING(sc, func_afex_rdata),
9384                        &bxe_func_sp_drv);
9385}
9386
9387static int
9388bxe_init_hw(struct bxe_softc *sc,
9389            uint32_t         load_code)
9390{
9391    struct ecore_func_state_params func_params = { NULL };
9392    int rc;
9393
9394    /* prepare the parameters for function state transitions */
9395    bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9396
9397    func_params.f_obj = &sc->func_obj;
9398    func_params.cmd = ECORE_F_CMD_HW_INIT;
9399
9400    func_params.params.hw_init.load_phase = load_code;
9401
9402    /*
9403     * Via a plethora of function pointers, we will eventually reach
9404     * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9405     */
9406    rc = ecore_func_state_change(sc, &func_params);
9407
9408    return (rc);
9409}
9410
9411static void
9412bxe_fill(struct bxe_softc *sc,
9413         uint32_t         addr,
9414         int              fill,
9415         uint32_t         len)
9416{
9417    uint32_t i;
9418
9419    if (!(len % 4) && !(addr % 4)) {
9420        for (i = 0; i < len; i += 4) {
9421            REG_WR(sc, (addr + i), fill);
9422        }
9423    } else {
9424        for (i = 0; i < len; i++) {
9425            REG_WR8(sc, (addr + i), fill);
9426        }
9427    }
9428}
9429
9430/* writes FP SP data to FW - data_size in dwords */
9431static void
9432bxe_wr_fp_sb_data(struct bxe_softc *sc,
9433                  int              fw_sb_id,
9434                  uint32_t         *sb_data_p,
9435                  uint32_t         data_size)
9436{
9437    int index;
9438
9439    for (index = 0; index < data_size; index++) {
9440        REG_WR(sc,
9441               (BAR_CSTRORM_INTMEM +
9442                CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9443                (sizeof(uint32_t) * index)),
9444               *(sb_data_p + index));
9445    }
9446}
9447
9448static void
9449bxe_zero_fp_sb(struct bxe_softc *sc,
9450               int              fw_sb_id)
9451{
9452    struct hc_status_block_data_e2 sb_data_e2;
9453    struct hc_status_block_data_e1x sb_data_e1x;
9454    uint32_t *sb_data_p;
9455    uint32_t data_size = 0;
9456
9457    if (!CHIP_IS_E1x(sc)) {
9458        memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9459        sb_data_e2.common.state = SB_DISABLED;
9460        sb_data_e2.common.p_func.vf_valid = FALSE;
9461        sb_data_p = (uint32_t *)&sb_data_e2;
9462        data_size = (sizeof(struct hc_status_block_data_e2) /
9463                     sizeof(uint32_t));
9464    } else {
9465        memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9466        sb_data_e1x.common.state = SB_DISABLED;
9467        sb_data_e1x.common.p_func.vf_valid = FALSE;
9468        sb_data_p = (uint32_t *)&sb_data_e1x;
9469        data_size = (sizeof(struct hc_status_block_data_e1x) /
9470                     sizeof(uint32_t));
9471    }
9472
9473    bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9474
9475    bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9476             0, CSTORM_STATUS_BLOCK_SIZE);
9477    bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9478             0, CSTORM_SYNC_BLOCK_SIZE);
9479}
9480
9481static void
9482bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9483                  struct hc_sp_status_block_data *sp_sb_data)
9484{
9485    int i;
9486
9487    for (i = 0;
9488         i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9489         i++) {
9490        REG_WR(sc,
9491               (BAR_CSTRORM_INTMEM +
9492                CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9493                (i * sizeof(uint32_t))),
9494               *((uint32_t *)sp_sb_data + i));
9495    }
9496}
9497
9498static void
9499bxe_zero_sp_sb(struct bxe_softc *sc)
9500{
9501    struct hc_sp_status_block_data sp_sb_data;
9502
9503    memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9504
9505    sp_sb_data.state           = SB_DISABLED;
9506    sp_sb_data.p_func.vf_valid = FALSE;
9507
9508    bxe_wr_sp_sb_data(sc, &sp_sb_data);
9509
9510    bxe_fill(sc,
9511             (BAR_CSTRORM_INTMEM +
9512              CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9513              0, CSTORM_SP_STATUS_BLOCK_SIZE);
9514    bxe_fill(sc,
9515             (BAR_CSTRORM_INTMEM +
9516              CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9517              0, CSTORM_SP_SYNC_BLOCK_SIZE);
9518}
9519
9520static void
9521bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9522                             int                       igu_sb_id,
9523                             int                       igu_seg_id)
9524{
9525    hc_sm->igu_sb_id      = igu_sb_id;
9526    hc_sm->igu_seg_id     = igu_seg_id;
9527    hc_sm->timer_value    = 0xFF;
9528    hc_sm->time_to_expire = 0xFFFFFFFF;
9529}
9530
9531static void
9532bxe_map_sb_state_machines(struct hc_index_data *index_data)
9533{
9534    /* zero out state machine indices */
9535
9536    /* rx indices */
9537    index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9538
9539    /* tx indices */
9540    index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9541    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9542    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9543    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9544
9545    /* map indices */
9546
9547    /* rx indices */
9548    index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9549        (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9550
9551    /* tx indices */
9552    index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9553        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9554    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9555        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9556    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9557        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9558    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9559        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9560}
9561
9562static void
9563bxe_init_sb(struct bxe_softc *sc,
9564            bus_addr_t       busaddr,
9565            int              vfid,
9566            uint8_t          vf_valid,
9567            int              fw_sb_id,
9568            int              igu_sb_id)
9569{
9570    struct hc_status_block_data_e2  sb_data_e2;
9571    struct hc_status_block_data_e1x sb_data_e1x;
9572    struct hc_status_block_sm       *hc_sm_p;
9573    uint32_t *sb_data_p;
9574    int igu_seg_id;
9575    int data_size;
9576
9577    if (CHIP_INT_MODE_IS_BC(sc)) {
9578        igu_seg_id = HC_SEG_ACCESS_NORM;
9579    } else {
9580        igu_seg_id = IGU_SEG_ACCESS_NORM;
9581    }
9582
9583    bxe_zero_fp_sb(sc, fw_sb_id);
9584
9585    if (!CHIP_IS_E1x(sc)) {
9586        memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9587        sb_data_e2.common.state = SB_ENABLED;
9588        sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9589        sb_data_e2.common.p_func.vf_id = vfid;
9590        sb_data_e2.common.p_func.vf_valid = vf_valid;
9591        sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9592        sb_data_e2.common.same_igu_sb_1b = TRUE;
9593        sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9594        sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9595        hc_sm_p = sb_data_e2.common.state_machine;
9596        sb_data_p = (uint32_t *)&sb_data_e2;
9597        data_size = (sizeof(struct hc_status_block_data_e2) /
9598                     sizeof(uint32_t));
9599        bxe_map_sb_state_machines(sb_data_e2.index_data);
9600    } else {
9601        memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9602        sb_data_e1x.common.state = SB_ENABLED;
9603        sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9604        sb_data_e1x.common.p_func.vf_id = 0xff;
9605        sb_data_e1x.common.p_func.vf_valid = FALSE;
9606        sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9607        sb_data_e1x.common.same_igu_sb_1b = TRUE;
9608        sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9609        sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9610        hc_sm_p = sb_data_e1x.common.state_machine;
9611        sb_data_p = (uint32_t *)&sb_data_e1x;
9612        data_size = (sizeof(struct hc_status_block_data_e1x) /
9613                     sizeof(uint32_t));
9614        bxe_map_sb_state_machines(sb_data_e1x.index_data);
9615    }
9616
9617    bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9618    bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9619
9620    BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9621
9622    /* write indices to HW - PCI guarantees endianity of regpairs */
9623    bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9624}
9625
9626static inline uint8_t
9627bxe_fp_qzone_id(struct bxe_fastpath *fp)
9628{
9629    if (CHIP_IS_E1x(fp->sc)) {
9630        return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9631    } else {
9632        return (fp->cl_id);
9633    }
9634}
9635
9636static inline uint32_t
9637bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9638                           struct bxe_fastpath *fp)
9639{
9640    uint32_t offset = BAR_USTRORM_INTMEM;
9641
9642    if (!CHIP_IS_E1x(sc)) {
9643        offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9644    } else {
9645        offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9646    }
9647
9648    return (offset);
9649}
9650
9651static void
9652bxe_init_eth_fp(struct bxe_softc *sc,
9653                int              idx)
9654{
9655    struct bxe_fastpath *fp = &sc->fp[idx];
9656    uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9657    unsigned long q_type = 0;
9658    int cos;
9659
9660    fp->sc    = sc;
9661    fp->index = idx;
9662
9663    fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9664    fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9665
9666    fp->cl_id = (CHIP_IS_E1x(sc)) ?
9667                    (SC_L_ID(sc) + idx) :
9668                    /* want client ID same as IGU SB ID for non-E1 */
9669                    fp->igu_sb_id;
9670    fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9671
9672    /* setup sb indices */
9673    if (!CHIP_IS_E1x(sc)) {
9674        fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9675        fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9676    } else {
9677        fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9678        fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9679    }
9680
9681    /* init shortcut */
9682    fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9683
9684    fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9685
9686    /*
9687     * XXX If multiple CoS is ever supported then each fastpath structure
9688     * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9689     */
9690    for (cos = 0; cos < sc->max_cos; cos++) {
9691        cids[cos] = idx;
9692    }
9693    fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9694
9695    /* nothing more for a VF to do */
9696    if (IS_VF(sc)) {
9697        return;
9698    }
9699
9700    bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9701                fp->fw_sb_id, fp->igu_sb_id);
9702
9703    bxe_update_fp_sb_idx(fp);
9704
9705    /* Configure Queue State object */
9706    bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9707    bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9708
9709    ecore_init_queue_obj(sc,
9710                         &sc->sp_objs[idx].q_obj,
9711                         fp->cl_id,
9712                         cids,
9713                         sc->max_cos,
9714                         SC_FUNC(sc),
9715                         BXE_SP(sc, q_rdata),
9716                         BXE_SP_MAPPING(sc, q_rdata),
9717                         q_type);
9718
9719    /* configure classification DBs */
9720    ecore_init_mac_obj(sc,
9721                       &sc->sp_objs[idx].mac_obj,
9722                       fp->cl_id,
9723                       idx,
9724                       SC_FUNC(sc),
9725                       BXE_SP(sc, mac_rdata),
9726                       BXE_SP_MAPPING(sc, mac_rdata),
9727                       ECORE_FILTER_MAC_PENDING,
9728                       &sc->sp_state,
9729                       ECORE_OBJ_TYPE_RX_TX,
9730                       &sc->macs_pool);
9731
9732    BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9733          idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9734}
9735
9736static inline void
9737bxe_update_rx_prod(struct bxe_softc    *sc,
9738                   struct bxe_fastpath *fp,
9739                   uint16_t            rx_bd_prod,
9740                   uint16_t            rx_cq_prod,
9741                   uint16_t            rx_sge_prod)
9742{
9743    struct ustorm_eth_rx_producers rx_prods = { 0 };
9744    uint32_t i;
9745
9746    /* update producers */
9747    rx_prods.bd_prod  = rx_bd_prod;
9748    rx_prods.cqe_prod = rx_cq_prod;
9749    rx_prods.sge_prod = rx_sge_prod;
9750
9751    /*
9752     * Make sure that the BD and SGE data is updated before updating the
9753     * producers since FW might read the BD/SGE right after the producer
9754     * is updated.
9755     * This is only applicable for weak-ordered memory model archs such
9756     * as IA-64. The following barrier is also mandatory since FW will
9757     * assumes BDs must have buffers.
9758     */
9759    wmb();
9760
9761    for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9762        REG_WR(sc,
9763               (fp->ustorm_rx_prods_offset + (i * 4)),
9764               ((uint32_t *)&rx_prods)[i]);
9765    }
9766
9767    wmb(); /* keep prod updates ordered */
9768
9769    BLOGD(sc, DBG_RX,
9770          "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9771          fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9772}
9773
9774static void
9775bxe_init_rx_rings(struct bxe_softc *sc)
9776{
9777    struct bxe_fastpath *fp;
9778    int i;
9779
9780    for (i = 0; i < sc->num_queues; i++) {
9781        fp = &sc->fp[i];
9782
9783        fp->rx_bd_cons = 0;
9784
9785        /*
9786         * Activate the BD ring...
9787         * Warning, this will generate an interrupt (to the TSTORM)
9788         * so this can only be done after the chip is initialized
9789         */
9790        bxe_update_rx_prod(sc, fp,
9791                           fp->rx_bd_prod,
9792                           fp->rx_cq_prod,
9793                           fp->rx_sge_prod);
9794
9795        if (i != 0) {
9796            continue;
9797        }
9798
9799        if (CHIP_IS_E1(sc)) {
9800            REG_WR(sc,
9801                   (BAR_USTRORM_INTMEM +
9802                    USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9803                   U64_LO(fp->rcq_dma.paddr));
9804            REG_WR(sc,
9805                   (BAR_USTRORM_INTMEM +
9806                    USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9807                   U64_HI(fp->rcq_dma.paddr));
9808        }
9809    }
9810}
9811
9812static void
9813bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9814{
9815    SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9816    fp->tx_db.data.zero_fill1 = 0;
9817    fp->tx_db.data.prod = 0;
9818
9819    fp->tx_pkt_prod = 0;
9820    fp->tx_pkt_cons = 0;
9821    fp->tx_bd_prod = 0;
9822    fp->tx_bd_cons = 0;
9823    fp->eth_q_stats.tx_pkts = 0;
9824}
9825
9826static inline void
9827bxe_init_tx_rings(struct bxe_softc *sc)
9828{
9829    int i;
9830
9831    for (i = 0; i < sc->num_queues; i++) {
9832        bxe_init_tx_ring_one(&sc->fp[i]);
9833    }
9834}
9835
9836static void
9837bxe_init_def_sb(struct bxe_softc *sc)
9838{
9839    struct host_sp_status_block *def_sb = sc->def_sb;
9840    bus_addr_t mapping = sc->def_sb_dma.paddr;
9841    int igu_sp_sb_index;
9842    int igu_seg_id;
9843    int port = SC_PORT(sc);
9844    int func = SC_FUNC(sc);
9845    int reg_offset, reg_offset_en5;
9846    uint64_t section;
9847    int index, sindex;
9848    struct hc_sp_status_block_data sp_sb_data;
9849
9850    memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9851
9852    if (CHIP_INT_MODE_IS_BC(sc)) {
9853        igu_sp_sb_index = DEF_SB_IGU_ID;
9854        igu_seg_id = HC_SEG_ACCESS_DEF;
9855    } else {
9856        igu_sp_sb_index = sc->igu_dsb_id;
9857        igu_seg_id = IGU_SEG_ACCESS_DEF;
9858    }
9859
9860    /* attentions */
9861    section = ((uint64_t)mapping +
9862               offsetof(struct host_sp_status_block, atten_status_block));
9863    def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9864    sc->attn_state = 0;
9865
9866    reg_offset = (port) ?
9867                     MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9868                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9869    reg_offset_en5 = (port) ?
9870                         MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9871                         MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9872
9873    for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9874        /* take care of sig[0]..sig[4] */
9875        for (sindex = 0; sindex < 4; sindex++) {
9876            sc->attn_group[index].sig[sindex] =
9877                REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9878        }
9879
9880        if (!CHIP_IS_E1x(sc)) {
9881            /*
9882             * enable5 is separate from the rest of the registers,
9883             * and the address skip is 4 and not 16 between the
9884             * different groups
9885             */
9886            sc->attn_group[index].sig[4] =
9887                REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9888        } else {
9889            sc->attn_group[index].sig[4] = 0;
9890        }
9891    }
9892
9893    if (sc->devinfo.int_block == INT_BLOCK_HC) {
9894        reg_offset = (port) ?
9895                         HC_REG_ATTN_MSG1_ADDR_L :
9896                         HC_REG_ATTN_MSG0_ADDR_L;
9897        REG_WR(sc, reg_offset, U64_LO(section));
9898        REG_WR(sc, (reg_offset + 4), U64_HI(section));
9899    } else if (!CHIP_IS_E1x(sc)) {
9900        REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9901        REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9902    }
9903
9904    section = ((uint64_t)mapping +
9905               offsetof(struct host_sp_status_block, sp_sb));
9906
9907    bxe_zero_sp_sb(sc);
9908
9909    /* PCI guarantees endianity of regpair */
9910    sp_sb_data.state           = SB_ENABLED;
9911    sp_sb_data.host_sb_addr.lo = U64_LO(section);
9912    sp_sb_data.host_sb_addr.hi = U64_HI(section);
9913    sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9914    sp_sb_data.igu_seg_id      = igu_seg_id;
9915    sp_sb_data.p_func.pf_id    = func;
9916    sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9917    sp_sb_data.p_func.vf_id    = 0xff;
9918
9919    bxe_wr_sp_sb_data(sc, &sp_sb_data);
9920
9921    bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9922}
9923
9924static void
9925bxe_init_sp_ring(struct bxe_softc *sc)
9926{
9927    atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9928    sc->spq_prod_idx = 0;
9929    sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9930    sc->spq_prod_bd = sc->spq;
9931    sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9932}
9933
9934static void
9935bxe_init_eq_ring(struct bxe_softc *sc)
9936{
9937    union event_ring_elem *elem;
9938    int i;
9939
9940    for (i = 1; i <= NUM_EQ_PAGES; i++) {
9941        elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9942
9943        elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9944                                                 BCM_PAGE_SIZE *
9945                                                 (i % NUM_EQ_PAGES)));
9946        elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9947                                                 BCM_PAGE_SIZE *
9948                                                 (i % NUM_EQ_PAGES)));
9949    }
9950
9951    sc->eq_cons    = 0;
9952    sc->eq_prod    = NUM_EQ_DESC;
9953    sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9954
9955    atomic_store_rel_long(&sc->eq_spq_left,
9956                          (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9957                               NUM_EQ_DESC) - 1));
9958}
9959
9960static void
9961bxe_init_internal_common(struct bxe_softc *sc)
9962{
9963    int i;
9964
9965    /*
9966     * Zero this manually as its initialization is currently missing
9967     * in the initTool.
9968     */
9969    for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9970        REG_WR(sc,
9971               (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9972               0);
9973    }
9974
9975    if (!CHIP_IS_E1x(sc)) {
9976        REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9977                CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9978    }
9979}
9980
9981static void
9982bxe_init_internal(struct bxe_softc *sc,
9983                  uint32_t         load_code)
9984{
9985    switch (load_code) {
9986    case FW_MSG_CODE_DRV_LOAD_COMMON:
9987    case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9988        bxe_init_internal_common(sc);
9989        /* no break */
9990
9991    case FW_MSG_CODE_DRV_LOAD_PORT:
9992        /* nothing to do */
9993        /* no break */
9994
9995    case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9996        /* internal memory per function is initialized inside bxe_pf_init */
9997        break;
9998
9999    default:
10000        BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
10001        break;
10002    }
10003}
10004
10005static void
10006storm_memset_func_cfg(struct bxe_softc                         *sc,
10007                      struct tstorm_eth_function_common_config *tcfg,
10008                      uint16_t                                  abs_fid)
10009{
10010    uint32_t addr;
10011    size_t size;
10012
10013    addr = (BAR_TSTRORM_INTMEM +
10014            TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
10015    size = sizeof(struct tstorm_eth_function_common_config);
10016    ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
10017}
10018
10019static void
10020bxe_func_init(struct bxe_softc            *sc,
10021              struct bxe_func_init_params *p)
10022{
10023    struct tstorm_eth_function_common_config tcfg = { 0 };
10024
10025    if (CHIP_IS_E1x(sc)) {
10026        storm_memset_func_cfg(sc, &tcfg, p->func_id);
10027    }
10028
10029    /* Enable the function in the FW */
10030    storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
10031    storm_memset_func_en(sc, p->func_id, 1);
10032
10033    /* spq */
10034    if (p->func_flgs & FUNC_FLG_SPQ) {
10035        storm_memset_spq_addr(sc, p->spq_map, p->func_id);
10036        REG_WR(sc,
10037               (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
10038               p->spq_prod);
10039    }
10040}
10041
10042/*
10043 * Calculates the sum of vn_min_rates.
10044 * It's needed for further normalizing of the min_rates.
10045 * Returns:
10046 *   sum of vn_min_rates.
10047 *     or
10048 *   0 - if all the min_rates are 0.
10049 * In the later case fainess algorithm should be deactivated.
10050 * If all min rates are not zero then those that are zeroes will be set to 1.
10051 */
10052static void
10053bxe_calc_vn_min(struct bxe_softc       *sc,
10054                struct cmng_init_input *input)
10055{
10056    uint32_t vn_cfg;
10057    uint32_t vn_min_rate;
10058    int all_zero = 1;
10059    int vn;
10060
10061    for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10062        vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10063        vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
10064                        FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
10065
10066        if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10067            /* skip hidden VNs */
10068            vn_min_rate = 0;
10069        } else if (!vn_min_rate) {
10070            /* If min rate is zero - set it to 100 */
10071            vn_min_rate = DEF_MIN_RATE;
10072        } else {
10073            all_zero = 0;
10074        }
10075
10076        input->vnic_min_rate[vn] = vn_min_rate;
10077    }
10078
10079    /* if ETS or all min rates are zeros - disable fairness */
10080    if (BXE_IS_ETS_ENABLED(sc)) {
10081        input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10082        BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10083    } else if (all_zero) {
10084        input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10085        BLOGD(sc, DBG_LOAD,
10086              "Fariness disabled (all MIN values are zeroes)\n");
10087    } else {
10088        input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10089    }
10090}
10091
10092static inline uint16_t
10093bxe_extract_max_cfg(struct bxe_softc *sc,
10094                    uint32_t         mf_cfg)
10095{
10096    uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10097                        FUNC_MF_CFG_MAX_BW_SHIFT);
10098
10099    if (!max_cfg) {
10100        BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10101        max_cfg = 100;
10102    }
10103
10104    return (max_cfg);
10105}
10106
10107static void
10108bxe_calc_vn_max(struct bxe_softc       *sc,
10109                int                    vn,
10110                struct cmng_init_input *input)
10111{
10112    uint16_t vn_max_rate;
10113    uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10114    uint32_t max_cfg;
10115
10116    if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10117        vn_max_rate = 0;
10118    } else {
10119        max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10120
10121        if (IS_MF_SI(sc)) {
10122            /* max_cfg in percents of linkspeed */
10123            vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10124        } else { /* SD modes */
10125            /* max_cfg is absolute in 100Mb units */
10126            vn_max_rate = (max_cfg * 100);
10127        }
10128    }
10129
10130    BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10131
10132    input->vnic_max_rate[vn] = vn_max_rate;
10133}
10134
10135static void
10136bxe_cmng_fns_init(struct bxe_softc *sc,
10137                  uint8_t          read_cfg,
10138                  uint8_t          cmng_type)
10139{
10140    struct cmng_init_input input;
10141    int vn;
10142
10143    memset(&input, 0, sizeof(struct cmng_init_input));
10144
10145    input.port_rate = sc->link_vars.line_speed;
10146
10147    if (cmng_type == CMNG_FNS_MINMAX) {
10148        /* read mf conf from shmem */
10149        if (read_cfg) {
10150            bxe_read_mf_cfg(sc);
10151        }
10152
10153        /* get VN min rate and enable fairness if not 0 */
10154        bxe_calc_vn_min(sc, &input);
10155
10156        /* get VN max rate */
10157        if (sc->port.pmf) {
10158            for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10159                bxe_calc_vn_max(sc, vn, &input);
10160            }
10161        }
10162
10163        /* always enable rate shaping and fairness */
10164        input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10165
10166        ecore_init_cmng(&input, &sc->cmng);
10167        return;
10168    }
10169
10170    /* rate shaping and fairness are disabled */
10171    BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10172}
10173
10174static int
10175bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10176{
10177    if (CHIP_REV_IS_SLOW(sc)) {
10178        return (CMNG_FNS_NONE);
10179    }
10180
10181    if (IS_MF(sc)) {
10182        return (CMNG_FNS_MINMAX);
10183    }
10184
10185    return (CMNG_FNS_NONE);
10186}
10187
10188static void
10189storm_memset_cmng(struct bxe_softc *sc,
10190                  struct cmng_init *cmng,
10191                  uint8_t          port)
10192{
10193    int vn;
10194    int func;
10195    uint32_t addr;
10196    size_t size;
10197
10198    addr = (BAR_XSTRORM_INTMEM +
10199            XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10200    size = sizeof(struct cmng_struct_per_port);
10201    ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10202
10203    for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10204        func = func_by_vn(sc, vn);
10205
10206        addr = (BAR_XSTRORM_INTMEM +
10207                XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10208        size = sizeof(struct rate_shaping_vars_per_vn);
10209        ecore_storm_memset_struct(sc, addr, size,
10210                                  (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10211
10212        addr = (BAR_XSTRORM_INTMEM +
10213                XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10214        size = sizeof(struct fairness_vars_per_vn);
10215        ecore_storm_memset_struct(sc, addr, size,
10216                                  (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10217    }
10218}
10219
10220static void
10221bxe_pf_init(struct bxe_softc *sc)
10222{
10223    struct bxe_func_init_params func_init = { 0 };
10224    struct event_ring_data eq_data = { { 0 } };
10225    uint16_t flags;
10226
10227    if (!CHIP_IS_E1x(sc)) {
10228        /* reset IGU PF statistics: MSIX + ATTN */
10229        /* PF */
10230        REG_WR(sc,
10231               (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10232                (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10233                ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10234               0);
10235        /* ATTN */
10236        REG_WR(sc,
10237               (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10238                (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10239                (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10240                ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10241               0);
10242    }
10243
10244    /* function setup flags */
10245    flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10246
10247    /*
10248     * This flag is relevant for E1x only.
10249     * E2 doesn't have a TPA configuration in a function level.
10250     */
10251    flags |= (if_getcapenable(sc->ifp) & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10252
10253    func_init.func_flgs = flags;
10254    func_init.pf_id     = SC_FUNC(sc);
10255    func_init.func_id   = SC_FUNC(sc);
10256    func_init.spq_map   = sc->spq_dma.paddr;
10257    func_init.spq_prod  = sc->spq_prod_idx;
10258
10259    bxe_func_init(sc, &func_init);
10260
10261    memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10262
10263    /*
10264     * Congestion management values depend on the link rate.
10265     * There is no active link so initial link rate is set to 10Gbps.
10266     * When the link comes up the congestion management values are
10267     * re-calculated according to the actual link rate.
10268     */
10269    sc->link_vars.line_speed = SPEED_10000;
10270    bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10271
10272    /* Only the PMF sets the HW */
10273    if (sc->port.pmf) {
10274        storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10275    }
10276
10277    /* init Event Queue - PCI bus guarantees correct endainity */
10278    eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10279    eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10280    eq_data.producer     = sc->eq_prod;
10281    eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10282    eq_data.sb_id        = DEF_SB_ID;
10283    storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10284}
10285
10286static void
10287bxe_hc_int_enable(struct bxe_softc *sc)
10288{
10289    int port = SC_PORT(sc);
10290    uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10291    uint32_t val = REG_RD(sc, addr);
10292    uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10293    uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10294                           (sc->intr_count == 1)) ? TRUE : FALSE;
10295    uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10296
10297    if (msix) {
10298        val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10299                 HC_CONFIG_0_REG_INT_LINE_EN_0);
10300        val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10301                HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10302        if (single_msix) {
10303            val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10304        }
10305    } else if (msi) {
10306        val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10307        val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10308                HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10309                HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10310    } else {
10311        val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10312                HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10313                HC_CONFIG_0_REG_INT_LINE_EN_0 |
10314                HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10315
10316        if (!CHIP_IS_E1(sc)) {
10317            BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10318                  val, port, addr);
10319
10320            REG_WR(sc, addr, val);
10321
10322            val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10323        }
10324    }
10325
10326    if (CHIP_IS_E1(sc)) {
10327        REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10328    }
10329
10330    BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10331          val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10332
10333    REG_WR(sc, addr, val);
10334
10335    /* ensure that HC_CONFIG is written before leading/trailing edge config */
10336    mb();
10337
10338    if (!CHIP_IS_E1(sc)) {
10339        /* init leading/trailing edge */
10340        if (IS_MF(sc)) {
10341            val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10342            if (sc->port.pmf) {
10343                /* enable nig and gpio3 attention */
10344                val |= 0x1100;
10345            }
10346        } else {
10347            val = 0xffff;
10348        }
10349
10350        REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10351        REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10352    }
10353
10354    /* make sure that interrupts are indeed enabled from here on */
10355    mb();
10356}
10357
10358static void
10359bxe_igu_int_enable(struct bxe_softc *sc)
10360{
10361    uint32_t val;
10362    uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10363    uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10364                           (sc->intr_count == 1)) ? TRUE : FALSE;
10365    uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10366
10367    val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10368
10369    if (msix) {
10370        val &= ~(IGU_PF_CONF_INT_LINE_EN |
10371                 IGU_PF_CONF_SINGLE_ISR_EN);
10372        val |= (IGU_PF_CONF_MSI_MSIX_EN |
10373                IGU_PF_CONF_ATTN_BIT_EN);
10374        if (single_msix) {
10375            val |= IGU_PF_CONF_SINGLE_ISR_EN;
10376        }
10377    } else if (msi) {
10378        val &= ~IGU_PF_CONF_INT_LINE_EN;
10379        val |= (IGU_PF_CONF_MSI_MSIX_EN |
10380                IGU_PF_CONF_ATTN_BIT_EN |
10381                IGU_PF_CONF_SINGLE_ISR_EN);
10382    } else {
10383        val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10384        val |= (IGU_PF_CONF_INT_LINE_EN |
10385                IGU_PF_CONF_ATTN_BIT_EN |
10386                IGU_PF_CONF_SINGLE_ISR_EN);
10387    }
10388
10389    /* clean previous status - need to configure igu prior to ack*/
10390    if ((!msix) || single_msix) {
10391        REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10392        bxe_ack_int(sc);
10393    }
10394
10395    val |= IGU_PF_CONF_FUNC_EN;
10396
10397    BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10398          val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10399
10400    REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10401
10402    mb();
10403
10404    /* init leading/trailing edge */
10405    if (IS_MF(sc)) {
10406        val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10407        if (sc->port.pmf) {
10408            /* enable nig and gpio3 attention */
10409            val |= 0x1100;
10410        }
10411    } else {
10412        val = 0xffff;
10413    }
10414
10415    REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10416    REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10417
10418    /* make sure that interrupts are indeed enabled from here on */
10419    mb();
10420}
10421
10422static void
10423bxe_int_enable(struct bxe_softc *sc)
10424{
10425    if (sc->devinfo.int_block == INT_BLOCK_HC) {
10426        bxe_hc_int_enable(sc);
10427    } else {
10428        bxe_igu_int_enable(sc);
10429    }
10430}
10431
10432static void
10433bxe_hc_int_disable(struct bxe_softc *sc)
10434{
10435    int port = SC_PORT(sc);
10436    uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10437    uint32_t val = REG_RD(sc, addr);
10438
10439    /*
10440     * In E1 we must use only PCI configuration space to disable MSI/MSIX
10441     * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10442     * block
10443     */
10444    if (CHIP_IS_E1(sc)) {
10445        /*
10446         * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10447         * to prevent from HC sending interrupts after we exit the function
10448         */
10449        REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10450
10451        val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10452                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10453                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10454    } else {
10455        val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10456                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10457                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10458                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10459    }
10460
10461    BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10462
10463    /* flush all outstanding writes */
10464    mb();
10465
10466    REG_WR(sc, addr, val);
10467    if (REG_RD(sc, addr) != val) {
10468        BLOGE(sc, "proper val not read from HC IGU!\n");
10469    }
10470}
10471
10472static void
10473bxe_igu_int_disable(struct bxe_softc *sc)
10474{
10475    uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10476
10477    val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10478             IGU_PF_CONF_INT_LINE_EN |
10479             IGU_PF_CONF_ATTN_BIT_EN);
10480
10481    BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10482
10483    /* flush all outstanding writes */
10484    mb();
10485
10486    REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10487    if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10488        BLOGE(sc, "proper val not read from IGU!\n");
10489    }
10490}
10491
10492static void
10493bxe_int_disable(struct bxe_softc *sc)
10494{
10495    if (sc->devinfo.int_block == INT_BLOCK_HC) {
10496        bxe_hc_int_disable(sc);
10497    } else {
10498        bxe_igu_int_disable(sc);
10499    }
10500}
10501
10502static void
10503bxe_nic_init(struct bxe_softc *sc,
10504             int              load_code)
10505{
10506    int i;
10507
10508    for (i = 0; i < sc->num_queues; i++) {
10509        bxe_init_eth_fp(sc, i);
10510    }
10511
10512    rmb(); /* ensure status block indices were read */
10513
10514    bxe_init_rx_rings(sc);
10515    bxe_init_tx_rings(sc);
10516
10517    if (IS_VF(sc)) {
10518        return;
10519    }
10520
10521    /* initialize MOD_ABS interrupts */
10522    elink_init_mod_abs_int(sc, &sc->link_vars,
10523                           sc->devinfo.chip_id,
10524                           sc->devinfo.shmem_base,
10525                           sc->devinfo.shmem2_base,
10526                           SC_PORT(sc));
10527
10528    bxe_init_def_sb(sc);
10529    bxe_update_dsb_idx(sc);
10530    bxe_init_sp_ring(sc);
10531    bxe_init_eq_ring(sc);
10532    bxe_init_internal(sc, load_code);
10533    bxe_pf_init(sc);
10534    bxe_stats_init(sc);
10535
10536    /* flush all before enabling interrupts */
10537    mb();
10538
10539    bxe_int_enable(sc);
10540
10541    /* check for SPIO5 */
10542    bxe_attn_int_deasserted0(sc,
10543                             REG_RD(sc,
10544                                    (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10545                                     SC_PORT(sc)*4)) &
10546                             AEU_INPUTS_ATTN_BITS_SPIO5);
10547}
10548
10549static inline void
10550bxe_init_objs(struct bxe_softc *sc)
10551{
10552    /* mcast rules must be added to tx if tx switching is enabled */
10553    ecore_obj_type o_type =
10554        (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10555                                         ECORE_OBJ_TYPE_RX;
10556
10557    /* RX_MODE controlling object */
10558    ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10559
10560    /* multicast configuration controlling object */
10561    ecore_init_mcast_obj(sc,
10562                         &sc->mcast_obj,
10563                         sc->fp[0].cl_id,
10564                         sc->fp[0].index,
10565                         SC_FUNC(sc),
10566                         SC_FUNC(sc),
10567                         BXE_SP(sc, mcast_rdata),
10568                         BXE_SP_MAPPING(sc, mcast_rdata),
10569                         ECORE_FILTER_MCAST_PENDING,
10570                         &sc->sp_state,
10571                         o_type);
10572
10573    /* Setup CAM credit pools */
10574    ecore_init_mac_credit_pool(sc,
10575                               &sc->macs_pool,
10576                               SC_FUNC(sc),
10577                               CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10578                                                 VNICS_PER_PATH(sc));
10579
10580    ecore_init_vlan_credit_pool(sc,
10581                                &sc->vlans_pool,
10582                                SC_ABS_FUNC(sc) >> 1,
10583                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10584                                                  VNICS_PER_PATH(sc));
10585
10586    /* RSS configuration object */
10587    ecore_init_rss_config_obj(sc,
10588                              &sc->rss_conf_obj,
10589                              sc->fp[0].cl_id,
10590                              sc->fp[0].index,
10591                              SC_FUNC(sc),
10592                              SC_FUNC(sc),
10593                              BXE_SP(sc, rss_rdata),
10594                              BXE_SP_MAPPING(sc, rss_rdata),
10595                              ECORE_FILTER_RSS_CONF_PENDING,
10596                              &sc->sp_state, ECORE_OBJ_TYPE_RX);
10597}
10598
10599/*
10600 * Initialize the function. This must be called before sending CLIENT_SETUP
10601 * for the first client.
10602 */
10603static inline int
10604bxe_func_start(struct bxe_softc *sc)
10605{
10606    struct ecore_func_state_params func_params = { NULL };
10607    struct ecore_func_start_params *start_params = &func_params.params.start;
10608
10609    /* Prepare parameters for function state transitions */
10610    bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10611
10612    func_params.f_obj = &sc->func_obj;
10613    func_params.cmd = ECORE_F_CMD_START;
10614
10615    /* Function parameters */
10616    start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10617    start_params->sd_vlan_tag = OVLAN(sc);
10618
10619    if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10620        start_params->network_cos_mode = STATIC_COS;
10621    } else { /* CHIP_IS_E1X */
10622        start_params->network_cos_mode = FW_WRR;
10623    }
10624
10625    //start_params->gre_tunnel_mode = 0;
10626    //start_params->gre_tunnel_rss  = 0;
10627
10628    return (ecore_func_state_change(sc, &func_params));
10629}
10630
10631static int
10632bxe_set_power_state(struct bxe_softc *sc,
10633                    uint8_t          state)
10634{
10635    uint16_t pmcsr;
10636
10637    /* If there is no power capability, silently succeed */
10638    if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10639        BLOGW(sc, "No power capability\n");
10640        return (0);
10641    }
10642
10643    pmcsr = pci_read_config(sc->dev,
10644                            (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10645                            2);
10646
10647    switch (state) {
10648    case PCI_PM_D0:
10649        pci_write_config(sc->dev,
10650                         (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10651                         ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10652
10653        if (pmcsr & PCIM_PSTAT_DMASK) {
10654            /* delay required during transition out of D3hot */
10655            DELAY(20000);
10656        }
10657
10658        break;
10659
10660    case PCI_PM_D3hot:
10661        /* XXX if there are other clients above don't shut down the power */
10662
10663        /* don't shut down the power for emulation and FPGA */
10664        if (CHIP_REV_IS_SLOW(sc)) {
10665            return (0);
10666        }
10667
10668        pmcsr &= ~PCIM_PSTAT_DMASK;
10669        pmcsr |= PCIM_PSTAT_D3;
10670
10671        if (sc->wol) {
10672            pmcsr |= PCIM_PSTAT_PMEENABLE;
10673        }
10674
10675        pci_write_config(sc->dev,
10676                         (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10677                         pmcsr, 4);
10678
10679        /*
10680         * No more memory access after this point until device is brought back
10681         * to D0 state.
10682         */
10683        break;
10684
10685    default:
10686        BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10687            state, pmcsr);
10688        return (-1);
10689    }
10690
10691    return (0);
10692}
10693
10694
10695/* return true if succeeded to acquire the lock */
10696static uint8_t
10697bxe_trylock_hw_lock(struct bxe_softc *sc,
10698                    uint32_t         resource)
10699{
10700    uint32_t lock_status;
10701    uint32_t resource_bit = (1 << resource);
10702    int func = SC_FUNC(sc);
10703    uint32_t hw_lock_control_reg;
10704
10705    BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10706
10707    /* Validating that the resource is within range */
10708    if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10709        BLOGD(sc, DBG_LOAD,
10710              "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10711              resource, HW_LOCK_MAX_RESOURCE_VALUE);
10712        return (FALSE);
10713    }
10714
10715    if (func <= 5) {
10716        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10717    } else {
10718        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10719    }
10720
10721    /* try to acquire the lock */
10722    REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10723    lock_status = REG_RD(sc, hw_lock_control_reg);
10724    if (lock_status & resource_bit) {
10725        return (TRUE);
10726    }
10727
10728    BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10729        "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10730        lock_status, resource_bit);
10731
10732    return (FALSE);
10733}
10734
10735/*
10736 * Get the recovery leader resource id according to the engine this function
10737 * belongs to. Currently only only 2 engines is supported.
10738 */
10739static int
10740bxe_get_leader_lock_resource(struct bxe_softc *sc)
10741{
10742    if (SC_PATH(sc)) {
10743        return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10744    } else {
10745        return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10746    }
10747}
10748
10749/* try to acquire a leader lock for current engine */
10750static uint8_t
10751bxe_trylock_leader_lock(struct bxe_softc *sc)
10752{
10753    return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10754}
10755
10756static int
10757bxe_release_leader_lock(struct bxe_softc *sc)
10758{
10759    return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10760}
10761
10762/* close gates #2, #3 and #4 */
10763static void
10764bxe_set_234_gates(struct bxe_softc *sc,
10765                  uint8_t          close)
10766{
10767    uint32_t val;
10768
10769    /* gates #2 and #4a are closed/opened for "not E1" only */
10770    if (!CHIP_IS_E1(sc)) {
10771        /* #4 */
10772        REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10773        /* #2 */
10774        REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10775    }
10776
10777    /* #3 */
10778    if (CHIP_IS_E1x(sc)) {
10779        /* prevent interrupts from HC on both ports */
10780        val = REG_RD(sc, HC_REG_CONFIG_1);
10781        REG_WR(sc, HC_REG_CONFIG_1,
10782               (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10783               (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10784
10785        val = REG_RD(sc, HC_REG_CONFIG_0);
10786        REG_WR(sc, HC_REG_CONFIG_0,
10787               (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10788               (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10789    } else {
10790        /* Prevent incoming interrupts in IGU */
10791        val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10792
10793        REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10794               (!close) ?
10795               (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10796               (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10797    }
10798
10799    BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10800          close ? "closing" : "opening");
10801
10802    wmb();
10803}
10804
10805/* poll for pending writes bit, it should get cleared in no more than 1s */
10806static int
10807bxe_er_poll_igu_vq(struct bxe_softc *sc)
10808{
10809    uint32_t cnt = 1000;
10810    uint32_t pend_bits = 0;
10811
10812    do {
10813        pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10814
10815        if (pend_bits == 0) {
10816            break;
10817        }
10818
10819        DELAY(1000);
10820    } while (--cnt > 0);
10821
10822    if (cnt == 0) {
10823        BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10824        return (-1);
10825    }
10826
10827    return (0);
10828}
10829
10830#define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10831
10832static void
10833bxe_clp_reset_prep(struct bxe_softc *sc,
10834                   uint32_t         *magic_val)
10835{
10836    /* Do some magic... */
10837    uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10838    *magic_val = val & SHARED_MF_CLP_MAGIC;
10839    MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10840}
10841
10842/* restore the value of the 'magic' bit */
10843static void
10844bxe_clp_reset_done(struct bxe_softc *sc,
10845                   uint32_t         magic_val)
10846{
10847    /* Restore the 'magic' bit value... */
10848    uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10849    MFCFG_WR(sc, shared_mf_config.clp_mb,
10850              (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10851}
10852
10853/* prepare for MCP reset, takes care of CLP configurations */
10854static void
10855bxe_reset_mcp_prep(struct bxe_softc *sc,
10856                   uint32_t         *magic_val)
10857{
10858    uint32_t shmem;
10859    uint32_t validity_offset;
10860
10861    /* set `magic' bit in order to save MF config */
10862    if (!CHIP_IS_E1(sc)) {
10863        bxe_clp_reset_prep(sc, magic_val);
10864    }
10865
10866    /* get shmem offset */
10867    shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10868    validity_offset =
10869        offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10870
10871    /* Clear validity map flags */
10872    if (shmem > 0) {
10873        REG_WR(sc, shmem + validity_offset, 0);
10874    }
10875}
10876
10877#define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10878#define MCP_ONE_TIMEOUT  100    /* 100 ms */
10879
10880static void
10881bxe_mcp_wait_one(struct bxe_softc *sc)
10882{
10883    /* special handling for emulation and FPGA (10 times longer) */
10884    if (CHIP_REV_IS_SLOW(sc)) {
10885        DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10886    } else {
10887        DELAY((MCP_ONE_TIMEOUT) * 1000);
10888    }
10889}
10890
10891/* initialize shmem_base and waits for validity signature to appear */
10892static int
10893bxe_init_shmem(struct bxe_softc *sc)
10894{
10895    int cnt = 0;
10896    uint32_t val = 0;
10897
10898    do {
10899        sc->devinfo.shmem_base     =
10900        sc->link_params.shmem_base =
10901            REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10902
10903        if (sc->devinfo.shmem_base) {
10904            val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10905            if (val & SHR_MEM_VALIDITY_MB)
10906                return (0);
10907        }
10908
10909        bxe_mcp_wait_one(sc);
10910
10911    } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10912
10913    BLOGE(sc, "BAD MCP validity signature\n");
10914
10915    return (-1);
10916}
10917
10918static int
10919bxe_reset_mcp_comp(struct bxe_softc *sc,
10920                   uint32_t         magic_val)
10921{
10922    int rc = bxe_init_shmem(sc);
10923
10924    /* Restore the `magic' bit value */
10925    if (!CHIP_IS_E1(sc)) {
10926        bxe_clp_reset_done(sc, magic_val);
10927    }
10928
10929    return (rc);
10930}
10931
10932static void
10933bxe_pxp_prep(struct bxe_softc *sc)
10934{
10935    if (!CHIP_IS_E1(sc)) {
10936        REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10937        REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10938        wmb();
10939    }
10940}
10941
10942/*
10943 * Reset the whole chip except for:
10944 *      - PCIE core
10945 *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10946 *      - IGU
10947 *      - MISC (including AEU)
10948 *      - GRC
10949 *      - RBCN, RBCP
10950 */
10951static void
10952bxe_process_kill_chip_reset(struct bxe_softc *sc,
10953                            uint8_t          global)
10954{
10955    uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10956    uint32_t global_bits2, stay_reset2;
10957
10958    /*
10959     * Bits that have to be set in reset_mask2 if we want to reset 'global'
10960     * (per chip) blocks.
10961     */
10962    global_bits2 =
10963        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10964        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10965
10966    /*
10967     * Don't reset the following blocks.
10968     * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10969     *            reset, as in 4 port device they might still be owned
10970     *            by the MCP (there is only one leader per path).
10971     */
10972    not_reset_mask1 =
10973        MISC_REGISTERS_RESET_REG_1_RST_HC |
10974        MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10975        MISC_REGISTERS_RESET_REG_1_RST_PXP;
10976
10977    not_reset_mask2 =
10978        MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10979        MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10980        MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10981        MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10982        MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10983        MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10984        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10985        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10986        MISC_REGISTERS_RESET_REG_2_RST_ATC |
10987        MISC_REGISTERS_RESET_REG_2_PGLC |
10988        MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10989        MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10990        MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10991        MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10992        MISC_REGISTERS_RESET_REG_2_UMAC0 |
10993        MISC_REGISTERS_RESET_REG_2_UMAC1;
10994
10995    /*
10996     * Keep the following blocks in reset:
10997     *  - all xxMACs are handled by the elink code.
10998     */
10999    stay_reset2 =
11000        MISC_REGISTERS_RESET_REG_2_XMAC |
11001        MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
11002
11003    /* Full reset masks according to the chip */
11004    reset_mask1 = 0xffffffff;
11005
11006    if (CHIP_IS_E1(sc))
11007        reset_mask2 = 0xffff;
11008    else if (CHIP_IS_E1H(sc))
11009        reset_mask2 = 0x1ffff;
11010    else if (CHIP_IS_E2(sc))
11011        reset_mask2 = 0xfffff;
11012    else /* CHIP_IS_E3 */
11013        reset_mask2 = 0x3ffffff;
11014
11015    /* Don't reset global blocks unless we need to */
11016    if (!global)
11017        reset_mask2 &= ~global_bits2;
11018
11019    /*
11020     * In case of attention in the QM, we need to reset PXP
11021     * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
11022     * because otherwise QM reset would release 'close the gates' shortly
11023     * before resetting the PXP, then the PSWRQ would send a write
11024     * request to PGLUE. Then when PXP is reset, PGLUE would try to
11025     * read the payload data from PSWWR, but PSWWR would not
11026     * respond. The write queue in PGLUE would stuck, dmae commands
11027     * would not return. Therefore it's important to reset the second
11028     * reset register (containing the
11029     * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
11030     * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
11031     * bit).
11032     */
11033    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
11034           reset_mask2 & (~not_reset_mask2));
11035
11036    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
11037           reset_mask1 & (~not_reset_mask1));
11038
11039    mb();
11040    wmb();
11041
11042    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
11043           reset_mask2 & (~stay_reset2));
11044
11045    mb();
11046    wmb();
11047
11048    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
11049    wmb();
11050}
11051
11052static int
11053bxe_process_kill(struct bxe_softc *sc,
11054                 uint8_t          global)
11055{
11056    int cnt = 1000;
11057    uint32_t val = 0;
11058    uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
11059    uint32_t tags_63_32 = 0;
11060
11061    /* Empty the Tetris buffer, wait for 1s */
11062    do {
11063        sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
11064        blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
11065        port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
11066        port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
11067        pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
11068        if (CHIP_IS_E3(sc)) {
11069            tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
11070        }
11071
11072        if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11073            ((port_is_idle_0 & 0x1) == 0x1) &&
11074            ((port_is_idle_1 & 0x1) == 0x1) &&
11075            (pgl_exp_rom2 == 0xffffffff) &&
11076            (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11077            break;
11078        DELAY(1000);
11079    } while (cnt-- > 0);
11080
11081    if (cnt <= 0) {
11082        BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11083                  "are still outstanding read requests after 1s! "
11084                  "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11085                  "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11086              sr_cnt, blk_cnt, port_is_idle_0,
11087              port_is_idle_1, pgl_exp_rom2);
11088        return (-1);
11089    }
11090
11091    mb();
11092
11093    /* Close gates #2, #3 and #4 */
11094    bxe_set_234_gates(sc, TRUE);
11095
11096    /* Poll for IGU VQs for 57712 and newer chips */
11097    if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11098        return (-1);
11099    }
11100
11101    /* XXX indicate that "process kill" is in progress to MCP */
11102
11103    /* clear "unprepared" bit */
11104    REG_WR(sc, MISC_REG_UNPREPARED, 0);
11105    mb();
11106
11107    /* Make sure all is written to the chip before the reset */
11108    wmb();
11109
11110    /*
11111     * Wait for 1ms to empty GLUE and PCI-E core queues,
11112     * PSWHST, GRC and PSWRD Tetris buffer.
11113     */
11114    DELAY(1000);
11115
11116    /* Prepare to chip reset: */
11117    /* MCP */
11118    if (global) {
11119        bxe_reset_mcp_prep(sc, &val);
11120    }
11121
11122    /* PXP */
11123    bxe_pxp_prep(sc);
11124    mb();
11125
11126    /* reset the chip */
11127    bxe_process_kill_chip_reset(sc, global);
11128    mb();
11129
11130    /* clear errors in PGB */
11131    if (!CHIP_IS_E1(sc))
11132        REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11133
11134    /* Recover after reset: */
11135    /* MCP */
11136    if (global && bxe_reset_mcp_comp(sc, val)) {
11137        return (-1);
11138    }
11139
11140    /* XXX add resetting the NO_MCP mode DB here */
11141
11142    /* Open the gates #2, #3 and #4 */
11143    bxe_set_234_gates(sc, FALSE);
11144
11145    /* XXX
11146     * IGU/AEU preparation bring back the AEU/IGU to a reset state
11147     * re-enable attentions
11148     */
11149
11150    return (0);
11151}
11152
11153static int
11154bxe_leader_reset(struct bxe_softc *sc)
11155{
11156    int rc = 0;
11157    uint8_t global = bxe_reset_is_global(sc);
11158    uint32_t load_code;
11159
11160    /*
11161     * If not going to reset MCP, load "fake" driver to reset HW while
11162     * driver is owner of the HW.
11163     */
11164    if (!global && !BXE_NOMCP(sc)) {
11165        load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11166                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11167        if (!load_code) {
11168            BLOGE(sc, "MCP response failure, aborting\n");
11169            rc = -1;
11170            goto exit_leader_reset;
11171        }
11172
11173        if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11174            (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11175            BLOGE(sc, "MCP unexpected response, aborting\n");
11176            rc = -1;
11177            goto exit_leader_reset2;
11178        }
11179
11180        load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11181        if (!load_code) {
11182            BLOGE(sc, "MCP response failure, aborting\n");
11183            rc = -1;
11184            goto exit_leader_reset2;
11185        }
11186    }
11187
11188    /* try to recover after the failure */
11189    if (bxe_process_kill(sc, global)) {
11190        BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11191        rc = -1;
11192        goto exit_leader_reset2;
11193    }
11194
11195    /*
11196     * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11197     * state.
11198     */
11199    bxe_set_reset_done(sc);
11200    if (global) {
11201        bxe_clear_reset_global(sc);
11202    }
11203
11204exit_leader_reset2:
11205
11206    /* unload "fake driver" if it was loaded */
11207    if (!global && !BXE_NOMCP(sc)) {
11208        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11209        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11210    }
11211
11212exit_leader_reset:
11213
11214    sc->is_leader = 0;
11215    bxe_release_leader_lock(sc);
11216
11217    mb();
11218    return (rc);
11219}
11220
11221/*
11222 * prepare INIT transition, parameters configured:
11223 *   - HC configuration
11224 *   - Queue's CDU context
11225 */
11226static void
11227bxe_pf_q_prep_init(struct bxe_softc               *sc,
11228                   struct bxe_fastpath            *fp,
11229                   struct ecore_queue_init_params *init_params)
11230{
11231    uint8_t cos;
11232    int cxt_index, cxt_offset;
11233
11234    bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11235    bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11236
11237    bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11238    bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11239
11240    /* HC rate */
11241    init_params->rx.hc_rate =
11242        sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11243    init_params->tx.hc_rate =
11244        sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11245
11246    /* FW SB ID */
11247    init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11248
11249    /* CQ index among the SB indices */
11250    init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11251    init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11252
11253    /* set maximum number of COSs supported by this queue */
11254    init_params->max_cos = sc->max_cos;
11255
11256    BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11257          fp->index, init_params->max_cos);
11258
11259    /* set the context pointers queue object */
11260    for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11261        /* XXX change index/cid here if ever support multiple tx CoS */
11262        /* fp->txdata[cos]->cid */
11263        cxt_index = fp->index / ILT_PAGE_CIDS;
11264        cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11265        init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11266    }
11267}
11268
11269/* set flags that are common for the Tx-only and not normal connections */
11270static unsigned long
11271bxe_get_common_flags(struct bxe_softc    *sc,
11272                     struct bxe_fastpath *fp,
11273                     uint8_t             zero_stats)
11274{
11275    unsigned long flags = 0;
11276
11277    /* PF driver will always initialize the Queue to an ACTIVE state */
11278    bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11279
11280    /*
11281     * tx only connections collect statistics (on the same index as the
11282     * parent connection). The statistics are zeroed when the parent
11283     * connection is initialized.
11284     */
11285
11286    bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11287    if (zero_stats) {
11288        bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11289    }
11290
11291    /*
11292     * tx only connections can support tx-switching, though their
11293     * CoS-ness doesn't survive the loopback
11294     */
11295    if (sc->flags & BXE_TX_SWITCHING) {
11296        bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11297    }
11298
11299    bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11300
11301    return (flags);
11302}
11303
11304static unsigned long
11305bxe_get_q_flags(struct bxe_softc    *sc,
11306                struct bxe_fastpath *fp,
11307                uint8_t             leading)
11308{
11309    unsigned long flags = 0;
11310
11311    if (IS_MF_SD(sc)) {
11312        bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11313    }
11314
11315    if (if_getcapenable(sc->ifp) & IFCAP_LRO) {
11316        bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11317#if __FreeBSD_version >= 800000
11318        bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11319#endif
11320    }
11321
11322    if (leading) {
11323        bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11324        bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11325    }
11326
11327    bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11328
11329    /* merge with common flags */
11330    return (flags | bxe_get_common_flags(sc, fp, TRUE));
11331}
11332
11333static void
11334bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11335                      struct bxe_fastpath               *fp,
11336                      struct ecore_general_setup_params *gen_init,
11337                      uint8_t                           cos)
11338{
11339    gen_init->stat_id = bxe_stats_id(fp);
11340    gen_init->spcl_id = fp->cl_id;
11341    gen_init->mtu = sc->mtu;
11342    gen_init->cos = cos;
11343}
11344
11345static void
11346bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11347                 struct bxe_fastpath           *fp,
11348                 struct rxq_pause_params       *pause,
11349                 struct ecore_rxq_setup_params *rxq_init)
11350{
11351    uint8_t max_sge = 0;
11352    uint16_t sge_sz = 0;
11353    uint16_t tpa_agg_size = 0;
11354
11355    pause->sge_th_lo = SGE_TH_LO(sc);
11356    pause->sge_th_hi = SGE_TH_HI(sc);
11357
11358    /* validate SGE ring has enough to cross high threshold */
11359    if (sc->dropless_fc &&
11360            (pause->sge_th_hi + FW_PREFETCH_CNT) >
11361            (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11362        BLOGW(sc, "sge ring threshold limit\n");
11363    }
11364
11365    /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11366    tpa_agg_size = (2 * sc->mtu);
11367    if (tpa_agg_size < sc->max_aggregation_size) {
11368        tpa_agg_size = sc->max_aggregation_size;
11369    }
11370
11371    max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11372    max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11373                   (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11374    sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11375
11376    /* pause - not for e1 */
11377    if (!CHIP_IS_E1(sc)) {
11378        pause->bd_th_lo = BD_TH_LO(sc);
11379        pause->bd_th_hi = BD_TH_HI(sc);
11380
11381        pause->rcq_th_lo = RCQ_TH_LO(sc);
11382        pause->rcq_th_hi = RCQ_TH_HI(sc);
11383
11384        /* validate rings have enough entries to cross high thresholds */
11385        if (sc->dropless_fc &&
11386            pause->bd_th_hi + FW_PREFETCH_CNT >
11387            sc->rx_ring_size) {
11388            BLOGW(sc, "rx bd ring threshold limit\n");
11389        }
11390
11391        if (sc->dropless_fc &&
11392            pause->rcq_th_hi + FW_PREFETCH_CNT >
11393            RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11394            BLOGW(sc, "rcq ring threshold limit\n");
11395        }
11396
11397        pause->pri_map = 1;
11398    }
11399
11400    /* rxq setup */
11401    rxq_init->dscr_map   = fp->rx_dma.paddr;
11402    rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11403    rxq_init->rcq_map    = fp->rcq_dma.paddr;
11404    rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11405
11406    /*
11407     * This should be a maximum number of data bytes that may be
11408     * placed on the BD (not including paddings).
11409     */
11410    rxq_init->buf_sz = (fp->rx_buf_size -
11411                        IP_HEADER_ALIGNMENT_PADDING);
11412
11413    rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11414    rxq_init->tpa_agg_sz      = tpa_agg_size;
11415    rxq_init->sge_buf_sz      = sge_sz;
11416    rxq_init->max_sges_pkt    = max_sge;
11417    rxq_init->rss_engine_id   = SC_FUNC(sc);
11418    rxq_init->mcast_engine_id = SC_FUNC(sc);
11419
11420    /*
11421     * Maximum number or simultaneous TPA aggregation for this Queue.
11422     * For PF Clients it should be the maximum available number.
11423     * VF driver(s) may want to define it to a smaller value.
11424     */
11425    rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11426
11427    rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11428    rxq_init->fw_sb_id = fp->fw_sb_id;
11429
11430    rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11431
11432    /*
11433     * configure silent vlan removal
11434     * if multi function mode is afex, then mask default vlan
11435     */
11436    if (IS_MF_AFEX(sc)) {
11437        rxq_init->silent_removal_value =
11438            sc->devinfo.mf_info.afex_def_vlan_tag;
11439        rxq_init->silent_removal_mask = EVL_VLID_MASK;
11440    }
11441}
11442
11443static void
11444bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11445                 struct bxe_fastpath           *fp,
11446                 struct ecore_txq_setup_params *txq_init,
11447                 uint8_t                       cos)
11448{
11449    /*
11450     * XXX If multiple CoS is ever supported then each fastpath structure
11451     * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11452     * fp->txdata[cos]->tx_dma.paddr;
11453     */
11454    txq_init->dscr_map     = fp->tx_dma.paddr;
11455    txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11456    txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11457    txq_init->fw_sb_id     = fp->fw_sb_id;
11458
11459    /*
11460     * set the TSS leading client id for TX classfication to the
11461     * leading RSS client id
11462     */
11463    txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11464}
11465
11466/*
11467 * This function performs 2 steps in a queue state machine:
11468 *   1) RESET->INIT
11469 *   2) INIT->SETUP
11470 */
11471static int
11472bxe_setup_queue(struct bxe_softc    *sc,
11473                struct bxe_fastpath *fp,
11474                uint8_t             leading)
11475{
11476    struct ecore_queue_state_params q_params = { NULL };
11477    struct ecore_queue_setup_params *setup_params =
11478                        &q_params.params.setup;
11479    int rc;
11480
11481    BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11482
11483    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11484
11485    q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11486
11487    /* we want to wait for completion in this context */
11488    bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11489
11490    /* prepare the INIT parameters */
11491    bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11492
11493    /* Set the command */
11494    q_params.cmd = ECORE_Q_CMD_INIT;
11495
11496    /* Change the state to INIT */
11497    rc = ecore_queue_state_change(sc, &q_params);
11498    if (rc) {
11499        BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11500        return (rc);
11501    }
11502
11503    BLOGD(sc, DBG_LOAD, "init complete\n");
11504
11505    /* now move the Queue to the SETUP state */
11506    memset(setup_params, 0, sizeof(*setup_params));
11507
11508    /* set Queue flags */
11509    setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11510
11511    /* set general SETUP parameters */
11512    bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11513                          FIRST_TX_COS_INDEX);
11514
11515    bxe_pf_rx_q_prep(sc, fp,
11516                     &setup_params->pause_params,
11517                     &setup_params->rxq_params);
11518
11519    bxe_pf_tx_q_prep(sc, fp,
11520                     &setup_params->txq_params,
11521                     FIRST_TX_COS_INDEX);
11522
11523    /* Set the command */
11524    q_params.cmd = ECORE_Q_CMD_SETUP;
11525
11526    /* change the state to SETUP */
11527    rc = ecore_queue_state_change(sc, &q_params);
11528    if (rc) {
11529        BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11530        return (rc);
11531    }
11532
11533    return (rc);
11534}
11535
11536static int
11537bxe_setup_leading(struct bxe_softc *sc)
11538{
11539    return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11540}
11541
11542static int
11543bxe_config_rss_pf(struct bxe_softc            *sc,
11544                  struct ecore_rss_config_obj *rss_obj,
11545                  uint8_t                     config_hash)
11546{
11547    struct ecore_config_rss_params params = { NULL };
11548    int i;
11549
11550    /*
11551     * Although RSS is meaningless when there is a single HW queue we
11552     * still need it enabled in order to have HW Rx hash generated.
11553     */
11554
11555    params.rss_obj = rss_obj;
11556
11557    bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11558
11559    bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11560
11561    /* RSS configuration */
11562    bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11563    bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11564    bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11565    bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11566    if (rss_obj->udp_rss_v4) {
11567        bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11568    }
11569    if (rss_obj->udp_rss_v6) {
11570        bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11571    }
11572
11573    /* Hash bits */
11574    params.rss_result_mask = MULTI_MASK;
11575
11576    memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11577
11578    if (config_hash) {
11579        /* RSS keys */
11580        for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11581            params.rss_key[i] = arc4random();
11582        }
11583
11584        bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11585    }
11586
11587    return (ecore_config_rss(sc, &params));
11588}
11589
11590static int
11591bxe_config_rss_eth(struct bxe_softc *sc,
11592                   uint8_t          config_hash)
11593{
11594    return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11595}
11596
11597static int
11598bxe_init_rss_pf(struct bxe_softc *sc)
11599{
11600    uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11601    int i;
11602
11603    /*
11604     * Prepare the initial contents of the indirection table if
11605     * RSS is enabled
11606     */
11607    for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11608        sc->rss_conf_obj.ind_table[i] =
11609            (sc->fp->cl_id + (i % num_eth_queues));
11610    }
11611
11612    if (sc->udp_rss) {
11613        sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11614    }
11615
11616    /*
11617     * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11618     * per-port, so if explicit configuration is needed, do it only
11619     * for a PMF.
11620     *
11621     * For 57712 and newer it's a per-function configuration.
11622     */
11623    return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11624}
11625
11626static int
11627bxe_set_mac_one(struct bxe_softc          *sc,
11628                uint8_t                   *mac,
11629                struct ecore_vlan_mac_obj *obj,
11630                uint8_t                   set,
11631                int                       mac_type,
11632                unsigned long             *ramrod_flags)
11633{
11634    struct ecore_vlan_mac_ramrod_params ramrod_param;
11635    int rc;
11636
11637    memset(&ramrod_param, 0, sizeof(ramrod_param));
11638
11639    /* fill in general parameters */
11640    ramrod_param.vlan_mac_obj = obj;
11641    ramrod_param.ramrod_flags = *ramrod_flags;
11642
11643    /* fill a user request section if needed */
11644    if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11645        memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11646
11647        bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11648
11649        /* Set the command: ADD or DEL */
11650        ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11651                                            ECORE_VLAN_MAC_DEL;
11652    }
11653
11654    rc = ecore_config_vlan_mac(sc, &ramrod_param);
11655
11656    if (rc == ECORE_EXISTS) {
11657        BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11658        /* do not treat adding same MAC as error */
11659        rc = 0;
11660    } else if (rc < 0) {
11661        BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11662    }
11663
11664    return (rc);
11665}
11666
11667static int
11668bxe_set_eth_mac(struct bxe_softc *sc,
11669                uint8_t          set)
11670{
11671    unsigned long ramrod_flags = 0;
11672
11673    BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11674
11675    bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11676
11677    /* Eth MAC is set on RSS leading client (fp[0]) */
11678    return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11679                            &sc->sp_objs->mac_obj,
11680                            set, ECORE_ETH_MAC, &ramrod_flags));
11681}
11682
11683static int
11684bxe_get_cur_phy_idx(struct bxe_softc *sc)
11685{
11686    uint32_t sel_phy_idx = 0;
11687
11688    if (sc->link_params.num_phys <= 1) {
11689        return (ELINK_INT_PHY);
11690    }
11691
11692    if (sc->link_vars.link_up) {
11693        sel_phy_idx = ELINK_EXT_PHY1;
11694        /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11695        if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11696            (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11697             ELINK_SUPPORTED_FIBRE))
11698            sel_phy_idx = ELINK_EXT_PHY2;
11699    } else {
11700        switch (elink_phy_selection(&sc->link_params)) {
11701        case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11702        case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11703        case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11704               sel_phy_idx = ELINK_EXT_PHY1;
11705               break;
11706        case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11707        case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11708               sel_phy_idx = ELINK_EXT_PHY2;
11709               break;
11710        }
11711    }
11712
11713    return (sel_phy_idx);
11714}
11715
11716static int
11717bxe_get_link_cfg_idx(struct bxe_softc *sc)
11718{
11719    uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11720
11721    /*
11722     * The selected activated PHY is always after swapping (in case PHY
11723     * swapping is enabled). So when swapping is enabled, we need to reverse
11724     * the configuration
11725     */
11726
11727    if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11728        if (sel_phy_idx == ELINK_EXT_PHY1)
11729            sel_phy_idx = ELINK_EXT_PHY2;
11730        else if (sel_phy_idx == ELINK_EXT_PHY2)
11731            sel_phy_idx = ELINK_EXT_PHY1;
11732    }
11733
11734    return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11735}
11736
11737static void
11738bxe_set_requested_fc(struct bxe_softc *sc)
11739{
11740    /*
11741     * Initialize link parameters structure variables
11742     * It is recommended to turn off RX FC for jumbo frames
11743     * for better performance
11744     */
11745    if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11746        sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11747    } else {
11748        sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11749    }
11750}
11751
11752static void
11753bxe_calc_fc_adv(struct bxe_softc *sc)
11754{
11755    uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11756
11757
11758    sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11759                                           ADVERTISED_Pause);
11760
11761    switch (sc->link_vars.ieee_fc &
11762            MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11763
11764    case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11765        sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11766                                          ADVERTISED_Pause);
11767        break;
11768
11769    case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11770        sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11771        break;
11772
11773    default:
11774        break;
11775
11776    }
11777}
11778
11779static uint16_t
11780bxe_get_mf_speed(struct bxe_softc *sc)
11781{
11782    uint16_t line_speed = sc->link_vars.line_speed;
11783    if (IS_MF(sc)) {
11784        uint16_t maxCfg =
11785            bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11786
11787        /* calculate the current MAX line speed limit for the MF devices */
11788        if (IS_MF_SI(sc)) {
11789            line_speed = (line_speed * maxCfg) / 100;
11790        } else { /* SD mode */
11791            uint16_t vn_max_rate = maxCfg * 100;
11792
11793            if (vn_max_rate < line_speed) {
11794                line_speed = vn_max_rate;
11795            }
11796        }
11797    }
11798
11799    return (line_speed);
11800}
11801
11802static void
11803bxe_fill_report_data(struct bxe_softc            *sc,
11804                     struct bxe_link_report_data *data)
11805{
11806    uint16_t line_speed = bxe_get_mf_speed(sc);
11807
11808    memset(data, 0, sizeof(*data));
11809
11810    /* fill the report data with the effective line speed */
11811    data->line_speed = line_speed;
11812
11813    /* Link is down */
11814    if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11815        bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11816    }
11817
11818    /* Full DUPLEX */
11819    if (sc->link_vars.duplex == DUPLEX_FULL) {
11820        bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11821    }
11822
11823    /* Rx Flow Control is ON */
11824    if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11825        bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11826    }
11827
11828    /* Tx Flow Control is ON */
11829    if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11830        bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11831    }
11832}
11833
11834/* report link status to OS, should be called under phy_lock */
11835static void
11836bxe_link_report_locked(struct bxe_softc *sc)
11837{
11838    struct bxe_link_report_data cur_data;
11839
11840    /* reread mf_cfg */
11841    if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11842        bxe_read_mf_cfg(sc);
11843    }
11844
11845    /* Read the current link report info */
11846    bxe_fill_report_data(sc, &cur_data);
11847
11848    /* Don't report link down or exactly the same link status twice */
11849    if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11850        (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11851                      &sc->last_reported_link.link_report_flags) &&
11852         bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11853                      &cur_data.link_report_flags))) {
11854        return;
11855    }
11856
11857	ELINK_DEBUG_P2(sc, "Change in link status : cur_data = %x, last_reported_link = %x\n",
11858					cur_data.link_report_flags, sc->last_reported_link.link_report_flags);
11859    sc->link_cnt++;
11860
11861	ELINK_DEBUG_P1(sc, "link status change count = %x\n", sc->link_cnt);
11862    /* report new link params and remember the state for the next time */
11863    memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11864
11865    if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11866                     &cur_data.link_report_flags)) {
11867        if_link_state_change(sc->ifp, LINK_STATE_DOWN);
11868    } else {
11869        const char *duplex;
11870        const char *flow;
11871
11872        if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11873                                   &cur_data.link_report_flags)) {
11874            duplex = "full";
11875			ELINK_DEBUG_P0(sc, "link set to full duplex\n");
11876        } else {
11877            duplex = "half";
11878			ELINK_DEBUG_P0(sc, "link set to half duplex\n");
11879        }
11880
11881        /*
11882         * Handle the FC at the end so that only these flags would be
11883         * possibly set. This way we may easily check if there is no FC
11884         * enabled.
11885         */
11886        if (cur_data.link_report_flags) {
11887            if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11888                             &cur_data.link_report_flags) &&
11889                bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11890                             &cur_data.link_report_flags)) {
11891                flow = "ON - receive & transmit";
11892            } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11893                                    &cur_data.link_report_flags) &&
11894                       !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11895                                     &cur_data.link_report_flags)) {
11896                flow = "ON - receive";
11897            } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11898                                     &cur_data.link_report_flags) &&
11899                       bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11900                                    &cur_data.link_report_flags)) {
11901                flow = "ON - transmit";
11902            } else {
11903                flow = "none"; /* possible? */
11904            }
11905        } else {
11906            flow = "none";
11907        }
11908
11909        if_link_state_change(sc->ifp, LINK_STATE_UP);
11910        BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11911              cur_data.line_speed, duplex, flow);
11912    }
11913}
11914
11915static void
11916bxe_link_report(struct bxe_softc *sc)
11917{
11918    bxe_acquire_phy_lock(sc);
11919    bxe_link_report_locked(sc);
11920    bxe_release_phy_lock(sc);
11921}
11922
11923static void
11924bxe_link_status_update(struct bxe_softc *sc)
11925{
11926    if (sc->state != BXE_STATE_OPEN) {
11927        return;
11928    }
11929
11930    if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11931        elink_link_status_update(&sc->link_params, &sc->link_vars);
11932    } else {
11933        sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11934                                  ELINK_SUPPORTED_10baseT_Full |
11935                                  ELINK_SUPPORTED_100baseT_Half |
11936                                  ELINK_SUPPORTED_100baseT_Full |
11937                                  ELINK_SUPPORTED_1000baseT_Full |
11938                                  ELINK_SUPPORTED_2500baseX_Full |
11939                                  ELINK_SUPPORTED_10000baseT_Full |
11940                                  ELINK_SUPPORTED_TP |
11941                                  ELINK_SUPPORTED_FIBRE |
11942                                  ELINK_SUPPORTED_Autoneg |
11943                                  ELINK_SUPPORTED_Pause |
11944                                  ELINK_SUPPORTED_Asym_Pause);
11945        sc->port.advertising[0] = sc->port.supported[0];
11946
11947        sc->link_params.sc                = sc;
11948        sc->link_params.port              = SC_PORT(sc);
11949        sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11950        sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11951        sc->link_params.req_line_speed[0] = SPEED_10000;
11952        sc->link_params.speed_cap_mask[0] = 0x7f0000;
11953        sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11954
11955        if (CHIP_REV_IS_FPGA(sc)) {
11956            sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11957            sc->link_vars.line_speed  = ELINK_SPEED_1000;
11958            sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11959                                         LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11960        } else {
11961            sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11962            sc->link_vars.line_speed  = ELINK_SPEED_10000;
11963            sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11964                                         LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11965        }
11966
11967        sc->link_vars.link_up = 1;
11968
11969        sc->link_vars.duplex    = DUPLEX_FULL;
11970        sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11971
11972        if (IS_PF(sc)) {
11973            REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11974            bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11975            bxe_link_report(sc);
11976        }
11977    }
11978
11979    if (IS_PF(sc)) {
11980        if (sc->link_vars.link_up) {
11981            bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11982        } else {
11983            bxe_stats_handle(sc, STATS_EVENT_STOP);
11984        }
11985        bxe_link_report(sc);
11986    } else {
11987        bxe_link_report(sc);
11988        bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11989    }
11990}
11991
11992static int
11993bxe_initial_phy_init(struct bxe_softc *sc,
11994                     int              load_mode)
11995{
11996    int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11997    uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11998    struct elink_params *lp = &sc->link_params;
11999
12000    bxe_set_requested_fc(sc);
12001
12002    if (CHIP_REV_IS_SLOW(sc)) {
12003        uint32_t bond = CHIP_BOND_ID(sc);
12004        uint32_t feat = 0;
12005
12006        if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
12007            feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
12008        } else if (bond & 0x4) {
12009            if (CHIP_IS_E3(sc)) {
12010                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
12011            } else {
12012                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
12013            }
12014        } else if (bond & 0x8) {
12015            if (CHIP_IS_E3(sc)) {
12016                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
12017            } else {
12018                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12019            }
12020        }
12021
12022        /* disable EMAC for E3 and above */
12023        if (bond & 0x2) {
12024            feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12025        }
12026
12027        sc->link_params.feature_config_flags |= feat;
12028    }
12029
12030    bxe_acquire_phy_lock(sc);
12031
12032    if (load_mode == LOAD_DIAG) {
12033        lp->loopback_mode = ELINK_LOOPBACK_XGXS;
12034        /* Prefer doing PHY loopback at 10G speed, if possible */
12035        if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
12036            if (lp->speed_cap_mask[cfg_idx] &
12037                PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
12038                lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
12039            } else {
12040                lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
12041            }
12042        }
12043    }
12044
12045    if (load_mode == LOAD_LOOPBACK_EXT) {
12046        lp->loopback_mode = ELINK_LOOPBACK_EXT;
12047    }
12048
12049    rc = elink_phy_init(&sc->link_params, &sc->link_vars);
12050
12051    bxe_release_phy_lock(sc);
12052
12053    bxe_calc_fc_adv(sc);
12054
12055    if (sc->link_vars.link_up) {
12056        bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12057        bxe_link_report(sc);
12058    }
12059
12060    if (!CHIP_REV_IS_SLOW(sc)) {
12061        bxe_periodic_start(sc);
12062    }
12063
12064    sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
12065    return (rc);
12066}
12067
12068/* must be called under IF_ADDR_LOCK */
12069static int
12070bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
12071                         struct ecore_mcast_ramrod_params *p)
12072{
12073    if_t ifp = sc->ifp;
12074    int mc_count = 0;
12075    struct ifmultiaddr *ifma;
12076    struct ecore_mcast_list_elem *mc_mac;
12077
12078    CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12079        if (ifma->ifma_addr->sa_family != AF_LINK) {
12080            continue;
12081        }
12082
12083        mc_count++;
12084    }
12085
12086    ECORE_LIST_INIT(&p->mcast_list);
12087    p->mcast_list_len = 0;
12088
12089    if (!mc_count) {
12090        return (0);
12091    }
12092
12093    mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12094                    (M_NOWAIT | M_ZERO));
12095    if (!mc_mac) {
12096        BLOGE(sc, "Failed to allocate temp mcast list\n");
12097        return (-1);
12098    }
12099    bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12100
12101    CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12102        if (ifma->ifma_addr->sa_family != AF_LINK) {
12103            continue;
12104        }
12105
12106        mc_mac->mac = (uint8_t *)LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
12107        ECORE_LIST_PUSH_TAIL(&mc_mac->link, &p->mcast_list);
12108
12109        BLOGD(sc, DBG_LOAD,
12110              "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X and mc_count %d\n",
12111              mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12112              mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5], mc_count);
12113       mc_mac++;
12114    }
12115
12116    p->mcast_list_len = mc_count;
12117
12118    return (0);
12119}
12120
12121static void
12122bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12123{
12124    struct ecore_mcast_list_elem *mc_mac =
12125        ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12126                               struct ecore_mcast_list_elem,
12127                               link);
12128
12129    if (mc_mac) {
12130        /* only a single free as all mc_macs are in the same heap array */
12131        free(mc_mac, M_DEVBUF);
12132    }
12133}
12134static int
12135bxe_set_mc_list(struct bxe_softc *sc)
12136{
12137    struct ecore_mcast_ramrod_params rparam = { NULL };
12138    int rc = 0;
12139
12140    rparam.mcast_obj = &sc->mcast_obj;
12141
12142    BXE_MCAST_LOCK(sc);
12143
12144    /* first, clear all configured multicast MACs */
12145    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12146    if (rc < 0) {
12147        BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12148        /* Manual backport parts of FreeBSD upstream r284470. */
12149        BXE_MCAST_UNLOCK(sc);
12150        return (rc);
12151    }
12152
12153    /* configure a new MACs list */
12154    rc = bxe_init_mcast_macs_list(sc, &rparam);
12155    if (rc) {
12156        BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12157        BXE_MCAST_UNLOCK(sc);
12158        return (rc);
12159    }
12160
12161    /* Now add the new MACs */
12162    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12163    if (rc < 0) {
12164        BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12165    }
12166
12167    bxe_free_mcast_macs_list(&rparam);
12168
12169    BXE_MCAST_UNLOCK(sc);
12170
12171    return (rc);
12172}
12173
12174static int
12175bxe_set_uc_list(struct bxe_softc *sc)
12176{
12177    if_t ifp = sc->ifp;
12178    struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12179    struct ifaddr *ifa;
12180    unsigned long ramrod_flags = 0;
12181    int rc;
12182
12183#if __FreeBSD_version < 800000
12184    IF_ADDR_LOCK(ifp);
12185#else
12186    if_addr_rlock(ifp);
12187#endif
12188
12189    /* first schedule a cleanup up of old configuration */
12190    rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12191    if (rc < 0) {
12192        BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12193#if __FreeBSD_version < 800000
12194        IF_ADDR_UNLOCK(ifp);
12195#else
12196        if_addr_runlock(ifp);
12197#endif
12198        return (rc);
12199    }
12200
12201    ifa = if_getifaddr(ifp); /* XXX Is this structure */
12202    while (ifa) {
12203        if (ifa->ifa_addr->sa_family != AF_LINK) {
12204            ifa = CK_STAILQ_NEXT(ifa, ifa_link);
12205            continue;
12206        }
12207
12208        rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12209                             mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12210        if (rc == -EEXIST) {
12211            BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12212            /* do not treat adding same MAC as an error */
12213            rc = 0;
12214        } else if (rc < 0) {
12215            BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12216#if __FreeBSD_version < 800000
12217            IF_ADDR_UNLOCK(ifp);
12218#else
12219            if_addr_runlock(ifp);
12220#endif
12221            return (rc);
12222        }
12223
12224        ifa = CK_STAILQ_NEXT(ifa, ifa_link);
12225    }
12226
12227#if __FreeBSD_version < 800000
12228    IF_ADDR_UNLOCK(ifp);
12229#else
12230    if_addr_runlock(ifp);
12231#endif
12232
12233    /* Execute the pending commands */
12234    bit_set(&ramrod_flags, RAMROD_CONT);
12235    return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12236                            ECORE_UC_LIST_MAC, &ramrod_flags));
12237}
12238
12239static void
12240bxe_set_rx_mode(struct bxe_softc *sc)
12241{
12242    if_t ifp = sc->ifp;
12243    uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12244
12245    if (sc->state != BXE_STATE_OPEN) {
12246        BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12247        return;
12248    }
12249
12250    BLOGD(sc, DBG_SP, "if_flags(ifp)=0x%x\n", if_getflags(sc->ifp));
12251
12252    if (if_getflags(ifp) & IFF_PROMISC) {
12253        rx_mode = BXE_RX_MODE_PROMISC;
12254    } else if ((if_getflags(ifp) & IFF_ALLMULTI) ||
12255               ((if_getamcount(ifp) > BXE_MAX_MULTICAST) &&
12256                CHIP_IS_E1(sc))) {
12257        rx_mode = BXE_RX_MODE_ALLMULTI;
12258    } else {
12259        if (IS_PF(sc)) {
12260            /* some multicasts */
12261            if (bxe_set_mc_list(sc) < 0) {
12262                rx_mode = BXE_RX_MODE_ALLMULTI;
12263            }
12264            if (bxe_set_uc_list(sc) < 0) {
12265                rx_mode = BXE_RX_MODE_PROMISC;
12266            }
12267        }
12268    }
12269
12270    sc->rx_mode = rx_mode;
12271
12272    /* schedule the rx_mode command */
12273    if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12274        BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12275        bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12276        return;
12277    }
12278
12279    if (IS_PF(sc)) {
12280        bxe_set_storm_rx_mode(sc);
12281    }
12282}
12283
12284
12285/* update flags in shmem */
12286static void
12287bxe_update_drv_flags(struct bxe_softc *sc,
12288                     uint32_t         flags,
12289                     uint32_t         set)
12290{
12291    uint32_t drv_flags;
12292
12293    if (SHMEM2_HAS(sc, drv_flags)) {
12294        bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12295        drv_flags = SHMEM2_RD(sc, drv_flags);
12296
12297        if (set) {
12298            SET_FLAGS(drv_flags, flags);
12299        } else {
12300            RESET_FLAGS(drv_flags, flags);
12301        }
12302
12303        SHMEM2_WR(sc, drv_flags, drv_flags);
12304        BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12305
12306        bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12307    }
12308}
12309
12310/* periodic timer callout routine, only runs when the interface is up */
12311
12312static void
12313bxe_periodic_callout_func(void *xsc)
12314{
12315    struct bxe_softc *sc = (struct bxe_softc *)xsc;
12316    int i;
12317
12318    if (!BXE_CORE_TRYLOCK(sc)) {
12319        /* just bail and try again next time */
12320
12321        if ((sc->state == BXE_STATE_OPEN) &&
12322            (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12323            /* schedule the next periodic callout */
12324            callout_reset(&sc->periodic_callout, hz,
12325                          bxe_periodic_callout_func, sc);
12326        }
12327
12328        return;
12329    }
12330
12331    if ((sc->state != BXE_STATE_OPEN) ||
12332        (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12333        BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12334        BXE_CORE_UNLOCK(sc);
12335        return;
12336        }
12337
12338
12339    /* Check for TX timeouts on any fastpath. */
12340    FOR_EACH_QUEUE(sc, i) {
12341        if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12342            /* Ruh-Roh, chip was reset! */
12343            break;
12344        }
12345    }
12346
12347    if (!CHIP_REV_IS_SLOW(sc)) {
12348        /*
12349         * This barrier is needed to ensure the ordering between the writing
12350         * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12351         * the reading here.
12352         */
12353        mb();
12354        if (sc->port.pmf) {
12355	    bxe_acquire_phy_lock(sc);
12356            elink_period_func(&sc->link_params, &sc->link_vars);
12357	    bxe_release_phy_lock(sc);
12358        }
12359    }
12360
12361    if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12362        int mb_idx = SC_FW_MB_IDX(sc);
12363        uint32_t drv_pulse;
12364        uint32_t mcp_pulse;
12365
12366        ++sc->fw_drv_pulse_wr_seq;
12367        sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12368
12369        drv_pulse = sc->fw_drv_pulse_wr_seq;
12370        bxe_drv_pulse(sc);
12371
12372        mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12373                     MCP_PULSE_SEQ_MASK);
12374
12375        /*
12376         * The delta between driver pulse and mcp response should
12377         * be 1 (before mcp response) or 0 (after mcp response).
12378         */
12379        if ((drv_pulse != mcp_pulse) &&
12380            (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12381            /* someone lost a heartbeat... */
12382            BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12383                  drv_pulse, mcp_pulse);
12384        }
12385    }
12386
12387    /* state is BXE_STATE_OPEN */
12388    bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12389
12390    BXE_CORE_UNLOCK(sc);
12391
12392    if ((sc->state == BXE_STATE_OPEN) &&
12393        (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12394        /* schedule the next periodic callout */
12395        callout_reset(&sc->periodic_callout, hz,
12396                      bxe_periodic_callout_func, sc);
12397    }
12398}
12399
12400static void
12401bxe_periodic_start(struct bxe_softc *sc)
12402{
12403    atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12404    callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12405}
12406
12407static void
12408bxe_periodic_stop(struct bxe_softc *sc)
12409{
12410    atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12411    callout_drain(&sc->periodic_callout);
12412}
12413
12414void
12415bxe_parity_recover(struct bxe_softc *sc)
12416{
12417    uint8_t global = FALSE;
12418    uint32_t error_recovered, error_unrecovered;
12419    bool is_parity;
12420
12421
12422    if ((sc->recovery_state == BXE_RECOVERY_FAILED) &&
12423        (sc->state == BXE_STATE_ERROR)) {
12424        BLOGE(sc, "RECOVERY failed, "
12425            "stack notified driver is NOT running! "
12426            "Please reboot/power cycle the system.\n");
12427        return;
12428    }
12429
12430    while (1) {
12431        BLOGD(sc, DBG_SP,
12432           "%s sc=%p state=0x%x rec_state=0x%x error_status=%x\n",
12433            __func__, sc, sc->state, sc->recovery_state, sc->error_status);
12434
12435        switch(sc->recovery_state) {
12436
12437        case BXE_RECOVERY_INIT:
12438            is_parity = bxe_chk_parity_attn(sc, &global, FALSE);
12439
12440            if ((CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ||
12441                (sc->error_status & BXE_ERR_MCP_ASSERT) ||
12442                (sc->error_status & BXE_ERR_GLOBAL)) {
12443
12444                BXE_CORE_LOCK(sc);
12445                if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12446                    bxe_periodic_stop(sc);
12447                }
12448                bxe_nic_unload(sc, UNLOAD_RECOVERY, false);
12449                sc->state = BXE_STATE_ERROR;
12450                sc->recovery_state = BXE_RECOVERY_FAILED;
12451                BLOGE(sc, " No Recovery tried for error 0x%x"
12452                    " stack notified driver is NOT running!"
12453                    " Please reboot/power cycle the system.\n",
12454                    sc->error_status);
12455                BXE_CORE_UNLOCK(sc);
12456                return;
12457            }
12458
12459
12460           /* Try to get a LEADER_LOCK HW lock */
12461            if (bxe_trylock_leader_lock(sc)) {
12462
12463                bxe_set_reset_in_progress(sc);
12464                /*
12465                 * Check if there is a global attention and if
12466                 * there was a global attention, set the global
12467                 * reset bit.
12468                 */
12469                if (global) {
12470                    bxe_set_reset_global(sc);
12471                }
12472                sc->is_leader = 1;
12473            }
12474
12475            /* If interface has been removed - break */
12476
12477            if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12478                bxe_periodic_stop(sc);
12479            }
12480
12481            BXE_CORE_LOCK(sc);
12482            bxe_nic_unload(sc,UNLOAD_RECOVERY, false);
12483            sc->recovery_state = BXE_RECOVERY_WAIT;
12484            BXE_CORE_UNLOCK(sc);
12485
12486            /*
12487             * Ensure "is_leader", MCP command sequence and
12488             * "recovery_state" update values are seen on other
12489             * CPUs.
12490             */
12491            mb();
12492            break;
12493        case BXE_RECOVERY_WAIT:
12494
12495            if (sc->is_leader) {
12496                int other_engine = SC_PATH(sc) ? 0 : 1;
12497                bool other_load_status =
12498                    bxe_get_load_status(sc, other_engine);
12499                bool load_status =
12500                    bxe_get_load_status(sc, SC_PATH(sc));
12501                global = bxe_reset_is_global(sc);
12502
12503                /*
12504                 * In case of a parity in a global block, let
12505                 * the first leader that performs a
12506                 * leader_reset() reset the global blocks in
12507                 * order to clear global attentions. Otherwise
12508                 * the gates will remain closed for that
12509                 * engine.
12510                 */
12511                if (load_status ||
12512                    (global && other_load_status)) {
12513                    /*
12514                     * Wait until all other functions get
12515                     * down.
12516                     */
12517                    taskqueue_enqueue_timeout(taskqueue_thread,
12518                        &sc->sp_err_timeout_task, hz/10);
12519                    return;
12520                } else {
12521                    /*
12522                     * If all other functions got down
12523                     * try to bring the chip back to
12524                     * normal. In any case it's an exit
12525                     * point for a leader.
12526                     */
12527                    if (bxe_leader_reset(sc)) {
12528                        BLOGE(sc, "RECOVERY failed, "
12529                            "stack notified driver is NOT running!\n");
12530                        sc->recovery_state = BXE_RECOVERY_FAILED;
12531                        sc->state = BXE_STATE_ERROR;
12532                        mb();
12533                        return;
12534                    }
12535
12536                    /*
12537                     * If we are here, means that the
12538                     * leader has succeeded and doesn't
12539                     * want to be a leader any more. Try
12540                     * to continue as a none-leader.
12541                     */
12542                break;
12543                }
12544
12545            } else { /* non-leader */
12546                if (!bxe_reset_is_done(sc, SC_PATH(sc))) {
12547                    /*
12548                     * Try to get a LEADER_LOCK HW lock as
12549                     * long as a former leader may have
12550                     * been unloaded by the user or
12551                     * released a leadership by another
12552                     * reason.
12553                     */
12554                    if (bxe_trylock_leader_lock(sc)) {
12555                        /*
12556                         * I'm a leader now! Restart a
12557                         * switch case.
12558                         */
12559                        sc->is_leader = 1;
12560                        break;
12561                    }
12562
12563                    taskqueue_enqueue_timeout(taskqueue_thread,
12564                        &sc->sp_err_timeout_task, hz/10);
12565                    return;
12566
12567                } else {
12568                    /*
12569                     * If there was a global attention, wait
12570                     * for it to be cleared.
12571                     */
12572                    if (bxe_reset_is_global(sc)) {
12573                        taskqueue_enqueue_timeout(taskqueue_thread,
12574                            &sc->sp_err_timeout_task, hz/10);
12575                        return;
12576                     }
12577
12578                     error_recovered =
12579                         sc->eth_stats.recoverable_error;
12580                     error_unrecovered =
12581                         sc->eth_stats.unrecoverable_error;
12582                     BXE_CORE_LOCK(sc);
12583                     sc->recovery_state =
12584                         BXE_RECOVERY_NIC_LOADING;
12585                     if (bxe_nic_load(sc, LOAD_NORMAL)) {
12586                         error_unrecovered++;
12587                         sc->recovery_state = BXE_RECOVERY_FAILED;
12588                         sc->state = BXE_STATE_ERROR;
12589                         BLOGE(sc, "Recovery is NOT successfull, "
12590                            " state=0x%x recovery_state=0x%x error=%x\n",
12591                            sc->state, sc->recovery_state, sc->error_status);
12592                         sc->error_status = 0;
12593                     } else {
12594                         sc->recovery_state =
12595                             BXE_RECOVERY_DONE;
12596                         error_recovered++;
12597                         BLOGI(sc, "Recovery is successfull from errors %x,"
12598                            " state=0x%x"
12599                            " recovery_state=0x%x \n", sc->error_status,
12600                            sc->state, sc->recovery_state);
12601                         mb();
12602                     }
12603                     sc->error_status = 0;
12604                     BXE_CORE_UNLOCK(sc);
12605                     sc->eth_stats.recoverable_error =
12606                         error_recovered;
12607                     sc->eth_stats.unrecoverable_error =
12608                         error_unrecovered;
12609
12610                     return;
12611                 }
12612             }
12613         default:
12614             return;
12615         }
12616    }
12617}
12618void
12619bxe_handle_error(struct bxe_softc * sc)
12620{
12621
12622    if(sc->recovery_state == BXE_RECOVERY_WAIT) {
12623        return;
12624    }
12625    if(sc->error_status) {
12626        if (sc->state == BXE_STATE_OPEN)  {
12627            bxe_int_disable(sc);
12628        }
12629        if (sc->link_vars.link_up) {
12630            if_link_state_change(sc->ifp, LINK_STATE_DOWN);
12631        }
12632        sc->recovery_state = BXE_RECOVERY_INIT;
12633        BLOGI(sc, "bxe%d: Recovery started errors 0x%x recovery state 0x%x\n",
12634            sc->unit, sc->error_status, sc->recovery_state);
12635        bxe_parity_recover(sc);
12636   }
12637}
12638
12639static void
12640bxe_sp_err_timeout_task(void *arg, int pending)
12641{
12642
12643    struct bxe_softc *sc = (struct bxe_softc *)arg;
12644
12645    BLOGD(sc, DBG_SP,
12646        "%s state = 0x%x rec state=0x%x error_status=%x\n",
12647        __func__, sc->state, sc->recovery_state, sc->error_status);
12648
12649    if((sc->recovery_state == BXE_RECOVERY_FAILED) &&
12650       (sc->state == BXE_STATE_ERROR)) {
12651        return;
12652    }
12653    /* if can be taken */
12654    if ((sc->error_status) && (sc->trigger_grcdump)) {
12655        bxe_grc_dump(sc);
12656    }
12657    if (sc->recovery_state != BXE_RECOVERY_DONE) {
12658        bxe_handle_error(sc);
12659        bxe_parity_recover(sc);
12660    } else if (sc->error_status) {
12661        bxe_handle_error(sc);
12662    }
12663
12664    return;
12665}
12666
12667/* start the controller */
12668static __noinline int
12669bxe_nic_load(struct bxe_softc *sc,
12670             int              load_mode)
12671{
12672    uint32_t val;
12673    int load_code = 0;
12674    int i, rc = 0;
12675
12676    BXE_CORE_LOCK_ASSERT(sc);
12677
12678    BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12679
12680    sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12681
12682    if (IS_PF(sc)) {
12683        /* must be called before memory allocation and HW init */
12684        bxe_ilt_set_info(sc);
12685    }
12686
12687    sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12688
12689    bxe_set_fp_rx_buf_size(sc);
12690
12691    if (bxe_alloc_fp_buffers(sc) != 0) {
12692        BLOGE(sc, "Failed to allocate fastpath memory\n");
12693        sc->state = BXE_STATE_CLOSED;
12694        rc = ENOMEM;
12695        goto bxe_nic_load_error0;
12696    }
12697
12698    if (bxe_alloc_mem(sc) != 0) {
12699        sc->state = BXE_STATE_CLOSED;
12700        rc = ENOMEM;
12701        goto bxe_nic_load_error0;
12702    }
12703
12704    if (bxe_alloc_fw_stats_mem(sc) != 0) {
12705        sc->state = BXE_STATE_CLOSED;
12706        rc = ENOMEM;
12707        goto bxe_nic_load_error0;
12708    }
12709
12710    if (IS_PF(sc)) {
12711        /* set pf load just before approaching the MCP */
12712        bxe_set_pf_load(sc);
12713
12714        /* if MCP exists send load request and analyze response */
12715        if (!BXE_NOMCP(sc)) {
12716            /* attempt to load pf */
12717            if (bxe_nic_load_request(sc, &load_code) != 0) {
12718                sc->state = BXE_STATE_CLOSED;
12719                rc = ENXIO;
12720                goto bxe_nic_load_error1;
12721            }
12722
12723            /* what did the MCP say? */
12724            if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12725                bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12726                sc->state = BXE_STATE_CLOSED;
12727                rc = ENXIO;
12728                goto bxe_nic_load_error2;
12729            }
12730        } else {
12731            BLOGI(sc, "Device has no MCP!\n");
12732            load_code = bxe_nic_load_no_mcp(sc);
12733        }
12734
12735        /* mark PMF if applicable */
12736        bxe_nic_load_pmf(sc, load_code);
12737
12738        /* Init Function state controlling object */
12739        bxe_init_func_obj(sc);
12740
12741        /* Initialize HW */
12742        if (bxe_init_hw(sc, load_code) != 0) {
12743            BLOGE(sc, "HW init failed\n");
12744            bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12745            sc->state = BXE_STATE_CLOSED;
12746            rc = ENXIO;
12747            goto bxe_nic_load_error2;
12748        }
12749    }
12750
12751    /* set ALWAYS_ALIVE bit in shmem */
12752    sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12753    bxe_drv_pulse(sc);
12754    sc->flags |= BXE_NO_PULSE;
12755
12756    /* attach interrupts */
12757    if (bxe_interrupt_attach(sc) != 0) {
12758        sc->state = BXE_STATE_CLOSED;
12759        rc = ENXIO;
12760        goto bxe_nic_load_error2;
12761    }
12762
12763    bxe_nic_init(sc, load_code);
12764
12765    /* Init per-function objects */
12766    if (IS_PF(sc)) {
12767        bxe_init_objs(sc);
12768        // XXX bxe_iov_nic_init(sc);
12769
12770        /* set AFEX default VLAN tag to an invalid value */
12771        sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12772        // XXX bxe_nic_load_afex_dcc(sc, load_code);
12773
12774        sc->state = BXE_STATE_OPENING_WAITING_PORT;
12775        rc = bxe_func_start(sc);
12776        if (rc) {
12777            BLOGE(sc, "Function start failed! rc = %d\n", rc);
12778            bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12779            sc->state = BXE_STATE_ERROR;
12780            goto bxe_nic_load_error3;
12781        }
12782
12783        /* send LOAD_DONE command to MCP */
12784        if (!BXE_NOMCP(sc)) {
12785            load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12786            if (!load_code) {
12787                BLOGE(sc, "MCP response failure, aborting\n");
12788                sc->state = BXE_STATE_ERROR;
12789                rc = ENXIO;
12790                goto bxe_nic_load_error3;
12791            }
12792        }
12793
12794        rc = bxe_setup_leading(sc);
12795        if (rc) {
12796            BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12797            sc->state = BXE_STATE_ERROR;
12798            goto bxe_nic_load_error3;
12799        }
12800
12801        FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12802            rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12803            if (rc) {
12804                BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12805                sc->state = BXE_STATE_ERROR;
12806                goto bxe_nic_load_error3;
12807            }
12808        }
12809
12810        rc = bxe_init_rss_pf(sc);
12811        if (rc) {
12812            BLOGE(sc, "PF RSS init failed\n");
12813            sc->state = BXE_STATE_ERROR;
12814            goto bxe_nic_load_error3;
12815        }
12816    }
12817    /* XXX VF */
12818
12819    /* now when Clients are configured we are ready to work */
12820    sc->state = BXE_STATE_OPEN;
12821
12822    /* Configure a ucast MAC */
12823    if (IS_PF(sc)) {
12824        rc = bxe_set_eth_mac(sc, TRUE);
12825    }
12826    if (rc) {
12827        BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12828        sc->state = BXE_STATE_ERROR;
12829        goto bxe_nic_load_error3;
12830    }
12831
12832    if (sc->port.pmf) {
12833        rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12834        if (rc) {
12835            sc->state = BXE_STATE_ERROR;
12836            goto bxe_nic_load_error3;
12837        }
12838    }
12839
12840    sc->link_params.feature_config_flags &=
12841        ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12842
12843    /* start fast path */
12844
12845    /* Initialize Rx filter */
12846    bxe_set_rx_mode(sc);
12847
12848    /* start the Tx */
12849    switch (/* XXX load_mode */LOAD_OPEN) {
12850    case LOAD_NORMAL:
12851    case LOAD_OPEN:
12852        break;
12853
12854    case LOAD_DIAG:
12855    case LOAD_LOOPBACK_EXT:
12856        sc->state = BXE_STATE_DIAG;
12857        break;
12858
12859    default:
12860        break;
12861    }
12862
12863    if (sc->port.pmf) {
12864        bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12865    } else {
12866        bxe_link_status_update(sc);
12867    }
12868
12869    /* start the periodic timer callout */
12870    bxe_periodic_start(sc);
12871
12872    if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12873        /* mark driver is loaded in shmem2 */
12874        val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12875        SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12876                  (val |
12877                   DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12878                   DRV_FLAGS_CAPABILITIES_LOADED_L2));
12879    }
12880
12881    /* wait for all pending SP commands to complete */
12882    if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12883        BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12884        bxe_periodic_stop(sc);
12885        bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12886        return (ENXIO);
12887    }
12888
12889    /* Tell the stack the driver is running! */
12890    if_setdrvflags(sc->ifp, IFF_DRV_RUNNING);
12891
12892    BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12893
12894    return (0);
12895
12896bxe_nic_load_error3:
12897
12898    if (IS_PF(sc)) {
12899        bxe_int_disable_sync(sc, 1);
12900
12901        /* clean out queued objects */
12902        bxe_squeeze_objects(sc);
12903    }
12904
12905    bxe_interrupt_detach(sc);
12906
12907bxe_nic_load_error2:
12908
12909    if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12910        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12911        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12912    }
12913
12914    sc->port.pmf = 0;
12915
12916bxe_nic_load_error1:
12917
12918    /* clear pf_load status, as it was already set */
12919    if (IS_PF(sc)) {
12920        bxe_clear_pf_load(sc);
12921    }
12922
12923bxe_nic_load_error0:
12924
12925    bxe_free_fw_stats_mem(sc);
12926    bxe_free_fp_buffers(sc);
12927    bxe_free_mem(sc);
12928
12929    return (rc);
12930}
12931
12932static int
12933bxe_init_locked(struct bxe_softc *sc)
12934{
12935    int other_engine = SC_PATH(sc) ? 0 : 1;
12936    uint8_t other_load_status, load_status;
12937    uint8_t global = FALSE;
12938    int rc;
12939
12940    BXE_CORE_LOCK_ASSERT(sc);
12941
12942    /* check if the driver is already running */
12943    if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12944        BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12945        return (0);
12946    }
12947
12948    if((sc->state == BXE_STATE_ERROR) &&
12949        (sc->recovery_state == BXE_RECOVERY_FAILED)) {
12950        BLOGE(sc, "Initialization not done, "
12951                  "as previous recovery failed."
12952                  "Reboot/Power-cycle the system\n" );
12953        return (ENXIO);
12954    }
12955
12956
12957    bxe_set_power_state(sc, PCI_PM_D0);
12958
12959    /*
12960     * If parity occurred during the unload, then attentions and/or
12961     * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12962     * loaded on the current engine to complete the recovery. Parity recovery
12963     * is only relevant for PF driver.
12964     */
12965    if (IS_PF(sc)) {
12966        other_load_status = bxe_get_load_status(sc, other_engine);
12967        load_status = bxe_get_load_status(sc, SC_PATH(sc));
12968
12969        if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12970            bxe_chk_parity_attn(sc, &global, TRUE)) {
12971            do {
12972                /*
12973                 * If there are attentions and they are in global blocks, set
12974                 * the GLOBAL_RESET bit regardless whether it will be this
12975                 * function that will complete the recovery or not.
12976                 */
12977                if (global) {
12978                    bxe_set_reset_global(sc);
12979                }
12980
12981                /*
12982                 * Only the first function on the current engine should try
12983                 * to recover in open. In case of attentions in global blocks
12984                 * only the first in the chip should try to recover.
12985                 */
12986                if ((!load_status && (!global || !other_load_status)) &&
12987                    bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12988                    BLOGI(sc, "Recovered during init\n");
12989                    break;
12990                }
12991
12992                /* recovery has failed... */
12993                bxe_set_power_state(sc, PCI_PM_D3hot);
12994                sc->recovery_state = BXE_RECOVERY_FAILED;
12995
12996                BLOGE(sc, "Recovery flow hasn't properly "
12997                          "completed yet, try again later. "
12998                          "If you still see this message after a "
12999                          "few retries then power cycle is required.\n");
13000
13001                rc = ENXIO;
13002                goto bxe_init_locked_done;
13003            } while (0);
13004        }
13005    }
13006
13007    sc->recovery_state = BXE_RECOVERY_DONE;
13008
13009    rc = bxe_nic_load(sc, LOAD_OPEN);
13010
13011bxe_init_locked_done:
13012
13013    if (rc) {
13014        /* Tell the stack the driver is NOT running! */
13015        BLOGE(sc, "Initialization failed, "
13016                  "stack notified driver is NOT running!\n");
13017	if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
13018    }
13019
13020    return (rc);
13021}
13022
13023static int
13024bxe_stop_locked(struct bxe_softc *sc)
13025{
13026    BXE_CORE_LOCK_ASSERT(sc);
13027    return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
13028}
13029
13030/*
13031 * Handles controller initialization when called from an unlocked routine.
13032 * ifconfig calls this function.
13033 *
13034 * Returns:
13035 *   void
13036 */
13037static void
13038bxe_init(void *xsc)
13039{
13040    struct bxe_softc *sc = (struct bxe_softc *)xsc;
13041
13042    BXE_CORE_LOCK(sc);
13043    bxe_init_locked(sc);
13044    BXE_CORE_UNLOCK(sc);
13045}
13046
13047static int
13048bxe_init_ifnet(struct bxe_softc *sc)
13049{
13050    if_t ifp;
13051    int capabilities;
13052
13053    /* ifconfig entrypoint for media type/status reporting */
13054    ifmedia_init(&sc->ifmedia, IFM_IMASK,
13055                 bxe_ifmedia_update,
13056                 bxe_ifmedia_status);
13057
13058    /* set the default interface values */
13059    ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
13060    ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
13061    ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
13062
13063    sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
13064	BLOGI(sc, "IFMEDIA flags : %x\n", sc->ifmedia.ifm_media);
13065
13066    /* allocate the ifnet structure */
13067    if ((ifp = if_gethandle(IFT_ETHER)) == NULL) {
13068        BLOGE(sc, "Interface allocation failed!\n");
13069        return (ENXIO);
13070    }
13071
13072    if_setsoftc(ifp, sc);
13073    if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
13074    if_setflags(ifp, (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST));
13075    if_setioctlfn(ifp, bxe_ioctl);
13076    if_setstartfn(ifp, bxe_tx_start);
13077    if_setgetcounterfn(ifp, bxe_get_counter);
13078#if __FreeBSD_version >= 901504
13079    if_settransmitfn(ifp, bxe_tx_mq_start);
13080    if_setqflushfn(ifp, bxe_mq_flush);
13081#endif
13082#ifdef FreeBSD8_0
13083    if_settimer(ifp, 0);
13084#endif
13085    if_setinitfn(ifp, bxe_init);
13086    if_setmtu(ifp, sc->mtu);
13087    if_sethwassist(ifp, (CSUM_IP      |
13088                        CSUM_TCP      |
13089                        CSUM_UDP      |
13090                        CSUM_TSO      |
13091                        CSUM_TCP_IPV6 |
13092                        CSUM_UDP_IPV6));
13093
13094    capabilities =
13095#if __FreeBSD_version < 700000
13096        (IFCAP_VLAN_MTU       |
13097         IFCAP_VLAN_HWTAGGING |
13098         IFCAP_HWCSUM         |
13099         IFCAP_JUMBO_MTU      |
13100         IFCAP_LRO);
13101#else
13102        (IFCAP_VLAN_MTU       |
13103         IFCAP_VLAN_HWTAGGING |
13104         IFCAP_VLAN_HWTSO     |
13105         IFCAP_VLAN_HWFILTER  |
13106         IFCAP_VLAN_HWCSUM    |
13107         IFCAP_HWCSUM         |
13108         IFCAP_JUMBO_MTU      |
13109         IFCAP_LRO            |
13110         IFCAP_TSO4           |
13111         IFCAP_TSO6           |
13112         IFCAP_WOL_MAGIC);
13113#endif
13114    if_setcapabilitiesbit(ifp, capabilities, 0); /* XXX */
13115    if_setcapenable(ifp, if_getcapabilities(ifp));
13116    if_setbaudrate(ifp, IF_Gbps(10));
13117/* XXX */
13118    if_setsendqlen(ifp, sc->tx_ring_size);
13119    if_setsendqready(ifp);
13120/* XXX */
13121
13122    sc->ifp = ifp;
13123
13124    /* attach to the Ethernet interface list */
13125    ether_ifattach(ifp, sc->link_params.mac_addr);
13126
13127    /* Attach driver netdump methods. */
13128    NETDUMP_SET(ifp, bxe);
13129
13130    return (0);
13131}
13132
13133static void
13134bxe_deallocate_bars(struct bxe_softc *sc)
13135{
13136    int i;
13137
13138    for (i = 0; i < MAX_BARS; i++) {
13139        if (sc->bar[i].resource != NULL) {
13140            bus_release_resource(sc->dev,
13141                                 SYS_RES_MEMORY,
13142                                 sc->bar[i].rid,
13143                                 sc->bar[i].resource);
13144            BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
13145                  i, PCIR_BAR(i));
13146        }
13147    }
13148}
13149
13150static int
13151bxe_allocate_bars(struct bxe_softc *sc)
13152{
13153    u_int flags;
13154    int i;
13155
13156    memset(sc->bar, 0, sizeof(sc->bar));
13157
13158    for (i = 0; i < MAX_BARS; i++) {
13159
13160        /* memory resources reside at BARs 0, 2, 4 */
13161        /* Run `pciconf -lb` to see mappings */
13162        if ((i != 0) && (i != 2) && (i != 4)) {
13163            continue;
13164        }
13165
13166        sc->bar[i].rid = PCIR_BAR(i);
13167
13168        flags = RF_ACTIVE;
13169        if (i == 0) {
13170            flags |= RF_SHAREABLE;
13171        }
13172
13173        if ((sc->bar[i].resource =
13174             bus_alloc_resource_any(sc->dev,
13175                                    SYS_RES_MEMORY,
13176                                    &sc->bar[i].rid,
13177                                    flags)) == NULL) {
13178            return (0);
13179        }
13180
13181        sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
13182        sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
13183        sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
13184
13185        BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %#jx-%#jx (%jd) -> %#jx\n",
13186              i, PCIR_BAR(i),
13187              rman_get_start(sc->bar[i].resource),
13188              rman_get_end(sc->bar[i].resource),
13189              rman_get_size(sc->bar[i].resource),
13190              (uintmax_t)sc->bar[i].kva);
13191    }
13192
13193    return (0);
13194}
13195
13196static void
13197bxe_get_function_num(struct bxe_softc *sc)
13198{
13199    uint32_t val = 0;
13200
13201    /*
13202     * Read the ME register to get the function number. The ME register
13203     * holds the relative-function number and absolute-function number. The
13204     * absolute-function number appears only in E2 and above. Before that
13205     * these bits always contained zero, therefore we cannot blindly use them.
13206     */
13207
13208    val = REG_RD(sc, BAR_ME_REGISTER);
13209
13210    sc->pfunc_rel =
13211        (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
13212    sc->path_id =
13213        (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
13214
13215    if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13216        sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
13217    } else {
13218        sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
13219    }
13220
13221    BLOGD(sc, DBG_LOAD,
13222          "Relative function %d, Absolute function %d, Path %d\n",
13223          sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
13224}
13225
13226static uint32_t
13227bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
13228{
13229    uint32_t shmem2_size;
13230    uint32_t offset;
13231    uint32_t mf_cfg_offset_value;
13232
13233    /* Non 57712 */
13234    offset = (SHMEM_RD(sc, func_mb) +
13235              (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
13236
13237    /* 57712 plus */
13238    if (sc->devinfo.shmem2_base != 0) {
13239        shmem2_size = SHMEM2_RD(sc, size);
13240        if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
13241            mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
13242            if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
13243                offset = mf_cfg_offset_value;
13244            }
13245        }
13246    }
13247
13248    return (offset);
13249}
13250
13251static uint32_t
13252bxe_pcie_capability_read(struct bxe_softc *sc,
13253                         int    reg,
13254                         int    width)
13255{
13256    int pcie_reg;
13257
13258    /* ensure PCIe capability is enabled */
13259    if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
13260        if (pcie_reg != 0) {
13261            BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
13262            return (pci_read_config(sc->dev, (pcie_reg + reg), width));
13263        }
13264    }
13265
13266    BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
13267
13268    return (0);
13269}
13270
13271static uint8_t
13272bxe_is_pcie_pending(struct bxe_softc *sc)
13273{
13274    return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
13275            PCIM_EXP_STA_TRANSACTION_PND);
13276}
13277
13278/*
13279 * Walk the PCI capabiites list for the device to find what features are
13280 * supported. These capabilites may be enabled/disabled by firmware so it's
13281 * best to walk the list rather than make assumptions.
13282 */
13283static void
13284bxe_probe_pci_caps(struct bxe_softc *sc)
13285{
13286    uint16_t link_status;
13287    int reg;
13288
13289    /* check if PCI Power Management is enabled */
13290    if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
13291        if (reg != 0) {
13292            BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
13293
13294            sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
13295            sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
13296        }
13297    }
13298
13299    link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
13300
13301    /* handle PCIe 2.0 workarounds for 57710 */
13302    if (CHIP_IS_E1(sc)) {
13303        /* workaround for 57710 errata E4_57710_27462 */
13304        sc->devinfo.pcie_link_speed =
13305            (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
13306
13307        /* workaround for 57710 errata E4_57710_27488 */
13308        sc->devinfo.pcie_link_width =
13309            ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13310        if (sc->devinfo.pcie_link_speed > 1) {
13311            sc->devinfo.pcie_link_width =
13312                ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
13313        }
13314    } else {
13315        sc->devinfo.pcie_link_speed =
13316            (link_status & PCIM_LINK_STA_SPEED);
13317        sc->devinfo.pcie_link_width =
13318            ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13319    }
13320
13321    BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
13322          sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
13323
13324    sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
13325    sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
13326
13327    /* check if MSI capability is enabled */
13328    if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
13329        if (reg != 0) {
13330            BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13331
13332            sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13333            sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13334        }
13335    }
13336
13337    /* check if MSI-X capability is enabled */
13338    if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13339        if (reg != 0) {
13340            BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13341
13342            sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13343            sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13344        }
13345    }
13346}
13347
13348static int
13349bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13350{
13351    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13352    uint32_t val;
13353
13354    /* get the outer vlan if we're in switch-dependent mode */
13355
13356    val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13357    mf_info->ext_id = (uint16_t)val;
13358
13359    mf_info->multi_vnics_mode = 1;
13360
13361    if (!VALID_OVLAN(mf_info->ext_id)) {
13362        BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13363        return (1);
13364    }
13365
13366    /* get the capabilities */
13367    if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13368        FUNC_MF_CFG_PROTOCOL_ISCSI) {
13369        mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13370    } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13371               FUNC_MF_CFG_PROTOCOL_FCOE) {
13372        mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13373    } else {
13374        mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13375    }
13376
13377    mf_info->vnics_per_port =
13378        (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13379
13380    return (0);
13381}
13382
13383static uint32_t
13384bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13385{
13386    uint32_t retval = 0;
13387    uint32_t val;
13388
13389    val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13390
13391    if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13392        if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13393            retval |= MF_PROTO_SUPPORT_ETHERNET;
13394        }
13395        if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13396            retval |= MF_PROTO_SUPPORT_ISCSI;
13397        }
13398        if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13399            retval |= MF_PROTO_SUPPORT_FCOE;
13400        }
13401    }
13402
13403    return (retval);
13404}
13405
13406static int
13407bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13408{
13409    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13410    uint32_t val;
13411
13412    /*
13413     * There is no outer vlan if we're in switch-independent mode.
13414     * If the mac is valid then assume multi-function.
13415     */
13416
13417    val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13418
13419    mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13420
13421    mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13422
13423    mf_info->vnics_per_port =
13424        (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13425
13426    return (0);
13427}
13428
13429static int
13430bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13431{
13432    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13433    uint32_t e1hov_tag;
13434    uint32_t func_config;
13435    uint32_t niv_config;
13436
13437    mf_info->multi_vnics_mode = 1;
13438
13439    e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13440    func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13441    niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13442
13443    mf_info->ext_id =
13444        (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13445                   FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13446
13447    mf_info->default_vlan =
13448        (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13449                   FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13450
13451    mf_info->niv_allowed_priorities =
13452        (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13453                  FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13454
13455    mf_info->niv_default_cos =
13456        (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13457                  FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13458
13459    mf_info->afex_vlan_mode =
13460        ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13461         FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13462
13463    mf_info->niv_mba_enabled =
13464        ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13465         FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13466
13467    mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13468
13469    mf_info->vnics_per_port =
13470        (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13471
13472    return (0);
13473}
13474
13475static int
13476bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13477{
13478    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13479    uint32_t mf_cfg1;
13480    uint32_t mf_cfg2;
13481    uint32_t ovlan1;
13482    uint32_t ovlan2;
13483    uint8_t i, j;
13484
13485    BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13486          SC_PORT(sc));
13487    BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13488          mf_info->mf_config[SC_VN(sc)]);
13489    BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13490          mf_info->multi_vnics_mode);
13491    BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13492          mf_info->vnics_per_port);
13493    BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13494          mf_info->ext_id);
13495    BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13496          mf_info->min_bw[0], mf_info->min_bw[1],
13497          mf_info->min_bw[2], mf_info->min_bw[3]);
13498    BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13499          mf_info->max_bw[0], mf_info->max_bw[1],
13500          mf_info->max_bw[2], mf_info->max_bw[3]);
13501    BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13502          sc->mac_addr_str);
13503
13504    /* various MF mode sanity checks... */
13505
13506    if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13507        BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13508              SC_PORT(sc));
13509        return (1);
13510    }
13511
13512    if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13513        BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13514              mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13515        return (1);
13516    }
13517
13518    if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13519        /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13520        if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13521            BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13522                  SC_VN(sc), OVLAN(sc));
13523            return (1);
13524        }
13525
13526        if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13527            BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13528                  mf_info->multi_vnics_mode, OVLAN(sc));
13529            return (1);
13530        }
13531
13532        /*
13533         * Verify all functions are either MF or SF mode. If MF, make sure
13534         * sure that all non-hidden functions have a valid ovlan. If SF,
13535         * make sure that all non-hidden functions have an invalid ovlan.
13536         */
13537        FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13538            mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13539            ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13540            if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13541                (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13542                 ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13543                BLOGE(sc, "mf_mode=SD function %d MF config "
13544                          "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13545                      i, mf_info->multi_vnics_mode, ovlan1);
13546                return (1);
13547            }
13548        }
13549
13550        /* Verify all funcs on the same port each have a different ovlan. */
13551        FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13552            mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13553            ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13554            /* iterate from the next function on the port to the max func */
13555            for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13556                mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13557                ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13558                if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13559                    VALID_OVLAN(ovlan1) &&
13560                    !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13561                    VALID_OVLAN(ovlan2) &&
13562                    (ovlan1 == ovlan2)) {
13563                    BLOGE(sc, "mf_mode=SD functions %d and %d "
13564                              "have the same ovlan (%d)\n",
13565                          i, j, ovlan1);
13566                    return (1);
13567                }
13568            }
13569        }
13570    } /* MULTI_FUNCTION_SD */
13571
13572    return (0);
13573}
13574
13575static int
13576bxe_get_mf_cfg_info(struct bxe_softc *sc)
13577{
13578    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13579    uint32_t val, mac_upper;
13580    uint8_t i, vnic;
13581
13582    /* initialize mf_info defaults */
13583    mf_info->vnics_per_port   = 1;
13584    mf_info->multi_vnics_mode = FALSE;
13585    mf_info->path_has_ovlan   = FALSE;
13586    mf_info->mf_mode          = SINGLE_FUNCTION;
13587
13588    if (!CHIP_IS_MF_CAP(sc)) {
13589        return (0);
13590    }
13591
13592    if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13593        BLOGE(sc, "Invalid mf_cfg_base!\n");
13594        return (1);
13595    }
13596
13597    /* get the MF mode (switch dependent / independent / single-function) */
13598
13599    val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13600
13601    switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13602    {
13603    case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13604
13605        mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13606
13607        /* check for legal upper mac bytes */
13608        if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13609            mf_info->mf_mode = MULTI_FUNCTION_SI;
13610        } else {
13611            BLOGE(sc, "Invalid config for Switch Independent mode\n");
13612        }
13613
13614        break;
13615
13616    case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13617    case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13618
13619        /* get outer vlan configuration */
13620        val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13621
13622        if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13623            FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13624            mf_info->mf_mode = MULTI_FUNCTION_SD;
13625        } else {
13626            BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13627        }
13628
13629        break;
13630
13631    case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13632
13633        /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13634        return (0);
13635
13636    case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13637
13638        /*
13639         * Mark MF mode as NIV if MCP version includes NPAR-SD support
13640         * and the MAC address is valid.
13641         */
13642        mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13643
13644        if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13645            (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13646            mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13647        } else {
13648            BLOGE(sc, "Invalid config for AFEX mode\n");
13649        }
13650
13651        break;
13652
13653    default:
13654
13655        BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13656              (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13657
13658        return (1);
13659    }
13660
13661    /* set path mf_mode (which could be different than function mf_mode) */
13662    if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13663        mf_info->path_has_ovlan = TRUE;
13664    } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13665        /*
13666         * Decide on path multi vnics mode. If we're not in MF mode and in
13667         * 4-port mode, this is good enough to check vnic-0 of the other port
13668         * on the same path
13669         */
13670        if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13671            uint8_t other_port = !(PORT_ID(sc) & 1);
13672            uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13673
13674            val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13675
13676            mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13677        }
13678    }
13679
13680    if (mf_info->mf_mode == SINGLE_FUNCTION) {
13681        /* invalid MF config */
13682        if (SC_VN(sc) >= 1) {
13683            BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13684            return (1);
13685        }
13686
13687        return (0);
13688    }
13689
13690    /* get the MF configuration */
13691    mf_info->mf_config[SC_VN(sc)] =
13692        MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13693
13694    switch(mf_info->mf_mode)
13695    {
13696    case MULTI_FUNCTION_SD:
13697
13698        bxe_get_shmem_mf_cfg_info_sd(sc);
13699        break;
13700
13701    case MULTI_FUNCTION_SI:
13702
13703        bxe_get_shmem_mf_cfg_info_si(sc);
13704        break;
13705
13706    case MULTI_FUNCTION_AFEX:
13707
13708        bxe_get_shmem_mf_cfg_info_niv(sc);
13709        break;
13710
13711    default:
13712
13713        BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13714              mf_info->mf_mode);
13715        return (1);
13716    }
13717
13718    /* get the congestion management parameters */
13719
13720    vnic = 0;
13721    FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13722        /* get min/max bw */
13723        val = MFCFG_RD(sc, func_mf_config[i].config);
13724        mf_info->min_bw[vnic] =
13725            ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13726        mf_info->max_bw[vnic] =
13727            ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13728        vnic++;
13729    }
13730
13731    return (bxe_check_valid_mf_cfg(sc));
13732}
13733
13734static int
13735bxe_get_shmem_info(struct bxe_softc *sc)
13736{
13737    int port;
13738    uint32_t mac_hi, mac_lo, val;
13739
13740    port = SC_PORT(sc);
13741    mac_hi = mac_lo = 0;
13742
13743    sc->link_params.sc   = sc;
13744    sc->link_params.port = port;
13745
13746    /* get the hardware config info */
13747    sc->devinfo.hw_config =
13748        SHMEM_RD(sc, dev_info.shared_hw_config.config);
13749    sc->devinfo.hw_config2 =
13750        SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13751
13752    sc->link_params.hw_led_mode =
13753        ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13754         SHARED_HW_CFG_LED_MODE_SHIFT);
13755
13756    /* get the port feature config */
13757    sc->port.config =
13758        SHMEM_RD(sc, dev_info.port_feature_config[port].config);
13759
13760    /* get the link params */
13761    sc->link_params.speed_cap_mask[0] =
13762        SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13763    sc->link_params.speed_cap_mask[1] =
13764        SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13765
13766    /* get the lane config */
13767    sc->link_params.lane_config =
13768        SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13769
13770    /* get the link config */
13771    val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13772    sc->port.link_config[ELINK_INT_PHY] = val;
13773    sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13774    sc->port.link_config[ELINK_EXT_PHY1] =
13775        SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13776
13777    /* get the override preemphasis flag and enable it or turn it off */
13778    val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13779    if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13780        sc->link_params.feature_config_flags |=
13781            ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13782    } else {
13783        sc->link_params.feature_config_flags &=
13784            ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13785    }
13786
13787    /* get the initial value of the link params */
13788    sc->link_params.multi_phy_config =
13789        SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13790
13791    /* get external phy info */
13792    sc->port.ext_phy_config =
13793        SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13794
13795    /* get the multifunction configuration */
13796    bxe_get_mf_cfg_info(sc);
13797
13798    /* get the mac address */
13799    if (IS_MF(sc)) {
13800        mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13801        mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13802    } else {
13803        mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13804        mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13805    }
13806
13807    if ((mac_lo == 0) && (mac_hi == 0)) {
13808        *sc->mac_addr_str = 0;
13809        BLOGE(sc, "No Ethernet address programmed!\n");
13810    } else {
13811        sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13812        sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13813        sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13814        sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13815        sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13816        sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13817        snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13818                 "%02x:%02x:%02x:%02x:%02x:%02x",
13819                 sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13820                 sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13821                 sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13822        BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13823    }
13824
13825    return (0);
13826}
13827
13828static void
13829bxe_get_tunable_params(struct bxe_softc *sc)
13830{
13831    /* sanity checks */
13832
13833    if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13834        (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13835        (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13836        BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13837        bxe_interrupt_mode = INTR_MODE_MSIX;
13838    }
13839
13840    if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13841        BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13842        bxe_queue_count = 0;
13843    }
13844
13845    if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13846        if (bxe_max_rx_bufs == 0) {
13847            bxe_max_rx_bufs = RX_BD_USABLE;
13848        } else {
13849            BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13850            bxe_max_rx_bufs = 2048;
13851        }
13852    }
13853
13854    if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13855        BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13856        bxe_hc_rx_ticks = 25;
13857    }
13858
13859    if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13860        BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13861        bxe_hc_tx_ticks = 50;
13862    }
13863
13864    if (bxe_max_aggregation_size == 0) {
13865        bxe_max_aggregation_size = TPA_AGG_SIZE;
13866    }
13867
13868    if (bxe_max_aggregation_size > 0xffff) {
13869        BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13870              bxe_max_aggregation_size);
13871        bxe_max_aggregation_size = TPA_AGG_SIZE;
13872    }
13873
13874    if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13875        BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13876        bxe_mrrs = -1;
13877    }
13878
13879    if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13880        BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13881        bxe_autogreeen = 0;
13882    }
13883
13884    if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13885        BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13886        bxe_udp_rss = 0;
13887    }
13888
13889    /* pull in user settings */
13890
13891    sc->interrupt_mode       = bxe_interrupt_mode;
13892    sc->max_rx_bufs          = bxe_max_rx_bufs;
13893    sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13894    sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13895    sc->max_aggregation_size = bxe_max_aggregation_size;
13896    sc->mrrs                 = bxe_mrrs;
13897    sc->autogreeen           = bxe_autogreeen;
13898    sc->udp_rss              = bxe_udp_rss;
13899
13900    if (bxe_interrupt_mode == INTR_MODE_INTX) {
13901        sc->num_queues = 1;
13902    } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13903        sc->num_queues =
13904            min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13905                MAX_RSS_CHAINS);
13906        if (sc->num_queues > mp_ncpus) {
13907            sc->num_queues = mp_ncpus;
13908        }
13909    }
13910
13911    BLOGD(sc, DBG_LOAD,
13912          "User Config: "
13913          "debug=0x%lx "
13914          "interrupt_mode=%d "
13915          "queue_count=%d "
13916          "hc_rx_ticks=%d "
13917          "hc_tx_ticks=%d "
13918          "rx_budget=%d "
13919          "max_aggregation_size=%d "
13920          "mrrs=%d "
13921          "autogreeen=%d "
13922          "udp_rss=%d\n",
13923          bxe_debug,
13924          sc->interrupt_mode,
13925          sc->num_queues,
13926          sc->hc_rx_ticks,
13927          sc->hc_tx_ticks,
13928          bxe_rx_budget,
13929          sc->max_aggregation_size,
13930          sc->mrrs,
13931          sc->autogreeen,
13932          sc->udp_rss);
13933}
13934
13935static int
13936bxe_media_detect(struct bxe_softc *sc)
13937{
13938    int port_type;
13939    uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13940
13941    switch (sc->link_params.phy[phy_idx].media_type) {
13942    case ELINK_ETH_PHY_SFPP_10G_FIBER:
13943    case ELINK_ETH_PHY_XFP_FIBER:
13944        BLOGI(sc, "Found 10Gb Fiber media.\n");
13945        sc->media = IFM_10G_SR;
13946        port_type = PORT_FIBRE;
13947        break;
13948    case ELINK_ETH_PHY_SFP_1G_FIBER:
13949        BLOGI(sc, "Found 1Gb Fiber media.\n");
13950        sc->media = IFM_1000_SX;
13951        port_type = PORT_FIBRE;
13952        break;
13953    case ELINK_ETH_PHY_KR:
13954    case ELINK_ETH_PHY_CX4:
13955        BLOGI(sc, "Found 10GBase-CX4 media.\n");
13956        sc->media = IFM_10G_CX4;
13957        port_type = PORT_FIBRE;
13958        break;
13959    case ELINK_ETH_PHY_DA_TWINAX:
13960        BLOGI(sc, "Found 10Gb Twinax media.\n");
13961        sc->media = IFM_10G_TWINAX;
13962        port_type = PORT_DA;
13963        break;
13964    case ELINK_ETH_PHY_BASE_T:
13965        if (sc->link_params.speed_cap_mask[0] &
13966            PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13967            BLOGI(sc, "Found 10GBase-T media.\n");
13968            sc->media = IFM_10G_T;
13969            port_type = PORT_TP;
13970        } else {
13971            BLOGI(sc, "Found 1000Base-T media.\n");
13972            sc->media = IFM_1000_T;
13973            port_type = PORT_TP;
13974        }
13975        break;
13976    case ELINK_ETH_PHY_NOT_PRESENT:
13977        BLOGI(sc, "Media not present.\n");
13978        sc->media = 0;
13979        port_type = PORT_OTHER;
13980        break;
13981    case ELINK_ETH_PHY_UNSPECIFIED:
13982    default:
13983        BLOGI(sc, "Unknown media!\n");
13984        sc->media = 0;
13985        port_type = PORT_OTHER;
13986        break;
13987    }
13988    return port_type;
13989}
13990
13991#define GET_FIELD(value, fname)                     \
13992    (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13993#define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13994#define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13995
13996static int
13997bxe_get_igu_cam_info(struct bxe_softc *sc)
13998{
13999    int pfid = SC_FUNC(sc);
14000    int igu_sb_id;
14001    uint32_t val;
14002    uint8_t fid, igu_sb_cnt = 0;
14003
14004    sc->igu_base_sb = 0xff;
14005
14006    if (CHIP_INT_MODE_IS_BC(sc)) {
14007        int vn = SC_VN(sc);
14008        igu_sb_cnt = sc->igu_sb_cnt;
14009        sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
14010                           FP_SB_MAX_E1x);
14011        sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
14012                          (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
14013        return (0);
14014    }
14015
14016    /* IGU in normal mode - read CAM */
14017    for (igu_sb_id = 0;
14018         igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
14019         igu_sb_id++) {
14020        val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
14021        if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
14022            continue;
14023        }
14024        fid = IGU_FID(val);
14025        if ((fid & IGU_FID_ENCODE_IS_PF)) {
14026            if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
14027                continue;
14028            }
14029            if (IGU_VEC(val) == 0) {
14030                /* default status block */
14031                sc->igu_dsb_id = igu_sb_id;
14032            } else {
14033                if (sc->igu_base_sb == 0xff) {
14034                    sc->igu_base_sb = igu_sb_id;
14035                }
14036                igu_sb_cnt++;
14037            }
14038        }
14039    }
14040
14041    /*
14042     * Due to new PF resource allocation by MFW T7.4 and above, it's optional
14043     * that number of CAM entries will not be equal to the value advertised in
14044     * PCI. Driver should use the minimal value of both as the actual status
14045     * block count
14046     */
14047    sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
14048
14049    if (igu_sb_cnt == 0) {
14050        BLOGE(sc, "CAM configuration error\n");
14051        return (-1);
14052    }
14053
14054    return (0);
14055}
14056
14057/*
14058 * Gather various information from the device config space, the device itself,
14059 * shmem, and the user input.
14060 */
14061static int
14062bxe_get_device_info(struct bxe_softc *sc)
14063{
14064    uint32_t val;
14065    int rc;
14066
14067    /* Get the data for the device */
14068    sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
14069    sc->devinfo.device_id    = pci_get_device(sc->dev);
14070    sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
14071    sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
14072
14073    /* get the chip revision (chip metal comes from pci config space) */
14074    sc->devinfo.chip_id     =
14075    sc->link_params.chip_id =
14076        (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
14077         ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
14078         (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
14079         ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
14080
14081    /* force 57811 according to MISC register */
14082    if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
14083        if (CHIP_IS_57810(sc)) {
14084            sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
14085                                   (sc->devinfo.chip_id & 0x0000ffff));
14086        } else if (CHIP_IS_57810_MF(sc)) {
14087            sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
14088                                   (sc->devinfo.chip_id & 0x0000ffff));
14089        }
14090        sc->devinfo.chip_id |= 0x1;
14091    }
14092
14093    BLOGD(sc, DBG_LOAD,
14094          "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
14095          sc->devinfo.chip_id,
14096          ((sc->devinfo.chip_id >> 16) & 0xffff),
14097          ((sc->devinfo.chip_id >> 12) & 0xf),
14098          ((sc->devinfo.chip_id >>  4) & 0xff),
14099          ((sc->devinfo.chip_id >>  0) & 0xf));
14100
14101    val = (REG_RD(sc, 0x2874) & 0x55);
14102    if ((sc->devinfo.chip_id & 0x1) ||
14103        (CHIP_IS_E1(sc) && val) ||
14104        (CHIP_IS_E1H(sc) && (val == 0x55))) {
14105        sc->flags |= BXE_ONE_PORT_FLAG;
14106        BLOGD(sc, DBG_LOAD, "single port device\n");
14107    }
14108
14109    /* set the doorbell size */
14110    sc->doorbell_size = (1 << BXE_DB_SHIFT);
14111
14112    /* determine whether the device is in 2 port or 4 port mode */
14113    sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
14114    if (CHIP_IS_E2E3(sc)) {
14115        /*
14116         * Read port4mode_en_ovwr[0]:
14117         *   If 1, four port mode is in port4mode_en_ovwr[1].
14118         *   If 0, four port mode is in port4mode_en[0].
14119         */
14120        val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
14121        if (val & 1) {
14122            val = ((val >> 1) & 1);
14123        } else {
14124            val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
14125        }
14126
14127        sc->devinfo.chip_port_mode =
14128            (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
14129
14130        BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
14131    }
14132
14133    /* get the function and path info for the device */
14134    bxe_get_function_num(sc);
14135
14136    /* get the shared memory base address */
14137    sc->devinfo.shmem_base     =
14138    sc->link_params.shmem_base =
14139        REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
14140    sc->devinfo.shmem2_base =
14141        REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
14142                                  MISC_REG_GENERIC_CR_0));
14143
14144    BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
14145          sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
14146
14147    if (!sc->devinfo.shmem_base) {
14148        /* this should ONLY prevent upcoming shmem reads */
14149        BLOGI(sc, "MCP not active\n");
14150        sc->flags |= BXE_NO_MCP_FLAG;
14151        return (0);
14152    }
14153
14154    /* make sure the shared memory contents are valid */
14155    val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
14156    if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
14157        (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
14158        BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
14159        return (0);
14160    }
14161    BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
14162
14163    /* get the bootcode version */
14164    sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
14165    snprintf(sc->devinfo.bc_ver_str,
14166             sizeof(sc->devinfo.bc_ver_str),
14167             "%d.%d.%d",
14168             ((sc->devinfo.bc_ver >> 24) & 0xff),
14169             ((sc->devinfo.bc_ver >> 16) & 0xff),
14170             ((sc->devinfo.bc_ver >>  8) & 0xff));
14171    BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
14172
14173    /* get the bootcode shmem address */
14174    sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
14175    BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
14176
14177    /* clean indirect addresses as they're not used */
14178    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
14179    if (IS_PF(sc)) {
14180        REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
14181        REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
14182        REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
14183        REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
14184        if (CHIP_IS_E1x(sc)) {
14185            REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
14186            REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
14187            REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
14188            REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
14189        }
14190
14191        /*
14192         * Enable internal target-read (in case we are probed after PF
14193         * FLR). Must be done prior to any BAR read access. Only for
14194         * 57712 and up
14195         */
14196        if (!CHIP_IS_E1x(sc)) {
14197            REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
14198        }
14199    }
14200
14201    /* get the nvram size */
14202    val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
14203    sc->devinfo.flash_size =
14204        (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
14205    BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
14206
14207    /* get PCI capabilites */
14208    bxe_probe_pci_caps(sc);
14209
14210    bxe_set_power_state(sc, PCI_PM_D0);
14211
14212    /* get various configuration parameters from shmem */
14213    bxe_get_shmem_info(sc);
14214
14215    if (sc->devinfo.pcie_msix_cap_reg != 0) {
14216        val = pci_read_config(sc->dev,
14217                              (sc->devinfo.pcie_msix_cap_reg +
14218                               PCIR_MSIX_CTRL),
14219                              2);
14220        sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
14221    } else {
14222        sc->igu_sb_cnt = 1;
14223    }
14224
14225    sc->igu_base_addr = BAR_IGU_INTMEM;
14226
14227    /* initialize IGU parameters */
14228    if (CHIP_IS_E1x(sc)) {
14229        sc->devinfo.int_block = INT_BLOCK_HC;
14230        sc->igu_dsb_id = DEF_SB_IGU_ID;
14231        sc->igu_base_sb = 0;
14232    } else {
14233        sc->devinfo.int_block = INT_BLOCK_IGU;
14234
14235        /* do not allow device reset during IGU info preocessing */
14236        bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14237
14238        val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
14239
14240        if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
14241            int tout = 5000;
14242
14243            BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
14244
14245            val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
14246            REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
14247            REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
14248
14249            while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14250                tout--;
14251                DELAY(1000);
14252            }
14253
14254            if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14255                BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
14256                bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14257                return (-1);
14258            }
14259        }
14260
14261        if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
14262            BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
14263            sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
14264        } else {
14265            BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
14266        }
14267
14268        rc = bxe_get_igu_cam_info(sc);
14269
14270        bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14271
14272        if (rc) {
14273            return (rc);
14274        }
14275    }
14276
14277    /*
14278     * Get base FW non-default (fast path) status block ID. This value is
14279     * used to initialize the fw_sb_id saved on the fp/queue structure to
14280     * determine the id used by the FW.
14281     */
14282    if (CHIP_IS_E1x(sc)) {
14283        sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
14284    } else {
14285        /*
14286         * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
14287         * the same queue are indicated on the same IGU SB). So we prefer
14288         * FW and IGU SBs to be the same value.
14289         */
14290        sc->base_fw_ndsb = sc->igu_base_sb;
14291    }
14292
14293    BLOGD(sc, DBG_LOAD,
14294          "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
14295          sc->igu_dsb_id, sc->igu_base_sb,
14296          sc->igu_sb_cnt, sc->base_fw_ndsb);
14297
14298    elink_phy_probe(&sc->link_params);
14299
14300    return (0);
14301}
14302
14303static void
14304bxe_link_settings_supported(struct bxe_softc *sc,
14305                            uint32_t         switch_cfg)
14306{
14307    uint32_t cfg_size = 0;
14308    uint32_t idx;
14309    uint8_t port = SC_PORT(sc);
14310
14311    /* aggregation of supported attributes of all external phys */
14312    sc->port.supported[0] = 0;
14313    sc->port.supported[1] = 0;
14314
14315    switch (sc->link_params.num_phys) {
14316    case 1:
14317        sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
14318        cfg_size = 1;
14319        break;
14320    case 2:
14321        sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
14322        cfg_size = 1;
14323        break;
14324    case 3:
14325        if (sc->link_params.multi_phy_config &
14326            PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
14327            sc->port.supported[1] =
14328                sc->link_params.phy[ELINK_EXT_PHY1].supported;
14329            sc->port.supported[0] =
14330                sc->link_params.phy[ELINK_EXT_PHY2].supported;
14331        } else {
14332            sc->port.supported[0] =
14333                sc->link_params.phy[ELINK_EXT_PHY1].supported;
14334            sc->port.supported[1] =
14335                sc->link_params.phy[ELINK_EXT_PHY2].supported;
14336        }
14337        cfg_size = 2;
14338        break;
14339    }
14340
14341    if (!(sc->port.supported[0] || sc->port.supported[1])) {
14342        BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14343              SHMEM_RD(sc,
14344                       dev_info.port_hw_config[port].external_phy_config),
14345              SHMEM_RD(sc,
14346                       dev_info.port_hw_config[port].external_phy_config2));
14347        return;
14348    }
14349
14350    if (CHIP_IS_E3(sc))
14351        sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14352    else {
14353        switch (switch_cfg) {
14354        case ELINK_SWITCH_CFG_1G:
14355            sc->port.phy_addr =
14356                REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14357            break;
14358        case ELINK_SWITCH_CFG_10G:
14359            sc->port.phy_addr =
14360                REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14361            break;
14362        default:
14363            BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14364                  sc->port.link_config[0]);
14365            return;
14366        }
14367    }
14368
14369    BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14370
14371    /* mask what we support according to speed_cap_mask per configuration */
14372    for (idx = 0; idx < cfg_size; idx++) {
14373        if (!(sc->link_params.speed_cap_mask[idx] &
14374              PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14375            sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14376        }
14377
14378        if (!(sc->link_params.speed_cap_mask[idx] &
14379              PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14380            sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14381        }
14382
14383        if (!(sc->link_params.speed_cap_mask[idx] &
14384              PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14385            sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14386        }
14387
14388        if (!(sc->link_params.speed_cap_mask[idx] &
14389              PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14390            sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14391        }
14392
14393        if (!(sc->link_params.speed_cap_mask[idx] &
14394              PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14395            sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14396        }
14397
14398        if (!(sc->link_params.speed_cap_mask[idx] &
14399              PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14400            sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14401        }
14402
14403        if (!(sc->link_params.speed_cap_mask[idx] &
14404              PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14405            sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14406        }
14407
14408        if (!(sc->link_params.speed_cap_mask[idx] &
14409              PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14410            sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14411        }
14412    }
14413
14414    BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14415          sc->port.supported[0], sc->port.supported[1]);
14416	ELINK_DEBUG_P2(sc, "PHY supported 0=0x%08x 1=0x%08x\n",
14417					sc->port.supported[0], sc->port.supported[1]);
14418}
14419
14420static void
14421bxe_link_settings_requested(struct bxe_softc *sc)
14422{
14423    uint32_t link_config;
14424    uint32_t idx;
14425    uint32_t cfg_size = 0;
14426
14427    sc->port.advertising[0] = 0;
14428    sc->port.advertising[1] = 0;
14429
14430    switch (sc->link_params.num_phys) {
14431    case 1:
14432    case 2:
14433        cfg_size = 1;
14434        break;
14435    case 3:
14436        cfg_size = 2;
14437        break;
14438    }
14439
14440    for (idx = 0; idx < cfg_size; idx++) {
14441        sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14442        link_config = sc->port.link_config[idx];
14443
14444        switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14445        case PORT_FEATURE_LINK_SPEED_AUTO:
14446            if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14447                sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14448                sc->port.advertising[idx] |= sc->port.supported[idx];
14449                if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14450                    PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14451                    sc->port.advertising[idx] |=
14452                        (ELINK_SUPPORTED_100baseT_Half |
14453                         ELINK_SUPPORTED_100baseT_Full);
14454            } else {
14455                /* force 10G, no AN */
14456                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14457                sc->port.advertising[idx] |=
14458                    (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14459                continue;
14460            }
14461            break;
14462
14463        case PORT_FEATURE_LINK_SPEED_10M_FULL:
14464            if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14465                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14466                sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14467                                              ADVERTISED_TP);
14468            } else {
14469                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14470                          "speed_cap_mask=0x%08x\n",
14471                      link_config, sc->link_params.speed_cap_mask[idx]);
14472                return;
14473            }
14474            break;
14475
14476        case PORT_FEATURE_LINK_SPEED_10M_HALF:
14477            if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14478                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14479                sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14480                sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14481                                              ADVERTISED_TP);
14482				ELINK_DEBUG_P1(sc, "driver requesting DUPLEX_HALF req_duplex = %x!\n",
14483								sc->link_params.req_duplex[idx]);
14484            } else {
14485                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14486                          "speed_cap_mask=0x%08x\n",
14487                      link_config, sc->link_params.speed_cap_mask[idx]);
14488                return;
14489            }
14490            break;
14491
14492        case PORT_FEATURE_LINK_SPEED_100M_FULL:
14493            if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14494                sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14495                sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14496                                              ADVERTISED_TP);
14497            } else {
14498                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14499                          "speed_cap_mask=0x%08x\n",
14500                      link_config, sc->link_params.speed_cap_mask[idx]);
14501                return;
14502            }
14503            break;
14504
14505        case PORT_FEATURE_LINK_SPEED_100M_HALF:
14506            if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14507                sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14508                sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14509                sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14510                                              ADVERTISED_TP);
14511            } else {
14512                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14513                          "speed_cap_mask=0x%08x\n",
14514                      link_config, sc->link_params.speed_cap_mask[idx]);
14515                return;
14516            }
14517            break;
14518
14519        case PORT_FEATURE_LINK_SPEED_1G:
14520            if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14521                sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14522                sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14523                                              ADVERTISED_TP);
14524            } else {
14525                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14526                          "speed_cap_mask=0x%08x\n",
14527                      link_config, sc->link_params.speed_cap_mask[idx]);
14528                return;
14529            }
14530            break;
14531
14532        case PORT_FEATURE_LINK_SPEED_2_5G:
14533            if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14534                sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14535                sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14536                                              ADVERTISED_TP);
14537            } else {
14538                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14539                          "speed_cap_mask=0x%08x\n",
14540                      link_config, sc->link_params.speed_cap_mask[idx]);
14541                return;
14542            }
14543            break;
14544
14545        case PORT_FEATURE_LINK_SPEED_10G_CX4:
14546            if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14547                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14548                sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14549                                              ADVERTISED_FIBRE);
14550            } else {
14551                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14552                          "speed_cap_mask=0x%08x\n",
14553                      link_config, sc->link_params.speed_cap_mask[idx]);
14554                return;
14555            }
14556            break;
14557
14558        case PORT_FEATURE_LINK_SPEED_20G:
14559            sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14560            break;
14561
14562        default:
14563            BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14564                      "speed_cap_mask=0x%08x\n",
14565                  link_config, sc->link_params.speed_cap_mask[idx]);
14566            sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14567            sc->port.advertising[idx] = sc->port.supported[idx];
14568            break;
14569        }
14570
14571        sc->link_params.req_flow_ctrl[idx] =
14572            (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14573
14574        if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14575            if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14576                sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14577            } else {
14578                bxe_set_requested_fc(sc);
14579            }
14580        }
14581
14582        BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14583                            "req_flow_ctrl=0x%x advertising=0x%x\n",
14584              sc->link_params.req_line_speed[idx],
14585              sc->link_params.req_duplex[idx],
14586              sc->link_params.req_flow_ctrl[idx],
14587              sc->port.advertising[idx]);
14588		ELINK_DEBUG_P3(sc, "req_line_speed=%d req_duplex=%d "
14589						"advertising=0x%x\n",
14590						sc->link_params.req_line_speed[idx],
14591						sc->link_params.req_duplex[idx],
14592						sc->port.advertising[idx]);
14593    }
14594}
14595
14596static void
14597bxe_get_phy_info(struct bxe_softc *sc)
14598{
14599    uint8_t port = SC_PORT(sc);
14600    uint32_t config = sc->port.config;
14601    uint32_t eee_mode;
14602
14603    /* shmem data already read in bxe_get_shmem_info() */
14604
14605    ELINK_DEBUG_P3(sc, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14606                        "link_config0=0x%08x\n",
14607               sc->link_params.lane_config,
14608               sc->link_params.speed_cap_mask[0],
14609               sc->port.link_config[0]);
14610
14611
14612    bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14613    bxe_link_settings_requested(sc);
14614
14615    if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14616        sc->link_params.feature_config_flags |=
14617            ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14618    } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14619        sc->link_params.feature_config_flags &=
14620            ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14621    } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14622        sc->link_params.feature_config_flags |=
14623            ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14624    }
14625
14626    /* configure link feature according to nvram value */
14627    eee_mode =
14628        (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14629          PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14630         PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14631    if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14632        sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14633                                    ELINK_EEE_MODE_ENABLE_LPI |
14634                                    ELINK_EEE_MODE_OUTPUT_TIME);
14635    } else {
14636        sc->link_params.eee_mode = 0;
14637    }
14638
14639    /* get the media type */
14640    bxe_media_detect(sc);
14641	ELINK_DEBUG_P1(sc, "detected media type\n", sc->media);
14642}
14643
14644static void
14645bxe_get_params(struct bxe_softc *sc)
14646{
14647    /* get user tunable params */
14648    bxe_get_tunable_params(sc);
14649
14650    /* select the RX and TX ring sizes */
14651    sc->tx_ring_size = TX_BD_USABLE;
14652    sc->rx_ring_size = RX_BD_USABLE;
14653
14654    /* XXX disable WoL */
14655    sc->wol = 0;
14656}
14657
14658static void
14659bxe_set_modes_bitmap(struct bxe_softc *sc)
14660{
14661    uint32_t flags = 0;
14662
14663    if (CHIP_REV_IS_FPGA(sc)) {
14664        SET_FLAGS(flags, MODE_FPGA);
14665    } else if (CHIP_REV_IS_EMUL(sc)) {
14666        SET_FLAGS(flags, MODE_EMUL);
14667    } else {
14668        SET_FLAGS(flags, MODE_ASIC);
14669    }
14670
14671    if (CHIP_IS_MODE_4_PORT(sc)) {
14672        SET_FLAGS(flags, MODE_PORT4);
14673    } else {
14674        SET_FLAGS(flags, MODE_PORT2);
14675    }
14676
14677    if (CHIP_IS_E2(sc)) {
14678        SET_FLAGS(flags, MODE_E2);
14679    } else if (CHIP_IS_E3(sc)) {
14680        SET_FLAGS(flags, MODE_E3);
14681        if (CHIP_REV(sc) == CHIP_REV_Ax) {
14682            SET_FLAGS(flags, MODE_E3_A0);
14683        } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14684            SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14685        }
14686    }
14687
14688    if (IS_MF(sc)) {
14689        SET_FLAGS(flags, MODE_MF);
14690        switch (sc->devinfo.mf_info.mf_mode) {
14691        case MULTI_FUNCTION_SD:
14692            SET_FLAGS(flags, MODE_MF_SD);
14693            break;
14694        case MULTI_FUNCTION_SI:
14695            SET_FLAGS(flags, MODE_MF_SI);
14696            break;
14697        case MULTI_FUNCTION_AFEX:
14698            SET_FLAGS(flags, MODE_MF_AFEX);
14699            break;
14700        }
14701    } else {
14702        SET_FLAGS(flags, MODE_SF);
14703    }
14704
14705#if defined(__LITTLE_ENDIAN)
14706    SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14707#else /* __BIG_ENDIAN */
14708    SET_FLAGS(flags, MODE_BIG_ENDIAN);
14709#endif
14710
14711    INIT_MODE_FLAGS(sc) = flags;
14712}
14713
14714static int
14715bxe_alloc_hsi_mem(struct bxe_softc *sc)
14716{
14717    struct bxe_fastpath *fp;
14718    bus_addr_t busaddr;
14719    int max_agg_queues;
14720    int max_segments;
14721    bus_size_t max_size;
14722    bus_size_t max_seg_size;
14723    char buf[32];
14724    int rc;
14725    int i, j;
14726
14727    /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14728
14729    /* allocate the parent bus DMA tag */
14730    rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14731                            1,                        /* alignment */
14732                            0,                        /* boundary limit */
14733                            BUS_SPACE_MAXADDR,        /* restricted low */
14734                            BUS_SPACE_MAXADDR,        /* restricted hi */
14735                            NULL,                     /* addr filter() */
14736                            NULL,                     /* addr filter() arg */
14737                            BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14738                            BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14739                            BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14740                            0,                        /* flags */
14741                            NULL,                     /* lock() */
14742                            NULL,                     /* lock() arg */
14743                            &sc->parent_dma_tag);     /* returned dma tag */
14744    if (rc != 0) {
14745        BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14746        return (1);
14747    }
14748
14749    /************************/
14750    /* DEFAULT STATUS BLOCK */
14751    /************************/
14752
14753    if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14754                      &sc->def_sb_dma, "default status block") != 0) {
14755        /* XXX */
14756        bus_dma_tag_destroy(sc->parent_dma_tag);
14757        return (1);
14758    }
14759
14760    sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14761
14762    /***************/
14763    /* EVENT QUEUE */
14764    /***************/
14765
14766    if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14767                      &sc->eq_dma, "event queue") != 0) {
14768        /* XXX */
14769        bxe_dma_free(sc, &sc->def_sb_dma);
14770        sc->def_sb = NULL;
14771        bus_dma_tag_destroy(sc->parent_dma_tag);
14772        return (1);
14773    }
14774
14775    sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14776
14777    /*************/
14778    /* SLOW PATH */
14779    /*************/
14780
14781    if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14782                      &sc->sp_dma, "slow path") != 0) {
14783        /* XXX */
14784        bxe_dma_free(sc, &sc->eq_dma);
14785        sc->eq = NULL;
14786        bxe_dma_free(sc, &sc->def_sb_dma);
14787        sc->def_sb = NULL;
14788        bus_dma_tag_destroy(sc->parent_dma_tag);
14789        return (1);
14790    }
14791
14792    sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14793
14794    /*******************/
14795    /* SLOW PATH QUEUE */
14796    /*******************/
14797
14798    if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14799                      &sc->spq_dma, "slow path queue") != 0) {
14800        /* XXX */
14801        bxe_dma_free(sc, &sc->sp_dma);
14802        sc->sp = NULL;
14803        bxe_dma_free(sc, &sc->eq_dma);
14804        sc->eq = NULL;
14805        bxe_dma_free(sc, &sc->def_sb_dma);
14806        sc->def_sb = NULL;
14807        bus_dma_tag_destroy(sc->parent_dma_tag);
14808        return (1);
14809    }
14810
14811    sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14812
14813    /***************************/
14814    /* FW DECOMPRESSION BUFFER */
14815    /***************************/
14816
14817    if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14818                      "fw decompression buffer") != 0) {
14819        /* XXX */
14820        bxe_dma_free(sc, &sc->spq_dma);
14821        sc->spq = NULL;
14822        bxe_dma_free(sc, &sc->sp_dma);
14823        sc->sp = NULL;
14824        bxe_dma_free(sc, &sc->eq_dma);
14825        sc->eq = NULL;
14826        bxe_dma_free(sc, &sc->def_sb_dma);
14827        sc->def_sb = NULL;
14828        bus_dma_tag_destroy(sc->parent_dma_tag);
14829        return (1);
14830    }
14831
14832    sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14833
14834    if ((sc->gz_strm =
14835         malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14836        /* XXX */
14837        bxe_dma_free(sc, &sc->gz_buf_dma);
14838        sc->gz_buf = NULL;
14839        bxe_dma_free(sc, &sc->spq_dma);
14840        sc->spq = NULL;
14841        bxe_dma_free(sc, &sc->sp_dma);
14842        sc->sp = NULL;
14843        bxe_dma_free(sc, &sc->eq_dma);
14844        sc->eq = NULL;
14845        bxe_dma_free(sc, &sc->def_sb_dma);
14846        sc->def_sb = NULL;
14847        bus_dma_tag_destroy(sc->parent_dma_tag);
14848        return (1);
14849    }
14850
14851    /*************/
14852    /* FASTPATHS */
14853    /*************/
14854
14855    /* allocate DMA memory for each fastpath structure */
14856    for (i = 0; i < sc->num_queues; i++) {
14857        fp = &sc->fp[i];
14858        fp->sc    = sc;
14859        fp->index = i;
14860
14861        /*******************/
14862        /* FP STATUS BLOCK */
14863        /*******************/
14864
14865        snprintf(buf, sizeof(buf), "fp %d status block", i);
14866        if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14867                          &fp->sb_dma, buf) != 0) {
14868            /* XXX unwind and free previous fastpath allocations */
14869            BLOGE(sc, "Failed to alloc %s\n", buf);
14870            return (1);
14871        } else {
14872            if (CHIP_IS_E2E3(sc)) {
14873                fp->status_block.e2_sb =
14874                    (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14875            } else {
14876                fp->status_block.e1x_sb =
14877                    (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14878            }
14879        }
14880
14881        /******************/
14882        /* FP TX BD CHAIN */
14883        /******************/
14884
14885        snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14886        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14887                          &fp->tx_dma, buf) != 0) {
14888            /* XXX unwind and free previous fastpath allocations */
14889            BLOGE(sc, "Failed to alloc %s\n", buf);
14890            return (1);
14891        } else {
14892            fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14893        }
14894
14895        /* link together the tx bd chain pages */
14896        for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14897            /* index into the tx bd chain array to last entry per page */
14898            struct eth_tx_next_bd *tx_next_bd =
14899                &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14900            /* point to the next page and wrap from last page */
14901            busaddr = (fp->tx_dma.paddr +
14902                       (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14903            tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14904            tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14905        }
14906
14907        /******************/
14908        /* FP RX BD CHAIN */
14909        /******************/
14910
14911        snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14912        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14913                          &fp->rx_dma, buf) != 0) {
14914            /* XXX unwind and free previous fastpath allocations */
14915            BLOGE(sc, "Failed to alloc %s\n", buf);
14916            return (1);
14917        } else {
14918            fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14919        }
14920
14921        /* link together the rx bd chain pages */
14922        for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14923            /* index into the rx bd chain array to last entry per page */
14924            struct eth_rx_bd *rx_bd =
14925                &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14926            /* point to the next page and wrap from last page */
14927            busaddr = (fp->rx_dma.paddr +
14928                       (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14929            rx_bd->addr_hi = htole32(U64_HI(busaddr));
14930            rx_bd->addr_lo = htole32(U64_LO(busaddr));
14931        }
14932
14933        /*******************/
14934        /* FP RX RCQ CHAIN */
14935        /*******************/
14936
14937        snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14938        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14939                          &fp->rcq_dma, buf) != 0) {
14940            /* XXX unwind and free previous fastpath allocations */
14941            BLOGE(sc, "Failed to alloc %s\n", buf);
14942            return (1);
14943        } else {
14944            fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14945        }
14946
14947        /* link together the rcq chain pages */
14948        for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14949            /* index into the rcq chain array to last entry per page */
14950            struct eth_rx_cqe_next_page *rx_cqe_next =
14951                (struct eth_rx_cqe_next_page *)
14952                &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14953            /* point to the next page and wrap from last page */
14954            busaddr = (fp->rcq_dma.paddr +
14955                       (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14956            rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14957            rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14958        }
14959
14960        /*******************/
14961        /* FP RX SGE CHAIN */
14962        /*******************/
14963
14964        snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14965        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14966                          &fp->rx_sge_dma, buf) != 0) {
14967            /* XXX unwind and free previous fastpath allocations */
14968            BLOGE(sc, "Failed to alloc %s\n", buf);
14969            return (1);
14970        } else {
14971            fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14972        }
14973
14974        /* link together the sge chain pages */
14975        for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14976            /* index into the rcq chain array to last entry per page */
14977            struct eth_rx_sge *rx_sge =
14978                &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14979            /* point to the next page and wrap from last page */
14980            busaddr = (fp->rx_sge_dma.paddr +
14981                       (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14982            rx_sge->addr_hi = htole32(U64_HI(busaddr));
14983            rx_sge->addr_lo = htole32(U64_LO(busaddr));
14984        }
14985
14986        /***********************/
14987        /* FP TX MBUF DMA MAPS */
14988        /***********************/
14989
14990        /* set required sizes before mapping to conserve resources */
14991        if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
14992            max_size     = BXE_TSO_MAX_SIZE;
14993            max_segments = BXE_TSO_MAX_SEGMENTS;
14994            max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14995        } else {
14996            max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14997            max_segments = BXE_MAX_SEGMENTS;
14998            max_seg_size = MCLBYTES;
14999        }
15000
15001        /* create a dma tag for the tx mbufs */
15002        rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15003                                1,                  /* alignment */
15004                                0,                  /* boundary limit */
15005                                BUS_SPACE_MAXADDR,  /* restricted low */
15006                                BUS_SPACE_MAXADDR,  /* restricted hi */
15007                                NULL,               /* addr filter() */
15008                                NULL,               /* addr filter() arg */
15009                                max_size,           /* max map size */
15010                                max_segments,       /* num discontinuous */
15011                                max_seg_size,       /* max seg size */
15012                                0,                  /* flags */
15013                                NULL,               /* lock() */
15014                                NULL,               /* lock() arg */
15015                                &fp->tx_mbuf_tag);  /* returned dma tag */
15016        if (rc != 0) {
15017            /* XXX unwind and free previous fastpath allocations */
15018            BLOGE(sc, "Failed to create dma tag for "
15019                      "'fp %d tx mbufs' (%d)\n", i, rc);
15020            return (1);
15021        }
15022
15023        /* create dma maps for each of the tx mbuf clusters */
15024        for (j = 0; j < TX_BD_TOTAL; j++) {
15025            if (bus_dmamap_create(fp->tx_mbuf_tag,
15026                                  BUS_DMA_NOWAIT,
15027                                  &fp->tx_mbuf_chain[j].m_map)) {
15028                /* XXX unwind and free previous fastpath allocations */
15029                BLOGE(sc, "Failed to create dma map for "
15030                          "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
15031                return (1);
15032            }
15033        }
15034
15035        /***********************/
15036        /* FP RX MBUF DMA MAPS */
15037        /***********************/
15038
15039        /* create a dma tag for the rx mbufs */
15040        rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15041                                1,                  /* alignment */
15042                                0,                  /* boundary limit */
15043                                BUS_SPACE_MAXADDR,  /* restricted low */
15044                                BUS_SPACE_MAXADDR,  /* restricted hi */
15045                                NULL,               /* addr filter() */
15046                                NULL,               /* addr filter() arg */
15047                                MJUM9BYTES,         /* max map size */
15048                                1,                  /* num discontinuous */
15049                                MJUM9BYTES,         /* max seg size */
15050                                0,                  /* flags */
15051                                NULL,               /* lock() */
15052                                NULL,               /* lock() arg */
15053                                &fp->rx_mbuf_tag);  /* returned dma tag */
15054        if (rc != 0) {
15055            /* XXX unwind and free previous fastpath allocations */
15056            BLOGE(sc, "Failed to create dma tag for "
15057                      "'fp %d rx mbufs' (%d)\n", i, rc);
15058            return (1);
15059        }
15060
15061        /* create dma maps for each of the rx mbuf clusters */
15062        for (j = 0; j < RX_BD_TOTAL; j++) {
15063            if (bus_dmamap_create(fp->rx_mbuf_tag,
15064                                  BUS_DMA_NOWAIT,
15065                                  &fp->rx_mbuf_chain[j].m_map)) {
15066                /* XXX unwind and free previous fastpath allocations */
15067                BLOGE(sc, "Failed to create dma map for "
15068                          "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
15069                return (1);
15070            }
15071        }
15072
15073        /* create dma map for the spare rx mbuf cluster */
15074        if (bus_dmamap_create(fp->rx_mbuf_tag,
15075                              BUS_DMA_NOWAIT,
15076                              &fp->rx_mbuf_spare_map)) {
15077            /* XXX unwind and free previous fastpath allocations */
15078            BLOGE(sc, "Failed to create dma map for "
15079                      "'fp %d spare rx mbuf' (%d)\n", i, rc);
15080            return (1);
15081        }
15082
15083        /***************************/
15084        /* FP RX SGE MBUF DMA MAPS */
15085        /***************************/
15086
15087        /* create a dma tag for the rx sge mbufs */
15088        rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15089                                1,                  /* alignment */
15090                                0,                  /* boundary limit */
15091                                BUS_SPACE_MAXADDR,  /* restricted low */
15092                                BUS_SPACE_MAXADDR,  /* restricted hi */
15093                                NULL,               /* addr filter() */
15094                                NULL,               /* addr filter() arg */
15095                                BCM_PAGE_SIZE,      /* max map size */
15096                                1,                  /* num discontinuous */
15097                                BCM_PAGE_SIZE,      /* max seg size */
15098                                0,                  /* flags */
15099                                NULL,               /* lock() */
15100                                NULL,               /* lock() arg */
15101                                &fp->rx_sge_mbuf_tag); /* returned dma tag */
15102        if (rc != 0) {
15103            /* XXX unwind and free previous fastpath allocations */
15104            BLOGE(sc, "Failed to create dma tag for "
15105                      "'fp %d rx sge mbufs' (%d)\n", i, rc);
15106            return (1);
15107        }
15108
15109        /* create dma maps for the rx sge mbuf clusters */
15110        for (j = 0; j < RX_SGE_TOTAL; j++) {
15111            if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
15112                                  BUS_DMA_NOWAIT,
15113                                  &fp->rx_sge_mbuf_chain[j].m_map)) {
15114                /* XXX unwind and free previous fastpath allocations */
15115                BLOGE(sc, "Failed to create dma map for "
15116                          "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
15117                return (1);
15118            }
15119        }
15120
15121        /* create dma map for the spare rx sge mbuf cluster */
15122        if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
15123                              BUS_DMA_NOWAIT,
15124                              &fp->rx_sge_mbuf_spare_map)) {
15125            /* XXX unwind and free previous fastpath allocations */
15126            BLOGE(sc, "Failed to create dma map for "
15127                      "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
15128            return (1);
15129        }
15130
15131        /***************************/
15132        /* FP RX TPA MBUF DMA MAPS */
15133        /***************************/
15134
15135        /* create dma maps for the rx tpa mbuf clusters */
15136        max_agg_queues = MAX_AGG_QS(sc);
15137
15138        for (j = 0; j < max_agg_queues; j++) {
15139            if (bus_dmamap_create(fp->rx_mbuf_tag,
15140                                  BUS_DMA_NOWAIT,
15141                                  &fp->rx_tpa_info[j].bd.m_map)) {
15142                /* XXX unwind and free previous fastpath allocations */
15143                BLOGE(sc, "Failed to create dma map for "
15144                          "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
15145                return (1);
15146            }
15147        }
15148
15149        /* create dma map for the spare rx tpa mbuf cluster */
15150        if (bus_dmamap_create(fp->rx_mbuf_tag,
15151                              BUS_DMA_NOWAIT,
15152                              &fp->rx_tpa_info_mbuf_spare_map)) {
15153            /* XXX unwind and free previous fastpath allocations */
15154            BLOGE(sc, "Failed to create dma map for "
15155                      "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
15156            return (1);
15157        }
15158
15159        bxe_init_sge_ring_bit_mask(fp);
15160    }
15161
15162    return (0);
15163}
15164
15165static void
15166bxe_free_hsi_mem(struct bxe_softc *sc)
15167{
15168    struct bxe_fastpath *fp;
15169    int max_agg_queues;
15170    int i, j;
15171
15172    if (sc->parent_dma_tag == NULL) {
15173        return; /* assume nothing was allocated */
15174    }
15175
15176    for (i = 0; i < sc->num_queues; i++) {
15177        fp = &sc->fp[i];
15178
15179        /*******************/
15180        /* FP STATUS BLOCK */
15181        /*******************/
15182
15183        bxe_dma_free(sc, &fp->sb_dma);
15184        memset(&fp->status_block, 0, sizeof(fp->status_block));
15185
15186        /******************/
15187        /* FP TX BD CHAIN */
15188        /******************/
15189
15190        bxe_dma_free(sc, &fp->tx_dma);
15191        fp->tx_chain = NULL;
15192
15193        /******************/
15194        /* FP RX BD CHAIN */
15195        /******************/
15196
15197        bxe_dma_free(sc, &fp->rx_dma);
15198        fp->rx_chain = NULL;
15199
15200        /*******************/
15201        /* FP RX RCQ CHAIN */
15202        /*******************/
15203
15204        bxe_dma_free(sc, &fp->rcq_dma);
15205        fp->rcq_chain = NULL;
15206
15207        /*******************/
15208        /* FP RX SGE CHAIN */
15209        /*******************/
15210
15211        bxe_dma_free(sc, &fp->rx_sge_dma);
15212        fp->rx_sge_chain = NULL;
15213
15214        /***********************/
15215        /* FP TX MBUF DMA MAPS */
15216        /***********************/
15217
15218        if (fp->tx_mbuf_tag != NULL) {
15219            for (j = 0; j < TX_BD_TOTAL; j++) {
15220                if (fp->tx_mbuf_chain[j].m_map != NULL) {
15221                    bus_dmamap_unload(fp->tx_mbuf_tag,
15222                                      fp->tx_mbuf_chain[j].m_map);
15223                    bus_dmamap_destroy(fp->tx_mbuf_tag,
15224                                       fp->tx_mbuf_chain[j].m_map);
15225                }
15226            }
15227
15228            bus_dma_tag_destroy(fp->tx_mbuf_tag);
15229            fp->tx_mbuf_tag = NULL;
15230        }
15231
15232        /***********************/
15233        /* FP RX MBUF DMA MAPS */
15234        /***********************/
15235
15236        if (fp->rx_mbuf_tag != NULL) {
15237            for (j = 0; j < RX_BD_TOTAL; j++) {
15238                if (fp->rx_mbuf_chain[j].m_map != NULL) {
15239                    bus_dmamap_unload(fp->rx_mbuf_tag,
15240                                      fp->rx_mbuf_chain[j].m_map);
15241                    bus_dmamap_destroy(fp->rx_mbuf_tag,
15242                                       fp->rx_mbuf_chain[j].m_map);
15243                }
15244            }
15245
15246            if (fp->rx_mbuf_spare_map != NULL) {
15247                bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
15248                bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
15249            }
15250
15251            /***************************/
15252            /* FP RX TPA MBUF DMA MAPS */
15253            /***************************/
15254
15255            max_agg_queues = MAX_AGG_QS(sc);
15256
15257            for (j = 0; j < max_agg_queues; j++) {
15258                if (fp->rx_tpa_info[j].bd.m_map != NULL) {
15259                    bus_dmamap_unload(fp->rx_mbuf_tag,
15260                                      fp->rx_tpa_info[j].bd.m_map);
15261                    bus_dmamap_destroy(fp->rx_mbuf_tag,
15262                                       fp->rx_tpa_info[j].bd.m_map);
15263                }
15264            }
15265
15266            if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
15267                bus_dmamap_unload(fp->rx_mbuf_tag,
15268                                  fp->rx_tpa_info_mbuf_spare_map);
15269                bus_dmamap_destroy(fp->rx_mbuf_tag,
15270                                   fp->rx_tpa_info_mbuf_spare_map);
15271            }
15272
15273            bus_dma_tag_destroy(fp->rx_mbuf_tag);
15274            fp->rx_mbuf_tag = NULL;
15275        }
15276
15277        /***************************/
15278        /* FP RX SGE MBUF DMA MAPS */
15279        /***************************/
15280
15281        if (fp->rx_sge_mbuf_tag != NULL) {
15282            for (j = 0; j < RX_SGE_TOTAL; j++) {
15283                if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
15284                    bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15285                                      fp->rx_sge_mbuf_chain[j].m_map);
15286                    bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15287                                       fp->rx_sge_mbuf_chain[j].m_map);
15288                }
15289            }
15290
15291            if (fp->rx_sge_mbuf_spare_map != NULL) {
15292                bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15293                                  fp->rx_sge_mbuf_spare_map);
15294                bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15295                                   fp->rx_sge_mbuf_spare_map);
15296            }
15297
15298            bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
15299            fp->rx_sge_mbuf_tag = NULL;
15300        }
15301    }
15302
15303    /***************************/
15304    /* FW DECOMPRESSION BUFFER */
15305    /***************************/
15306
15307    bxe_dma_free(sc, &sc->gz_buf_dma);
15308    sc->gz_buf = NULL;
15309    free(sc->gz_strm, M_DEVBUF);
15310    sc->gz_strm = NULL;
15311
15312    /*******************/
15313    /* SLOW PATH QUEUE */
15314    /*******************/
15315
15316    bxe_dma_free(sc, &sc->spq_dma);
15317    sc->spq = NULL;
15318
15319    /*************/
15320    /* SLOW PATH */
15321    /*************/
15322
15323    bxe_dma_free(sc, &sc->sp_dma);
15324    sc->sp = NULL;
15325
15326    /***************/
15327    /* EVENT QUEUE */
15328    /***************/
15329
15330    bxe_dma_free(sc, &sc->eq_dma);
15331    sc->eq = NULL;
15332
15333    /************************/
15334    /* DEFAULT STATUS BLOCK */
15335    /************************/
15336
15337    bxe_dma_free(sc, &sc->def_sb_dma);
15338    sc->def_sb = NULL;
15339
15340    bus_dma_tag_destroy(sc->parent_dma_tag);
15341    sc->parent_dma_tag = NULL;
15342}
15343
15344/*
15345 * Previous driver DMAE transaction may have occurred when pre-boot stage
15346 * ended and boot began. This would invalidate the addresses of the
15347 * transaction, resulting in was-error bit set in the PCI causing all
15348 * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15349 * the interrupt which detected this from the pglueb and the was-done bit
15350 */
15351static void
15352bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15353{
15354    uint32_t val;
15355
15356    if (!CHIP_IS_E1x(sc)) {
15357        val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15358        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15359            BLOGD(sc, DBG_LOAD,
15360                  "Clearing 'was-error' bit that was set in pglueb");
15361            REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15362        }
15363    }
15364}
15365
15366static int
15367bxe_prev_mcp_done(struct bxe_softc *sc)
15368{
15369    uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15370                                 DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15371    if (!rc) {
15372        BLOGE(sc, "MCP response failure, aborting\n");
15373        return (-1);
15374    }
15375
15376    return (0);
15377}
15378
15379static struct bxe_prev_list_node *
15380bxe_prev_path_get_entry(struct bxe_softc *sc)
15381{
15382    struct bxe_prev_list_node *tmp;
15383
15384    LIST_FOREACH(tmp, &bxe_prev_list, node) {
15385        if ((sc->pcie_bus == tmp->bus) &&
15386            (sc->pcie_device == tmp->slot) &&
15387            (SC_PATH(sc) == tmp->path)) {
15388            return (tmp);
15389        }
15390    }
15391
15392    return (NULL);
15393}
15394
15395static uint8_t
15396bxe_prev_is_path_marked(struct bxe_softc *sc)
15397{
15398    struct bxe_prev_list_node *tmp;
15399    int rc = FALSE;
15400
15401    mtx_lock(&bxe_prev_mtx);
15402
15403    tmp = bxe_prev_path_get_entry(sc);
15404    if (tmp) {
15405        if (tmp->aer) {
15406            BLOGD(sc, DBG_LOAD,
15407                  "Path %d/%d/%d was marked by AER\n",
15408                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15409        } else {
15410            rc = TRUE;
15411            BLOGD(sc, DBG_LOAD,
15412                  "Path %d/%d/%d was already cleaned from previous drivers\n",
15413                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15414        }
15415    }
15416
15417    mtx_unlock(&bxe_prev_mtx);
15418
15419    return (rc);
15420}
15421
15422static int
15423bxe_prev_mark_path(struct bxe_softc *sc,
15424                   uint8_t          after_undi)
15425{
15426    struct bxe_prev_list_node *tmp;
15427
15428    mtx_lock(&bxe_prev_mtx);
15429
15430    /* Check whether the entry for this path already exists */
15431    tmp = bxe_prev_path_get_entry(sc);
15432    if (tmp) {
15433        if (!tmp->aer) {
15434            BLOGD(sc, DBG_LOAD,
15435                  "Re-marking AER in path %d/%d/%d\n",
15436                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15437        } else {
15438            BLOGD(sc, DBG_LOAD,
15439                  "Removing AER indication from path %d/%d/%d\n",
15440                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15441            tmp->aer = 0;
15442        }
15443
15444        mtx_unlock(&bxe_prev_mtx);
15445        return (0);
15446    }
15447
15448    mtx_unlock(&bxe_prev_mtx);
15449
15450    /* Create an entry for this path and add it */
15451    tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15452                 (M_NOWAIT | M_ZERO));
15453    if (!tmp) {
15454        BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15455        return (-1);
15456    }
15457
15458    tmp->bus  = sc->pcie_bus;
15459    tmp->slot = sc->pcie_device;
15460    tmp->path = SC_PATH(sc);
15461    tmp->aer  = 0;
15462    tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15463
15464    mtx_lock(&bxe_prev_mtx);
15465
15466    BLOGD(sc, DBG_LOAD,
15467          "Marked path %d/%d/%d - finished previous unload\n",
15468          sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15469    LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15470
15471    mtx_unlock(&bxe_prev_mtx);
15472
15473    return (0);
15474}
15475
15476static int
15477bxe_do_flr(struct bxe_softc *sc)
15478{
15479    int i;
15480
15481    /* only E2 and onwards support FLR */
15482    if (CHIP_IS_E1x(sc)) {
15483        BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15484        return (-1);
15485    }
15486
15487    /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15488    if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15489        BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15490              sc->devinfo.bc_ver);
15491        return (-1);
15492    }
15493
15494    /* Wait for Transaction Pending bit clean */
15495    for (i = 0; i < 4; i++) {
15496        if (i) {
15497            DELAY(((1 << (i - 1)) * 100) * 1000);
15498        }
15499
15500        if (!bxe_is_pcie_pending(sc)) {
15501            goto clear;
15502        }
15503    }
15504
15505    BLOGE(sc, "PCIE transaction is not cleared, "
15506              "proceeding with reset anyway\n");
15507
15508clear:
15509
15510    BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15511    bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15512
15513    return (0);
15514}
15515
15516struct bxe_mac_vals {
15517    uint32_t xmac_addr;
15518    uint32_t xmac_val;
15519    uint32_t emac_addr;
15520    uint32_t emac_val;
15521    uint32_t umac_addr;
15522    uint32_t umac_val;
15523    uint32_t bmac_addr;
15524    uint32_t bmac_val[2];
15525};
15526
15527static void
15528bxe_prev_unload_close_mac(struct bxe_softc *sc,
15529                          struct bxe_mac_vals *vals)
15530{
15531    uint32_t val, base_addr, offset, mask, reset_reg;
15532    uint8_t mac_stopped = FALSE;
15533    uint8_t port = SC_PORT(sc);
15534    uint32_t wb_data[2];
15535
15536    /* reset addresses as they also mark which values were changed */
15537    vals->bmac_addr = 0;
15538    vals->umac_addr = 0;
15539    vals->xmac_addr = 0;
15540    vals->emac_addr = 0;
15541
15542    reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15543
15544    if (!CHIP_IS_E3(sc)) {
15545        val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15546        mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15547        if ((mask & reset_reg) && val) {
15548            BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15549            base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15550                                    : NIG_REG_INGRESS_BMAC0_MEM;
15551            offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15552                                    : BIGMAC_REGISTER_BMAC_CONTROL;
15553
15554            /*
15555             * use rd/wr since we cannot use dmae. This is safe
15556             * since MCP won't access the bus due to the request
15557             * to unload, and no function on the path can be
15558             * loaded at this time.
15559             */
15560            wb_data[0] = REG_RD(sc, base_addr + offset);
15561            wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15562            vals->bmac_addr = base_addr + offset;
15563            vals->bmac_val[0] = wb_data[0];
15564            vals->bmac_val[1] = wb_data[1];
15565            wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15566            REG_WR(sc, vals->bmac_addr, wb_data[0]);
15567            REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15568        }
15569
15570        BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15571        vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15572        vals->emac_val = REG_RD(sc, vals->emac_addr);
15573        REG_WR(sc, vals->emac_addr, 0);
15574        mac_stopped = TRUE;
15575    } else {
15576        if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15577            BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15578            base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15579            val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15580            REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15581            REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15582            vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15583            vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15584            REG_WR(sc, vals->xmac_addr, 0);
15585            mac_stopped = TRUE;
15586        }
15587
15588        mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15589        if (mask & reset_reg) {
15590            BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15591            base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15592            vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15593            vals->umac_val = REG_RD(sc, vals->umac_addr);
15594            REG_WR(sc, vals->umac_addr, 0);
15595            mac_stopped = TRUE;
15596        }
15597    }
15598
15599    if (mac_stopped) {
15600        DELAY(20000);
15601    }
15602}
15603
15604#define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15605#define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15606#define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15607#define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15608
15609static void
15610bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15611                         uint8_t          port,
15612                         uint8_t          inc)
15613{
15614    uint16_t rcq, bd;
15615    uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15616
15617    rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15618    bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15619
15620    tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15621    REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15622
15623    BLOGD(sc, DBG_LOAD,
15624          "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15625          port, bd, rcq);
15626}
15627
15628static int
15629bxe_prev_unload_common(struct bxe_softc *sc)
15630{
15631    uint32_t reset_reg, tmp_reg = 0, rc;
15632    uint8_t prev_undi = FALSE;
15633    struct bxe_mac_vals mac_vals;
15634    uint32_t timer_count = 1000;
15635    uint32_t prev_brb;
15636
15637    /*
15638     * It is possible a previous function received 'common' answer,
15639     * but hasn't loaded yet, therefore creating a scenario of
15640     * multiple functions receiving 'common' on the same path.
15641     */
15642    BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15643
15644    memset(&mac_vals, 0, sizeof(mac_vals));
15645
15646    if (bxe_prev_is_path_marked(sc)) {
15647        return (bxe_prev_mcp_done(sc));
15648    }
15649
15650    reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15651
15652    /* Reset should be performed after BRB is emptied */
15653    if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15654        /* Close the MAC Rx to prevent BRB from filling up */
15655        bxe_prev_unload_close_mac(sc, &mac_vals);
15656
15657        /* close LLH filters towards the BRB */
15658        elink_set_rx_filter(&sc->link_params, 0);
15659
15660        /*
15661         * Check if the UNDI driver was previously loaded.
15662         * UNDI driver initializes CID offset for normal bell to 0x7
15663         */
15664        if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15665            tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15666            if (tmp_reg == 0x7) {
15667                BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15668                prev_undi = TRUE;
15669                /* clear the UNDI indication */
15670                REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15671                /* clear possible idle check errors */
15672                REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15673            }
15674        }
15675
15676        /* wait until BRB is empty */
15677        tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15678        while (timer_count) {
15679            prev_brb = tmp_reg;
15680
15681            tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15682            if (!tmp_reg) {
15683                break;
15684            }
15685
15686            BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15687
15688            /* reset timer as long as BRB actually gets emptied */
15689            if (prev_brb > tmp_reg) {
15690                timer_count = 1000;
15691            } else {
15692                timer_count--;
15693            }
15694
15695            /* If UNDI resides in memory, manually increment it */
15696            if (prev_undi) {
15697                bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15698            }
15699
15700            DELAY(10);
15701        }
15702
15703        if (!timer_count) {
15704            BLOGE(sc, "Failed to empty BRB\n");
15705        }
15706    }
15707
15708    /* No packets are in the pipeline, path is ready for reset */
15709    bxe_reset_common(sc);
15710
15711    if (mac_vals.xmac_addr) {
15712        REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15713    }
15714    if (mac_vals.umac_addr) {
15715        REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15716    }
15717    if (mac_vals.emac_addr) {
15718        REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15719    }
15720    if (mac_vals.bmac_addr) {
15721        REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15722        REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15723    }
15724
15725    rc = bxe_prev_mark_path(sc, prev_undi);
15726    if (rc) {
15727        bxe_prev_mcp_done(sc);
15728        return (rc);
15729    }
15730
15731    return (bxe_prev_mcp_done(sc));
15732}
15733
15734static int
15735bxe_prev_unload_uncommon(struct bxe_softc *sc)
15736{
15737    int rc;
15738
15739    BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15740
15741    /* Test if previous unload process was already finished for this path */
15742    if (bxe_prev_is_path_marked(sc)) {
15743        return (bxe_prev_mcp_done(sc));
15744    }
15745
15746    BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15747
15748    /*
15749     * If function has FLR capabilities, and existing FW version matches
15750     * the one required, then FLR will be sufficient to clean any residue
15751     * left by previous driver
15752     */
15753    rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15754    if (!rc) {
15755        /* fw version is good */
15756        BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15757        rc = bxe_do_flr(sc);
15758    }
15759
15760    if (!rc) {
15761        /* FLR was performed */
15762        BLOGD(sc, DBG_LOAD, "FLR successful\n");
15763        return (0);
15764    }
15765
15766    BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15767
15768    /* Close the MCP request, return failure*/
15769    rc = bxe_prev_mcp_done(sc);
15770    if (!rc) {
15771        rc = BXE_PREV_WAIT_NEEDED;
15772    }
15773
15774    return (rc);
15775}
15776
15777static int
15778bxe_prev_unload(struct bxe_softc *sc)
15779{
15780    int time_counter = 10;
15781    uint32_t fw, hw_lock_reg, hw_lock_val;
15782    uint32_t rc = 0;
15783
15784    /*
15785     * Clear HW from errors which may have resulted from an interrupted
15786     * DMAE transaction.
15787     */
15788    bxe_prev_interrupted_dmae(sc);
15789
15790    /* Release previously held locks */
15791    hw_lock_reg =
15792        (SC_FUNC(sc) <= 5) ?
15793            (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15794            (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15795
15796    hw_lock_val = (REG_RD(sc, hw_lock_reg));
15797    if (hw_lock_val) {
15798        if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15799            BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15800            REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15801                   (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15802        }
15803        BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15804        REG_WR(sc, hw_lock_reg, 0xffffffff);
15805    } else {
15806        BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15807    }
15808
15809    if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15810        BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15811        REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15812    }
15813
15814    do {
15815        /* Lock MCP using an unload request */
15816        fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15817        if (!fw) {
15818            BLOGE(sc, "MCP response failure, aborting\n");
15819            rc = -1;
15820            break;
15821        }
15822
15823        if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15824            rc = bxe_prev_unload_common(sc);
15825            break;
15826        }
15827
15828        /* non-common reply from MCP night require looping */
15829        rc = bxe_prev_unload_uncommon(sc);
15830        if (rc != BXE_PREV_WAIT_NEEDED) {
15831            break;
15832        }
15833
15834        DELAY(20000);
15835    } while (--time_counter);
15836
15837    if (!time_counter || rc) {
15838        BLOGE(sc, "Failed to unload previous driver!"
15839            " time_counter %d rc %d\n", time_counter, rc);
15840        rc = -1;
15841    }
15842
15843    return (rc);
15844}
15845
15846void
15847bxe_dcbx_set_state(struct bxe_softc *sc,
15848                   uint8_t          dcb_on,
15849                   uint32_t         dcbx_enabled)
15850{
15851    if (!CHIP_IS_E1x(sc)) {
15852        sc->dcb_state = dcb_on;
15853        sc->dcbx_enabled = dcbx_enabled;
15854    } else {
15855        sc->dcb_state = FALSE;
15856        sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15857    }
15858    BLOGD(sc, DBG_LOAD,
15859          "DCB state [%s:%s]\n",
15860          dcb_on ? "ON" : "OFF",
15861          (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15862          (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15863          (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15864          "on-chip with negotiation" : "invalid");
15865}
15866
15867/* must be called after sriov-enable */
15868static int
15869bxe_set_qm_cid_count(struct bxe_softc *sc)
15870{
15871    int cid_count = BXE_L2_MAX_CID(sc);
15872
15873    if (IS_SRIOV(sc)) {
15874        cid_count += BXE_VF_CIDS;
15875    }
15876
15877    if (CNIC_SUPPORT(sc)) {
15878        cid_count += CNIC_CID_MAX;
15879    }
15880
15881    return (roundup(cid_count, QM_CID_ROUND));
15882}
15883
15884static void
15885bxe_init_multi_cos(struct bxe_softc *sc)
15886{
15887    int pri, cos;
15888
15889    uint32_t pri_map = 0; /* XXX change to user config */
15890
15891    for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15892        cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15893        if (cos < sc->max_cos) {
15894            sc->prio_to_cos[pri] = cos;
15895        } else {
15896            BLOGW(sc, "Invalid COS %d for priority %d "
15897                      "(max COS is %d), setting to 0\n",
15898                  cos, pri, (sc->max_cos - 1));
15899            sc->prio_to_cos[pri] = 0;
15900        }
15901    }
15902}
15903
15904static int
15905bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15906{
15907    struct bxe_softc *sc;
15908    int error, result;
15909
15910    result = 0;
15911    error = sysctl_handle_int(oidp, &result, 0, req);
15912
15913    if (error || !req->newptr) {
15914        return (error);
15915    }
15916
15917    if (result == 1) {
15918        uint32_t  temp;
15919        sc = (struct bxe_softc *)arg1;
15920
15921        BLOGI(sc, "... dumping driver state ...\n");
15922        temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15923        BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15924    }
15925
15926    return (error);
15927}
15928
15929static int
15930bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15931{
15932    struct bxe_softc *sc = (struct bxe_softc *)arg1;
15933    uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15934    uint32_t *offset;
15935    uint64_t value = 0;
15936    int index = (int)arg2;
15937
15938    if (index >= BXE_NUM_ETH_STATS) {
15939        BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15940        return (-1);
15941    }
15942
15943    offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15944
15945    switch (bxe_eth_stats_arr[index].size) {
15946    case 4:
15947        value = (uint64_t)*offset;
15948        break;
15949    case 8:
15950        value = HILO_U64(*offset, *(offset + 1));
15951        break;
15952    default:
15953        BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15954              index, bxe_eth_stats_arr[index].size);
15955        return (-1);
15956    }
15957
15958    return (sysctl_handle_64(oidp, &value, 0, req));
15959}
15960
15961static int
15962bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15963{
15964    struct bxe_softc *sc = (struct bxe_softc *)arg1;
15965    uint32_t *eth_stats;
15966    uint32_t *offset;
15967    uint64_t value = 0;
15968    uint32_t q_stat = (uint32_t)arg2;
15969    uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15970    uint32_t index = (q_stat & 0xffff);
15971
15972    eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15973
15974    if (index >= BXE_NUM_ETH_Q_STATS) {
15975        BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15976        return (-1);
15977    }
15978
15979    offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15980
15981    switch (bxe_eth_q_stats_arr[index].size) {
15982    case 4:
15983        value = (uint64_t)*offset;
15984        break;
15985    case 8:
15986        value = HILO_U64(*offset, *(offset + 1));
15987        break;
15988    default:
15989        BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15990              index, bxe_eth_q_stats_arr[index].size);
15991        return (-1);
15992    }
15993
15994    return (sysctl_handle_64(oidp, &value, 0, req));
15995}
15996
15997static void bxe_force_link_reset(struct bxe_softc *sc)
15998{
15999
16000        bxe_acquire_phy_lock(sc);
16001        elink_link_reset(&sc->link_params, &sc->link_vars, 1);
16002        bxe_release_phy_lock(sc);
16003}
16004
16005static int
16006bxe_sysctl_pauseparam(SYSCTL_HANDLER_ARGS)
16007{
16008        struct bxe_softc *sc = (struct bxe_softc *)arg1;;
16009        uint32_t cfg_idx = bxe_get_link_cfg_idx(sc);
16010        int rc = 0;
16011        int error;
16012        int result;
16013
16014
16015        error = sysctl_handle_int(oidp, &sc->bxe_pause_param, 0, req);
16016
16017        if (error || !req->newptr) {
16018                return (error);
16019        }
16020        if ((sc->bxe_pause_param < 0) ||  (sc->bxe_pause_param > 8)) {
16021                BLOGW(sc, "invalid pause param (%d) - use intergers between 1 & 8\n",sc->bxe_pause_param);
16022                sc->bxe_pause_param = 8;
16023        }
16024
16025        result = (sc->bxe_pause_param << PORT_FEATURE_FLOW_CONTROL_SHIFT);
16026
16027
16028        if((result & 0x400) && !(sc->port.supported[cfg_idx] & ELINK_SUPPORTED_Autoneg))  {
16029                        BLOGW(sc, "Does not support Autoneg pause_param %d\n", sc->bxe_pause_param);
16030                        return -EINVAL;
16031        }
16032
16033        if(IS_MF(sc))
16034                return 0;
16035       sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_AUTO;
16036        if(result & ELINK_FLOW_CTRL_RX)
16037                sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_RX;
16038
16039        if(result & ELINK_FLOW_CTRL_TX)
16040                sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_TX;
16041        if(sc->link_params.req_flow_ctrl[cfg_idx] == ELINK_FLOW_CTRL_AUTO)
16042                sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_NONE;
16043
16044        if(result & 0x400) {
16045                if (sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG) {
16046                        sc->link_params.req_flow_ctrl[cfg_idx] =
16047                                ELINK_FLOW_CTRL_AUTO;
16048                }
16049                sc->link_params.req_fc_auto_adv = 0;
16050                if (result & ELINK_FLOW_CTRL_RX)
16051                        sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_RX;
16052
16053                if (result & ELINK_FLOW_CTRL_TX)
16054                        sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_TX;
16055                if (!sc->link_params.req_fc_auto_adv)
16056                        sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_NONE;
16057        }
16058         if (IS_PF(sc)) {
16059                        if (sc->link_vars.link_up) {
16060                                bxe_stats_handle(sc, STATS_EVENT_STOP);
16061                        }
16062			if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
16063                        bxe_force_link_reset(sc);
16064                        bxe_acquire_phy_lock(sc);
16065
16066                        rc = elink_phy_init(&sc->link_params, &sc->link_vars);
16067
16068                        bxe_release_phy_lock(sc);
16069
16070                        bxe_calc_fc_adv(sc);
16071                        }
16072        }
16073        return rc;
16074}
16075
16076
16077static void
16078bxe_add_sysctls(struct bxe_softc *sc)
16079{
16080    struct sysctl_ctx_list *ctx;
16081    struct sysctl_oid_list *children;
16082    struct sysctl_oid *queue_top, *queue;
16083    struct sysctl_oid_list *queue_top_children, *queue_children;
16084    char queue_num_buf[32];
16085    uint32_t q_stat;
16086    int i, j;
16087
16088    ctx = device_get_sysctl_ctx(sc->dev);
16089    children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
16090
16091    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
16092                      CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
16093                      "version");
16094
16095    snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
16096             BCM_5710_FW_MAJOR_VERSION,
16097             BCM_5710_FW_MINOR_VERSION,
16098             BCM_5710_FW_REVISION_VERSION,
16099             BCM_5710_FW_ENGINEERING_VERSION);
16100
16101    snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
16102        ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
16103         (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
16104         (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
16105         (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
16106                                                                "Unknown"));
16107    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
16108                    CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
16109                    "multifunction vnics per port");
16110
16111    snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
16112        ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
16113         (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
16114         (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
16115                                              "???GT/s"),
16116        sc->devinfo.pcie_link_width);
16117
16118    sc->debug = bxe_debug;
16119
16120#if __FreeBSD_version >= 900000
16121    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
16122                      CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
16123                      "bootcode version");
16124    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
16125                      CTLFLAG_RD, sc->fw_ver_str, 0,
16126                      "firmware version");
16127    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
16128                      CTLFLAG_RD, sc->mf_mode_str, 0,
16129                      "multifunction mode");
16130    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
16131                      CTLFLAG_RD, sc->mac_addr_str, 0,
16132                      "mac address");
16133    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
16134                      CTLFLAG_RD, sc->pci_link_str, 0,
16135                      "pci link status");
16136    SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
16137                    CTLFLAG_RW, &sc->debug,
16138                    "debug logging mode");
16139#else
16140    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
16141                      CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
16142                      "bootcode version");
16143    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
16144                      CTLFLAG_RD, &sc->fw_ver_str, 0,
16145                      "firmware version");
16146    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
16147                      CTLFLAG_RD, &sc->mf_mode_str, 0,
16148                      "multifunction mode");
16149    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
16150                      CTLFLAG_RD, &sc->mac_addr_str, 0,
16151                      "mac address");
16152    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
16153                      CTLFLAG_RD, &sc->pci_link_str, 0,
16154                      "pci link status");
16155    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
16156                    CTLFLAG_RW, &sc->debug, 0,
16157                    "debug logging mode");
16158#endif /* #if __FreeBSD_version >= 900000 */
16159
16160    sc->trigger_grcdump = 0;
16161    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
16162                   CTLFLAG_RW, &sc->trigger_grcdump, 0,
16163                   "trigger grcdump should be invoked"
16164                   "  before collecting grcdump");
16165
16166    sc->grcdump_started = 0;
16167    sc->grcdump_done = 0;
16168    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
16169                   CTLFLAG_RD, &sc->grcdump_done, 0,
16170                   "set by driver when grcdump is done");
16171
16172    sc->rx_budget = bxe_rx_budget;
16173    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
16174                    CTLFLAG_RW, &sc->rx_budget, 0,
16175                    "rx processing budget");
16176
16177   SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_param",
16178                    CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
16179                    bxe_sysctl_pauseparam, "IU",
16180                    "need pause frames- DEF:0/TX:1/RX:2/BOTH:3/AUTO:4/AUTOTX:5/AUTORX:6/AUTORXTX:7/NONE:8");
16181
16182
16183    SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
16184                    CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
16185                    bxe_sysctl_state, "IU", "dump driver state");
16186
16187    for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
16188        SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
16189                        bxe_eth_stats_arr[i].string,
16190                        CTLTYPE_U64 | CTLFLAG_RD, sc, i,
16191                        bxe_sysctl_eth_stat, "LU",
16192                        bxe_eth_stats_arr[i].string);
16193    }
16194
16195    /* add a new parent node for all queues "dev.bxe.#.queue" */
16196    queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
16197                                CTLFLAG_RD, NULL, "queue");
16198    queue_top_children = SYSCTL_CHILDREN(queue_top);
16199
16200    for (i = 0; i < sc->num_queues; i++) {
16201        /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
16202        snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
16203        queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
16204                                queue_num_buf, CTLFLAG_RD, NULL,
16205                                "single queue");
16206        queue_children = SYSCTL_CHILDREN(queue);
16207
16208        for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
16209            q_stat = ((i << 16) | j);
16210            SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
16211                            bxe_eth_q_stats_arr[j].string,
16212                            CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
16213                            bxe_sysctl_eth_q_stat, "LU",
16214                            bxe_eth_q_stats_arr[j].string);
16215        }
16216    }
16217}
16218
16219static int
16220bxe_alloc_buf_rings(struct bxe_softc *sc)
16221{
16222#if __FreeBSD_version >= 901504
16223
16224    int i;
16225    struct bxe_fastpath *fp;
16226
16227    for (i = 0; i < sc->num_queues; i++) {
16228
16229        fp = &sc->fp[i];
16230
16231        fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
16232                                   M_NOWAIT, &fp->tx_mtx);
16233        if (fp->tx_br == NULL)
16234            return (-1);
16235    }
16236#endif
16237    return (0);
16238}
16239
16240static void
16241bxe_free_buf_rings(struct bxe_softc *sc)
16242{
16243#if __FreeBSD_version >= 901504
16244
16245    int i;
16246    struct bxe_fastpath *fp;
16247
16248    for (i = 0; i < sc->num_queues; i++) {
16249
16250        fp = &sc->fp[i];
16251
16252        if (fp->tx_br) {
16253            buf_ring_free(fp->tx_br, M_DEVBUF);
16254            fp->tx_br = NULL;
16255        }
16256    }
16257
16258#endif
16259}
16260
16261static void
16262bxe_init_fp_mutexs(struct bxe_softc *sc)
16263{
16264    int i;
16265    struct bxe_fastpath *fp;
16266
16267    for (i = 0; i < sc->num_queues; i++) {
16268
16269        fp = &sc->fp[i];
16270
16271        snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
16272            "bxe%d_fp%d_tx_lock", sc->unit, i);
16273        mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
16274
16275        snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
16276            "bxe%d_fp%d_rx_lock", sc->unit, i);
16277        mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
16278    }
16279}
16280
16281static void
16282bxe_destroy_fp_mutexs(struct bxe_softc *sc)
16283{
16284    int i;
16285    struct bxe_fastpath *fp;
16286
16287    for (i = 0; i < sc->num_queues; i++) {
16288
16289        fp = &sc->fp[i];
16290
16291        if (mtx_initialized(&fp->tx_mtx)) {
16292            mtx_destroy(&fp->tx_mtx);
16293        }
16294
16295        if (mtx_initialized(&fp->rx_mtx)) {
16296            mtx_destroy(&fp->rx_mtx);
16297        }
16298    }
16299}
16300
16301
16302/*
16303 * Device attach function.
16304 *
16305 * Allocates device resources, performs secondary chip identification, and
16306 * initializes driver instance variables. This function is called from driver
16307 * load after a successful probe.
16308 *
16309 * Returns:
16310 *   0 = Success, >0 = Failure
16311 */
16312static int
16313bxe_attach(device_t dev)
16314{
16315    struct bxe_softc *sc;
16316
16317    sc = device_get_softc(dev);
16318
16319    BLOGD(sc, DBG_LOAD, "Starting attach...\n");
16320
16321    sc->state = BXE_STATE_CLOSED;
16322
16323    sc->dev  = dev;
16324    sc->unit = device_get_unit(dev);
16325
16326    BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
16327
16328    sc->pcie_bus    = pci_get_bus(dev);
16329    sc->pcie_device = pci_get_slot(dev);
16330    sc->pcie_func   = pci_get_function(dev);
16331
16332    /* enable bus master capability */
16333    pci_enable_busmaster(dev);
16334
16335    /* get the BARs */
16336    if (bxe_allocate_bars(sc) != 0) {
16337        return (ENXIO);
16338    }
16339
16340    /* initialize the mutexes */
16341    bxe_init_mutexes(sc);
16342
16343    /* prepare the periodic callout */
16344    callout_init(&sc->periodic_callout, 0);
16345
16346    /* prepare the chip taskqueue */
16347    sc->chip_tq_flags = CHIP_TQ_NONE;
16348    snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
16349             "bxe%d_chip_tq", sc->unit);
16350    TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
16351    sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
16352                                   taskqueue_thread_enqueue,
16353                                   &sc->chip_tq);
16354    taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
16355                            "%s", sc->chip_tq_name);
16356
16357    TIMEOUT_TASK_INIT(taskqueue_thread,
16358        &sc->sp_err_timeout_task, 0, bxe_sp_err_timeout_task,  sc);
16359
16360
16361    /* get device info and set params */
16362    if (bxe_get_device_info(sc) != 0) {
16363        BLOGE(sc, "getting device info\n");
16364        bxe_deallocate_bars(sc);
16365        pci_disable_busmaster(dev);
16366        return (ENXIO);
16367    }
16368
16369    /* get final misc params */
16370    bxe_get_params(sc);
16371
16372    /* set the default MTU (changed via ifconfig) */
16373    sc->mtu = ETHERMTU;
16374
16375    bxe_set_modes_bitmap(sc);
16376
16377    /* XXX
16378     * If in AFEX mode and the function is configured for FCoE
16379     * then bail... no L2 allowed.
16380     */
16381
16382    /* get phy settings from shmem and 'and' against admin settings */
16383    bxe_get_phy_info(sc);
16384
16385    /* initialize the FreeBSD ifnet interface */
16386    if (bxe_init_ifnet(sc) != 0) {
16387        bxe_release_mutexes(sc);
16388        bxe_deallocate_bars(sc);
16389        pci_disable_busmaster(dev);
16390        return (ENXIO);
16391    }
16392
16393    if (bxe_add_cdev(sc) != 0) {
16394        if (sc->ifp != NULL) {
16395            ether_ifdetach(sc->ifp);
16396        }
16397        ifmedia_removeall(&sc->ifmedia);
16398        bxe_release_mutexes(sc);
16399        bxe_deallocate_bars(sc);
16400        pci_disable_busmaster(dev);
16401        return (ENXIO);
16402    }
16403
16404    /* allocate device interrupts */
16405    if (bxe_interrupt_alloc(sc) != 0) {
16406        bxe_del_cdev(sc);
16407        if (sc->ifp != NULL) {
16408            ether_ifdetach(sc->ifp);
16409        }
16410        ifmedia_removeall(&sc->ifmedia);
16411        bxe_release_mutexes(sc);
16412        bxe_deallocate_bars(sc);
16413        pci_disable_busmaster(dev);
16414        return (ENXIO);
16415    }
16416
16417    bxe_init_fp_mutexs(sc);
16418
16419    if (bxe_alloc_buf_rings(sc) != 0) {
16420	bxe_free_buf_rings(sc);
16421        bxe_interrupt_free(sc);
16422        bxe_del_cdev(sc);
16423        if (sc->ifp != NULL) {
16424            ether_ifdetach(sc->ifp);
16425        }
16426        ifmedia_removeall(&sc->ifmedia);
16427        bxe_release_mutexes(sc);
16428        bxe_deallocate_bars(sc);
16429        pci_disable_busmaster(dev);
16430        return (ENXIO);
16431    }
16432
16433    /* allocate ilt */
16434    if (bxe_alloc_ilt_mem(sc) != 0) {
16435	bxe_free_buf_rings(sc);
16436        bxe_interrupt_free(sc);
16437        bxe_del_cdev(sc);
16438        if (sc->ifp != NULL) {
16439            ether_ifdetach(sc->ifp);
16440        }
16441        ifmedia_removeall(&sc->ifmedia);
16442        bxe_release_mutexes(sc);
16443        bxe_deallocate_bars(sc);
16444        pci_disable_busmaster(dev);
16445        return (ENXIO);
16446    }
16447
16448    /* allocate the host hardware/software hsi structures */
16449    if (bxe_alloc_hsi_mem(sc) != 0) {
16450        bxe_free_ilt_mem(sc);
16451	bxe_free_buf_rings(sc);
16452        bxe_interrupt_free(sc);
16453        bxe_del_cdev(sc);
16454        if (sc->ifp != NULL) {
16455            ether_ifdetach(sc->ifp);
16456        }
16457        ifmedia_removeall(&sc->ifmedia);
16458        bxe_release_mutexes(sc);
16459        bxe_deallocate_bars(sc);
16460        pci_disable_busmaster(dev);
16461        return (ENXIO);
16462    }
16463
16464    /* need to reset chip if UNDI was active */
16465    if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16466        /* init fw_seq */
16467        sc->fw_seq =
16468            (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16469             DRV_MSG_SEQ_NUMBER_MASK);
16470        BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16471        bxe_prev_unload(sc);
16472    }
16473
16474#if 1
16475    /* XXX */
16476    bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16477#else
16478    if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16479        SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16480        SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16481        SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16482        bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16483        bxe_dcbx_init_params(sc);
16484    } else {
16485        bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16486    }
16487#endif
16488
16489    /* calculate qm_cid_count */
16490    sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16491    BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16492
16493    sc->max_cos = 1;
16494    bxe_init_multi_cos(sc);
16495
16496    bxe_add_sysctls(sc);
16497
16498    return (0);
16499}
16500
16501/*
16502 * Device detach function.
16503 *
16504 * Stops the controller, resets the controller, and releases resources.
16505 *
16506 * Returns:
16507 *   0 = Success, >0 = Failure
16508 */
16509static int
16510bxe_detach(device_t dev)
16511{
16512    struct bxe_softc *sc;
16513    if_t ifp;
16514
16515    sc = device_get_softc(dev);
16516
16517    BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16518
16519    ifp = sc->ifp;
16520    if (ifp != NULL && if_vlantrunkinuse(ifp)) {
16521        BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16522        return(EBUSY);
16523    }
16524
16525    bxe_del_cdev(sc);
16526
16527    /* stop the periodic callout */
16528    bxe_periodic_stop(sc);
16529
16530    /* stop the chip taskqueue */
16531    atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16532    if (sc->chip_tq) {
16533        taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16534        taskqueue_free(sc->chip_tq);
16535        sc->chip_tq = NULL;
16536        taskqueue_drain_timeout(taskqueue_thread,
16537            &sc->sp_err_timeout_task);
16538    }
16539
16540    /* stop and reset the controller if it was open */
16541    if (sc->state != BXE_STATE_CLOSED) {
16542        BXE_CORE_LOCK(sc);
16543        bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16544        sc->state = BXE_STATE_DISABLED;
16545        BXE_CORE_UNLOCK(sc);
16546    }
16547
16548    /* release the network interface */
16549    if (ifp != NULL) {
16550        ether_ifdetach(ifp);
16551    }
16552    ifmedia_removeall(&sc->ifmedia);
16553
16554    /* XXX do the following based on driver state... */
16555
16556    /* free the host hardware/software hsi structures */
16557    bxe_free_hsi_mem(sc);
16558
16559    /* free ilt */
16560    bxe_free_ilt_mem(sc);
16561
16562    bxe_free_buf_rings(sc);
16563
16564    /* release the interrupts */
16565    bxe_interrupt_free(sc);
16566
16567    /* Release the mutexes*/
16568    bxe_destroy_fp_mutexs(sc);
16569    bxe_release_mutexes(sc);
16570
16571
16572    /* Release the PCIe BAR mapped memory */
16573    bxe_deallocate_bars(sc);
16574
16575    /* Release the FreeBSD interface. */
16576    if (sc->ifp != NULL) {
16577        if_free(sc->ifp);
16578    }
16579
16580    pci_disable_busmaster(dev);
16581
16582    return (0);
16583}
16584
16585/*
16586 * Device shutdown function.
16587 *
16588 * Stops and resets the controller.
16589 *
16590 * Returns:
16591 *   Nothing
16592 */
16593static int
16594bxe_shutdown(device_t dev)
16595{
16596    struct bxe_softc *sc;
16597
16598    sc = device_get_softc(dev);
16599
16600    BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16601
16602    /* stop the periodic callout */
16603    bxe_periodic_stop(sc);
16604
16605    if (sc->state != BXE_STATE_CLOSED) {
16606    	BXE_CORE_LOCK(sc);
16607    	bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16608    	BXE_CORE_UNLOCK(sc);
16609    }
16610
16611    return (0);
16612}
16613
16614void
16615bxe_igu_ack_sb(struct bxe_softc *sc,
16616               uint8_t          igu_sb_id,
16617               uint8_t          segment,
16618               uint16_t         index,
16619               uint8_t          op,
16620               uint8_t          update)
16621{
16622    uint32_t igu_addr = sc->igu_base_addr;
16623    igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16624    bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16625}
16626
16627static void
16628bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16629                     uint8_t          func,
16630                     uint8_t          idu_sb_id,
16631                     uint8_t          is_pf)
16632{
16633    uint32_t data, ctl, cnt = 100;
16634    uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16635    uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16636    uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16637    uint32_t sb_bit =  1 << (idu_sb_id%32);
16638    uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16639    uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16640
16641    /* Not supported in BC mode */
16642    if (CHIP_INT_MODE_IS_BC(sc)) {
16643        return;
16644    }
16645
16646    data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16647             IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16648            IGU_REGULAR_CLEANUP_SET |
16649            IGU_REGULAR_BCLEANUP);
16650
16651    ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16652           (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16653           (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16654
16655    BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16656            data, igu_addr_data);
16657    REG_WR(sc, igu_addr_data, data);
16658
16659    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16660                      BUS_SPACE_BARRIER_WRITE);
16661    mb();
16662
16663    BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16664            ctl, igu_addr_ctl);
16665    REG_WR(sc, igu_addr_ctl, ctl);
16666
16667    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16668                      BUS_SPACE_BARRIER_WRITE);
16669    mb();
16670
16671    /* wait for clean up to finish */
16672    while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16673        DELAY(20000);
16674    }
16675
16676    if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16677        BLOGD(sc, DBG_LOAD,
16678              "Unable to finish IGU cleanup: "
16679              "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16680              idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16681    }
16682}
16683
16684static void
16685bxe_igu_clear_sb(struct bxe_softc *sc,
16686                 uint8_t          idu_sb_id)
16687{
16688    bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16689}
16690
16691
16692
16693
16694
16695
16696
16697/*******************/
16698/* ECORE CALLBACKS */
16699/*******************/
16700
16701static void
16702bxe_reset_common(struct bxe_softc *sc)
16703{
16704    uint32_t val = 0x1400;
16705
16706    /* reset_common */
16707    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16708
16709    if (CHIP_IS_E3(sc)) {
16710        val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16711        val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16712    }
16713
16714    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16715}
16716
16717static void
16718bxe_common_init_phy(struct bxe_softc *sc)
16719{
16720    uint32_t shmem_base[2];
16721    uint32_t shmem2_base[2];
16722
16723    /* Avoid common init in case MFW supports LFA */
16724    if (SHMEM2_RD(sc, size) >
16725        (uint32_t)offsetof(struct shmem2_region,
16726                           lfa_host_addr[SC_PORT(sc)])) {
16727        return;
16728    }
16729
16730    shmem_base[0]  = sc->devinfo.shmem_base;
16731    shmem2_base[0] = sc->devinfo.shmem2_base;
16732
16733    if (!CHIP_IS_E1x(sc)) {
16734        shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16735        shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16736    }
16737
16738    bxe_acquire_phy_lock(sc);
16739    elink_common_init_phy(sc, shmem_base, shmem2_base,
16740                          sc->devinfo.chip_id, 0);
16741    bxe_release_phy_lock(sc);
16742}
16743
16744static void
16745bxe_pf_disable(struct bxe_softc *sc)
16746{
16747    uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16748
16749    val &= ~IGU_PF_CONF_FUNC_EN;
16750
16751    REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16752    REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16753    REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16754}
16755
16756static void
16757bxe_init_pxp(struct bxe_softc *sc)
16758{
16759    uint16_t devctl;
16760    int r_order, w_order;
16761
16762    devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16763
16764    BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16765
16766    w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16767
16768    if (sc->mrrs == -1) {
16769        r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16770    } else {
16771        BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16772        r_order = sc->mrrs;
16773    }
16774
16775    ecore_init_pxp_arb(sc, r_order, w_order);
16776}
16777
16778static uint32_t
16779bxe_get_pretend_reg(struct bxe_softc *sc)
16780{
16781    uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16782    uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16783    return (base + (SC_ABS_FUNC(sc)) * stride);
16784}
16785
16786/*
16787 * Called only on E1H or E2.
16788 * When pretending to be PF, the pretend value is the function number 0..7.
16789 * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16790 * combination.
16791 */
16792static int
16793bxe_pretend_func(struct bxe_softc *sc,
16794                 uint16_t         pretend_func_val)
16795{
16796    uint32_t pretend_reg;
16797
16798    if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16799        return (-1);
16800    }
16801
16802    /* get my own pretend register */
16803    pretend_reg = bxe_get_pretend_reg(sc);
16804    REG_WR(sc, pretend_reg, pretend_func_val);
16805    REG_RD(sc, pretend_reg);
16806    return (0);
16807}
16808
16809static void
16810bxe_iov_init_dmae(struct bxe_softc *sc)
16811{
16812    return;
16813}
16814
16815static void
16816bxe_iov_init_dq(struct bxe_softc *sc)
16817{
16818    return;
16819}
16820
16821/* send a NIG loopback debug packet */
16822static void
16823bxe_lb_pckt(struct bxe_softc *sc)
16824{
16825    uint32_t wb_write[3];
16826
16827    /* Ethernet source and destination addresses */
16828    wb_write[0] = 0x55555555;
16829    wb_write[1] = 0x55555555;
16830    wb_write[2] = 0x20;     /* SOP */
16831    REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16832
16833    /* NON-IP protocol */
16834    wb_write[0] = 0x09000000;
16835    wb_write[1] = 0x55555555;
16836    wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16837    REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16838}
16839
16840/*
16841 * Some of the internal memories are not directly readable from the driver.
16842 * To test them we send debug packets.
16843 */
16844static int
16845bxe_int_mem_test(struct bxe_softc *sc)
16846{
16847    int factor;
16848    int count, i;
16849    uint32_t val = 0;
16850
16851    if (CHIP_REV_IS_FPGA(sc)) {
16852        factor = 120;
16853    } else if (CHIP_REV_IS_EMUL(sc)) {
16854        factor = 200;
16855    } else {
16856        factor = 1;
16857    }
16858
16859    /* disable inputs of parser neighbor blocks */
16860    REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16861    REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16862    REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16863    REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16864
16865    /*  write 0 to parser credits for CFC search request */
16866    REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16867
16868    /* send Ethernet packet */
16869    bxe_lb_pckt(sc);
16870
16871    /* TODO do i reset NIG statistic? */
16872    /* Wait until NIG register shows 1 packet of size 0x10 */
16873    count = 1000 * factor;
16874    while (count) {
16875        bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16876        val = *BXE_SP(sc, wb_data[0]);
16877        if (val == 0x10) {
16878            break;
16879        }
16880
16881        DELAY(10000);
16882        count--;
16883    }
16884
16885    if (val != 0x10) {
16886        BLOGE(sc, "NIG timeout val=0x%x\n", val);
16887        return (-1);
16888    }
16889
16890    /* wait until PRS register shows 1 packet */
16891    count = (1000 * factor);
16892    while (count) {
16893        val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16894        if (val == 1) {
16895            break;
16896        }
16897
16898        DELAY(10000);
16899        count--;
16900    }
16901
16902    if (val != 0x1) {
16903        BLOGE(sc, "PRS timeout val=0x%x\n", val);
16904        return (-2);
16905    }
16906
16907    /* Reset and init BRB, PRS */
16908    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16909    DELAY(50000);
16910    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16911    DELAY(50000);
16912    ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16913    ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16914
16915    /* Disable inputs of parser neighbor blocks */
16916    REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16917    REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16918    REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16919    REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16920
16921    /* Write 0 to parser credits for CFC search request */
16922    REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16923
16924    /* send 10 Ethernet packets */
16925    for (i = 0; i < 10; i++) {
16926        bxe_lb_pckt(sc);
16927    }
16928
16929    /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16930    count = (1000 * factor);
16931    while (count) {
16932        bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16933        val = *BXE_SP(sc, wb_data[0]);
16934        if (val == 0xb0) {
16935            break;
16936        }
16937
16938        DELAY(10000);
16939        count--;
16940    }
16941
16942    if (val != 0xb0) {
16943        BLOGE(sc, "NIG timeout val=0x%x\n", val);
16944        return (-3);
16945    }
16946
16947    /* Wait until PRS register shows 2 packets */
16948    val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16949    if (val != 2) {
16950        BLOGE(sc, "PRS timeout val=0x%x\n", val);
16951    }
16952
16953    /* Write 1 to parser credits for CFC search request */
16954    REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16955
16956    /* Wait until PRS register shows 3 packets */
16957    DELAY(10000 * factor);
16958
16959    /* Wait until NIG register shows 1 packet of size 0x10 */
16960    val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16961    if (val != 3) {
16962        BLOGE(sc, "PRS timeout val=0x%x\n", val);
16963    }
16964
16965    /* clear NIG EOP FIFO */
16966    for (i = 0; i < 11; i++) {
16967        REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16968    }
16969
16970    val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16971    if (val != 1) {
16972        BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16973        return (-4);
16974    }
16975
16976    /* Reset and init BRB, PRS, NIG */
16977    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16978    DELAY(50000);
16979    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16980    DELAY(50000);
16981    ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16982    ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16983    if (!CNIC_SUPPORT(sc)) {
16984        /* set NIC mode */
16985        REG_WR(sc, PRS_REG_NIC_MODE, 1);
16986    }
16987
16988    /* Enable inputs of parser neighbor blocks */
16989    REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16990    REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16991    REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16992    REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16993
16994    return (0);
16995}
16996
16997static void
16998bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16999{
17000    int is_required;
17001    uint32_t val;
17002    int port;
17003
17004    is_required = 0;
17005    val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
17006           SHARED_HW_CFG_FAN_FAILURE_MASK);
17007
17008    if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
17009        is_required = 1;
17010    }
17011    /*
17012     * The fan failure mechanism is usually related to the PHY type since
17013     * the power consumption of the board is affected by the PHY. Currently,
17014     * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
17015     */
17016    else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
17017        for (port = PORT_0; port < PORT_MAX; port++) {
17018            is_required |= elink_fan_failure_det_req(sc,
17019                                                     sc->devinfo.shmem_base,
17020                                                     sc->devinfo.shmem2_base,
17021                                                     port);
17022        }
17023    }
17024
17025    BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
17026
17027    if (is_required == 0) {
17028        return;
17029    }
17030
17031    /* Fan failure is indicated by SPIO 5 */
17032    bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
17033
17034    /* set to active low mode */
17035    val = REG_RD(sc, MISC_REG_SPIO_INT);
17036    val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
17037    REG_WR(sc, MISC_REG_SPIO_INT, val);
17038
17039    /* enable interrupt to signal the IGU */
17040    val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17041    val |= MISC_SPIO_SPIO5;
17042    REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
17043}
17044
17045static void
17046bxe_enable_blocks_attention(struct bxe_softc *sc)
17047{
17048    uint32_t val;
17049
17050    REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
17051    if (!CHIP_IS_E1x(sc)) {
17052        REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
17053    } else {
17054        REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
17055    }
17056    REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17057    REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17058    /*
17059     * mask read length error interrupts in brb for parser
17060     * (parsing unit and 'checksum and crc' unit)
17061     * these errors are legal (PU reads fixed length and CAC can cause
17062     * read length error on truncated packets)
17063     */
17064    REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
17065    REG_WR(sc, QM_REG_QM_INT_MASK, 0);
17066    REG_WR(sc, TM_REG_TM_INT_MASK, 0);
17067    REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
17068    REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
17069    REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
17070/*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
17071/*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
17072    REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
17073    REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
17074    REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
17075/*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
17076/*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
17077    REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
17078    REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
17079    REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
17080    REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
17081/*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
17082/*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
17083
17084    val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
17085           PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
17086           PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
17087    if (!CHIP_IS_E1x(sc)) {
17088        val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
17089                PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
17090    }
17091    REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
17092
17093    REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
17094    REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
17095    REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
17096/*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
17097
17098    if (!CHIP_IS_E1x(sc)) {
17099        /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
17100        REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
17101    }
17102
17103    REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
17104    REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
17105/*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
17106    REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
17107}
17108
17109/**
17110 * bxe_init_hw_common - initialize the HW at the COMMON phase.
17111 *
17112 * @sc:     driver handle
17113 */
17114static int
17115bxe_init_hw_common(struct bxe_softc *sc)
17116{
17117    uint8_t abs_func_id;
17118    uint32_t val;
17119
17120    BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
17121          SC_ABS_FUNC(sc));
17122
17123    /*
17124     * take the RESET lock to protect undi_unload flow from accessing
17125     * registers while we are resetting the chip
17126     */
17127    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
17128
17129    bxe_reset_common(sc);
17130
17131    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
17132
17133    val = 0xfffc;
17134    if (CHIP_IS_E3(sc)) {
17135        val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
17136        val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
17137    }
17138
17139    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
17140
17141    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
17142
17143    ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
17144    BLOGD(sc, DBG_LOAD, "after misc block init\n");
17145
17146    if (!CHIP_IS_E1x(sc)) {
17147        /*
17148         * 4-port mode or 2-port mode we need to turn off master-enable for
17149         * everyone. After that we turn it back on for self. So, we disregard
17150         * multi-function, and always disable all functions on the given path,
17151         * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
17152         */
17153        for (abs_func_id = SC_PATH(sc);
17154             abs_func_id < (E2_FUNC_MAX * 2);
17155             abs_func_id += 2) {
17156            if (abs_func_id == SC_ABS_FUNC(sc)) {
17157                REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17158                continue;
17159            }
17160
17161            bxe_pretend_func(sc, abs_func_id);
17162
17163            /* clear pf enable */
17164            bxe_pf_disable(sc);
17165
17166            bxe_pretend_func(sc, SC_ABS_FUNC(sc));
17167        }
17168    }
17169
17170    BLOGD(sc, DBG_LOAD, "after pf disable\n");
17171
17172    ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
17173
17174    if (CHIP_IS_E1(sc)) {
17175        /*
17176         * enable HW interrupt from PXP on USDM overflow
17177         * bit 16 on INT_MASK_0
17178         */
17179        REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
17180    }
17181
17182    ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
17183    bxe_init_pxp(sc);
17184
17185#ifdef __BIG_ENDIAN
17186    REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
17187    REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
17188    REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
17189    REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
17190    REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
17191    /* make sure this value is 0 */
17192    REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
17193
17194    //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
17195    REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
17196    REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
17197    REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
17198    REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
17199#endif
17200
17201    ecore_ilt_init_page_size(sc, INITOP_SET);
17202
17203    if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
17204        REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
17205    }
17206
17207    /* let the HW do it's magic... */
17208    DELAY(100000);
17209
17210    /* finish PXP init */
17211    val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
17212    if (val != 1) {
17213        BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
17214            val);
17215        return (-1);
17216    }
17217    val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
17218    if (val != 1) {
17219        BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
17220        return (-1);
17221    }
17222
17223    BLOGD(sc, DBG_LOAD, "after pxp init\n");
17224
17225    /*
17226     * Timer bug workaround for E2 only. We need to set the entire ILT to have
17227     * entries with value "0" and valid bit on. This needs to be done by the
17228     * first PF that is loaded in a path (i.e. common phase)
17229     */
17230    if (!CHIP_IS_E1x(sc)) {
17231/*
17232 * In E2 there is a bug in the timers block that can cause function 6 / 7
17233 * (i.e. vnic3) to start even if it is marked as "scan-off".
17234 * This occurs when a different function (func2,3) is being marked
17235 * as "scan-off". Real-life scenario for example: if a driver is being
17236 * load-unloaded while func6,7 are down. This will cause the timer to access
17237 * the ilt, translate to a logical address and send a request to read/write.
17238 * Since the ilt for the function that is down is not valid, this will cause
17239 * a translation error which is unrecoverable.
17240 * The Workaround is intended to make sure that when this happens nothing
17241 * fatal will occur. The workaround:
17242 *  1.  First PF driver which loads on a path will:
17243 *      a.  After taking the chip out of reset, by using pretend,
17244 *          it will write "0" to the following registers of
17245 *          the other vnics.
17246 *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
17247 *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
17248 *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
17249 *          And for itself it will write '1' to
17250 *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
17251 *          dmae-operations (writing to pram for example.)
17252 *          note: can be done for only function 6,7 but cleaner this
17253 *            way.
17254 *      b.  Write zero+valid to the entire ILT.
17255 *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
17256 *          VNIC3 (of that port). The range allocated will be the
17257 *          entire ILT. This is needed to prevent  ILT range error.
17258 *  2.  Any PF driver load flow:
17259 *      a.  ILT update with the physical addresses of the allocated
17260 *          logical pages.
17261 *      b.  Wait 20msec. - note that this timeout is needed to make
17262 *          sure there are no requests in one of the PXP internal
17263 *          queues with "old" ILT addresses.
17264 *      c.  PF enable in the PGLC.
17265 *      d.  Clear the was_error of the PF in the PGLC. (could have
17266 *          occurred while driver was down)
17267 *      e.  PF enable in the CFC (WEAK + STRONG)
17268 *      f.  Timers scan enable
17269 *  3.  PF driver unload flow:
17270 *      a.  Clear the Timers scan_en.
17271 *      b.  Polling for scan_on=0 for that PF.
17272 *      c.  Clear the PF enable bit in the PXP.
17273 *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
17274 *      e.  Write zero+valid to all ILT entries (The valid bit must
17275 *          stay set)
17276 *      f.  If this is VNIC 3 of a port then also init
17277 *          first_timers_ilt_entry to zero and last_timers_ilt_entry
17278 *          to the last enrty in the ILT.
17279 *
17280 *      Notes:
17281 *      Currently the PF error in the PGLC is non recoverable.
17282 *      In the future the there will be a recovery routine for this error.
17283 *      Currently attention is masked.
17284 *      Having an MCP lock on the load/unload process does not guarantee that
17285 *      there is no Timer disable during Func6/7 enable. This is because the
17286 *      Timers scan is currently being cleared by the MCP on FLR.
17287 *      Step 2.d can be done only for PF6/7 and the driver can also check if
17288 *      there is error before clearing it. But the flow above is simpler and
17289 *      more general.
17290 *      All ILT entries are written by zero+valid and not just PF6/7
17291 *      ILT entries since in the future the ILT entries allocation for
17292 *      PF-s might be dynamic.
17293 */
17294        struct ilt_client_info ilt_cli;
17295        struct ecore_ilt ilt;
17296
17297        memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
17298        memset(&ilt, 0, sizeof(struct ecore_ilt));
17299
17300        /* initialize dummy TM client */
17301        ilt_cli.start      = 0;
17302        ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
17303        ilt_cli.client_num = ILT_CLIENT_TM;
17304
17305        /*
17306         * Step 1: set zeroes to all ilt page entries with valid bit on
17307         * Step 2: set the timers first/last ilt entry to point
17308         * to the entire range to prevent ILT range error for 3rd/4th
17309         * vnic (this code assumes existence of the vnic)
17310         *
17311         * both steps performed by call to ecore_ilt_client_init_op()
17312         * with dummy TM client
17313         *
17314         * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
17315         * and his brother are split registers
17316         */
17317
17318        bxe_pretend_func(sc, (SC_PATH(sc) + 6));
17319        ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
17320        bxe_pretend_func(sc, SC_ABS_FUNC(sc));
17321
17322        REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
17323        REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
17324        REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
17325    }
17326
17327    REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
17328    REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
17329
17330    if (!CHIP_IS_E1x(sc)) {
17331        int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
17332                     (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
17333
17334        ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
17335        ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
17336
17337        /* let the HW do it's magic... */
17338        do {
17339            DELAY(200000);
17340            val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
17341        } while (factor-- && (val != 1));
17342
17343        if (val != 1) {
17344            BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
17345            return (-1);
17346        }
17347    }
17348
17349    BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
17350
17351    ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
17352
17353    bxe_iov_init_dmae(sc);
17354
17355    /* clean the DMAE memory */
17356    sc->dmae_ready = 1;
17357    ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
17358
17359    ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
17360
17361    ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
17362
17363    ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
17364
17365    ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
17366
17367    bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
17368    bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17369    bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17370    bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17371
17372    ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17373
17374    /* QM queues pointers table */
17375    ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17376
17377    /* soft reset pulse */
17378    REG_WR(sc, QM_REG_SOFT_RESET, 1);
17379    REG_WR(sc, QM_REG_SOFT_RESET, 0);
17380
17381    if (CNIC_SUPPORT(sc))
17382        ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17383
17384    ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17385    REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17386    if (!CHIP_REV_IS_SLOW(sc)) {
17387        /* enable hw interrupt from doorbell Q */
17388        REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17389    }
17390
17391    ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17392
17393    ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17394    REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17395
17396    if (!CHIP_IS_E1(sc)) {
17397        REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17398    }
17399
17400    if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17401        if (IS_MF_AFEX(sc)) {
17402            /*
17403             * configure that AFEX and VLAN headers must be
17404             * received in AFEX mode
17405             */
17406            REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17407            REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17408            REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17409            REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17410            REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17411        } else {
17412            /*
17413             * Bit-map indicating which L2 hdrs may appear
17414             * after the basic Ethernet header
17415             */
17416            REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17417                   sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17418        }
17419    }
17420
17421    ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17422    ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17423    ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17424    ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17425
17426    if (!CHIP_IS_E1x(sc)) {
17427        /* reset VFC memories */
17428        REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17429               VFC_MEMORIES_RST_REG_CAM_RST |
17430               VFC_MEMORIES_RST_REG_RAM_RST);
17431        REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17432               VFC_MEMORIES_RST_REG_CAM_RST |
17433               VFC_MEMORIES_RST_REG_RAM_RST);
17434
17435        DELAY(20000);
17436    }
17437
17438    ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17439    ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17440    ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17441    ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17442
17443    /* sync semi rtc */
17444    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17445           0x80000000);
17446    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17447           0x80000000);
17448
17449    ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17450    ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17451    ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17452
17453    if (!CHIP_IS_E1x(sc)) {
17454        if (IS_MF_AFEX(sc)) {
17455            /*
17456             * configure that AFEX and VLAN headers must be
17457             * sent in AFEX mode
17458             */
17459            REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17460            REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17461            REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17462            REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17463            REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17464        } else {
17465            REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17466                   sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17467        }
17468    }
17469
17470    REG_WR(sc, SRC_REG_SOFT_RST, 1);
17471
17472    ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17473
17474    if (CNIC_SUPPORT(sc)) {
17475        REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17476        REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17477        REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17478        REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17479        REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17480        REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17481        REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17482        REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17483        REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17484        REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17485    }
17486    REG_WR(sc, SRC_REG_SOFT_RST, 0);
17487
17488    if (sizeof(union cdu_context) != 1024) {
17489        /* we currently assume that a context is 1024 bytes */
17490        BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17491              (long)sizeof(union cdu_context));
17492    }
17493
17494    ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17495    val = (4 << 24) + (0 << 12) + 1024;
17496    REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17497
17498    ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17499
17500    REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17501    /* enable context validation interrupt from CFC */
17502    REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17503
17504    /* set the thresholds to prevent CFC/CDU race */
17505    REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17506    ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17507
17508    if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17509        REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17510    }
17511
17512    ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17513    ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17514
17515    /* Reset PCIE errors for debug */
17516    REG_WR(sc, 0x2814, 0xffffffff);
17517    REG_WR(sc, 0x3820, 0xffffffff);
17518
17519    if (!CHIP_IS_E1x(sc)) {
17520        REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17521               (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17522                PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17523        REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17524               (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17525                PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17526                PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17527        REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17528               (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17529                PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17530                PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17531    }
17532
17533    ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17534
17535    if (!CHIP_IS_E1(sc)) {
17536        /* in E3 this done in per-port section */
17537        if (!CHIP_IS_E3(sc))
17538            REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17539    }
17540
17541    if (CHIP_IS_E1H(sc)) {
17542        /* not applicable for E2 (and above ...) */
17543        REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17544    }
17545
17546    if (CHIP_REV_IS_SLOW(sc)) {
17547        DELAY(200000);
17548    }
17549
17550    /* finish CFC init */
17551    val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17552    if (val != 1) {
17553        BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17554        return (-1);
17555    }
17556    val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17557    if (val != 1) {
17558        BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17559        return (-1);
17560    }
17561    val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17562    if (val != 1) {
17563        BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17564        return (-1);
17565    }
17566    REG_WR(sc, CFC_REG_DEBUG0, 0);
17567
17568    if (CHIP_IS_E1(sc)) {
17569        /* read NIG statistic to see if this is our first up since powerup */
17570        bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17571        val = *BXE_SP(sc, wb_data[0]);
17572
17573        /* do internal memory self test */
17574        if ((val == 0) && bxe_int_mem_test(sc)) {
17575            BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17576            return (-1);
17577        }
17578    }
17579
17580    bxe_setup_fan_failure_detection(sc);
17581
17582    /* clear PXP2 attentions */
17583    REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17584
17585    bxe_enable_blocks_attention(sc);
17586
17587    if (!CHIP_REV_IS_SLOW(sc)) {
17588        ecore_enable_blocks_parity(sc);
17589    }
17590
17591    if (!BXE_NOMCP(sc)) {
17592        if (CHIP_IS_E1x(sc)) {
17593            bxe_common_init_phy(sc);
17594        }
17595    }
17596
17597    return (0);
17598}
17599
17600/**
17601 * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17602 *
17603 * @sc:     driver handle
17604 */
17605static int
17606bxe_init_hw_common_chip(struct bxe_softc *sc)
17607{
17608    int rc = bxe_init_hw_common(sc);
17609
17610    if (rc) {
17611        BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17612        return (rc);
17613    }
17614
17615    /* In E2 2-PORT mode, same ext phy is used for the two paths */
17616    if (!BXE_NOMCP(sc)) {
17617        bxe_common_init_phy(sc);
17618    }
17619
17620    return (0);
17621}
17622
17623static int
17624bxe_init_hw_port(struct bxe_softc *sc)
17625{
17626    int port = SC_PORT(sc);
17627    int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17628    uint32_t low, high;
17629    uint32_t val;
17630
17631    BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17632
17633    REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17634
17635    ecore_init_block(sc, BLOCK_MISC, init_phase);
17636    ecore_init_block(sc, BLOCK_PXP, init_phase);
17637    ecore_init_block(sc, BLOCK_PXP2, init_phase);
17638
17639    /*
17640     * Timers bug workaround: disables the pf_master bit in pglue at
17641     * common phase, we need to enable it here before any dmae access are
17642     * attempted. Therefore we manually added the enable-master to the
17643     * port phase (it also happens in the function phase)
17644     */
17645    if (!CHIP_IS_E1x(sc)) {
17646        REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17647    }
17648
17649    ecore_init_block(sc, BLOCK_ATC, init_phase);
17650    ecore_init_block(sc, BLOCK_DMAE, init_phase);
17651    ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17652    ecore_init_block(sc, BLOCK_QM, init_phase);
17653
17654    ecore_init_block(sc, BLOCK_TCM, init_phase);
17655    ecore_init_block(sc, BLOCK_UCM, init_phase);
17656    ecore_init_block(sc, BLOCK_CCM, init_phase);
17657    ecore_init_block(sc, BLOCK_XCM, init_phase);
17658
17659    /* QM cid (connection) count */
17660    ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17661
17662    if (CNIC_SUPPORT(sc)) {
17663        ecore_init_block(sc, BLOCK_TM, init_phase);
17664        REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17665        REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17666    }
17667
17668    ecore_init_block(sc, BLOCK_DORQ, init_phase);
17669
17670    ecore_init_block(sc, BLOCK_BRB1, init_phase);
17671
17672    if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17673        if (IS_MF(sc)) {
17674            low = (BXE_ONE_PORT(sc) ? 160 : 246);
17675        } else if (sc->mtu > 4096) {
17676            if (BXE_ONE_PORT(sc)) {
17677                low = 160;
17678            } else {
17679                val = sc->mtu;
17680                /* (24*1024 + val*4)/256 */
17681                low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17682            }
17683        } else {
17684            low = (BXE_ONE_PORT(sc) ? 80 : 160);
17685        }
17686        high = (low + 56); /* 14*1024/256 */
17687        REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17688        REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17689    }
17690
17691    if (CHIP_IS_MODE_4_PORT(sc)) {
17692        REG_WR(sc, SC_PORT(sc) ?
17693               BRB1_REG_MAC_GUARANTIED_1 :
17694               BRB1_REG_MAC_GUARANTIED_0, 40);
17695    }
17696
17697    ecore_init_block(sc, BLOCK_PRS, init_phase);
17698    if (CHIP_IS_E3B0(sc)) {
17699        if (IS_MF_AFEX(sc)) {
17700            /* configure headers for AFEX mode */
17701            REG_WR(sc, SC_PORT(sc) ?
17702                   PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17703                   PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17704            REG_WR(sc, SC_PORT(sc) ?
17705                   PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17706                   PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17707            REG_WR(sc, SC_PORT(sc) ?
17708                   PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17709                   PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17710        } else {
17711            /* Ovlan exists only if we are in multi-function +
17712             * switch-dependent mode, in switch-independent there
17713             * is no ovlan headers
17714             */
17715            REG_WR(sc, SC_PORT(sc) ?
17716                   PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17717                   PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17718                   (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17719        }
17720    }
17721
17722    ecore_init_block(sc, BLOCK_TSDM, init_phase);
17723    ecore_init_block(sc, BLOCK_CSDM, init_phase);
17724    ecore_init_block(sc, BLOCK_USDM, init_phase);
17725    ecore_init_block(sc, BLOCK_XSDM, init_phase);
17726
17727    ecore_init_block(sc, BLOCK_TSEM, init_phase);
17728    ecore_init_block(sc, BLOCK_USEM, init_phase);
17729    ecore_init_block(sc, BLOCK_CSEM, init_phase);
17730    ecore_init_block(sc, BLOCK_XSEM, init_phase);
17731
17732    ecore_init_block(sc, BLOCK_UPB, init_phase);
17733    ecore_init_block(sc, BLOCK_XPB, init_phase);
17734
17735    ecore_init_block(sc, BLOCK_PBF, init_phase);
17736
17737    if (CHIP_IS_E1x(sc)) {
17738        /* configure PBF to work without PAUSE mtu 9000 */
17739        REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17740
17741        /* update threshold */
17742        REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17743        /* update init credit */
17744        REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17745
17746        /* probe changes */
17747        REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17748        DELAY(50);
17749        REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17750    }
17751
17752    if (CNIC_SUPPORT(sc)) {
17753        ecore_init_block(sc, BLOCK_SRC, init_phase);
17754    }
17755
17756    ecore_init_block(sc, BLOCK_CDU, init_phase);
17757    ecore_init_block(sc, BLOCK_CFC, init_phase);
17758
17759    if (CHIP_IS_E1(sc)) {
17760        REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17761        REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17762    }
17763    ecore_init_block(sc, BLOCK_HC, init_phase);
17764
17765    ecore_init_block(sc, BLOCK_IGU, init_phase);
17766
17767    ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17768    /* init aeu_mask_attn_func_0/1:
17769     *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17770     *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17771     *             bits 4-7 are used for "per vn group attention" */
17772    val = IS_MF(sc) ? 0xF7 : 0x7;
17773    /* Enable DCBX attention for all but E1 */
17774    val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17775    REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17776
17777    ecore_init_block(sc, BLOCK_NIG, init_phase);
17778
17779    if (!CHIP_IS_E1x(sc)) {
17780        /* Bit-map indicating which L2 hdrs may appear after the
17781         * basic Ethernet header
17782         */
17783        if (IS_MF_AFEX(sc)) {
17784            REG_WR(sc, SC_PORT(sc) ?
17785                   NIG_REG_P1_HDRS_AFTER_BASIC :
17786                   NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17787        } else {
17788            REG_WR(sc, SC_PORT(sc) ?
17789                   NIG_REG_P1_HDRS_AFTER_BASIC :
17790                   NIG_REG_P0_HDRS_AFTER_BASIC,
17791                   IS_MF_SD(sc) ? 7 : 6);
17792        }
17793
17794        if (CHIP_IS_E3(sc)) {
17795            REG_WR(sc, SC_PORT(sc) ?
17796                   NIG_REG_LLH1_MF_MODE :
17797                   NIG_REG_LLH_MF_MODE, IS_MF(sc));
17798        }
17799    }
17800    if (!CHIP_IS_E3(sc)) {
17801        REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17802    }
17803
17804    if (!CHIP_IS_E1(sc)) {
17805        /* 0x2 disable mf_ov, 0x1 enable */
17806        REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17807               (IS_MF_SD(sc) ? 0x1 : 0x2));
17808
17809        if (!CHIP_IS_E1x(sc)) {
17810            val = 0;
17811            switch (sc->devinfo.mf_info.mf_mode) {
17812            case MULTI_FUNCTION_SD:
17813                val = 1;
17814                break;
17815            case MULTI_FUNCTION_SI:
17816            case MULTI_FUNCTION_AFEX:
17817                val = 2;
17818                break;
17819            }
17820
17821            REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17822                        NIG_REG_LLH0_CLS_TYPE), val);
17823        }
17824        REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17825        REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17826        REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17827    }
17828
17829    /* If SPIO5 is set to generate interrupts, enable it for this port */
17830    val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17831    if (val & MISC_SPIO_SPIO5) {
17832        uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17833                                    MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17834        val = REG_RD(sc, reg_addr);
17835        val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17836        REG_WR(sc, reg_addr, val);
17837    }
17838
17839    return (0);
17840}
17841
17842static uint32_t
17843bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17844                       uint32_t         reg,
17845                       uint32_t         expected,
17846                       uint32_t         poll_count)
17847{
17848    uint32_t cur_cnt = poll_count;
17849    uint32_t val;
17850
17851    while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17852        DELAY(FLR_WAIT_INTERVAL);
17853    }
17854
17855    return (val);
17856}
17857
17858static int
17859bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17860                              uint32_t         reg,
17861                              char             *msg,
17862                              uint32_t         poll_cnt)
17863{
17864    uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17865
17866    if (val != 0) {
17867        BLOGE(sc, "%s usage count=%d\n", msg, val);
17868        return (1);
17869    }
17870
17871    return (0);
17872}
17873
17874/* Common routines with VF FLR cleanup */
17875static uint32_t
17876bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17877{
17878    /* adjust polling timeout */
17879    if (CHIP_REV_IS_EMUL(sc)) {
17880        return (FLR_POLL_CNT * 2000);
17881    }
17882
17883    if (CHIP_REV_IS_FPGA(sc)) {
17884        return (FLR_POLL_CNT * 120);
17885    }
17886
17887    return (FLR_POLL_CNT);
17888}
17889
17890static int
17891bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17892                           uint32_t         poll_cnt)
17893{
17894    /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17895    if (bxe_flr_clnup_poll_hw_counter(sc,
17896                                      CFC_REG_NUM_LCIDS_INSIDE_PF,
17897                                      "CFC PF usage counter timed out",
17898                                      poll_cnt)) {
17899        return (1);
17900    }
17901
17902    /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17903    if (bxe_flr_clnup_poll_hw_counter(sc,
17904                                      DORQ_REG_PF_USAGE_CNT,
17905                                      "DQ PF usage counter timed out",
17906                                      poll_cnt)) {
17907        return (1);
17908    }
17909
17910    /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17911    if (bxe_flr_clnup_poll_hw_counter(sc,
17912                                      QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17913                                      "QM PF usage counter timed out",
17914                                      poll_cnt)) {
17915        return (1);
17916    }
17917
17918    /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17919    if (bxe_flr_clnup_poll_hw_counter(sc,
17920                                      TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17921                                      "Timers VNIC usage counter timed out",
17922                                      poll_cnt)) {
17923        return (1);
17924    }
17925
17926    if (bxe_flr_clnup_poll_hw_counter(sc,
17927                                      TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17928                                      "Timers NUM_SCANS usage counter timed out",
17929                                      poll_cnt)) {
17930        return (1);
17931    }
17932
17933    /* Wait DMAE PF usage counter to zero */
17934    if (bxe_flr_clnup_poll_hw_counter(sc,
17935                                      dmae_reg_go_c[INIT_DMAE_C(sc)],
17936                                      "DMAE dommand register timed out",
17937                                      poll_cnt)) {
17938        return (1);
17939    }
17940
17941    return (0);
17942}
17943
17944#define OP_GEN_PARAM(param)                                            \
17945    (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17946#define OP_GEN_TYPE(type)                                           \
17947    (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17948#define OP_GEN_AGG_VECT(index)                                             \
17949    (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17950
17951static int
17952bxe_send_final_clnup(struct bxe_softc *sc,
17953                     uint8_t          clnup_func,
17954                     uint32_t         poll_cnt)
17955{
17956    uint32_t op_gen_command = 0;
17957    uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17958                          CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17959    int ret = 0;
17960
17961    if (REG_RD(sc, comp_addr)) {
17962        BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17963        return (1);
17964    }
17965
17966    op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17967    op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17968    op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17969    op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17970
17971    BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17972    REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17973
17974    if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17975        BLOGE(sc, "FW final cleanup did not succeed\n");
17976        BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17977              (REG_RD(sc, comp_addr)));
17978        bxe_panic(sc, ("FLR cleanup failed\n"));
17979        return (1);
17980    }
17981
17982    /* Zero completion for nxt FLR */
17983    REG_WR(sc, comp_addr, 0);
17984
17985    return (ret);
17986}
17987
17988static void
17989bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17990                       struct pbf_pN_buf_regs *regs,
17991                       uint32_t               poll_count)
17992{
17993    uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17994    uint32_t cur_cnt = poll_count;
17995
17996    crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17997    crd = crd_start = REG_RD(sc, regs->crd);
17998    init_crd = REG_RD(sc, regs->init_crd);
17999
18000    BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
18001    BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
18002    BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
18003
18004    while ((crd != init_crd) &&
18005           ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
18006            (init_crd - crd_start))) {
18007        if (cur_cnt--) {
18008            DELAY(FLR_WAIT_INTERVAL);
18009            crd = REG_RD(sc, regs->crd);
18010            crd_freed = REG_RD(sc, regs->crd_freed);
18011        } else {
18012            BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
18013            BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
18014            BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
18015            break;
18016        }
18017    }
18018
18019    BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
18020          poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
18021}
18022
18023static void
18024bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
18025                       struct pbf_pN_cmd_regs *regs,
18026                       uint32_t               poll_count)
18027{
18028    uint32_t occup, to_free, freed, freed_start;
18029    uint32_t cur_cnt = poll_count;
18030
18031    occup = to_free = REG_RD(sc, regs->lines_occup);
18032    freed = freed_start = REG_RD(sc, regs->lines_freed);
18033
18034    BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
18035    BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
18036
18037    while (occup &&
18038           ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
18039        if (cur_cnt--) {
18040            DELAY(FLR_WAIT_INTERVAL);
18041            occup = REG_RD(sc, regs->lines_occup);
18042            freed = REG_RD(sc, regs->lines_freed);
18043        } else {
18044            BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
18045            BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
18046            BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
18047            break;
18048        }
18049    }
18050
18051    BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
18052          poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
18053}
18054
18055static void
18056bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
18057{
18058    struct pbf_pN_cmd_regs cmd_regs[] = {
18059        {0, (CHIP_IS_E3B0(sc)) ?
18060            PBF_REG_TQ_OCCUPANCY_Q0 :
18061            PBF_REG_P0_TQ_OCCUPANCY,
18062            (CHIP_IS_E3B0(sc)) ?
18063            PBF_REG_TQ_LINES_FREED_CNT_Q0 :
18064            PBF_REG_P0_TQ_LINES_FREED_CNT},
18065        {1, (CHIP_IS_E3B0(sc)) ?
18066            PBF_REG_TQ_OCCUPANCY_Q1 :
18067            PBF_REG_P1_TQ_OCCUPANCY,
18068            (CHIP_IS_E3B0(sc)) ?
18069            PBF_REG_TQ_LINES_FREED_CNT_Q1 :
18070            PBF_REG_P1_TQ_LINES_FREED_CNT},
18071        {4, (CHIP_IS_E3B0(sc)) ?
18072            PBF_REG_TQ_OCCUPANCY_LB_Q :
18073            PBF_REG_P4_TQ_OCCUPANCY,
18074            (CHIP_IS_E3B0(sc)) ?
18075            PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
18076            PBF_REG_P4_TQ_LINES_FREED_CNT}
18077    };
18078
18079    struct pbf_pN_buf_regs buf_regs[] = {
18080        {0, (CHIP_IS_E3B0(sc)) ?
18081            PBF_REG_INIT_CRD_Q0 :
18082            PBF_REG_P0_INIT_CRD ,
18083            (CHIP_IS_E3B0(sc)) ?
18084            PBF_REG_CREDIT_Q0 :
18085            PBF_REG_P0_CREDIT,
18086            (CHIP_IS_E3B0(sc)) ?
18087            PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
18088            PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
18089        {1, (CHIP_IS_E3B0(sc)) ?
18090            PBF_REG_INIT_CRD_Q1 :
18091            PBF_REG_P1_INIT_CRD,
18092            (CHIP_IS_E3B0(sc)) ?
18093            PBF_REG_CREDIT_Q1 :
18094            PBF_REG_P1_CREDIT,
18095            (CHIP_IS_E3B0(sc)) ?
18096            PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
18097            PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
18098        {4, (CHIP_IS_E3B0(sc)) ?
18099            PBF_REG_INIT_CRD_LB_Q :
18100            PBF_REG_P4_INIT_CRD,
18101            (CHIP_IS_E3B0(sc)) ?
18102            PBF_REG_CREDIT_LB_Q :
18103            PBF_REG_P4_CREDIT,
18104            (CHIP_IS_E3B0(sc)) ?
18105            PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
18106            PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
18107    };
18108
18109    int i;
18110
18111    /* Verify the command queues are flushed P0, P1, P4 */
18112    for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
18113        bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
18114    }
18115
18116    /* Verify the transmission buffers are flushed P0, P1, P4 */
18117    for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
18118        bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
18119    }
18120}
18121
18122static void
18123bxe_hw_enable_status(struct bxe_softc *sc)
18124{
18125    uint32_t val;
18126
18127    val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
18128    BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
18129
18130    val = REG_RD(sc, PBF_REG_DISABLE_PF);
18131    BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
18132
18133    val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
18134    BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
18135
18136    val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
18137    BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
18138
18139    val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
18140    BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
18141
18142    val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
18143    BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
18144
18145    val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
18146    BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
18147
18148    val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
18149    BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
18150}
18151
18152static int
18153bxe_pf_flr_clnup(struct bxe_softc *sc)
18154{
18155    uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
18156
18157    BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
18158
18159    /* Re-enable PF target read access */
18160    REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
18161
18162    /* Poll HW usage counters */
18163    BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
18164    if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
18165        return (-1);
18166    }
18167
18168    /* Zero the igu 'trailing edge' and 'leading edge' */
18169
18170    /* Send the FW cleanup command */
18171    if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
18172        return (-1);
18173    }
18174
18175    /* ATC cleanup */
18176
18177    /* Verify TX hw is flushed */
18178    bxe_tx_hw_flushed(sc, poll_cnt);
18179
18180    /* Wait 100ms (not adjusted according to platform) */
18181    DELAY(100000);
18182
18183    /* Verify no pending pci transactions */
18184    if (bxe_is_pcie_pending(sc)) {
18185        BLOGE(sc, "PCIE Transactions still pending\n");
18186    }
18187
18188    /* Debug */
18189    bxe_hw_enable_status(sc);
18190
18191    /*
18192     * Master enable - Due to WB DMAE writes performed before this
18193     * register is re-initialized as part of the regular function init
18194     */
18195    REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
18196
18197    return (0);
18198}
18199
18200static int
18201bxe_init_hw_func(struct bxe_softc *sc)
18202{
18203    int port = SC_PORT(sc);
18204    int func = SC_FUNC(sc);
18205    int init_phase = PHASE_PF0 + func;
18206    struct ecore_ilt *ilt = sc->ilt;
18207    uint16_t cdu_ilt_start;
18208    uint32_t addr, val;
18209    uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
18210    int i, main_mem_width, rc;
18211
18212    BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
18213
18214    /* FLR cleanup */
18215    if (!CHIP_IS_E1x(sc)) {
18216        rc = bxe_pf_flr_clnup(sc);
18217        if (rc) {
18218            BLOGE(sc, "FLR cleanup failed!\n");
18219            // XXX bxe_fw_dump(sc);
18220            // XXX bxe_idle_chk(sc);
18221            return (rc);
18222        }
18223    }
18224
18225    /* set MSI reconfigure capability */
18226    if (sc->devinfo.int_block == INT_BLOCK_HC) {
18227        addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
18228        val = REG_RD(sc, addr);
18229        val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
18230        REG_WR(sc, addr, val);
18231    }
18232
18233    ecore_init_block(sc, BLOCK_PXP, init_phase);
18234    ecore_init_block(sc, BLOCK_PXP2, init_phase);
18235
18236    ilt = sc->ilt;
18237    cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
18238
18239    for (i = 0; i < L2_ILT_LINES(sc); i++) {
18240        ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
18241        ilt->lines[cdu_ilt_start + i].page_mapping =
18242            sc->context[i].vcxt_dma.paddr;
18243        ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
18244    }
18245    ecore_ilt_init_op(sc, INITOP_SET);
18246
18247    /* Set NIC mode */
18248    REG_WR(sc, PRS_REG_NIC_MODE, 1);
18249    BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
18250
18251    if (!CHIP_IS_E1x(sc)) {
18252        uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
18253
18254        /* Turn on a single ISR mode in IGU if driver is going to use
18255         * INT#x or MSI
18256         */
18257        if (sc->interrupt_mode != INTR_MODE_MSIX) {
18258            pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
18259        }
18260
18261        /*
18262         * Timers workaround bug: function init part.
18263         * Need to wait 20msec after initializing ILT,
18264         * needed to make sure there are no requests in
18265         * one of the PXP internal queues with "old" ILT addresses
18266         */
18267        DELAY(20000);
18268
18269        /*
18270         * Master enable - Due to WB DMAE writes performed before this
18271         * register is re-initialized as part of the regular function
18272         * init
18273         */
18274        REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
18275        /* Enable the function in IGU */
18276        REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
18277    }
18278
18279    sc->dmae_ready = 1;
18280
18281    ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
18282
18283    if (!CHIP_IS_E1x(sc))
18284        REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
18285
18286    ecore_init_block(sc, BLOCK_ATC, init_phase);
18287    ecore_init_block(sc, BLOCK_DMAE, init_phase);
18288    ecore_init_block(sc, BLOCK_NIG, init_phase);
18289    ecore_init_block(sc, BLOCK_SRC, init_phase);
18290    ecore_init_block(sc, BLOCK_MISC, init_phase);
18291    ecore_init_block(sc, BLOCK_TCM, init_phase);
18292    ecore_init_block(sc, BLOCK_UCM, init_phase);
18293    ecore_init_block(sc, BLOCK_CCM, init_phase);
18294    ecore_init_block(sc, BLOCK_XCM, init_phase);
18295    ecore_init_block(sc, BLOCK_TSEM, init_phase);
18296    ecore_init_block(sc, BLOCK_USEM, init_phase);
18297    ecore_init_block(sc, BLOCK_CSEM, init_phase);
18298    ecore_init_block(sc, BLOCK_XSEM, init_phase);
18299
18300    if (!CHIP_IS_E1x(sc))
18301        REG_WR(sc, QM_REG_PF_EN, 1);
18302
18303    if (!CHIP_IS_E1x(sc)) {
18304        REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18305        REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18306        REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18307        REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18308    }
18309    ecore_init_block(sc, BLOCK_QM, init_phase);
18310
18311    ecore_init_block(sc, BLOCK_TM, init_phase);
18312    ecore_init_block(sc, BLOCK_DORQ, init_phase);
18313
18314    bxe_iov_init_dq(sc);
18315
18316    ecore_init_block(sc, BLOCK_BRB1, init_phase);
18317    ecore_init_block(sc, BLOCK_PRS, init_phase);
18318    ecore_init_block(sc, BLOCK_TSDM, init_phase);
18319    ecore_init_block(sc, BLOCK_CSDM, init_phase);
18320    ecore_init_block(sc, BLOCK_USDM, init_phase);
18321    ecore_init_block(sc, BLOCK_XSDM, init_phase);
18322    ecore_init_block(sc, BLOCK_UPB, init_phase);
18323    ecore_init_block(sc, BLOCK_XPB, init_phase);
18324    ecore_init_block(sc, BLOCK_PBF, init_phase);
18325    if (!CHIP_IS_E1x(sc))
18326        REG_WR(sc, PBF_REG_DISABLE_PF, 0);
18327
18328    ecore_init_block(sc, BLOCK_CDU, init_phase);
18329
18330    ecore_init_block(sc, BLOCK_CFC, init_phase);
18331
18332    if (!CHIP_IS_E1x(sc))
18333        REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
18334
18335    if (IS_MF(sc)) {
18336        REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
18337        REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
18338    }
18339
18340    ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
18341
18342    /* HC init per function */
18343    if (sc->devinfo.int_block == INT_BLOCK_HC) {
18344        if (CHIP_IS_E1H(sc)) {
18345            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18346
18347            REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18348            REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18349        }
18350        ecore_init_block(sc, BLOCK_HC, init_phase);
18351
18352    } else {
18353        int num_segs, sb_idx, prod_offset;
18354
18355        REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18356
18357        if (!CHIP_IS_E1x(sc)) {
18358            REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18359            REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18360        }
18361
18362        ecore_init_block(sc, BLOCK_IGU, init_phase);
18363
18364        if (!CHIP_IS_E1x(sc)) {
18365            int dsb_idx = 0;
18366            /**
18367             * Producer memory:
18368             * E2 mode: address 0-135 match to the mapping memory;
18369             * 136 - PF0 default prod; 137 - PF1 default prod;
18370             * 138 - PF2 default prod; 139 - PF3 default prod;
18371             * 140 - PF0 attn prod;    141 - PF1 attn prod;
18372             * 142 - PF2 attn prod;    143 - PF3 attn prod;
18373             * 144-147 reserved.
18374             *
18375             * E1.5 mode - In backward compatible mode;
18376             * for non default SB; each even line in the memory
18377             * holds the U producer and each odd line hold
18378             * the C producer. The first 128 producers are for
18379             * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18380             * producers are for the DSB for each PF.
18381             * Each PF has five segments: (the order inside each
18382             * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18383             * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18384             * 144-147 attn prods;
18385             */
18386            /* non-default-status-blocks */
18387            num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18388                IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18389            for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18390                prod_offset = (sc->igu_base_sb + sb_idx) *
18391                    num_segs;
18392
18393                for (i = 0; i < num_segs; i++) {
18394                    addr = IGU_REG_PROD_CONS_MEMORY +
18395                            (prod_offset + i) * 4;
18396                    REG_WR(sc, addr, 0);
18397                }
18398                /* send consumer update with value 0 */
18399                bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18400                           USTORM_ID, 0, IGU_INT_NOP, 1);
18401                bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18402            }
18403
18404            /* default-status-blocks */
18405            num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18406                IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18407
18408            if (CHIP_IS_MODE_4_PORT(sc))
18409                dsb_idx = SC_FUNC(sc);
18410            else
18411                dsb_idx = SC_VN(sc);
18412
18413            prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18414                       IGU_BC_BASE_DSB_PROD + dsb_idx :
18415                       IGU_NORM_BASE_DSB_PROD + dsb_idx);
18416
18417            /*
18418             * igu prods come in chunks of E1HVN_MAX (4) -
18419             * does not matters what is the current chip mode
18420             */
18421            for (i = 0; i < (num_segs * E1HVN_MAX);
18422                 i += E1HVN_MAX) {
18423                addr = IGU_REG_PROD_CONS_MEMORY +
18424                            (prod_offset + i)*4;
18425                REG_WR(sc, addr, 0);
18426            }
18427            /* send consumer update with 0 */
18428            if (CHIP_INT_MODE_IS_BC(sc)) {
18429                bxe_ack_sb(sc, sc->igu_dsb_id,
18430                           USTORM_ID, 0, IGU_INT_NOP, 1);
18431                bxe_ack_sb(sc, sc->igu_dsb_id,
18432                           CSTORM_ID, 0, IGU_INT_NOP, 1);
18433                bxe_ack_sb(sc, sc->igu_dsb_id,
18434                           XSTORM_ID, 0, IGU_INT_NOP, 1);
18435                bxe_ack_sb(sc, sc->igu_dsb_id,
18436                           TSTORM_ID, 0, IGU_INT_NOP, 1);
18437                bxe_ack_sb(sc, sc->igu_dsb_id,
18438                           ATTENTION_ID, 0, IGU_INT_NOP, 1);
18439            } else {
18440                bxe_ack_sb(sc, sc->igu_dsb_id,
18441                           USTORM_ID, 0, IGU_INT_NOP, 1);
18442                bxe_ack_sb(sc, sc->igu_dsb_id,
18443                           ATTENTION_ID, 0, IGU_INT_NOP, 1);
18444            }
18445            bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18446
18447            /* !!! these should become driver const once
18448               rf-tool supports split-68 const */
18449            REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18450            REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18451            REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18452            REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18453            REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18454            REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18455        }
18456    }
18457
18458    /* Reset PCIE errors for debug */
18459    REG_WR(sc, 0x2114, 0xffffffff);
18460    REG_WR(sc, 0x2120, 0xffffffff);
18461
18462    if (CHIP_IS_E1x(sc)) {
18463        main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18464        main_mem_base = HC_REG_MAIN_MEMORY +
18465                SC_PORT(sc) * (main_mem_size * 4);
18466        main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18467        main_mem_width = 8;
18468
18469        val = REG_RD(sc, main_mem_prty_clr);
18470        if (val) {
18471            BLOGD(sc, DBG_LOAD,
18472                  "Parity errors in HC block during function init (0x%x)!\n",
18473                  val);
18474        }
18475
18476        /* Clear "false" parity errors in MSI-X table */
18477        for (i = main_mem_base;
18478             i < main_mem_base + main_mem_size * 4;
18479             i += main_mem_width) {
18480            bxe_read_dmae(sc, i, main_mem_width / 4);
18481            bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18482                           i, main_mem_width / 4);
18483        }
18484        /* Clear HC parity attention */
18485        REG_RD(sc, main_mem_prty_clr);
18486    }
18487
18488#if 1
18489    /* Enable STORMs SP logging */
18490    REG_WR8(sc, BAR_USTRORM_INTMEM +
18491           USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18492    REG_WR8(sc, BAR_TSTRORM_INTMEM +
18493           TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18494    REG_WR8(sc, BAR_CSTRORM_INTMEM +
18495           CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18496    REG_WR8(sc, BAR_XSTRORM_INTMEM +
18497           XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18498#endif
18499
18500    elink_phy_probe(&sc->link_params);
18501
18502    return (0);
18503}
18504
18505static void
18506bxe_link_reset(struct bxe_softc *sc)
18507{
18508    if (!BXE_NOMCP(sc)) {
18509	bxe_acquire_phy_lock(sc);
18510        elink_lfa_reset(&sc->link_params, &sc->link_vars);
18511	bxe_release_phy_lock(sc);
18512    } else {
18513        if (!CHIP_REV_IS_SLOW(sc)) {
18514            BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18515        }
18516    }
18517}
18518
18519static void
18520bxe_reset_port(struct bxe_softc *sc)
18521{
18522    int port = SC_PORT(sc);
18523    uint32_t val;
18524
18525	ELINK_DEBUG_P0(sc, "bxe_reset_port called\n");
18526    /* reset physical Link */
18527    bxe_link_reset(sc);
18528
18529    REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18530
18531    /* Do not rcv packets to BRB */
18532    REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18533    /* Do not direct rcv packets that are not for MCP to the BRB */
18534    REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18535               NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18536
18537    /* Configure AEU */
18538    REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18539
18540    DELAY(100000);
18541
18542    /* Check for BRB port occupancy */
18543    val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18544    if (val) {
18545        BLOGD(sc, DBG_LOAD,
18546              "BRB1 is not empty, %d blocks are occupied\n", val);
18547    }
18548
18549    /* TODO: Close Doorbell port? */
18550}
18551
18552static void
18553bxe_ilt_wr(struct bxe_softc *sc,
18554           uint32_t         index,
18555           bus_addr_t       addr)
18556{
18557    int reg;
18558    uint32_t wb_write[2];
18559
18560    if (CHIP_IS_E1(sc)) {
18561        reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18562    } else {
18563        reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18564    }
18565
18566    wb_write[0] = ONCHIP_ADDR1(addr);
18567    wb_write[1] = ONCHIP_ADDR2(addr);
18568    REG_WR_DMAE(sc, reg, wb_write, 2);
18569}
18570
18571static void
18572bxe_clear_func_ilt(struct bxe_softc *sc,
18573                   uint32_t         func)
18574{
18575    uint32_t i, base = FUNC_ILT_BASE(func);
18576    for (i = base; i < base + ILT_PER_FUNC; i++) {
18577        bxe_ilt_wr(sc, i, 0);
18578    }
18579}
18580
18581static void
18582bxe_reset_func(struct bxe_softc *sc)
18583{
18584    struct bxe_fastpath *fp;
18585    int port = SC_PORT(sc);
18586    int func = SC_FUNC(sc);
18587    int i;
18588
18589    /* Disable the function in the FW */
18590    REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18591    REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18592    REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18593    REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18594
18595    /* FP SBs */
18596    FOR_EACH_ETH_QUEUE(sc, i) {
18597        fp = &sc->fp[i];
18598        REG_WR8(sc, BAR_CSTRORM_INTMEM +
18599                CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18600                SB_DISABLED);
18601    }
18602
18603    /* SP SB */
18604    REG_WR8(sc, BAR_CSTRORM_INTMEM +
18605            CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18606            SB_DISABLED);
18607
18608    for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18609        REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18610    }
18611
18612    /* Configure IGU */
18613    if (sc->devinfo.int_block == INT_BLOCK_HC) {
18614        REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18615        REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18616    } else {
18617        REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18618        REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18619    }
18620
18621    if (CNIC_LOADED(sc)) {
18622        /* Disable Timer scan */
18623        REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18624        /*
18625         * Wait for at least 10ms and up to 2 second for the timers
18626         * scan to complete
18627         */
18628        for (i = 0; i < 200; i++) {
18629            DELAY(10000);
18630            if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18631                break;
18632        }
18633    }
18634
18635    /* Clear ILT */
18636    bxe_clear_func_ilt(sc, func);
18637
18638    /*
18639     * Timers workaround bug for E2: if this is vnic-3,
18640     * we need to set the entire ilt range for this timers.
18641     */
18642    if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18643        struct ilt_client_info ilt_cli;
18644        /* use dummy TM client */
18645        memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18646        ilt_cli.start = 0;
18647        ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18648        ilt_cli.client_num = ILT_CLIENT_TM;
18649
18650        ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18651    }
18652
18653    /* this assumes that reset_port() called before reset_func()*/
18654    if (!CHIP_IS_E1x(sc)) {
18655        bxe_pf_disable(sc);
18656    }
18657
18658    sc->dmae_ready = 0;
18659}
18660
18661static int
18662bxe_gunzip_init(struct bxe_softc *sc)
18663{
18664    return (0);
18665}
18666
18667static void
18668bxe_gunzip_end(struct bxe_softc *sc)
18669{
18670    return;
18671}
18672
18673static int
18674bxe_init_firmware(struct bxe_softc *sc)
18675{
18676    if (CHIP_IS_E1(sc)) {
18677        ecore_init_e1_firmware(sc);
18678        sc->iro_array = e1_iro_arr;
18679    } else if (CHIP_IS_E1H(sc)) {
18680        ecore_init_e1h_firmware(sc);
18681        sc->iro_array = e1h_iro_arr;
18682    } else if (!CHIP_IS_E1x(sc)) {
18683        ecore_init_e2_firmware(sc);
18684        sc->iro_array = e2_iro_arr;
18685    } else {
18686        BLOGE(sc, "Unsupported chip revision\n");
18687        return (-1);
18688    }
18689
18690    return (0);
18691}
18692
18693static void
18694bxe_release_firmware(struct bxe_softc *sc)
18695{
18696    /* Do nothing */
18697    return;
18698}
18699
18700static int
18701ecore_gunzip(struct bxe_softc *sc,
18702             const uint8_t    *zbuf,
18703             int              len)
18704{
18705    /* XXX : Implement... */
18706    BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18707    return (FALSE);
18708}
18709
18710static void
18711ecore_reg_wr_ind(struct bxe_softc *sc,
18712                 uint32_t         addr,
18713                 uint32_t         val)
18714{
18715    bxe_reg_wr_ind(sc, addr, val);
18716}
18717
18718static void
18719ecore_write_dmae_phys_len(struct bxe_softc *sc,
18720                          bus_addr_t       phys_addr,
18721                          uint32_t         addr,
18722                          uint32_t         len)
18723{
18724    bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18725}
18726
18727void
18728ecore_storm_memset_struct(struct bxe_softc *sc,
18729                          uint32_t         addr,
18730                          size_t           size,
18731                          uint32_t         *data)
18732{
18733    uint8_t i;
18734    for (i = 0; i < size/4; i++) {
18735        REG_WR(sc, addr + (i * 4), data[i]);
18736    }
18737}
18738
18739
18740/*
18741 * character device - ioctl interface definitions
18742 */
18743
18744
18745#include "bxe_dump.h"
18746#include "bxe_ioctl.h"
18747#include <sys/conf.h>
18748
18749static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18750                struct thread *td);
18751
18752static struct cdevsw bxe_cdevsw = {
18753    .d_version = D_VERSION,
18754    .d_ioctl = bxe_eioctl,
18755    .d_name = "bxecnic",
18756};
18757
18758#define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18759
18760
18761#define DUMP_ALL_PRESETS        0x1FFF
18762#define DUMP_MAX_PRESETS        13
18763#define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18764#define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18765#define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18766#define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18767#define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18768
18769#define IS_REG_IN_PRESET(presets, idx)  \
18770                ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18771
18772
18773static int
18774bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18775{
18776    if (CHIP_IS_E1(sc))
18777        return dump_num_registers[0][preset-1];
18778    else if (CHIP_IS_E1H(sc))
18779        return dump_num_registers[1][preset-1];
18780    else if (CHIP_IS_E2(sc))
18781        return dump_num_registers[2][preset-1];
18782    else if (CHIP_IS_E3A0(sc))
18783        return dump_num_registers[3][preset-1];
18784    else if (CHIP_IS_E3B0(sc))
18785        return dump_num_registers[4][preset-1];
18786    else
18787        return 0;
18788}
18789
18790static int
18791bxe_get_total_regs_len32(struct bxe_softc *sc)
18792{
18793    uint32_t preset_idx;
18794    int regdump_len32 = 0;
18795
18796
18797    /* Calculate the total preset regs length */
18798    for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18799        regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18800    }
18801
18802    return regdump_len32;
18803}
18804
18805static const uint32_t *
18806__bxe_get_page_addr_ar(struct bxe_softc *sc)
18807{
18808    if (CHIP_IS_E2(sc))
18809        return page_vals_e2;
18810    else if (CHIP_IS_E3(sc))
18811        return page_vals_e3;
18812    else
18813        return NULL;
18814}
18815
18816static uint32_t
18817__bxe_get_page_reg_num(struct bxe_softc *sc)
18818{
18819    if (CHIP_IS_E2(sc))
18820        return PAGE_MODE_VALUES_E2;
18821    else if (CHIP_IS_E3(sc))
18822        return PAGE_MODE_VALUES_E3;
18823    else
18824        return 0;
18825}
18826
18827static const uint32_t *
18828__bxe_get_page_write_ar(struct bxe_softc *sc)
18829{
18830    if (CHIP_IS_E2(sc))
18831        return page_write_regs_e2;
18832    else if (CHIP_IS_E3(sc))
18833        return page_write_regs_e3;
18834    else
18835        return NULL;
18836}
18837
18838static uint32_t
18839__bxe_get_page_write_num(struct bxe_softc *sc)
18840{
18841    if (CHIP_IS_E2(sc))
18842        return PAGE_WRITE_REGS_E2;
18843    else if (CHIP_IS_E3(sc))
18844        return PAGE_WRITE_REGS_E3;
18845    else
18846        return 0;
18847}
18848
18849static const struct reg_addr *
18850__bxe_get_page_read_ar(struct bxe_softc *sc)
18851{
18852    if (CHIP_IS_E2(sc))
18853        return page_read_regs_e2;
18854    else if (CHIP_IS_E3(sc))
18855        return page_read_regs_e3;
18856    else
18857        return NULL;
18858}
18859
18860static uint32_t
18861__bxe_get_page_read_num(struct bxe_softc *sc)
18862{
18863    if (CHIP_IS_E2(sc))
18864        return PAGE_READ_REGS_E2;
18865    else if (CHIP_IS_E3(sc))
18866        return PAGE_READ_REGS_E3;
18867    else
18868        return 0;
18869}
18870
18871static bool
18872bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18873{
18874    if (CHIP_IS_E1(sc))
18875        return IS_E1_REG(reg_info->chips);
18876    else if (CHIP_IS_E1H(sc))
18877        return IS_E1H_REG(reg_info->chips);
18878    else if (CHIP_IS_E2(sc))
18879        return IS_E2_REG(reg_info->chips);
18880    else if (CHIP_IS_E3A0(sc))
18881        return IS_E3A0_REG(reg_info->chips);
18882    else if (CHIP_IS_E3B0(sc))
18883        return IS_E3B0_REG(reg_info->chips);
18884    else
18885        return 0;
18886}
18887
18888static bool
18889bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18890{
18891    if (CHIP_IS_E1(sc))
18892        return IS_E1_REG(wreg_info->chips);
18893    else if (CHIP_IS_E1H(sc))
18894        return IS_E1H_REG(wreg_info->chips);
18895    else if (CHIP_IS_E2(sc))
18896        return IS_E2_REG(wreg_info->chips);
18897    else if (CHIP_IS_E3A0(sc))
18898        return IS_E3A0_REG(wreg_info->chips);
18899    else if (CHIP_IS_E3B0(sc))
18900        return IS_E3B0_REG(wreg_info->chips);
18901    else
18902        return 0;
18903}
18904
18905/**
18906 * bxe_read_pages_regs - read "paged" registers
18907 *
18908 * @bp          device handle
18909 * @p           output buffer
18910 *
18911 * Reads "paged" memories: memories that may only be read by first writing to a
18912 * specific address ("write address") and then reading from a specific address
18913 * ("read address"). There may be more than one write address per "page" and
18914 * more than one read address per write address.
18915 */
18916static void
18917bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18918{
18919    uint32_t i, j, k, n;
18920
18921    /* addresses of the paged registers */
18922    const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18923    /* number of paged registers */
18924    int num_pages = __bxe_get_page_reg_num(sc);
18925    /* write addresses */
18926    const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18927    /* number of write addresses */
18928    int write_num = __bxe_get_page_write_num(sc);
18929    /* read addresses info */
18930    const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18931    /* number of read addresses */
18932    int read_num = __bxe_get_page_read_num(sc);
18933    uint32_t addr, size;
18934
18935    for (i = 0; i < num_pages; i++) {
18936        for (j = 0; j < write_num; j++) {
18937            REG_WR(sc, write_addr[j], page_addr[i]);
18938
18939            for (k = 0; k < read_num; k++) {
18940                if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18941                    size = read_addr[k].size;
18942                    for (n = 0; n < size; n++) {
18943                        addr = read_addr[k].addr + n*4;
18944                        *p++ = REG_RD(sc, addr);
18945                    }
18946                }
18947            }
18948        }
18949    }
18950    return;
18951}
18952
18953
18954static int
18955bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18956{
18957    uint32_t i, j, addr;
18958    const struct wreg_addr *wreg_addr_p = NULL;
18959
18960    if (CHIP_IS_E1(sc))
18961        wreg_addr_p = &wreg_addr_e1;
18962    else if (CHIP_IS_E1H(sc))
18963        wreg_addr_p = &wreg_addr_e1h;
18964    else if (CHIP_IS_E2(sc))
18965        wreg_addr_p = &wreg_addr_e2;
18966    else if (CHIP_IS_E3A0(sc))
18967        wreg_addr_p = &wreg_addr_e3;
18968    else if (CHIP_IS_E3B0(sc))
18969        wreg_addr_p = &wreg_addr_e3b0;
18970    else
18971        return (-1);
18972
18973    /* Read the idle_chk registers */
18974    for (i = 0; i < IDLE_REGS_COUNT; i++) {
18975        if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18976            IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18977            for (j = 0; j < idle_reg_addrs[i].size; j++)
18978                *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18979        }
18980    }
18981
18982    /* Read the regular registers */
18983    for (i = 0; i < REGS_COUNT; i++) {
18984        if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18985            IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18986            for (j = 0; j < reg_addrs[i].size; j++)
18987                *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18988        }
18989    }
18990
18991    /* Read the CAM registers */
18992    if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18993        IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18994        for (i = 0; i < wreg_addr_p->size; i++) {
18995            *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18996
18997            /* In case of wreg_addr register, read additional
18998               registers from read_regs array
18999             */
19000            for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
19001                addr = *(wreg_addr_p->read_regs);
19002                *p++ = REG_RD(sc, addr + j*4);
19003            }
19004        }
19005    }
19006
19007    /* Paged registers are supported in E2 & E3 only */
19008    if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
19009        /* Read "paged" registers */
19010        bxe_read_pages_regs(sc, p, preset);
19011    }
19012
19013    return 0;
19014}
19015
19016int
19017bxe_grc_dump(struct bxe_softc *sc)
19018{
19019    int rval = 0;
19020    uint32_t preset_idx;
19021    uint8_t *buf;
19022    uint32_t size;
19023    struct  dump_header *d_hdr;
19024    uint32_t i;
19025    uint32_t reg_val;
19026    uint32_t reg_addr;
19027    uint32_t cmd_offset;
19028    struct ecore_ilt *ilt = SC_ILT(sc);
19029    struct bxe_fastpath *fp;
19030    struct ilt_client_info *ilt_cli;
19031    int grc_dump_size;
19032
19033
19034    if (sc->grcdump_done || sc->grcdump_started)
19035	return (rval);
19036
19037    sc->grcdump_started = 1;
19038    BLOGI(sc, "Started collecting grcdump\n");
19039
19040    grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19041                sizeof(struct  dump_header);
19042
19043    sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
19044
19045    if (sc->grc_dump == NULL) {
19046        BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
19047        return(ENOMEM);
19048    }
19049
19050
19051
19052    /* Disable parity attentions as long as following dump may
19053     * cause false alarms by reading never written registers. We
19054     * will re-enable parity attentions right after the dump.
19055     */
19056
19057    /* Disable parity on path 0 */
19058    bxe_pretend_func(sc, 0);
19059
19060    ecore_disable_blocks_parity(sc);
19061
19062    /* Disable parity on path 1 */
19063    bxe_pretend_func(sc, 1);
19064    ecore_disable_blocks_parity(sc);
19065
19066    /* Return to current function */
19067    bxe_pretend_func(sc, SC_ABS_FUNC(sc));
19068
19069    buf = sc->grc_dump;
19070    d_hdr = sc->grc_dump;
19071
19072    d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
19073    d_hdr->version = BNX2X_DUMP_VERSION;
19074    d_hdr->preset = DUMP_ALL_PRESETS;
19075
19076    if (CHIP_IS_E1(sc)) {
19077        d_hdr->dump_meta_data = DUMP_CHIP_E1;
19078    } else if (CHIP_IS_E1H(sc)) {
19079        d_hdr->dump_meta_data = DUMP_CHIP_E1H;
19080    } else if (CHIP_IS_E2(sc)) {
19081        d_hdr->dump_meta_data = DUMP_CHIP_E2 |
19082                (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
19083    } else if (CHIP_IS_E3A0(sc)) {
19084        d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
19085                (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
19086    } else if (CHIP_IS_E3B0(sc)) {
19087        d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
19088                (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
19089    }
19090
19091    buf += sizeof(struct  dump_header);
19092
19093    for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
19094
19095        /* Skip presets with IOR */
19096        if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
19097            (preset_idx == 11))
19098            continue;
19099
19100        rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
19101
19102	if (rval)
19103            break;
19104
19105        size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
19106
19107        buf += size;
19108    }
19109
19110    bxe_pretend_func(sc, 0);
19111    ecore_clear_blocks_parity(sc);
19112    ecore_enable_blocks_parity(sc);
19113
19114    bxe_pretend_func(sc, 1);
19115    ecore_clear_blocks_parity(sc);
19116    ecore_enable_blocks_parity(sc);
19117
19118    /* Return to current function */
19119    bxe_pretend_func(sc, SC_ABS_FUNC(sc));
19120
19121
19122
19123    if(sc->state == BXE_STATE_OPEN) {
19124        if(sc->fw_stats_req  != NULL) {
19125    		BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
19126        			(uintmax_t)sc->fw_stats_req_mapping,
19127        			(uintmax_t)sc->fw_stats_data_mapping,
19128        			sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
19129		}
19130		if(sc->def_sb != NULL) {
19131			BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
19132        			(void *)sc->def_sb_dma.paddr, sc->def_sb,
19133        			sizeof(struct host_sp_status_block));
19134		}
19135		if(sc->eq_dma.vaddr != NULL) {
19136    		BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
19137        			(uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
19138		}
19139		if(sc->sp_dma.vaddr != NULL) {
19140    		BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
19141        			(uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
19142        			sizeof(struct bxe_slowpath));
19143		}
19144		if(sc->spq_dma.vaddr != NULL) {
19145    		BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
19146        			(uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
19147		}
19148		if(sc->gz_buf_dma.vaddr != NULL) {
19149    		BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
19150        			(uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
19151        			FW_BUF_SIZE);
19152		}
19153    	for (i = 0; i < sc->num_queues; i++) {
19154        	fp = &sc->fp[i];
19155			if(fp->sb_dma.vaddr != NULL && fp->tx_dma.vaddr != NULL &&
19156                        fp->rx_dma.vaddr != NULL && fp->rcq_dma.vaddr != NULL &&
19157                        fp->rx_sge_dma.vaddr != NULL) {
19158
19159				BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
19160            			(uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
19161            			sizeof(union bxe_host_hc_status_block));
19162				BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
19163            			(uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
19164            			(BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
19165        		BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
19166            			(uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
19167            			(BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
19168        		BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
19169            			(uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
19170            			(BCM_PAGE_SIZE * RCQ_NUM_PAGES));
19171        		BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
19172            			(uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
19173            			(BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
19174    		}
19175		}
19176		if(ilt != NULL ) {
19177    		ilt_cli = &ilt->clients[1];
19178			if(ilt->lines != NULL) {
19179    		for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
19180        		BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
19181            			(uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
19182            			((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
19183    		}
19184			}
19185		}
19186
19187
19188    	cmd_offset = DMAE_REG_CMD_MEM;
19189    	for (i = 0; i < 224; i++) {
19190        	reg_addr = (cmd_offset +(i * 4));
19191        	reg_val = REG_RD(sc, reg_addr);
19192        	BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
19193            			reg_addr, reg_val);
19194    	}
19195	}
19196
19197    BLOGI(sc, "Collection of grcdump done\n");
19198    sc->grcdump_done = 1;
19199    return(rval);
19200}
19201
19202static int
19203bxe_add_cdev(struct bxe_softc *sc)
19204{
19205    sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
19206
19207    if (sc->eeprom == NULL) {
19208        BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
19209        return (-1);
19210    }
19211
19212    sc->ioctl_dev = make_dev(&bxe_cdevsw,
19213                            sc->ifp->if_dunit,
19214                            UID_ROOT,
19215                            GID_WHEEL,
19216                            0600,
19217                            "%s",
19218                            if_name(sc->ifp));
19219
19220    if (sc->ioctl_dev == NULL) {
19221        free(sc->eeprom, M_DEVBUF);
19222        sc->eeprom = NULL;
19223        return (-1);
19224    }
19225
19226    sc->ioctl_dev->si_drv1 = sc;
19227
19228    return (0);
19229}
19230
19231static void
19232bxe_del_cdev(struct bxe_softc *sc)
19233{
19234    if (sc->ioctl_dev != NULL)
19235        destroy_dev(sc->ioctl_dev);
19236
19237    if (sc->eeprom != NULL) {
19238        free(sc->eeprom, M_DEVBUF);
19239        sc->eeprom = NULL;
19240    }
19241    sc->ioctl_dev = NULL;
19242
19243    return;
19244}
19245
19246static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
19247{
19248
19249    if ((if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) == 0)
19250        return FALSE;
19251
19252    return TRUE;
19253}
19254
19255
19256static int
19257bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
19258{
19259    int rval = 0;
19260
19261    if(!bxe_is_nvram_accessible(sc)) {
19262        BLOGW(sc, "Cannot access eeprom when interface is down\n");
19263        return (-EAGAIN);
19264    }
19265    rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
19266
19267
19268   return (rval);
19269}
19270
19271static int
19272bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
19273{
19274    int rval = 0;
19275
19276    if(!bxe_is_nvram_accessible(sc)) {
19277        BLOGW(sc, "Cannot access eeprom when interface is down\n");
19278        return (-EAGAIN);
19279    }
19280    rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
19281
19282   return (rval);
19283}
19284
19285static int
19286bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
19287{
19288    int rval = 0;
19289
19290    switch (eeprom->eeprom_cmd) {
19291
19292    case BXE_EEPROM_CMD_SET_EEPROM:
19293
19294        rval = copyin(eeprom->eeprom_data, sc->eeprom,
19295                       eeprom->eeprom_data_len);
19296
19297        if (rval)
19298            break;
19299
19300        rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
19301                       eeprom->eeprom_data_len);
19302        break;
19303
19304    case BXE_EEPROM_CMD_GET_EEPROM:
19305
19306        rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
19307                       eeprom->eeprom_data_len);
19308
19309        if (rval) {
19310            break;
19311        }
19312
19313        rval = copyout(sc->eeprom, eeprom->eeprom_data,
19314                       eeprom->eeprom_data_len);
19315        break;
19316
19317    default:
19318            rval = EINVAL;
19319            break;
19320    }
19321
19322    if (rval) {
19323        BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
19324    }
19325
19326    return (rval);
19327}
19328
19329static int
19330bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
19331{
19332    uint32_t ext_phy_config;
19333    int port = SC_PORT(sc);
19334    int cfg_idx = bxe_get_link_cfg_idx(sc);
19335
19336    dev_p->supported = sc->port.supported[cfg_idx] |
19337            (sc->port.supported[cfg_idx ^ 1] &
19338            (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
19339    dev_p->advertising = sc->port.advertising[cfg_idx];
19340    if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
19341        ELINK_ETH_PHY_SFP_1G_FIBER) {
19342        dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
19343        dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
19344    }
19345    if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
19346        !(sc->flags & BXE_MF_FUNC_DIS)) {
19347        dev_p->duplex = sc->link_vars.duplex;
19348        if (IS_MF(sc) && !BXE_NOMCP(sc))
19349            dev_p->speed = bxe_get_mf_speed(sc);
19350        else
19351            dev_p->speed = sc->link_vars.line_speed;
19352    } else {
19353        dev_p->duplex = DUPLEX_UNKNOWN;
19354        dev_p->speed = SPEED_UNKNOWN;
19355    }
19356
19357    dev_p->port = bxe_media_detect(sc);
19358
19359    ext_phy_config = SHMEM_RD(sc,
19360                         dev_info.port_hw_config[port].external_phy_config);
19361    if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
19362        PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
19363        dev_p->phy_address =  sc->port.phy_addr;
19364    else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19365            PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
19366        ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19367            PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
19368        dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
19369    else
19370        dev_p->phy_address = 0;
19371
19372    if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
19373        dev_p->autoneg = AUTONEG_ENABLE;
19374    else
19375       dev_p->autoneg = AUTONEG_DISABLE;
19376
19377
19378    return 0;
19379}
19380
19381static int
19382bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
19383        struct thread *td)
19384{
19385    struct bxe_softc    *sc;
19386    int                 rval = 0;
19387    device_t            pci_dev;
19388    bxe_grcdump_t       *dump = NULL;
19389    int grc_dump_size;
19390    bxe_drvinfo_t   *drv_infop = NULL;
19391    bxe_dev_setting_t  *dev_p;
19392    bxe_dev_setting_t  dev_set;
19393    bxe_get_regs_t  *reg_p;
19394    bxe_reg_rdw_t *reg_rdw_p;
19395    bxe_pcicfg_rdw_t *cfg_rdw_p;
19396    bxe_perm_mac_addr_t *mac_addr_p;
19397
19398
19399    if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
19400        return ENXIO;
19401
19402    pci_dev= sc->dev;
19403
19404    dump = (bxe_grcdump_t *)data;
19405
19406    switch(cmd) {
19407
19408        case BXE_GRC_DUMP_SIZE:
19409            dump->pci_func = sc->pcie_func;
19410            dump->grcdump_size =
19411                (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19412                     sizeof(struct  dump_header);
19413            break;
19414
19415        case BXE_GRC_DUMP:
19416
19417            grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19418                                sizeof(struct  dump_header);
19419            if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
19420                (dump->grcdump_size < grc_dump_size)) {
19421                rval = EINVAL;
19422                break;
19423            }
19424
19425            if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
19426                (!sc->grcdump_started)) {
19427                rval =  bxe_grc_dump(sc);
19428            }
19429
19430            if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
19431                (sc->grc_dump != NULL))  {
19432                dump->grcdump_dwords = grc_dump_size >> 2;
19433                rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
19434                free(sc->grc_dump, M_DEVBUF);
19435                sc->grc_dump = NULL;
19436                sc->grcdump_started = 0;
19437                sc->grcdump_done = 0;
19438            }
19439
19440            break;
19441
19442        case BXE_DRV_INFO:
19443            drv_infop = (bxe_drvinfo_t *)data;
19444            snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
19445            snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
19446                BXE_DRIVER_VERSION);
19447            snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
19448                sc->devinfo.bc_ver_str);
19449            snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
19450                "%s", sc->fw_ver_str);
19451            drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
19452            drv_infop->reg_dump_len =
19453                (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
19454                    + sizeof(struct  dump_header);
19455            snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
19456                sc->pcie_bus, sc->pcie_device, sc->pcie_func);
19457            break;
19458
19459        case BXE_DEV_SETTING:
19460            dev_p = (bxe_dev_setting_t *)data;
19461            bxe_get_settings(sc, &dev_set);
19462            dev_p->supported = dev_set.supported;
19463            dev_p->advertising = dev_set.advertising;
19464            dev_p->speed = dev_set.speed;
19465            dev_p->duplex = dev_set.duplex;
19466            dev_p->port = dev_set.port;
19467            dev_p->phy_address = dev_set.phy_address;
19468            dev_p->autoneg = dev_set.autoneg;
19469
19470            break;
19471
19472        case BXE_GET_REGS:
19473
19474            reg_p = (bxe_get_regs_t *)data;
19475            grc_dump_size = reg_p->reg_buf_len;
19476
19477            if((!sc->grcdump_done) && (!sc->grcdump_started)) {
19478                bxe_grc_dump(sc);
19479            }
19480            if((sc->grcdump_done) && (sc->grcdump_started) &&
19481                (sc->grc_dump != NULL))  {
19482                rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
19483                free(sc->grc_dump, M_DEVBUF);
19484                sc->grc_dump = NULL;
19485                sc->grcdump_started = 0;
19486                sc->grcdump_done = 0;
19487            }
19488
19489            break;
19490
19491        case BXE_RDW_REG:
19492            reg_rdw_p = (bxe_reg_rdw_t *)data;
19493            if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
19494                (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19495                reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
19496
19497            if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
19498                (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19499                REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
19500
19501            break;
19502
19503        case BXE_RDW_PCICFG:
19504            cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
19505            if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
19506
19507                cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
19508                                         cfg_rdw_p->cfg_width);
19509
19510            } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
19511                pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
19512                            cfg_rdw_p->cfg_width);
19513            } else {
19514                BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
19515            }
19516            break;
19517
19518        case BXE_MAC_ADDR:
19519            mac_addr_p = (bxe_perm_mac_addr_t *)data;
19520            snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
19521                sc->mac_addr_str);
19522            break;
19523
19524        case BXE_EEPROM:
19525            rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
19526            break;
19527
19528
19529        default:
19530            break;
19531    }
19532
19533    return (rval);
19534}
19535
19536#ifdef NETDUMP
19537static void
19538bxe_netdump_init(struct ifnet *ifp, int *nrxr, int *ncl, int *clsize)
19539{
19540	struct bxe_softc *sc;
19541
19542	sc = if_getsoftc(ifp);
19543	BXE_CORE_LOCK(sc);
19544	*nrxr = sc->num_queues;
19545	*ncl = NETDUMP_MAX_IN_FLIGHT;
19546	*clsize = sc->fp[0].mbuf_alloc_size;
19547	BXE_CORE_UNLOCK(sc);
19548}
19549
19550static void
19551bxe_netdump_event(struct ifnet *ifp __unused, enum netdump_ev event __unused)
19552{
19553}
19554
19555static int
19556bxe_netdump_transmit(struct ifnet *ifp, struct mbuf *m)
19557{
19558	struct bxe_softc *sc;
19559	int error;
19560
19561	sc = if_getsoftc(ifp);
19562	if ((if_getdrvflags(ifp) & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
19563	    IFF_DRV_RUNNING || !sc->link_vars.link_up)
19564		return (ENOENT);
19565
19566	error = bxe_tx_encap(&sc->fp[0], &m);
19567	if (error != 0 && m != NULL)
19568		m_freem(m);
19569	return (error);
19570}
19571
19572static int
19573bxe_netdump_poll(struct ifnet *ifp, int count)
19574{
19575	struct bxe_softc *sc;
19576	int i;
19577
19578	sc = if_getsoftc(ifp);
19579	if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0 ||
19580	    !sc->link_vars.link_up)
19581		return (ENOENT);
19582
19583	for (i = 0; i < sc->num_queues; i++)
19584		(void)bxe_rxeof(sc, &sc->fp[i]);
19585	(void)bxe_txeof(sc, &sc->fp[0]);
19586	return (0);
19587}
19588#endif /* NETDUMP */
19589