bxe.c revision 255736
1/*-
2 * Copyright (c) 2007-2013 Broadcom Corporation. All rights reserved.
3 *
4 * Eric Davis        <edavis@broadcom.com>
5 * David Christensen <davidch@broadcom.com>
6 * Gary Zambrano     <zambrano@broadcom.com>
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of Broadcom Corporation nor the name of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written consent.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS'
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34#include <sys/cdefs.h>
35__FBSDID("$FreeBSD: head/sys/dev/bxe/bxe.c 255736 2013-09-20 20:18:49Z davidch $");
36
37#define BXE_DRIVER_VERSION "1.78.17"
38
39#include "bxe.h"
40#include "ecore_sp.h"
41#include "ecore_init.h"
42#include "ecore_init_ops.h"
43
44#include "57710_int_offsets.h"
45#include "57711_int_offsets.h"
46#include "57712_int_offsets.h"
47
48/*
49 * CTLTYPE_U64 and sysctl_handle_64 were added in r217616. Define these
50 * explicitly here for older kernels that don't include this changeset.
51 */
52#ifndef CTLTYPE_U64
53#define CTLTYPE_U64      CTLTYPE_QUAD
54#define sysctl_handle_64 sysctl_handle_quad
55#endif
56
57/*
58 * CSUM_TCP_IPV6 and CSUM_UDP_IPV6 were added in r236170. Define these
59 * here as zero(0) for older kernels that don't include this changeset
60 * thereby masking the functionality.
61 */
62#ifndef CSUM_TCP_IPV6
63#define CSUM_TCP_IPV6 0
64#define CSUM_UDP_IPV6 0
65#endif
66
67/*
68 * pci_find_cap was added in r219865. Re-define this at pci_find_extcap
69 * for older kernels that don't include this changeset.
70 */
71#if __FreeBSD_version < 900035
72#define pci_find_cap pci_find_extcap
73#endif
74
75#define BXE_DEF_SB_ATT_IDX 0x0001
76#define BXE_DEF_SB_IDX     0x0002
77
78/*
79 * FLR Support - bxe_pf_flr_clnup() is called during nic_load in the per
80 * function HW initialization.
81 */
82#define FLR_WAIT_USEC     10000 /* 10 msecs */
83#define FLR_WAIT_INTERVAL 50    /* usecs */
84#define FLR_POLL_CNT      (FLR_WAIT_USEC / FLR_WAIT_INTERVAL) /* 200 */
85
86struct pbf_pN_buf_regs {
87    int pN;
88    uint32_t init_crd;
89    uint32_t crd;
90    uint32_t crd_freed;
91};
92
93struct pbf_pN_cmd_regs {
94    int pN;
95    uint32_t lines_occup;
96    uint32_t lines_freed;
97};
98
99/*
100 * PCI Device ID Table used by bxe_probe().
101 */
102#define BXE_DEVDESC_MAX 64
103static struct bxe_device_type bxe_devs[] = {
104    {
105        BRCM_VENDORID,
106        CHIP_NUM_57710,
107        PCI_ANY_ID, PCI_ANY_ID,
108        "Broadcom NetXtreme II BCM57710 10GbE"
109    },
110    {
111        BRCM_VENDORID,
112        CHIP_NUM_57711,
113        PCI_ANY_ID, PCI_ANY_ID,
114        "Broadcom NetXtreme II BCM57711 10GbE"
115    },
116    {
117        BRCM_VENDORID,
118        CHIP_NUM_57711E,
119        PCI_ANY_ID, PCI_ANY_ID,
120        "Broadcom NetXtreme II BCM57711E 10GbE"
121    },
122    {
123        BRCM_VENDORID,
124        CHIP_NUM_57712,
125        PCI_ANY_ID, PCI_ANY_ID,
126        "Broadcom NetXtreme II BCM57712 10GbE"
127    },
128    {
129        BRCM_VENDORID,
130        CHIP_NUM_57712_MF,
131        PCI_ANY_ID, PCI_ANY_ID,
132        "Broadcom NetXtreme II BCM57712 MF 10GbE"
133    },
134#if 0
135    {
136        BRCM_VENDORID,
137        CHIP_NUM_57712_VF,
138        PCI_ANY_ID, PCI_ANY_ID,
139        "Broadcom NetXtreme II BCM57712 VF 10GbE"
140    },
141#endif
142    {
143        BRCM_VENDORID,
144        CHIP_NUM_57800,
145        PCI_ANY_ID, PCI_ANY_ID,
146        "Broadcom NetXtreme II BCM57800 10GbE"
147    },
148    {
149        BRCM_VENDORID,
150        CHIP_NUM_57800_MF,
151        PCI_ANY_ID, PCI_ANY_ID,
152        "Broadcom NetXtreme II BCM57800 MF 10GbE"
153    },
154#if 0
155    {
156        BRCM_VENDORID,
157        CHIP_NUM_57800_VF,
158        PCI_ANY_ID, PCI_ANY_ID,
159        "Broadcom NetXtreme II BCM57800 VF 10GbE"
160    },
161#endif
162    {
163        BRCM_VENDORID,
164        CHIP_NUM_57810,
165        PCI_ANY_ID, PCI_ANY_ID,
166        "Broadcom NetXtreme II BCM57810 10GbE"
167    },
168    {
169        BRCM_VENDORID,
170        CHIP_NUM_57810_MF,
171        PCI_ANY_ID, PCI_ANY_ID,
172        "Broadcom NetXtreme II BCM57810 MF 10GbE"
173    },
174#if 0
175    {
176        BRCM_VENDORID,
177        CHIP_NUM_57810_VF,
178        PCI_ANY_ID, PCI_ANY_ID,
179        "Broadcom NetXtreme II BCM57810 VF 10GbE"
180    },
181#endif
182    {
183        BRCM_VENDORID,
184        CHIP_NUM_57811,
185        PCI_ANY_ID, PCI_ANY_ID,
186        "Broadcom NetXtreme II BCM57811 10GbE"
187    },
188    {
189        BRCM_VENDORID,
190        CHIP_NUM_57811_MF,
191        PCI_ANY_ID, PCI_ANY_ID,
192        "Broadcom NetXtreme II BCM57811 MF 10GbE"
193    },
194#if 0
195    {
196        BRCM_VENDORID,
197        CHIP_NUM_57811_VF,
198        PCI_ANY_ID, PCI_ANY_ID,
199        "Broadcom NetXtreme II BCM57811 VF 10GbE"
200    },
201#endif
202    {
203        BRCM_VENDORID,
204        CHIP_NUM_57840_4_10,
205        PCI_ANY_ID, PCI_ANY_ID,
206        "Broadcom NetXtreme II BCM57840 4x10GbE"
207    },
208#if 0
209    {
210        BRCM_VENDORID,
211        CHIP_NUM_57840_2_20,
212        PCI_ANY_ID, PCI_ANY_ID,
213        "Broadcom NetXtreme II BCM57840 2x20GbE"
214    },
215#endif
216    {
217        BRCM_VENDORID,
218        CHIP_NUM_57840_MF,
219        PCI_ANY_ID, PCI_ANY_ID,
220        "Broadcom NetXtreme II BCM57840 MF 10GbE"
221    },
222#if 0
223    {
224        BRCM_VENDORID,
225        CHIP_NUM_57840_VF,
226        PCI_ANY_ID, PCI_ANY_ID,
227        "Broadcom NetXtreme II BCM57840 VF 10GbE"
228    },
229#endif
230    {
231        0, 0, 0, 0, NULL
232    }
233};
234
235MALLOC_DECLARE(M_BXE_ILT);
236MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
237
238/*
239 * FreeBSD device entry points.
240 */
241static int bxe_probe(device_t);
242static int bxe_attach(device_t);
243static int bxe_detach(device_t);
244static int bxe_shutdown(device_t);
245
246/*
247 * FreeBSD KLD module/device interface event handler method.
248 */
249static device_method_t bxe_methods[] = {
250    /* Device interface (device_if.h) */
251    DEVMETHOD(device_probe,     bxe_probe),
252    DEVMETHOD(device_attach,    bxe_attach),
253    DEVMETHOD(device_detach,    bxe_detach),
254    DEVMETHOD(device_shutdown,  bxe_shutdown),
255#if 0
256    DEVMETHOD(device_suspend,   bxe_suspend),
257    DEVMETHOD(device_resume,    bxe_resume),
258#endif
259    /* Bus interface (bus_if.h) */
260    DEVMETHOD(bus_print_child,  bus_generic_print_child),
261    DEVMETHOD(bus_driver_added, bus_generic_driver_added),
262    KOBJMETHOD_END
263};
264
265/*
266 * FreeBSD KLD Module data declaration
267 */
268static driver_t bxe_driver = {
269    "bxe",                   /* module name */
270    bxe_methods,             /* event handler */
271    sizeof(struct bxe_softc) /* extra data */
272};
273
274/*
275 * FreeBSD dev class is needed to manage dev instances and
276 * to associate with a bus type
277 */
278static devclass_t bxe_devclass;
279
280MODULE_DEPEND(bxe, pci, 1, 1, 1);
281MODULE_DEPEND(bxe, ether, 1, 1, 1);
282DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
283
284/* resources needed for unloading a previously loaded device */
285
286#define BXE_PREV_WAIT_NEEDED 1
287struct mtx bxe_prev_mtx;
288MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
289struct bxe_prev_list_node {
290    LIST_ENTRY(bxe_prev_list_node) node;
291    uint8_t bus;
292    uint8_t slot;
293    uint8_t path;
294    uint8_t aer; /* XXX automatic error recovery */
295    uint8_t undi;
296};
297static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
298
299static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
300
301/* Tunable device values... */
302
303SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
304
305/* Debug */
306uint32_t bxe_debug = 0;
307TUNABLE_INT("hw.bxe.debug", &bxe_debug);
308SYSCTL_UINT(_hw_bxe, OID_AUTO, debug, (CTLFLAG_RDTUN),
309            &bxe_debug, 0, "Debug logging mode");
310
311/* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
312static int bxe_interrupt_mode = INTR_MODE_MSIX;
313TUNABLE_INT("hw.bxe.interrupt_mode", &bxe_interrupt_mode);
314SYSCTL_UINT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
315            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
316
317/* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
318static int bxe_queue_count = 4;
319TUNABLE_INT("hw.bxe.queue_count", &bxe_queue_count);
320SYSCTL_UINT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
321            &bxe_queue_count, 0, "Multi-Queue queue count");
322
323/* max number of buffers per queue (default RX_BD_USABLE) */
324static uint32_t bxe_max_rx_bufs = 0;
325TUNABLE_INT("hw.bxe.max_rx_bufs", &bxe_max_rx_bufs);
326SYSCTL_UINT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
327            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
328
329/* Host interrupt coalescing RX tick timer (usecs) */
330static uint32_t bxe_hc_rx_ticks = 25;
331TUNABLE_INT("hw.bxe.hc_rx_ticks", &bxe_hc_rx_ticks);
332SYSCTL_UINT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
333            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
334
335/* Host interrupt coalescing TX tick timer (usecs) */
336static uint32_t bxe_hc_tx_ticks = 50;
337TUNABLE_INT("hw.bxe.hc_tx_ticks", &bxe_hc_tx_ticks);
338SYSCTL_UINT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
339            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
340
341/* Maximum number of Rx packets to process at a time */
342static uint32_t bxe_rx_budget = 0xffffffff;
343TUNABLE_INT("hw.bxe.rx_budget", &bxe_rx_budget);
344SYSCTL_UINT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
345            &bxe_rx_budget, 0, "Rx processing budget");
346
347/* Maximum LRO aggregation size */
348static uint32_t bxe_max_aggregation_size = 0;
349TUNABLE_INT("hw.bxe.max_aggregation_size", &bxe_max_aggregation_size);
350SYSCTL_UINT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
351            &bxe_max_aggregation_size, 0, "max aggregation size");
352
353/* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
354static int bxe_mrrs = -1;
355TUNABLE_INT("hw.bxe.mrrs", &bxe_mrrs);
356SYSCTL_UINT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
357            &bxe_mrrs, 0, "PCIe maximum read request size");
358
359/* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
360static int bxe_autogreeen = 0;
361TUNABLE_INT("hw.bxe.autogreeen", &bxe_autogreeen);
362SYSCTL_UINT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
363            &bxe_autogreeen, 0, "AutoGrEEEn support");
364
365/* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
366static int bxe_udp_rss = 0;
367TUNABLE_INT("hw.bxe.udp_rss", &bxe_udp_rss);
368SYSCTL_UINT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
369            &bxe_udp_rss, 0, "UDP RSS support");
370
371
372#define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
373
374#define STATS_OFFSET32(stat_name)                   \
375    (offsetof(struct bxe_eth_stats, stat_name) / 4)
376
377#define Q_STATS_OFFSET32(stat_name)                   \
378    (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
379
380static const struct {
381    uint32_t offset;
382    uint32_t size;
383    uint32_t flags;
384#define STATS_FLAGS_PORT  1
385#define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
386#define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
387    char string[STAT_NAME_LEN];
388} bxe_eth_stats_arr[] = {
389    { STATS_OFFSET32(total_bytes_received_hi),
390                8, STATS_FLAGS_BOTH, "rx_bytes" },
391    { STATS_OFFSET32(error_bytes_received_hi),
392                8, STATS_FLAGS_BOTH, "rx_error_bytes" },
393    { STATS_OFFSET32(total_unicast_packets_received_hi),
394                8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
395    { STATS_OFFSET32(total_multicast_packets_received_hi),
396                8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
397    { STATS_OFFSET32(total_broadcast_packets_received_hi),
398                8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
399    { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
400                8, STATS_FLAGS_PORT, "rx_crc_errors" },
401    { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
402                8, STATS_FLAGS_PORT, "rx_align_errors" },
403    { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
404                8, STATS_FLAGS_PORT, "rx_undersize_packets" },
405    { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
406                8, STATS_FLAGS_PORT, "rx_oversize_packets" },
407    { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
408                8, STATS_FLAGS_PORT, "rx_fragments" },
409    { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
410                8, STATS_FLAGS_PORT, "rx_jabbers" },
411    { STATS_OFFSET32(no_buff_discard_hi),
412                8, STATS_FLAGS_BOTH, "rx_discards" },
413    { STATS_OFFSET32(mac_filter_discard),
414                4, STATS_FLAGS_PORT, "rx_filtered_packets" },
415    { STATS_OFFSET32(mf_tag_discard),
416                4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
417    { STATS_OFFSET32(pfc_frames_received_hi),
418                8, STATS_FLAGS_PORT, "pfc_frames_received" },
419    { STATS_OFFSET32(pfc_frames_sent_hi),
420                8, STATS_FLAGS_PORT, "pfc_frames_sent" },
421    { STATS_OFFSET32(brb_drop_hi),
422                8, STATS_FLAGS_PORT, "rx_brb_discard" },
423    { STATS_OFFSET32(brb_truncate_hi),
424                8, STATS_FLAGS_PORT, "rx_brb_truncate" },
425    { STATS_OFFSET32(pause_frames_received_hi),
426                8, STATS_FLAGS_PORT, "rx_pause_frames" },
427    { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
428                8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
429    { STATS_OFFSET32(nig_timer_max),
430                4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
431    { STATS_OFFSET32(total_bytes_transmitted_hi),
432                8, STATS_FLAGS_BOTH, "tx_bytes" },
433    { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
434                8, STATS_FLAGS_PORT, "tx_error_bytes" },
435    { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
436                8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
437    { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
438                8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
439    { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
440                8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
441    { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
442                8, STATS_FLAGS_PORT, "tx_mac_errors" },
443    { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
444                8, STATS_FLAGS_PORT, "tx_carrier_errors" },
445    { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
446                8, STATS_FLAGS_PORT, "tx_single_collisions" },
447    { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
448                8, STATS_FLAGS_PORT, "tx_multi_collisions" },
449    { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
450                8, STATS_FLAGS_PORT, "tx_deferred" },
451    { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
452                8, STATS_FLAGS_PORT, "tx_excess_collisions" },
453    { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
454                8, STATS_FLAGS_PORT, "tx_late_collisions" },
455    { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
456                8, STATS_FLAGS_PORT, "tx_total_collisions" },
457    { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
458                8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
459    { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
460                8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
461    { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
462                8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
463    { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
464                8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
465    { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
466                8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
467    { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
468                8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
469    { STATS_OFFSET32(etherstatspktsover1522octets_hi),
470                8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
471    { STATS_OFFSET32(pause_frames_sent_hi),
472                8, STATS_FLAGS_PORT, "tx_pause_frames" },
473    { STATS_OFFSET32(total_tpa_aggregations_hi),
474                8, STATS_FLAGS_FUNC, "tpa_aggregations" },
475    { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
476                8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
477    { STATS_OFFSET32(total_tpa_bytes_hi),
478                8, STATS_FLAGS_FUNC, "tpa_bytes"},
479#if 0
480    { STATS_OFFSET32(recoverable_error),
481                4, STATS_FLAGS_FUNC, "recoverable_errors" },
482    { STATS_OFFSET32(unrecoverable_error),
483                4, STATS_FLAGS_FUNC, "unrecoverable_errors" },
484#endif
485    { STATS_OFFSET32(eee_tx_lpi),
486                4, STATS_FLAGS_PORT, "eee_tx_lpi"},
487    { STATS_OFFSET32(rx_calls),
488                4, STATS_FLAGS_FUNC, "rx_calls"},
489    { STATS_OFFSET32(rx_pkts),
490                4, STATS_FLAGS_FUNC, "rx_pkts"},
491    { STATS_OFFSET32(rx_tpa_pkts),
492                4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
493    { STATS_OFFSET32(rx_soft_errors),
494                4, STATS_FLAGS_FUNC, "rx_soft_errors"},
495    { STATS_OFFSET32(rx_hw_csum_errors),
496                4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
497    { STATS_OFFSET32(rx_ofld_frames_csum_ip),
498                4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
499    { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
500                4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
501    { STATS_OFFSET32(rx_budget_reached),
502                4, STATS_FLAGS_FUNC, "rx_budget_reached"},
503    { STATS_OFFSET32(tx_pkts),
504                4, STATS_FLAGS_FUNC, "tx_pkts"},
505    { STATS_OFFSET32(tx_soft_errors),
506                4, STATS_FLAGS_FUNC, "tx_soft_errors"},
507    { STATS_OFFSET32(tx_ofld_frames_csum_ip),
508                4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
509    { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
510                4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
511    { STATS_OFFSET32(tx_ofld_frames_csum_udp),
512                4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
513    { STATS_OFFSET32(tx_ofld_frames_lso),
514                4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
515    { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
516                4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
517    { STATS_OFFSET32(tx_encap_failures),
518                4, STATS_FLAGS_FUNC, "tx_encap_failures"},
519    { STATS_OFFSET32(tx_hw_queue_full),
520                4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
521    { STATS_OFFSET32(tx_hw_max_queue_depth),
522                4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
523    { STATS_OFFSET32(tx_dma_mapping_failure),
524                4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
525    { STATS_OFFSET32(tx_max_drbr_queue_depth),
526                4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
527    { STATS_OFFSET32(tx_window_violation_std),
528                4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
529    { STATS_OFFSET32(tx_window_violation_tso),
530                4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
531#if 0
532    { STATS_OFFSET32(tx_unsupported_tso_request_ipv6),
533                4, STATS_FLAGS_FUNC, "tx_unsupported_tso_request_ipv6"},
534    { STATS_OFFSET32(tx_unsupported_tso_request_not_tcp),
535                4, STATS_FLAGS_FUNC, "tx_unsupported_tso_request_not_tcp"},
536#endif
537    { STATS_OFFSET32(tx_chain_lost_mbuf),
538                4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
539    { STATS_OFFSET32(tx_frames_deferred),
540                4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
541    { STATS_OFFSET32(tx_queue_xoff),
542                4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
543    { STATS_OFFSET32(mbuf_defrag_attempts),
544                4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
545    { STATS_OFFSET32(mbuf_defrag_failures),
546                4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
547    { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
548                4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
549    { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
550                4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
551    { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
552                4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
553    { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
554                4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
555    { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
556                4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
557    { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
558                4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
559    { STATS_OFFSET32(mbuf_alloc_tx),
560                4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
561    { STATS_OFFSET32(mbuf_alloc_rx),
562                4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
563    { STATS_OFFSET32(mbuf_alloc_sge),
564                4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
565    { STATS_OFFSET32(mbuf_alloc_tpa),
566                4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"}
567};
568
569static const struct {
570    uint32_t offset;
571    uint32_t size;
572    char string[STAT_NAME_LEN];
573} bxe_eth_q_stats_arr[] = {
574    { Q_STATS_OFFSET32(total_bytes_received_hi),
575                8, "rx_bytes" },
576    { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
577                8, "rx_ucast_packets" },
578    { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
579                8, "rx_mcast_packets" },
580    { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
581                8, "rx_bcast_packets" },
582    { Q_STATS_OFFSET32(no_buff_discard_hi),
583                8, "rx_discards" },
584    { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
585                8, "tx_bytes" },
586    { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
587                8, "tx_ucast_packets" },
588    { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
589                8, "tx_mcast_packets" },
590    { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
591                8, "tx_bcast_packets" },
592    { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
593                8, "tpa_aggregations" },
594    { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
595                8, "tpa_aggregated_frames"},
596    { Q_STATS_OFFSET32(total_tpa_bytes_hi),
597                8, "tpa_bytes"},
598    { Q_STATS_OFFSET32(rx_calls),
599                4, "rx_calls"},
600    { Q_STATS_OFFSET32(rx_pkts),
601                4, "rx_pkts"},
602    { Q_STATS_OFFSET32(rx_tpa_pkts),
603                4, "rx_tpa_pkts"},
604    { Q_STATS_OFFSET32(rx_soft_errors),
605                4, "rx_soft_errors"},
606    { Q_STATS_OFFSET32(rx_hw_csum_errors),
607                4, "rx_hw_csum_errors"},
608    { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
609                4, "rx_ofld_frames_csum_ip"},
610    { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
611                4, "rx_ofld_frames_csum_tcp_udp"},
612    { Q_STATS_OFFSET32(rx_budget_reached),
613                4, "rx_budget_reached"},
614    { Q_STATS_OFFSET32(tx_pkts),
615                4, "tx_pkts"},
616    { Q_STATS_OFFSET32(tx_soft_errors),
617                4, "tx_soft_errors"},
618    { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
619                4, "tx_ofld_frames_csum_ip"},
620    { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
621                4, "tx_ofld_frames_csum_tcp"},
622    { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
623                4, "tx_ofld_frames_csum_udp"},
624    { Q_STATS_OFFSET32(tx_ofld_frames_lso),
625                4, "tx_ofld_frames_lso"},
626    { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
627                4, "tx_ofld_frames_lso_hdr_splits"},
628    { Q_STATS_OFFSET32(tx_encap_failures),
629                4, "tx_encap_failures"},
630    { Q_STATS_OFFSET32(tx_hw_queue_full),
631                4, "tx_hw_queue_full"},
632    { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
633                4, "tx_hw_max_queue_depth"},
634    { Q_STATS_OFFSET32(tx_dma_mapping_failure),
635                4, "tx_dma_mapping_failure"},
636    { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
637                4, "tx_max_drbr_queue_depth"},
638    { Q_STATS_OFFSET32(tx_window_violation_std),
639                4, "tx_window_violation_std"},
640    { Q_STATS_OFFSET32(tx_window_violation_tso),
641                4, "tx_window_violation_tso"},
642#if 0
643    { Q_STATS_OFFSET32(tx_unsupported_tso_request_ipv6),
644                4, "tx_unsupported_tso_request_ipv6"},
645    { Q_STATS_OFFSET32(tx_unsupported_tso_request_not_tcp),
646                4, "tx_unsupported_tso_request_not_tcp"},
647#endif
648    { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
649                4, "tx_chain_lost_mbuf"},
650    { Q_STATS_OFFSET32(tx_frames_deferred),
651                4, "tx_frames_deferred"},
652    { Q_STATS_OFFSET32(tx_queue_xoff),
653                4, "tx_queue_xoff"},
654    { Q_STATS_OFFSET32(mbuf_defrag_attempts),
655                4, "mbuf_defrag_attempts"},
656    { Q_STATS_OFFSET32(mbuf_defrag_failures),
657                4, "mbuf_defrag_failures"},
658    { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
659                4, "mbuf_rx_bd_alloc_failed"},
660    { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
661                4, "mbuf_rx_bd_mapping_failed"},
662    { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
663                4, "mbuf_rx_tpa_alloc_failed"},
664    { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
665                4, "mbuf_rx_tpa_mapping_failed"},
666    { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
667                4, "mbuf_rx_sge_alloc_failed"},
668    { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
669                4, "mbuf_rx_sge_mapping_failed"},
670    { Q_STATS_OFFSET32(mbuf_alloc_tx),
671                4, "mbuf_alloc_tx"},
672    { Q_STATS_OFFSET32(mbuf_alloc_rx),
673                4, "mbuf_alloc_rx"},
674    { Q_STATS_OFFSET32(mbuf_alloc_sge),
675                4, "mbuf_alloc_sge"},
676    { Q_STATS_OFFSET32(mbuf_alloc_tpa),
677                4, "mbuf_alloc_tpa"}
678};
679
680#define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
681#define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
682
683
684static void    bxe_cmng_fns_init(struct bxe_softc *sc,
685                                 uint8_t          read_cfg,
686                                 uint8_t          cmng_type);
687static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
688static void    storm_memset_cmng(struct bxe_softc *sc,
689                                 struct cmng_init *cmng,
690                                 uint8_t          port);
691static void    bxe_set_reset_global(struct bxe_softc *sc);
692static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
693static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
694                                 int              engine);
695static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
696static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
697                                   uint8_t          *global,
698                                   uint8_t          print);
699static void    bxe_int_disable(struct bxe_softc *sc);
700static int     bxe_release_leader_lock(struct bxe_softc *sc);
701static void    bxe_pf_disable(struct bxe_softc *sc);
702static void    bxe_free_fp_buffers(struct bxe_softc *sc);
703static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
704                                      struct bxe_fastpath *fp,
705                                      uint16_t            rx_bd_prod,
706                                      uint16_t            rx_cq_prod,
707                                      uint16_t            rx_sge_prod);
708static void    bxe_link_report_locked(struct bxe_softc *sc);
709static void    bxe_link_report(struct bxe_softc *sc);
710static void    bxe_link_status_update(struct bxe_softc *sc);
711static void    bxe_periodic_callout_func(void *xsc);
712static void    bxe_periodic_start(struct bxe_softc *sc);
713static void    bxe_periodic_stop(struct bxe_softc *sc);
714static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
715                                    uint16_t prev_index,
716                                    uint16_t index);
717static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
718                                     int                 queue);
719static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
720                                     uint16_t            index);
721static uint8_t bxe_txeof(struct bxe_softc *sc,
722                         struct bxe_fastpath *fp);
723static void    bxe_task_fp(struct bxe_fastpath *fp);
724static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
725                                     struct mbuf      *m,
726                                     uint8_t          contents);
727static int     bxe_alloc_mem(struct bxe_softc *sc);
728static void    bxe_free_mem(struct bxe_softc *sc);
729static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
730static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
731static int     bxe_interrupt_attach(struct bxe_softc *sc);
732static void    bxe_interrupt_detach(struct bxe_softc *sc);
733static void    bxe_set_rx_mode(struct bxe_softc *sc);
734static int     bxe_init_locked(struct bxe_softc *sc);
735static int     bxe_stop_locked(struct bxe_softc *sc);
736static __noinline int bxe_nic_load(struct bxe_softc *sc,
737                                   int              load_mode);
738static __noinline int bxe_nic_unload(struct bxe_softc *sc,
739                                     uint32_t         unload_mode,
740                                     uint8_t          keep_link);
741
742static void bxe_handle_sp_tq(void *context, int pending);
743static void bxe_handle_rx_mode_tq(void *context, int pending);
744static void bxe_handle_fp_tq(void *context, int pending);
745
746
747/* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
748uint32_t
749calc_crc32(uint8_t  *crc32_packet,
750           uint32_t crc32_length,
751           uint32_t crc32_seed,
752           uint8_t  complement)
753{
754   uint32_t byte         = 0;
755   uint32_t bit          = 0;
756   uint8_t  msb          = 0;
757   uint32_t temp         = 0;
758   uint32_t shft         = 0;
759   uint8_t  current_byte = 0;
760   uint32_t crc32_result = crc32_seed;
761   const uint32_t CRC32_POLY = 0x1edc6f41;
762
763   if ((crc32_packet == NULL) ||
764       (crc32_length == 0) ||
765       ((crc32_length % 8) != 0))
766    {
767        return (crc32_result);
768    }
769
770    for (byte = 0; byte < crc32_length; byte = byte + 1)
771    {
772        current_byte = crc32_packet[byte];
773        for (bit = 0; bit < 8; bit = bit + 1)
774        {
775            /* msb = crc32_result[31]; */
776            msb = (uint8_t)(crc32_result >> 31);
777
778            crc32_result = crc32_result << 1;
779
780            /* it (msb != current_byte[bit]) */
781            if (msb != (0x1 & (current_byte >> bit)))
782            {
783                crc32_result = crc32_result ^ CRC32_POLY;
784                /* crc32_result[0] = 1 */
785                crc32_result |= 1;
786            }
787        }
788    }
789
790    /* Last step is to:
791     * 1. "mirror" every bit
792     * 2. swap the 4 bytes
793     * 3. complement each bit
794     */
795
796    /* Mirror */
797    temp = crc32_result;
798    shft = sizeof(crc32_result) * 8 - 1;
799
800    for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
801    {
802        temp <<= 1;
803        temp |= crc32_result & 1;
804        shft-- ;
805    }
806
807    /* temp[31-bit] = crc32_result[bit] */
808    temp <<= shft;
809
810    /* Swap */
811    /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
812    {
813        uint32_t t0, t1, t2, t3;
814        t0 = (0x000000ff & (temp >> 24));
815        t1 = (0x0000ff00 & (temp >> 8));
816        t2 = (0x00ff0000 & (temp << 8));
817        t3 = (0xff000000 & (temp << 24));
818        crc32_result = t0 | t1 | t2 | t3;
819    }
820
821    /* Complement */
822    if (complement)
823    {
824        crc32_result = ~crc32_result;
825    }
826
827    return (crc32_result);
828}
829
830int
831bxe_test_bit(int                    nr,
832             volatile unsigned long *addr)
833{
834    return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
835}
836
837void
838bxe_set_bit(unsigned int           nr,
839            volatile unsigned long *addr)
840{
841    atomic_set_acq_long(addr, (1 << nr));
842}
843
844void
845bxe_clear_bit(int                    nr,
846              volatile unsigned long *addr)
847{
848    atomic_clear_acq_long(addr, (1 << nr));
849}
850
851int
852bxe_test_and_set_bit(int                    nr,
853                       volatile unsigned long *addr)
854{
855    unsigned long x;
856    nr = (1 << nr);
857    do {
858        x = *addr;
859    } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
860    // if (x & nr) bit_was_set; else bit_was_not_set;
861    return (x & nr);
862}
863
864int
865bxe_test_and_clear_bit(int                    nr,
866                       volatile unsigned long *addr)
867{
868    unsigned long x;
869    nr = (1 << nr);
870    do {
871        x = *addr;
872    } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
873    // if (x & nr) bit_was_set; else bit_was_not_set;
874    return (x & nr);
875}
876
877int
878bxe_cmpxchg(volatile int *addr,
879            int          old,
880            int          new)
881{
882    int x;
883    do {
884        x = *addr;
885    } while (atomic_cmpset_acq_int(addr, old, new) == 0);
886    return (x);
887}
888
889/*
890 * Get DMA memory from the OS.
891 *
892 * Validates that the OS has provided DMA buffers in response to a
893 * bus_dmamap_load call and saves the physical address of those buffers.
894 * When the callback is used the OS will return 0 for the mapping function
895 * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
896 * failures back to the caller.
897 *
898 * Returns:
899 *   Nothing.
900 */
901static void
902bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
903{
904    struct bxe_dma *dma = arg;
905
906    if (error) {
907        dma->paddr = 0;
908        dma->nseg  = 0;
909        BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
910    } else {
911        dma->paddr = segs->ds_addr;
912        dma->nseg  = nseg;
913#if 0
914        BLOGD(dma->sc, DBG_LOAD,,
915              "DMA alloc '%s': vaddr=%p paddr=%p nseg=%d size=%lu\n",
916              dma->msg, dma->vaddr, (void *)dma->paddr,
917              dma->nseg, dma->size);
918#endif
919    }
920}
921
922/*
923 * Allocate a block of memory and map it for DMA. No partial completions
924 * allowed and release any resources acquired if we can't acquire all
925 * resources.
926 *
927 * Returns:
928 *   0 = Success, !0 = Failure
929 */
930int
931bxe_dma_alloc(struct bxe_softc *sc,
932              bus_size_t       size,
933              struct bxe_dma   *dma,
934              const char       *msg)
935{
936    int rc;
937
938    if (dma->size > 0) {
939        BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
940	  (unsigned long) dma->size);
941        return (1);
942    }
943
944    memset(dma, 0, sizeof(*dma)); /* sanity */
945    dma->sc   = sc;
946    dma->size = size;
947    snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
948
949    rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
950                            BCM_PAGE_SIZE,      /* alignment */
951                            0,                  /* boundary limit */
952                            BUS_SPACE_MAXADDR,  /* restricted low */
953                            BUS_SPACE_MAXADDR,  /* restricted hi */
954                            NULL,               /* addr filter() */
955                            NULL,               /* addr filter() arg */
956                            size,               /* max map size */
957                            1,                  /* num discontinuous */
958                            size,               /* max seg size */
959                            BUS_DMA_ALLOCNOW,   /* flags */
960                            NULL,               /* lock() */
961                            NULL,               /* lock() arg */
962                            &dma->tag);         /* returned dma tag */
963    if (rc != 0) {
964        BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
965        memset(dma, 0, sizeof(*dma));
966        return (1);
967    }
968
969    rc = bus_dmamem_alloc(dma->tag,
970                          (void **)&dma->vaddr,
971                          (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
972                          &dma->map);
973    if (rc != 0) {
974        BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
975        bus_dma_tag_destroy(dma->tag);
976        memset(dma, 0, sizeof(*dma));
977        return (1);
978    }
979
980    rc = bus_dmamap_load(dma->tag,
981                         dma->map,
982                         dma->vaddr,
983                         size,
984                         bxe_dma_map_addr, /* BLOGD in here */
985                         dma,
986                         BUS_DMA_NOWAIT);
987    if (rc != 0) {
988        BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
989        bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
990        bus_dma_tag_destroy(dma->tag);
991        memset(dma, 0, sizeof(*dma));
992        return (1);
993    }
994
995    return (0);
996}
997
998void
999bxe_dma_free(struct bxe_softc *sc,
1000             struct bxe_dma   *dma)
1001{
1002    if (dma->size > 0) {
1003#if 0
1004        BLOGD(sc, DBG_LOAD,
1005              "DMA free '%s': vaddr=%p paddr=%p nseg=%d size=%lu\n",
1006              dma->msg, dma->vaddr, (void *)dma->paddr,
1007              dma->nseg, dma->size);
1008#endif
1009
1010        DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
1011
1012        bus_dmamap_sync(dma->tag, dma->map,
1013                        (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
1014        bus_dmamap_unload(dma->tag, dma->map);
1015        bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
1016        bus_dma_tag_destroy(dma->tag);
1017    }
1018
1019    memset(dma, 0, sizeof(*dma));
1020}
1021
1022/*
1023 * These indirect read and write routines are only during init.
1024 * The locking is handled by the MCP.
1025 */
1026
1027void
1028bxe_reg_wr_ind(struct bxe_softc *sc,
1029               uint32_t         addr,
1030               uint32_t         val)
1031{
1032    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1033    pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
1034    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1035}
1036
1037uint32_t
1038bxe_reg_rd_ind(struct bxe_softc *sc,
1039               uint32_t         addr)
1040{
1041    uint32_t val;
1042
1043    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1044    val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
1045    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1046
1047    return (val);
1048}
1049
1050#if 0
1051void bxe_dp_dmae(struct bxe_softc *sc, struct dmae_command *dmae, int msglvl)
1052{
1053    uint32_t src_type = dmae->opcode & DMAE_COMMAND_SRC;
1054
1055    switch (dmae->opcode & DMAE_COMMAND_DST) {
1056    case DMAE_CMD_DST_PCI:
1057        if (src_type == DMAE_CMD_SRC_PCI)
1058            DP(msglvl, "DMAE: opcode 0x%08x\n"
1059               "src [%x:%08x], len [%d*4], dst [%x:%08x]\n"
1060               "comp_addr [%x:%08x], comp_val 0x%08x\n",
1061               dmae->opcode, dmae->src_addr_hi, dmae->src_addr_lo,
1062               dmae->len, dmae->dst_addr_hi, dmae->dst_addr_lo,
1063               dmae->comp_addr_hi, dmae->comp_addr_lo,
1064               dmae->comp_val);
1065        else
1066            DP(msglvl, "DMAE: opcode 0x%08x\n"
1067               "src [%08x], len [%d*4], dst [%x:%08x]\n"
1068               "comp_addr [%x:%08x], comp_val 0x%08x\n",
1069               dmae->opcode, dmae->src_addr_lo >> 2,
1070               dmae->len, dmae->dst_addr_hi, dmae->dst_addr_lo,
1071               dmae->comp_addr_hi, dmae->comp_addr_lo,
1072               dmae->comp_val);
1073        break;
1074    case DMAE_CMD_DST_GRC:
1075        if (src_type == DMAE_CMD_SRC_PCI)
1076            DP(msglvl, "DMAE: opcode 0x%08x\n"
1077               "src [%x:%08x], len [%d*4], dst_addr [%08x]\n"
1078               "comp_addr [%x:%08x], comp_val 0x%08x\n",
1079               dmae->opcode, dmae->src_addr_hi, dmae->src_addr_lo,
1080               dmae->len, dmae->dst_addr_lo >> 2,
1081               dmae->comp_addr_hi, dmae->comp_addr_lo,
1082               dmae->comp_val);
1083        else
1084            DP(msglvl, "DMAE: opcode 0x%08x\n"
1085               "src [%08x], len [%d*4], dst [%08x]\n"
1086               "comp_addr [%x:%08x], comp_val 0x%08x\n",
1087               dmae->opcode, dmae->src_addr_lo >> 2,
1088               dmae->len, dmae->dst_addr_lo >> 2,
1089               dmae->comp_addr_hi, dmae->comp_addr_lo,
1090               dmae->comp_val);
1091        break;
1092    default:
1093        if (src_type == DMAE_CMD_SRC_PCI)
1094            DP(msglvl, "DMAE: opcode 0x%08x\n"
1095               "src_addr [%x:%08x]  len [%d * 4]  dst_addr [none]\n"
1096               "comp_addr [%x:%08x]  comp_val 0x%08x\n",
1097               dmae->opcode, dmae->src_addr_hi, dmae->src_addr_lo,
1098               dmae->len, dmae->comp_addr_hi, dmae->comp_addr_lo,
1099               dmae->comp_val);
1100        else
1101            DP(msglvl, "DMAE: opcode 0x%08x\n"
1102               "src_addr [%08x]  len [%d * 4]  dst_addr [none]\n"
1103               "comp_addr [%x:%08x]  comp_val 0x%08x\n",
1104               dmae->opcode, dmae->src_addr_lo >> 2,
1105               dmae->len, dmae->comp_addr_hi, dmae->comp_addr_lo,
1106               dmae->comp_val);
1107        break;
1108    }
1109
1110}
1111#endif
1112
1113static int
1114bxe_acquire_hw_lock(struct bxe_softc *sc,
1115                    uint32_t         resource)
1116{
1117    uint32_t lock_status;
1118    uint32_t resource_bit = (1 << resource);
1119    int func = SC_FUNC(sc);
1120    uint32_t hw_lock_control_reg;
1121    int cnt;
1122
1123    /* validate the resource is within range */
1124    if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1125        BLOGE(sc, "resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE\n", resource);
1126        return (-1);
1127    }
1128
1129    if (func <= 5) {
1130        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1131    } else {
1132        hw_lock_control_reg =
1133                (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1134    }
1135
1136    /* validate the resource is not already taken */
1137    lock_status = REG_RD(sc, hw_lock_control_reg);
1138    if (lock_status & resource_bit) {
1139        BLOGE(sc, "resource in use (status 0x%x bit 0x%x)\n",
1140              lock_status, resource_bit);
1141        return (-1);
1142    }
1143
1144    /* try every 5ms for 5 seconds */
1145    for (cnt = 0; cnt < 1000; cnt++) {
1146        REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1147        lock_status = REG_RD(sc, hw_lock_control_reg);
1148        if (lock_status & resource_bit) {
1149            return (0);
1150        }
1151        DELAY(5000);
1152    }
1153
1154    BLOGE(sc, "Resource lock timeout!\n");
1155    return (-1);
1156}
1157
1158static int
1159bxe_release_hw_lock(struct bxe_softc *sc,
1160                    uint32_t         resource)
1161{
1162    uint32_t lock_status;
1163    uint32_t resource_bit = (1 << resource);
1164    int func = SC_FUNC(sc);
1165    uint32_t hw_lock_control_reg;
1166
1167    /* validate the resource is within range */
1168    if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1169        BLOGE(sc, "resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE\n", resource);
1170        return (-1);
1171    }
1172
1173    if (func <= 5) {
1174        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1175    } else {
1176        hw_lock_control_reg =
1177                (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1178    }
1179
1180    /* validate the resource is currently taken */
1181    lock_status = REG_RD(sc, hw_lock_control_reg);
1182    if (!(lock_status & resource_bit)) {
1183        BLOGE(sc, "resource not in use (status 0x%x bit 0x%x)\n",
1184              lock_status, resource_bit);
1185        return (-1);
1186    }
1187
1188    REG_WR(sc, hw_lock_control_reg, resource_bit);
1189    return (0);
1190}
1191
1192/*
1193 * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1194 * had we done things the other way around, if two pfs from the same port
1195 * would attempt to access nvram at the same time, we could run into a
1196 * scenario such as:
1197 * pf A takes the port lock.
1198 * pf B succeeds in taking the same lock since they are from the same port.
1199 * pf A takes the per pf misc lock. Performs eeprom access.
1200 * pf A finishes. Unlocks the per pf misc lock.
1201 * Pf B takes the lock and proceeds to perform it's own access.
1202 * pf A unlocks the per port lock, while pf B is still working (!).
1203 * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1204 * access corrupted by pf B).*
1205 */
1206static int
1207bxe_acquire_nvram_lock(struct bxe_softc *sc)
1208{
1209    int port = SC_PORT(sc);
1210    int count, i;
1211    uint32_t val = 0;
1212
1213    /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1214    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1215
1216    /* adjust timeout for emulation/FPGA */
1217    count = NVRAM_TIMEOUT_COUNT;
1218    if (CHIP_REV_IS_SLOW(sc)) {
1219        count *= 100;
1220    }
1221
1222    /* request access to nvram interface */
1223    REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1224           (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1225
1226    for (i = 0; i < count*10; i++) {
1227        val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1228        if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1229            break;
1230        }
1231
1232        DELAY(5);
1233    }
1234
1235    if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1236        BLOGE(sc, "Cannot get access to nvram interface\n");
1237        return (-1);
1238    }
1239
1240    return (0);
1241}
1242
1243static int
1244bxe_release_nvram_lock(struct bxe_softc *sc)
1245{
1246    int port = SC_PORT(sc);
1247    int count, i;
1248    uint32_t val = 0;
1249
1250    /* adjust timeout for emulation/FPGA */
1251    count = NVRAM_TIMEOUT_COUNT;
1252    if (CHIP_REV_IS_SLOW(sc)) {
1253        count *= 100;
1254    }
1255
1256    /* relinquish nvram interface */
1257    REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1258           (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1259
1260    for (i = 0; i < count*10; i++) {
1261        val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1262        if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1263            break;
1264        }
1265
1266        DELAY(5);
1267    }
1268
1269    if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1270        BLOGE(sc, "Cannot free access to nvram interface\n");
1271        return (-1);
1272    }
1273
1274    /* release HW lock: protect against other PFs in PF Direct Assignment */
1275    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1276
1277    return (0);
1278}
1279
1280static void
1281bxe_enable_nvram_access(struct bxe_softc *sc)
1282{
1283    uint32_t val;
1284
1285    val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1286
1287    /* enable both bits, even on read */
1288    REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1289           (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1290}
1291
1292static void
1293bxe_disable_nvram_access(struct bxe_softc *sc)
1294{
1295    uint32_t val;
1296
1297    val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1298
1299    /* disable both bits, even after read */
1300    REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1301           (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1302                    MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1303}
1304
1305static int
1306bxe_nvram_read_dword(struct bxe_softc *sc,
1307                     uint32_t         offset,
1308                     uint32_t         *ret_val,
1309                     uint32_t         cmd_flags)
1310{
1311    int count, i, rc;
1312    uint32_t val;
1313
1314    /* build the command word */
1315    cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1316
1317    /* need to clear DONE bit separately */
1318    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1319
1320    /* address of the NVRAM to read from */
1321    REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1322           (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1323
1324    /* issue a read command */
1325    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1326
1327    /* adjust timeout for emulation/FPGA */
1328    count = NVRAM_TIMEOUT_COUNT;
1329    if (CHIP_REV_IS_SLOW(sc)) {
1330        count *= 100;
1331    }
1332
1333    /* wait for completion */
1334    *ret_val = 0;
1335    rc = -1;
1336    for (i = 0; i < count; i++) {
1337        DELAY(5);
1338        val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1339
1340        if (val & MCPR_NVM_COMMAND_DONE) {
1341            val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1342            /* we read nvram data in cpu order
1343             * but ethtool sees it as an array of bytes
1344             * converting to big-endian will do the work
1345             */
1346            *ret_val = htobe32(val);
1347            rc = 0;
1348            break;
1349        }
1350    }
1351
1352    if (rc == -1) {
1353        BLOGE(sc, "nvram read timeout expired\n");
1354    }
1355
1356    return (rc);
1357}
1358
1359static int
1360bxe_nvram_read(struct bxe_softc *sc,
1361               uint32_t         offset,
1362               uint8_t          *ret_buf,
1363               int              buf_size)
1364{
1365    uint32_t cmd_flags;
1366    uint32_t val;
1367    int rc;
1368
1369    if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1370        BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1371              offset, buf_size);
1372        return (-1);
1373    }
1374
1375    if ((offset + buf_size) > sc->devinfo.flash_size) {
1376        BLOGE(sc, "Invalid parameter, "
1377                  "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1378              offset, buf_size, sc->devinfo.flash_size);
1379        return (-1);
1380    }
1381
1382    /* request access to nvram interface */
1383    rc = bxe_acquire_nvram_lock(sc);
1384    if (rc) {
1385        return (rc);
1386    }
1387
1388    /* enable access to nvram interface */
1389    bxe_enable_nvram_access(sc);
1390
1391    /* read the first word(s) */
1392    cmd_flags = MCPR_NVM_COMMAND_FIRST;
1393    while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1394        rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1395        memcpy(ret_buf, &val, 4);
1396
1397        /* advance to the next dword */
1398        offset += sizeof(uint32_t);
1399        ret_buf += sizeof(uint32_t);
1400        buf_size -= sizeof(uint32_t);
1401        cmd_flags = 0;
1402    }
1403
1404    if (rc == 0) {
1405        cmd_flags |= MCPR_NVM_COMMAND_LAST;
1406        rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1407        memcpy(ret_buf, &val, 4);
1408    }
1409
1410    /* disable access to nvram interface */
1411    bxe_disable_nvram_access(sc);
1412    bxe_release_nvram_lock(sc);
1413
1414    return (rc);
1415}
1416
1417static int
1418bxe_nvram_write_dword(struct bxe_softc *sc,
1419                      uint32_t         offset,
1420                      uint32_t         val,
1421                      uint32_t         cmd_flags)
1422{
1423    int count, i, rc;
1424
1425    /* build the command word */
1426    cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1427
1428    /* need to clear DONE bit separately */
1429    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1430
1431    /* write the data */
1432    REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1433
1434    /* address of the NVRAM to write to */
1435    REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1436           (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1437
1438    /* issue the write command */
1439    REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1440
1441    /* adjust timeout for emulation/FPGA */
1442    count = NVRAM_TIMEOUT_COUNT;
1443    if (CHIP_REV_IS_SLOW(sc)) {
1444        count *= 100;
1445    }
1446
1447    /* wait for completion */
1448    rc = -1;
1449    for (i = 0; i < count; i++) {
1450        DELAY(5);
1451        val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1452        if (val & MCPR_NVM_COMMAND_DONE) {
1453            rc = 0;
1454            break;
1455        }
1456    }
1457
1458    if (rc == -1) {
1459        BLOGE(sc, "nvram write timeout expired\n");
1460    }
1461
1462    return (rc);
1463}
1464
1465#define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1466
1467static int
1468bxe_nvram_write1(struct bxe_softc *sc,
1469                 uint32_t         offset,
1470                 uint8_t          *data_buf,
1471                 int              buf_size)
1472{
1473    uint32_t cmd_flags;
1474    uint32_t align_offset;
1475    uint32_t val;
1476    int rc;
1477
1478    if ((offset + buf_size) > sc->devinfo.flash_size) {
1479        BLOGE(sc, "Invalid parameter, "
1480                  "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1481              offset, buf_size, sc->devinfo.flash_size);
1482        return (-1);
1483    }
1484
1485    /* request access to nvram interface */
1486    rc = bxe_acquire_nvram_lock(sc);
1487    if (rc) {
1488        return (rc);
1489    }
1490
1491    /* enable access to nvram interface */
1492    bxe_enable_nvram_access(sc);
1493
1494    cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1495    align_offset = (offset & ~0x03);
1496    rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1497
1498    if (rc == 0) {
1499        val &= ~(0xff << BYTE_OFFSET(offset));
1500        val |= (*data_buf << BYTE_OFFSET(offset));
1501
1502        /* nvram data is returned as an array of bytes
1503         * convert it back to cpu order
1504         */
1505        val = be32toh(val);
1506
1507        rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1508    }
1509
1510    /* disable access to nvram interface */
1511    bxe_disable_nvram_access(sc);
1512    bxe_release_nvram_lock(sc);
1513
1514    return (rc);
1515}
1516
1517static int
1518bxe_nvram_write(struct bxe_softc *sc,
1519                uint32_t         offset,
1520                uint8_t          *data_buf,
1521                int              buf_size)
1522{
1523    uint32_t cmd_flags;
1524    uint32_t val;
1525    uint32_t written_so_far;
1526    int rc;
1527
1528    if (buf_size == 1) {
1529        return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1530    }
1531
1532    if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1533        BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1534              offset, buf_size);
1535        return (-1);
1536    }
1537
1538    if (buf_size == 0) {
1539        return (0); /* nothing to do */
1540    }
1541
1542    if ((offset + buf_size) > sc->devinfo.flash_size) {
1543        BLOGE(sc, "Invalid parameter, "
1544                  "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1545              offset, buf_size, sc->devinfo.flash_size);
1546        return (-1);
1547    }
1548
1549    /* request access to nvram interface */
1550    rc = bxe_acquire_nvram_lock(sc);
1551    if (rc) {
1552        return (rc);
1553    }
1554
1555    /* enable access to nvram interface */
1556    bxe_enable_nvram_access(sc);
1557
1558    written_so_far = 0;
1559    cmd_flags = MCPR_NVM_COMMAND_FIRST;
1560    while ((written_so_far < buf_size) && (rc == 0)) {
1561        if (written_so_far == (buf_size - sizeof(uint32_t))) {
1562            cmd_flags |= MCPR_NVM_COMMAND_LAST;
1563        } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1564            cmd_flags |= MCPR_NVM_COMMAND_LAST;
1565        } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1566            cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1567        }
1568
1569        memcpy(&val, data_buf, 4);
1570
1571        rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1572
1573        /* advance to the next dword */
1574        offset += sizeof(uint32_t);
1575        data_buf += sizeof(uint32_t);
1576        written_so_far += sizeof(uint32_t);
1577        cmd_flags = 0;
1578    }
1579
1580    /* disable access to nvram interface */
1581    bxe_disable_nvram_access(sc);
1582    bxe_release_nvram_lock(sc);
1583
1584    return (rc);
1585}
1586
1587/* copy command into DMAE command memory and set DMAE command Go */
1588void
1589bxe_post_dmae(struct bxe_softc    *sc,
1590              struct dmae_command *dmae,
1591              int                 idx)
1592{
1593    uint32_t cmd_offset;
1594    int i;
1595
1596    cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_command) * idx));
1597    for (i = 0; i < ((sizeof(struct dmae_command) / 4)); i++) {
1598        REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1599    }
1600
1601    REG_WR(sc, dmae_reg_go_c[idx], 1);
1602}
1603
1604uint32_t
1605bxe_dmae_opcode_add_comp(uint32_t opcode,
1606                         uint8_t  comp_type)
1607{
1608    return (opcode | ((comp_type << DMAE_COMMAND_C_DST_SHIFT) |
1609                      DMAE_COMMAND_C_TYPE_ENABLE));
1610}
1611
1612uint32_t
1613bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1614{
1615    return (opcode & ~DMAE_COMMAND_SRC_RESET);
1616}
1617
1618uint32_t
1619bxe_dmae_opcode(struct bxe_softc *sc,
1620                uint8_t          src_type,
1621                uint8_t          dst_type,
1622                uint8_t          with_comp,
1623                uint8_t          comp_type)
1624{
1625    uint32_t opcode = 0;
1626
1627    opcode |= ((src_type << DMAE_COMMAND_SRC_SHIFT) |
1628               (dst_type << DMAE_COMMAND_DST_SHIFT));
1629
1630    opcode |= (DMAE_COMMAND_SRC_RESET | DMAE_COMMAND_DST_RESET);
1631
1632    opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1633
1634    opcode |= ((SC_VN(sc) << DMAE_COMMAND_E1HVN_SHIFT) |
1635               (SC_VN(sc) << DMAE_COMMAND_DST_VN_SHIFT));
1636
1637    opcode |= (DMAE_COM_SET_ERR << DMAE_COMMAND_ERR_POLICY_SHIFT);
1638
1639#ifdef __BIG_ENDIAN
1640    opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1641#else
1642    opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1643#endif
1644
1645    if (with_comp) {
1646        opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1647    }
1648
1649    return (opcode);
1650}
1651
1652static void
1653bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1654                        struct dmae_command *dmae,
1655                        uint8_t             src_type,
1656                        uint8_t             dst_type)
1657{
1658    memset(dmae, 0, sizeof(struct dmae_command));
1659
1660    /* set the opcode */
1661    dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1662                                   TRUE, DMAE_COMP_PCI);
1663
1664    /* fill in the completion parameters */
1665    dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1666    dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1667    dmae->comp_val     = DMAE_COMP_VAL;
1668}
1669
1670/* issue a DMAE command over the init channel and wait for completion */
1671static int
1672bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1673                         struct dmae_command *dmae)
1674{
1675    uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1676    int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1677
1678    BXE_DMAE_LOCK(sc);
1679
1680    /* reset completion */
1681    *wb_comp = 0;
1682
1683    /* post the command on the channel used for initializations */
1684    bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1685
1686    /* wait for completion */
1687    DELAY(5);
1688
1689    while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1690        if (!timeout ||
1691            (sc->recovery_state != BXE_RECOVERY_DONE &&
1692             sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1693            BLOGE(sc, "DMAE timeout!\n");
1694            BXE_DMAE_UNLOCK(sc);
1695            return (DMAE_TIMEOUT);
1696        }
1697
1698        timeout--;
1699        DELAY(50);
1700    }
1701
1702    if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1703        BLOGE(sc, "DMAE PCI error!\n");
1704        BXE_DMAE_UNLOCK(sc);
1705        return (DMAE_PCI_ERROR);
1706    }
1707
1708    BXE_DMAE_UNLOCK(sc);
1709    return (0);
1710}
1711
1712void
1713bxe_read_dmae(struct bxe_softc *sc,
1714              uint32_t         src_addr,
1715              uint32_t         len32)
1716{
1717    struct dmae_command dmae;
1718    uint32_t *data;
1719    int i, rc;
1720
1721    DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1722
1723    if (!sc->dmae_ready) {
1724        data = BXE_SP(sc, wb_data[0]);
1725
1726        for (i = 0; i < len32; i++) {
1727            data[i] = (CHIP_IS_E1(sc)) ?
1728                          bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1729                          REG_RD(sc, (src_addr + (i * 4)));
1730        }
1731
1732        return;
1733    }
1734
1735    /* set opcode and fixed command fields */
1736    bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1737
1738    /* fill in addresses and len */
1739    dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1740    dmae.src_addr_hi = 0;
1741    dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1742    dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1743    dmae.len         = len32;
1744
1745    /* issue the command and wait for completion */
1746    if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1747        bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1748    };
1749}
1750
1751void
1752bxe_write_dmae(struct bxe_softc *sc,
1753               bus_addr_t       dma_addr,
1754               uint32_t         dst_addr,
1755               uint32_t         len32)
1756{
1757    struct dmae_command dmae;
1758    int rc;
1759
1760    if (!sc->dmae_ready) {
1761        DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1762
1763        if (CHIP_IS_E1(sc)) {
1764            ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1765        } else {
1766            ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1767        }
1768
1769        return;
1770    }
1771
1772    /* set opcode and fixed command fields */
1773    bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1774
1775    /* fill in addresses and len */
1776    dmae.src_addr_lo = U64_LO(dma_addr);
1777    dmae.src_addr_hi = U64_HI(dma_addr);
1778    dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1779    dmae.dst_addr_hi = 0;
1780    dmae.len         = len32;
1781
1782    /* issue the command and wait for completion */
1783    if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1784        bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1785    }
1786}
1787
1788void
1789bxe_write_dmae_phys_len(struct bxe_softc *sc,
1790                        bus_addr_t       phys_addr,
1791                        uint32_t         addr,
1792                        uint32_t         len)
1793{
1794    int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1795    int offset = 0;
1796
1797    while (len > dmae_wr_max) {
1798        bxe_write_dmae(sc,
1799                       (phys_addr + offset), /* src DMA address */
1800                       (addr + offset),      /* dst GRC address */
1801                       dmae_wr_max);
1802        offset += (dmae_wr_max * 4);
1803        len -= dmae_wr_max;
1804    }
1805
1806    bxe_write_dmae(sc,
1807                   (phys_addr + offset), /* src DMA address */
1808                   (addr + offset),      /* dst GRC address */
1809                   len);
1810}
1811
1812void
1813bxe_set_ctx_validation(struct bxe_softc   *sc,
1814                       struct eth_context *cxt,
1815                       uint32_t           cid)
1816{
1817    /* ustorm cxt validation */
1818    cxt->ustorm_ag_context.cdu_usage =
1819        CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1820            CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1821    /* xcontext validation */
1822    cxt->xstorm_ag_context.cdu_reserved =
1823        CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1824            CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1825}
1826
1827static void
1828bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1829                            uint8_t          port,
1830                            uint8_t          fw_sb_id,
1831                            uint8_t          sb_index,
1832                            uint8_t          ticks)
1833{
1834    uint32_t addr =
1835        (BAR_CSTRORM_INTMEM +
1836         CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1837
1838    REG_WR8(sc, addr, ticks);
1839
1840    BLOGD(sc, DBG_LOAD,
1841          "port %d fw_sb_id %d sb_index %d ticks %d\n",
1842          port, fw_sb_id, sb_index, ticks);
1843}
1844
1845static void
1846bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1847                            uint8_t          port,
1848                            uint16_t         fw_sb_id,
1849                            uint8_t          sb_index,
1850                            uint8_t          disable)
1851{
1852    uint32_t enable_flag =
1853        (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1854    uint32_t addr =
1855        (BAR_CSTRORM_INTMEM +
1856         CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1857    uint8_t flags;
1858
1859    /* clear and set */
1860    flags = REG_RD8(sc, addr);
1861    flags &= ~HC_INDEX_DATA_HC_ENABLED;
1862    flags |= enable_flag;
1863    REG_WR8(sc, addr, flags);
1864
1865    BLOGD(sc, DBG_LOAD,
1866          "port %d fw_sb_id %d sb_index %d disable %d\n",
1867          port, fw_sb_id, sb_index, disable);
1868}
1869
1870void
1871bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1872                             uint8_t          fw_sb_id,
1873                             uint8_t          sb_index,
1874                             uint8_t          disable,
1875                             uint16_t         usec)
1876{
1877    int port = SC_PORT(sc);
1878    uint8_t ticks = (usec / 4); /* XXX ??? */
1879
1880    bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1881
1882    disable = (disable) ? 1 : ((usec) ? 0 : 1);
1883    bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1884}
1885
1886void
1887elink_cb_udelay(struct bxe_softc *sc,
1888                uint32_t         usecs)
1889{
1890    DELAY(usecs);
1891}
1892
1893uint32_t
1894elink_cb_reg_read(struct bxe_softc *sc,
1895                  uint32_t         reg_addr)
1896{
1897    return (REG_RD(sc, reg_addr));
1898}
1899
1900void
1901elink_cb_reg_write(struct bxe_softc *sc,
1902                   uint32_t         reg_addr,
1903                   uint32_t         val)
1904{
1905    REG_WR(sc, reg_addr, val);
1906}
1907
1908void
1909elink_cb_reg_wb_write(struct bxe_softc *sc,
1910                      uint32_t         offset,
1911                      uint32_t         *wb_write,
1912                      uint16_t         len)
1913{
1914    REG_WR_DMAE(sc, offset, wb_write, len);
1915}
1916
1917void
1918elink_cb_reg_wb_read(struct bxe_softc *sc,
1919                     uint32_t         offset,
1920                     uint32_t         *wb_write,
1921                     uint16_t         len)
1922{
1923    REG_RD_DMAE(sc, offset, wb_write, len);
1924}
1925
1926uint8_t
1927elink_cb_path_id(struct bxe_softc *sc)
1928{
1929    return (SC_PATH(sc));
1930}
1931
1932void
1933elink_cb_event_log(struct bxe_softc     *sc,
1934                   const elink_log_id_t elink_log_id,
1935                   ...)
1936{
1937    /* XXX */
1938#if 0
1939    //va_list ap;
1940    va_start(ap, elink_log_id);
1941    _XXX_(sc, lm_log_id, ap);
1942    va_end(ap);
1943#endif
1944    BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1945}
1946
1947static int
1948bxe_set_spio(struct bxe_softc *sc,
1949             int              spio,
1950             uint32_t         mode)
1951{
1952    uint32_t spio_reg;
1953
1954    /* Only 2 SPIOs are configurable */
1955    if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1956        BLOGE(sc, "Invalid SPIO 0x%x\n", spio);
1957        return (-1);
1958    }
1959
1960    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1961
1962    /* read SPIO and mask except the float bits */
1963    spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1964
1965    switch (mode) {
1966    case MISC_SPIO_OUTPUT_LOW:
1967        BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1968        /* clear FLOAT and set CLR */
1969        spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1970        spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1971        break;
1972
1973    case MISC_SPIO_OUTPUT_HIGH:
1974        BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1975        /* clear FLOAT and set SET */
1976        spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1977        spio_reg |=  (spio << MISC_SPIO_SET_POS);
1978        break;
1979
1980    case MISC_SPIO_INPUT_HI_Z:
1981        BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1982        /* set FLOAT */
1983        spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1984        break;
1985
1986    default:
1987        break;
1988    }
1989
1990    REG_WR(sc, MISC_REG_SPIO, spio_reg);
1991    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1992
1993    return (0);
1994}
1995
1996static int
1997bxe_gpio_read(struct bxe_softc *sc,
1998              int              gpio_num,
1999              uint8_t          port)
2000{
2001    /* The GPIO should be swapped if swap register is set and active */
2002    int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2003                      REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2004    int gpio_shift = (gpio_num +
2005                      (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2006    uint32_t gpio_mask = (1 << gpio_shift);
2007    uint32_t gpio_reg;
2008
2009    if (gpio_num > MISC_REGISTERS_GPIO_3) {
2010        BLOGE(sc, "Invalid GPIO %d\n", gpio_num);
2011        return (-1);
2012    }
2013
2014    /* read GPIO value */
2015    gpio_reg = REG_RD(sc, MISC_REG_GPIO);
2016
2017    /* get the requested pin value */
2018    return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
2019}
2020
2021static int
2022bxe_gpio_write(struct bxe_softc *sc,
2023               int              gpio_num,
2024               uint32_t         mode,
2025               uint8_t          port)
2026{
2027    /* The GPIO should be swapped if swap register is set and active */
2028    int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2029                      REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2030    int gpio_shift = (gpio_num +
2031                      (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2032    uint32_t gpio_mask = (1 << gpio_shift);
2033    uint32_t gpio_reg;
2034
2035    if (gpio_num > MISC_REGISTERS_GPIO_3) {
2036        BLOGE(sc, "Invalid GPIO %d\n", gpio_num);
2037        return (-1);
2038    }
2039
2040    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2041
2042    /* read GPIO and mask except the float bits */
2043    gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
2044
2045    switch (mode) {
2046    case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2047        BLOGD(sc, DBG_PHY,
2048              "Set GPIO %d (shift %d) -> output low\n",
2049              gpio_num, gpio_shift);
2050        /* clear FLOAT and set CLR */
2051        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
2052        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
2053        break;
2054
2055    case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2056        BLOGD(sc, DBG_PHY,
2057              "Set GPIO %d (shift %d) -> output high\n",
2058              gpio_num, gpio_shift);
2059        /* clear FLOAT and set SET */
2060        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
2061        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
2062        break;
2063
2064    case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2065        BLOGD(sc, DBG_PHY,
2066              "Set GPIO %d (shift %d) -> input\n",
2067              gpio_num, gpio_shift);
2068        /* set FLOAT */
2069        gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
2070        break;
2071
2072    default:
2073        break;
2074    }
2075
2076    REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2077    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2078
2079    return (0);
2080}
2081
2082static int
2083bxe_gpio_mult_write(struct bxe_softc *sc,
2084                    uint8_t          pins,
2085                    uint32_t         mode)
2086{
2087    uint32_t gpio_reg;
2088
2089    /* any port swapping should be handled by caller */
2090
2091    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2092
2093    /* read GPIO and mask except the float bits */
2094    gpio_reg = REG_RD(sc, MISC_REG_GPIO);
2095    gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2096    gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
2097    gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
2098
2099    switch (mode) {
2100    case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2101        BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
2102        /* set CLR */
2103        gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
2104        break;
2105
2106    case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2107        BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
2108        /* set SET */
2109        gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2110        break;
2111
2112    case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2113        BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2114        /* set FLOAT */
2115        gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2116        break;
2117
2118    default:
2119        BLOGE(sc, "Invalid GPIO mode assignment %d\n", mode);
2120        bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2121        return (-1);
2122    }
2123
2124    REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2125    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2126
2127    return (0);
2128}
2129
2130static int
2131bxe_gpio_int_write(struct bxe_softc *sc,
2132                   int              gpio_num,
2133                   uint32_t         mode,
2134                   uint8_t          port)
2135{
2136    /* The GPIO should be swapped if swap register is set and active */
2137    int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2138                      REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2139    int gpio_shift = (gpio_num +
2140                      (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2141    uint32_t gpio_mask = (1 << gpio_shift);
2142    uint32_t gpio_reg;
2143
2144    if (gpio_num > MISC_REGISTERS_GPIO_3) {
2145        BLOGE(sc, "Invalid GPIO %d\n", gpio_num);
2146        return (-1);
2147    }
2148
2149    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2150
2151    /* read GPIO int */
2152    gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2153
2154    switch (mode) {
2155    case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2156        BLOGD(sc, DBG_PHY,
2157              "Clear GPIO INT %d (shift %d) -> output low\n",
2158              gpio_num, gpio_shift);
2159        /* clear SET and set CLR */
2160        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2161        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2162        break;
2163
2164    case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2165        BLOGD(sc, DBG_PHY,
2166              "Set GPIO INT %d (shift %d) -> output high\n",
2167              gpio_num, gpio_shift);
2168        /* clear CLR and set SET */
2169        gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2170        gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2171        break;
2172
2173    default:
2174        break;
2175    }
2176
2177    REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2178    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2179
2180    return (0);
2181}
2182
2183uint32_t
2184elink_cb_gpio_read(struct bxe_softc *sc,
2185                   uint16_t         gpio_num,
2186                   uint8_t          port)
2187{
2188    return (bxe_gpio_read(sc, gpio_num, port));
2189}
2190
2191uint8_t
2192elink_cb_gpio_write(struct bxe_softc *sc,
2193                    uint16_t         gpio_num,
2194                    uint8_t          mode, /* 0=low 1=high */
2195                    uint8_t          port)
2196{
2197    return (bxe_gpio_write(sc, gpio_num, mode, port));
2198}
2199
2200uint8_t
2201elink_cb_gpio_mult_write(struct bxe_softc *sc,
2202                         uint8_t          pins,
2203                         uint8_t          mode) /* 0=low 1=high */
2204{
2205    return (bxe_gpio_mult_write(sc, pins, mode));
2206}
2207
2208uint8_t
2209elink_cb_gpio_int_write(struct bxe_softc *sc,
2210                        uint16_t         gpio_num,
2211                        uint8_t          mode, /* 0=low 1=high */
2212                        uint8_t          port)
2213{
2214    return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2215}
2216
2217void
2218elink_cb_notify_link_changed(struct bxe_softc *sc)
2219{
2220    REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2221                (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2222}
2223
2224/* send the MCP a request, block until there is a reply */
2225uint32_t
2226elink_cb_fw_command(struct bxe_softc *sc,
2227                    uint32_t         command,
2228                    uint32_t         param)
2229{
2230    int mb_idx = SC_FW_MB_IDX(sc);
2231    uint32_t seq;
2232    uint32_t rc = 0;
2233    uint32_t cnt = 1;
2234    uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2235
2236    BXE_FWMB_LOCK(sc);
2237
2238    seq = ++sc->fw_seq;
2239    SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2240    SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2241
2242    BLOGD(sc, DBG_PHY,
2243          "wrote command 0x%08x to FW MB param 0x%08x\n",
2244          (command | seq), param);
2245
2246    /* Let the FW do it's magic. GIve it up to 5 seconds... */
2247    do {
2248        DELAY(delay * 1000);
2249        rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2250    } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2251
2252    BLOGD(sc, DBG_PHY,
2253          "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2254          cnt*delay, rc, seq);
2255
2256    /* is this a reply to our command? */
2257    if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2258        rc &= FW_MSG_CODE_MASK;
2259    } else {
2260        /* Ruh-roh! */
2261        BLOGE(sc, "FW failed to respond!\n");
2262        // XXX bxe_fw_dump(sc);
2263        rc = 0;
2264    }
2265
2266    BXE_FWMB_UNLOCK(sc);
2267    return (rc);
2268}
2269
2270static uint32_t
2271bxe_fw_command(struct bxe_softc *sc,
2272               uint32_t         command,
2273               uint32_t         param)
2274{
2275    return (elink_cb_fw_command(sc, command, param));
2276}
2277
2278static void
2279__storm_memset_dma_mapping(struct bxe_softc *sc,
2280                           uint32_t         addr,
2281                           bus_addr_t       mapping)
2282{
2283    REG_WR(sc, addr, U64_LO(mapping));
2284    REG_WR(sc, (addr + 4), U64_HI(mapping));
2285}
2286
2287static void
2288storm_memset_spq_addr(struct bxe_softc *sc,
2289                      bus_addr_t       mapping,
2290                      uint16_t         abs_fid)
2291{
2292    uint32_t addr = (XSEM_REG_FAST_MEMORY +
2293                     XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2294    __storm_memset_dma_mapping(sc, addr, mapping);
2295}
2296
2297static void
2298storm_memset_vf_to_pf(struct bxe_softc *sc,
2299                      uint16_t         abs_fid,
2300                      uint16_t         pf_id)
2301{
2302    REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2303    REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2304    REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2305    REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2306}
2307
2308static void
2309storm_memset_func_en(struct bxe_softc *sc,
2310                     uint16_t         abs_fid,
2311                     uint8_t          enable)
2312{
2313    REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2314    REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2315    REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2316    REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2317}
2318
2319static void
2320storm_memset_eq_data(struct bxe_softc       *sc,
2321                     struct event_ring_data *eq_data,
2322                     uint16_t               pfid)
2323{
2324    uint32_t addr;
2325    size_t size;
2326
2327    addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2328    size = sizeof(struct event_ring_data);
2329    ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2330}
2331
2332static void
2333storm_memset_eq_prod(struct bxe_softc *sc,
2334                     uint16_t         eq_prod,
2335                     uint16_t         pfid)
2336{
2337    uint32_t addr = (BAR_CSTRORM_INTMEM +
2338                     CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2339    REG_WR16(sc, addr, eq_prod);
2340}
2341
2342/*
2343 * Post a slowpath command.
2344 *
2345 * A slowpath command is used to propogate a configuration change through
2346 * the controller in a controlled manner, allowing each STORM processor and
2347 * other H/W blocks to phase in the change.  The commands sent on the
2348 * slowpath are referred to as ramrods.  Depending on the ramrod used the
2349 * completion of the ramrod will occur in different ways.  Here's a
2350 * breakdown of ramrods and how they complete:
2351 *
2352 * RAMROD_CMD_ID_ETH_PORT_SETUP
2353 *   Used to setup the leading connection on a port.  Completes on the
2354 *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2355 *
2356 * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2357 *   Used to setup an additional connection on a port.  Completes on the
2358 *   RCQ of the multi-queue/RSS connection being initialized.
2359 *
2360 * RAMROD_CMD_ID_ETH_STAT_QUERY
2361 *   Used to force the storm processors to update the statistics database
2362 *   in host memory.  This ramrod is send on the leading connection CID and
2363 *   completes as an index increment of the CSTORM on the default status
2364 *   block.
2365 *
2366 * RAMROD_CMD_ID_ETH_UPDATE
2367 *   Used to update the state of the leading connection, usually to udpate
2368 *   the RSS indirection table.  Completes on the RCQ of the leading
2369 *   connection. (Not currently used under FreeBSD until OS support becomes
2370 *   available.)
2371 *
2372 * RAMROD_CMD_ID_ETH_HALT
2373 *   Used when tearing down a connection prior to driver unload.  Completes
2374 *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2375 *   use this on the leading connection.
2376 *
2377 * RAMROD_CMD_ID_ETH_SET_MAC
2378 *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2379 *   the RCQ of the leading connection.
2380 *
2381 * RAMROD_CMD_ID_ETH_CFC_DEL
2382 *   Used when tearing down a conneciton prior to driver unload.  Completes
2383 *   on the RCQ of the leading connection (since the current connection
2384 *   has been completely removed from controller memory).
2385 *
2386 * RAMROD_CMD_ID_ETH_PORT_DEL
2387 *   Used to tear down the leading connection prior to driver unload,
2388 *   typically fp[0].  Completes as an index increment of the CSTORM on the
2389 *   default status block.
2390 *
2391 * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2392 *   Used for connection offload.  Completes on the RCQ of the multi-queue
2393 *   RSS connection that is being offloaded.  (Not currently used under
2394 *   FreeBSD.)
2395 *
2396 * There can only be one command pending per function.
2397 *
2398 * Returns:
2399 *   0 = Success, !0 = Failure.
2400 */
2401
2402/* must be called under the spq lock */
2403static inline
2404struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2405{
2406    struct eth_spe *next_spe = sc->spq_prod_bd;
2407
2408    if (sc->spq_prod_bd == sc->spq_last_bd) {
2409        /* wrap back to the first eth_spq */
2410        sc->spq_prod_bd = sc->spq;
2411        sc->spq_prod_idx = 0;
2412    } else {
2413        sc->spq_prod_bd++;
2414        sc->spq_prod_idx++;
2415    }
2416
2417    return (next_spe);
2418}
2419
2420/* must be called under the spq lock */
2421static inline
2422void bxe_sp_prod_update(struct bxe_softc *sc)
2423{
2424    int func = SC_FUNC(sc);
2425
2426    /*
2427     * Make sure that BD data is updated before writing the producer.
2428     * BD data is written to the memory, the producer is read from the
2429     * memory, thus we need a full memory barrier to ensure the ordering.
2430     */
2431    mb();
2432
2433    REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2434             sc->spq_prod_idx);
2435
2436    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2437                      BUS_SPACE_BARRIER_WRITE);
2438}
2439
2440/**
2441 * bxe_is_contextless_ramrod - check if the current command ends on EQ
2442 *
2443 * @cmd:      command to check
2444 * @cmd_type: command type
2445 */
2446static inline
2447int bxe_is_contextless_ramrod(int cmd,
2448                              int cmd_type)
2449{
2450    if ((cmd_type == NONE_CONNECTION_TYPE) ||
2451        (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2452        (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2453        (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2454        (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2455        (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2456        (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2457        return (TRUE);
2458    } else {
2459        return (FALSE);
2460    }
2461}
2462
2463/**
2464 * bxe_sp_post - place a single command on an SP ring
2465 *
2466 * @sc:         driver handle
2467 * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2468 * @cid:        SW CID the command is related to
2469 * @data_hi:    command private data address (high 32 bits)
2470 * @data_lo:    command private data address (low 32 bits)
2471 * @cmd_type:   command type (e.g. NONE, ETH)
2472 *
2473 * SP data is handled as if it's always an address pair, thus data fields are
2474 * not swapped to little endian in upper functions. Instead this function swaps
2475 * data as if it's two uint32 fields.
2476 */
2477int
2478bxe_sp_post(struct bxe_softc *sc,
2479            int              command,
2480            int              cid,
2481            uint32_t         data_hi,
2482            uint32_t         data_lo,
2483            int              cmd_type)
2484{
2485    struct eth_spe *spe;
2486    uint16_t type;
2487    int common;
2488
2489    common = bxe_is_contextless_ramrod(command, cmd_type);
2490
2491    BXE_SP_LOCK(sc);
2492
2493    if (common) {
2494        if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2495            BLOGE(sc, "EQ ring is full!\n");
2496            BXE_SP_UNLOCK(sc);
2497            return (-1);
2498        }
2499    } else {
2500        if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2501            BLOGE(sc, "SPQ ring is full!\n");
2502            BXE_SP_UNLOCK(sc);
2503            return (-1);
2504        }
2505    }
2506
2507    spe = bxe_sp_get_next(sc);
2508
2509    /* CID needs port number to be encoded int it */
2510    spe->hdr.conn_and_cmd_data =
2511        htole32((command << SPE_HDR_CMD_ID_SHIFT) | HW_CID(sc, cid));
2512
2513    type = (cmd_type << SPE_HDR_CONN_TYPE_SHIFT) & SPE_HDR_CONN_TYPE;
2514
2515    /* TBD: Check if it works for VFs */
2516    type |= ((SC_FUNC(sc) << SPE_HDR_FUNCTION_ID_SHIFT) &
2517             SPE_HDR_FUNCTION_ID);
2518
2519    spe->hdr.type = htole16(type);
2520
2521    spe->data.update_data_addr.hi = htole32(data_hi);
2522    spe->data.update_data_addr.lo = htole32(data_lo);
2523
2524    /*
2525     * It's ok if the actual decrement is issued towards the memory
2526     * somewhere between the lock and unlock. Thus no more explict
2527     * memory barrier is needed.
2528     */
2529    if (common) {
2530        atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2531    } else {
2532        atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2533    }
2534
2535    BLOGD(sc, DBG_SP, "SPQE -> %p\n", (void *)sc->spq_dma.paddr);
2536    BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %p\n",
2537          BXE_SP(sc, func_rdata), (void *)BXE_SP_MAPPING(sc, func_rdata));
2538    BLOGD(sc, DBG_SP,
2539          "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2540          sc->spq_prod_idx,
2541          (uint32_t)U64_HI(sc->spq_dma.paddr),
2542          (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2543          command,
2544          common,
2545          HW_CID(sc, cid),
2546          data_hi,
2547          data_lo,
2548          type,
2549          atomic_load_acq_long(&sc->cq_spq_left),
2550          atomic_load_acq_long(&sc->eq_spq_left));
2551
2552    bxe_sp_prod_update(sc);
2553
2554    BXE_SP_UNLOCK(sc);
2555    return (0);
2556}
2557
2558/**
2559 * bxe_debug_print_ind_table - prints the indirection table configuration.
2560 *
2561 * @sc: driver hanlde
2562 * @p:  pointer to rss configuration
2563 */
2564#if 0
2565static void
2566bxe_debug_print_ind_table(struct bxe_softc               *sc,
2567                          struct ecore_config_rss_params *p)
2568{
2569    int i;
2570
2571    BLOGD(sc, DBG_LOAD, "Setting indirection table to:\n");
2572    BLOGD(sc, DBG_LOAD, "    0x0000: ");
2573    for (i = 0; i < T_ETH_INDIRECTION_TABLE_SIZE; i++) {
2574        BLOGD(sc, DBG_LOAD, "0x%02x ", p->ind_table[i]);
2575
2576        /* Print 4 bytes in a line */
2577        if ((i + 1 < T_ETH_INDIRECTION_TABLE_SIZE) &&
2578            (((i + 1) & 0x3) == 0)) {
2579            BLOGD(sc, DBG_LOAD, "\n");
2580            BLOGD(sc, DBG_LOAD, "0x%04x: ", i + 1);
2581        }
2582    }
2583
2584    BLOGD(sc, DBG_LOAD, "\n");
2585}
2586#endif
2587
2588/*
2589 * FreeBSD Device probe function.
2590 *
2591 * Compares the device found to the driver's list of supported devices and
2592 * reports back to the bsd loader whether this is the right driver for the device.
2593 * This is the driver entry function called from the "kldload" command.
2594 *
2595 * Returns:
2596 *   BUS_PROBE_DEFAULT on success, positive value on failure.
2597 */
2598static int
2599bxe_probe(device_t dev)
2600{
2601    struct bxe_softc *sc;
2602    struct bxe_device_type *t;
2603    char *descbuf;
2604    uint16_t did, sdid, svid, vid;
2605
2606    /* Find our device structure */
2607    sc = device_get_softc(dev);
2608    sc->dev = dev;
2609    t = bxe_devs;
2610
2611    /* Get the data for the device to be probed. */
2612    vid  = pci_get_vendor(dev);
2613    did  = pci_get_device(dev);
2614    svid = pci_get_subvendor(dev);
2615    sdid = pci_get_subdevice(dev);
2616
2617    BLOGD(sc, DBG_LOAD,
2618          "%s(); VID = 0x%04X, DID = 0x%04X, SVID = 0x%04X, "
2619          "SDID = 0x%04X\n", __FUNCTION__, vid, did, svid, sdid);
2620
2621    /* Look through the list of known devices for a match. */
2622    while (t->bxe_name != NULL) {
2623        if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2624            ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2625            ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2626            descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2627            if (descbuf == NULL)
2628                return (ENOMEM);
2629
2630            /* Print out the device identity. */
2631            snprintf(descbuf, BXE_DEVDESC_MAX,
2632                     "%s (%c%d) BXE v:%s\n", t->bxe_name,
2633                     (((pci_read_config(dev, PCIR_REVID, 4) &
2634                        0xf0) >> 4) + 'A'),
2635                     (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2636                     BXE_DRIVER_VERSION);
2637
2638            device_set_desc_copy(dev, descbuf);
2639            free(descbuf, M_TEMP);
2640            return (BUS_PROBE_DEFAULT);
2641        }
2642        t++;
2643    }
2644
2645    return (ENXIO);
2646}
2647
2648static void
2649bxe_init_mutexes(struct bxe_softc *sc)
2650{
2651#ifdef BXE_CORE_LOCK_SX
2652    snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2653             "bxe%d_core_lock", sc->unit);
2654    sx_init(&sc->core_sx, sc->core_sx_name);
2655#else
2656    snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2657             "bxe%d_core_lock", sc->unit);
2658    mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2659#endif
2660
2661    snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2662             "bxe%d_sp_lock", sc->unit);
2663    mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2664
2665    snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2666             "bxe%d_dmae_lock", sc->unit);
2667    mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2668
2669    snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2670             "bxe%d_phy_lock", sc->unit);
2671    mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2672
2673    snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2674             "bxe%d_fwmb_lock", sc->unit);
2675    mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2676
2677    snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2678             "bxe%d_print_lock", sc->unit);
2679    mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2680
2681    snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2682             "bxe%d_stats_lock", sc->unit);
2683    mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2684
2685    snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2686             "bxe%d_mcast_lock", sc->unit);
2687    mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2688}
2689
2690static void
2691bxe_release_mutexes(struct bxe_softc *sc)
2692{
2693#ifdef BXE_CORE_LOCK_SX
2694    sx_destroy(&sc->core_sx);
2695#else
2696    if (mtx_initialized(&sc->core_mtx)) {
2697        mtx_destroy(&sc->core_mtx);
2698    }
2699#endif
2700
2701    if (mtx_initialized(&sc->sp_mtx)) {
2702        mtx_destroy(&sc->sp_mtx);
2703    }
2704
2705    if (mtx_initialized(&sc->dmae_mtx)) {
2706        mtx_destroy(&sc->dmae_mtx);
2707    }
2708
2709    if (mtx_initialized(&sc->port.phy_mtx)) {
2710        mtx_destroy(&sc->port.phy_mtx);
2711    }
2712
2713    if (mtx_initialized(&sc->fwmb_mtx)) {
2714        mtx_destroy(&sc->fwmb_mtx);
2715    }
2716
2717    if (mtx_initialized(&sc->print_mtx)) {
2718        mtx_destroy(&sc->print_mtx);
2719    }
2720
2721    if (mtx_initialized(&sc->stats_mtx)) {
2722        mtx_destroy(&sc->stats_mtx);
2723    }
2724
2725    if (mtx_initialized(&sc->mcast_mtx)) {
2726        mtx_destroy(&sc->mcast_mtx);
2727    }
2728}
2729
2730static void
2731bxe_tx_disable(struct bxe_softc* sc)
2732{
2733    struct ifnet *ifp = sc->ifnet;
2734
2735    /* tell the stack the driver is stopped and TX queue is full */
2736    if (ifp != NULL) {
2737        ifp->if_drv_flags = 0;
2738    }
2739}
2740
2741static void
2742bxe_drv_pulse(struct bxe_softc *sc)
2743{
2744    SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2745             sc->fw_drv_pulse_wr_seq);
2746}
2747
2748static inline int
2749bxe_has_tx_work_unload(struct bxe_fastpath *fp)
2750{
2751    mb(); /* consumer and producer can change */
2752    return (fp->tx_pkt_prod != fp->tx_pkt_cons);
2753}
2754
2755static inline uint16_t
2756bxe_tx_avail(struct bxe_softc *sc,
2757             struct bxe_fastpath *fp)
2758{
2759    int16_t  used;
2760    uint16_t prod;
2761    uint16_t cons;
2762
2763    prod = fp->tx_bd_prod;
2764    cons = fp->tx_bd_cons;
2765
2766    used = SUB_S16(prod, cons);
2767
2768#if 0
2769    KASSERT((used < 0), ("used tx bds < 0"));
2770    KASSERT((used > sc->tx_ring_size), ("used tx bds > tx_ring_size"));
2771    KASSERT(((sc->tx_ring_size - used) > MAX_TX_AVAIL),
2772            ("invalid number of tx bds used"));
2773#endif
2774
2775    return (int16_t)(sc->tx_ring_size) - used;
2776}
2777
2778static inline int
2779bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2780{
2781    uint16_t hw_cons;
2782
2783    mb(); /* status block fields can change */
2784    hw_cons = le16toh(*fp->tx_cons_sb);
2785    return (hw_cons != fp->tx_pkt_cons);
2786}
2787
2788static inline uint8_t
2789bxe_has_tx_work(struct bxe_fastpath *fp)
2790{
2791    /* expand this for multi-cos if ever supported */
2792    return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2793}
2794
2795static inline int
2796bxe_has_rx_work(struct bxe_fastpath *fp)
2797{
2798    uint16_t rx_cq_cons_sb;
2799
2800    mb(); /* status block fields can change */
2801    rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2802    if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2803        rx_cq_cons_sb++;
2804    return (fp->rx_cq_cons != rx_cq_cons_sb);
2805}
2806
2807static void
2808bxe_sp_event(struct bxe_softc    *sc,
2809             struct bxe_fastpath *fp,
2810             union eth_rx_cqe    *rr_cqe)
2811{
2812    int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2813    int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2814    enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2815    struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2816
2817    BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2818          fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2819
2820#if 0
2821    /*
2822     * If cid is within VF range, replace the slowpath object with the
2823     * one corresponding to this VF
2824     */
2825    if ((cid >= BXE_FIRST_VF_CID) && (cid < BXE_FIRST_VF_CID + BXE_VF_CIDS)) {
2826        bxe_iov_set_queue_sp_obj(sc, cid, &q_obj);
2827    }
2828#endif
2829
2830    switch (command) {
2831    case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2832        BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2833        drv_cmd = ECORE_Q_CMD_UPDATE;
2834        break;
2835
2836    case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2837        BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2838        drv_cmd = ECORE_Q_CMD_SETUP;
2839        break;
2840
2841    case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2842        BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2843        drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2844        break;
2845
2846    case (RAMROD_CMD_ID_ETH_HALT):
2847        BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2848        drv_cmd = ECORE_Q_CMD_HALT;
2849        break;
2850
2851    case (RAMROD_CMD_ID_ETH_TERMINATE):
2852        BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2853        drv_cmd = ECORE_Q_CMD_TERMINATE;
2854        break;
2855
2856    case (RAMROD_CMD_ID_ETH_EMPTY):
2857        BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2858        drv_cmd = ECORE_Q_CMD_EMPTY;
2859        break;
2860
2861    default:
2862        BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2863              command, fp->index);
2864        return;
2865    }
2866
2867    if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2868        q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2869        /*
2870         * q_obj->complete_cmd() failure means that this was
2871         * an unexpected completion.
2872         *
2873         * In this case we don't want to increase the sc->spq_left
2874         * because apparently we haven't sent this command the first
2875         * place.
2876         */
2877        // bxe_panic(sc, ("Unexpected SP completion\n"));
2878        return;
2879    }
2880
2881#if 0
2882    /* SRIOV: reschedule any 'in_progress' operations */
2883    bxe_iov_sp_event(sc, cid, TRUE);
2884#endif
2885
2886    atomic_add_acq_long(&sc->cq_spq_left, 1);
2887
2888    BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2889          atomic_load_acq_long(&sc->cq_spq_left));
2890
2891#if 0
2892    if ((drv_cmd == ECORE_Q_CMD_UPDATE) && (IS_FCOE_FP(fp)) &&
2893        (!!bxe_test_bit(ECORE_AFEX_FCOE_Q_UPDATE_PENDING, &sc->sp_state))) {
2894        /*
2895         * If Queue update ramrod is completed for last Queue in AFEX VIF set
2896         * flow, then ACK MCP at the end. Mark pending ACK to MCP bit to
2897         * prevent case that both bits are cleared. At the end of load/unload
2898         * driver checks that sp_state is cleared and this order prevents
2899         * races.
2900         */
2901        bxe_set_bit(ECORE_AFEX_PENDING_VIFSET_MCP_ACK, &sc->sp_state);
2902        wmb();
2903        bxe_clear_bit(ECORE_AFEX_FCOE_Q_UPDATE_PENDING, &sc->sp_state);
2904
2905        /* schedule the sp task as MCP ack is required */
2906        bxe_schedule_sp_task(sc);
2907    }
2908#endif
2909}
2910
2911/*
2912 * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2913 * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2914 * the current aggregation queue as in-progress.
2915 */
2916static void
2917bxe_tpa_start(struct bxe_softc            *sc,
2918              struct bxe_fastpath         *fp,
2919              uint16_t                    queue,
2920              uint16_t                    cons,
2921              uint16_t                    prod,
2922              struct eth_fast_path_rx_cqe *cqe)
2923{
2924    struct bxe_sw_rx_bd tmp_bd;
2925    struct bxe_sw_rx_bd *rx_buf;
2926    struct eth_rx_bd *rx_bd;
2927    int max_agg_queues;
2928    struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2929    uint16_t index;
2930
2931    BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2932                       "cons=%d prod=%d\n",
2933          fp->index, queue, cons, prod);
2934
2935    max_agg_queues = MAX_AGG_QS(sc);
2936
2937    KASSERT((queue < max_agg_queues),
2938            ("fp[%02d] invalid aggr queue (%d >= %d)!",
2939             fp->index, queue, max_agg_queues));
2940
2941    KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2942            ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2943             fp->index, queue));
2944
2945    /* copy the existing mbuf and mapping from the TPA pool */
2946    tmp_bd = tpa_info->bd;
2947
2948    if (tmp_bd.m == NULL) {
2949        BLOGE(sc, "fp[%02d].tpa[%02d] mbuf not allocated!\n",
2950              fp->index, queue);
2951        /* XXX Error handling? */
2952        return;
2953    }
2954
2955    /* change the TPA queue to the start state */
2956    tpa_info->state            = BXE_TPA_STATE_START;
2957    tpa_info->placement_offset = cqe->placement_offset;
2958    tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2959    tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2960    tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2961
2962    fp->rx_tpa_queue_used |= (1 << queue);
2963
2964    /*
2965     * If all the buffer descriptors are filled with mbufs then fill in
2966     * the current consumer index with a new BD. Else if a maximum Rx
2967     * buffer limit is imposed then fill in the next producer index.
2968     */
2969    index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2970                prod : cons;
2971
2972    /* move the received mbuf and mapping to TPA pool */
2973    tpa_info->bd = fp->rx_mbuf_chain[cons];
2974
2975    /* release any existing RX BD mbuf mappings */
2976    if (cons != index) {
2977        rx_buf = &fp->rx_mbuf_chain[cons];
2978
2979        if (rx_buf->m_map != NULL) {
2980            bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2981                            BUS_DMASYNC_POSTREAD);
2982            bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2983        }
2984
2985        /*
2986         * We get here when the maximum number of rx buffers is less than
2987         * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2988         * it out here without concern of a memory leak.
2989         */
2990        fp->rx_mbuf_chain[cons].m = NULL;
2991    }
2992
2993    /* update the Rx SW BD with the mbuf info from the TPA pool */
2994    fp->rx_mbuf_chain[index] = tmp_bd;
2995
2996    /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2997    rx_bd = &fp->rx_chain[index];
2998    rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2999    rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
3000}
3001
3002/*
3003 * When a TPA aggregation is completed, loop through the individual mbufs
3004 * of the aggregation, combining them into a single mbuf which will be sent
3005 * up the stack. Refill all freed SGEs with mbufs as we go along.
3006 */
3007static int
3008bxe_fill_frag_mbuf(struct bxe_softc          *sc,
3009                   struct bxe_fastpath       *fp,
3010                   struct bxe_sw_tpa_info    *tpa_info,
3011                   uint16_t                  queue,
3012                   uint16_t                  pages,
3013                   struct mbuf               *m,
3014			       struct eth_end_agg_rx_cqe *cqe,
3015                   uint16_t                  cqe_idx)
3016{
3017    struct mbuf *m_frag;
3018    uint32_t frag_len, frag_size, i;
3019    uint16_t sge_idx;
3020    int rc = 0;
3021    int j;
3022
3023    frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
3024
3025    BLOGD(sc, DBG_LRO,
3026          "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
3027          fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
3028
3029    /* make sure the aggregated frame is not too big to handle */
3030    if (pages > 8 * PAGES_PER_SGE) {
3031        BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
3032                  "pkt_len=%d len_on_bd=%d frag_size=%d\n",
3033              fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
3034              tpa_info->len_on_bd, frag_size);
3035        bxe_panic(sc, ("sge page count error\n"));
3036        return (EINVAL);
3037    }
3038
3039    /*
3040     * Scan through the scatter gather list pulling individual mbufs into a
3041     * single mbuf for the host stack.
3042     */
3043    for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
3044        sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
3045
3046        /*
3047         * Firmware gives the indices of the SGE as if the ring is an array
3048         * (meaning that the "next" element will consume 2 indices).
3049         */
3050        frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
3051
3052        BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
3053                           "sge_idx=%d frag_size=%d frag_len=%d\n",
3054              fp->index, queue, i, j, sge_idx, frag_size, frag_len);
3055
3056        m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3057
3058        /* allocate a new mbuf for the SGE */
3059        rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3060        if (rc) {
3061            /* Leave all remaining SGEs in the ring! */
3062            return (rc);
3063        }
3064
3065        /* update the fragment length */
3066        m_frag->m_len = frag_len;
3067
3068        /* concatenate the fragment to the head mbuf */
3069        m_cat(m, m_frag);
3070        fp->eth_q_stats.mbuf_alloc_sge--;
3071
3072        /* update the TPA mbuf size and remaining fragment size */
3073        m->m_pkthdr.len += frag_len;
3074        frag_size -= frag_len;
3075    }
3076
3077    BLOGD(sc, DBG_LRO,
3078          "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
3079          fp->index, queue, frag_size);
3080
3081    return (rc);
3082}
3083
3084static inline void
3085bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
3086{
3087    int i, j;
3088
3089    for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
3090        int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
3091
3092        for (j = 0; j < 2; j++) {
3093            BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
3094            idx--;
3095        }
3096    }
3097}
3098
3099static inline void
3100bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
3101{
3102    /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
3103    memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
3104
3105    /*
3106     * Clear the two last indices in the page to 1. These are the indices that
3107     * correspond to the "next" element, hence will never be indicated and
3108     * should be removed from the calculations.
3109     */
3110    bxe_clear_sge_mask_next_elems(fp);
3111}
3112
3113static inline void
3114bxe_update_last_max_sge(struct bxe_fastpath *fp,
3115                        uint16_t            idx)
3116{
3117    uint16_t last_max = fp->last_max_sge;
3118
3119    if (SUB_S16(idx, last_max) > 0) {
3120        fp->last_max_sge = idx;
3121    }
3122}
3123
3124static inline void
3125bxe_update_sge_prod(struct bxe_softc          *sc,
3126                    struct bxe_fastpath       *fp,
3127                    uint16_t                  sge_len,
3128                    struct eth_end_agg_rx_cqe *cqe)
3129{
3130    uint16_t last_max, last_elem, first_elem;
3131    uint16_t delta = 0;
3132    uint16_t i;
3133
3134    if (!sge_len) {
3135        return;
3136    }
3137
3138    /* first mark all used pages */
3139    for (i = 0; i < sge_len; i++) {
3140        BIT_VEC64_CLEAR_BIT(fp->sge_mask,
3141                            RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[i])));
3142    }
3143
3144    BLOGD(sc, DBG_LRO,
3145          "fp[%02d] fp_cqe->sgl[%d] = %d\n",
3146          fp->index, sge_len - 1,
3147          le16toh(cqe->sgl_or_raw_data.sgl[sge_len - 1]));
3148
3149    /* assume that the last SGE index is the biggest */
3150    bxe_update_last_max_sge(fp,
3151                            le16toh(cqe->sgl_or_raw_data.sgl[sge_len - 1]));
3152
3153    last_max = RX_SGE(fp->last_max_sge);
3154    last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
3155    first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
3156
3157    /* if ring is not full */
3158    if (last_elem + 1 != first_elem) {
3159        last_elem++;
3160    }
3161
3162    /* now update the prod */
3163    for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
3164        if (__predict_true(fp->sge_mask[i])) {
3165            break;
3166        }
3167
3168        fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3169        delta += BIT_VEC64_ELEM_SZ;
3170    }
3171
3172    if (delta > 0) {
3173        fp->rx_sge_prod += delta;
3174        /* clear page-end entries */
3175        bxe_clear_sge_mask_next_elems(fp);
3176    }
3177
3178    BLOGD(sc, DBG_LRO,
3179          "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3180          fp->index, fp->last_max_sge, fp->rx_sge_prod);
3181}
3182
3183/*
3184 * The aggregation on the current TPA queue has completed. Pull the individual
3185 * mbuf fragments together into a single mbuf, perform all necessary checksum
3186 * calculations, and send the resuting mbuf to the stack.
3187 */
3188static void
3189bxe_tpa_stop(struct bxe_softc          *sc,
3190             struct bxe_fastpath       *fp,
3191             struct bxe_sw_tpa_info    *tpa_info,
3192             uint16_t                  queue,
3193             uint16_t                  pages,
3194			 struct eth_end_agg_rx_cqe *cqe,
3195             uint16_t                  cqe_idx)
3196{
3197    struct ifnet *ifp = sc->ifnet;
3198    struct mbuf *m;
3199    int rc = 0;
3200
3201    BLOGD(sc, DBG_LRO,
3202          "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3203          fp->index, queue, tpa_info->placement_offset,
3204          le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3205
3206    m = tpa_info->bd.m;
3207
3208    /* allocate a replacement before modifying existing mbuf */
3209    rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3210    if (rc) {
3211        /* drop the frame and log an error */
3212        fp->eth_q_stats.rx_soft_errors++;
3213        goto bxe_tpa_stop_exit;
3214    }
3215
3216    /* we have a replacement, fixup the current mbuf */
3217    m_adj(m, tpa_info->placement_offset);
3218    m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3219
3220    /* mark the checksums valid (taken care of by the firmware) */
3221    fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3222    fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3223    m->m_pkthdr.csum_data = 0xffff;
3224    m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3225                               CSUM_IP_VALID   |
3226                               CSUM_DATA_VALID |
3227                               CSUM_PSEUDO_HDR);
3228
3229    /* aggregate all of the SGEs into a single mbuf */
3230    rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3231    if (rc) {
3232        /* drop the packet and log an error */
3233        fp->eth_q_stats.rx_soft_errors++;
3234        m_freem(m);
3235    } else {
3236        if (tpa_info->parsing_flags & PARSING_FLAGS_VLAN) {
3237            m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3238            m->m_flags |= M_VLANTAG;
3239        }
3240
3241        /* assign packet to this interface interface */
3242        m->m_pkthdr.rcvif = ifp;
3243
3244#if __FreeBSD_version >= 800000
3245        /* specify what RSS queue was used for this flow */
3246        m->m_pkthdr.flowid = fp->index;
3247        m->m_flags |= M_FLOWID;
3248#endif
3249
3250        ifp->if_ipackets++;
3251        fp->eth_q_stats.rx_tpa_pkts++;
3252
3253        /* pass the frame to the stack */
3254        (*ifp->if_input)(ifp, m);
3255    }
3256
3257    /* we passed an mbuf up the stack or dropped the frame */
3258    fp->eth_q_stats.mbuf_alloc_tpa--;
3259
3260bxe_tpa_stop_exit:
3261
3262    fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3263    fp->rx_tpa_queue_used &= ~(1 << queue);
3264}
3265
3266static uint8_t
3267bxe_rxeof(struct bxe_softc    *sc,
3268          struct bxe_fastpath *fp)
3269{
3270    struct ifnet *ifp = sc->ifnet;
3271    uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3272    uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3273    int rx_pkts = 0;
3274    int rc;
3275
3276    BXE_FP_RX_LOCK(fp);
3277
3278    /* CQ "next element" is of the size of the regular element */
3279    hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3280    if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3281        hw_cq_cons++;
3282    }
3283
3284    bd_cons = fp->rx_bd_cons;
3285    bd_prod = fp->rx_bd_prod;
3286    bd_prod_fw = bd_prod;
3287    sw_cq_cons = fp->rx_cq_cons;
3288    sw_cq_prod = fp->rx_cq_prod;
3289
3290    /*
3291     * Memory barrier necessary as speculative reads of the rx
3292     * buffer can be ahead of the index in the status block
3293     */
3294    rmb();
3295
3296    BLOGD(sc, DBG_RX,
3297          "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3298          fp->index, hw_cq_cons, sw_cq_cons);
3299
3300    while (sw_cq_cons != hw_cq_cons) {
3301        struct bxe_sw_rx_bd *rx_buf = NULL;
3302        union eth_rx_cqe *cqe;
3303        struct eth_fast_path_rx_cqe *cqe_fp;
3304        uint8_t cqe_fp_flags;
3305        enum eth_rx_cqe_type cqe_fp_type;
3306        uint16_t len, pad;
3307        struct mbuf *m = NULL;
3308
3309        comp_ring_cons = RCQ(sw_cq_cons);
3310        bd_prod = RX_BD(bd_prod);
3311        bd_cons = RX_BD(bd_cons);
3312
3313        cqe          = &fp->rcq_chain[comp_ring_cons];
3314        cqe_fp       = &cqe->fast_path_cqe;
3315        cqe_fp_flags = cqe_fp->type_error_flags;
3316        cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3317
3318        BLOGD(sc, DBG_RX,
3319              "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3320              "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3321              "status=0x%x rss_hash=0x%x vlan=0x%x len=%u\n",
3322              fp->index,
3323              hw_cq_cons,
3324              sw_cq_cons,
3325              bd_prod,
3326              bd_cons,
3327              CQE_TYPE(cqe_fp_flags),
3328              cqe_fp_flags,
3329              cqe_fp->status_flags,
3330              le32toh(cqe_fp->rss_hash_result),
3331              le16toh(cqe_fp->vlan_tag),
3332              le16toh(cqe_fp->pkt_len_or_gro_seg_len));
3333
3334        /* is this a slowpath msg? */
3335        if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3336            bxe_sp_event(sc, fp, cqe);
3337            goto next_cqe;
3338        }
3339
3340        rx_buf = &fp->rx_mbuf_chain[bd_cons];
3341
3342        if (!CQE_TYPE_FAST(cqe_fp_type)) {
3343            struct bxe_sw_tpa_info *tpa_info;
3344            uint16_t frag_size, pages;
3345            uint8_t queue;
3346
3347#if 0
3348            /* sanity check */
3349            if (!fp->tpa_enable &&
3350                (CQE_TYPE_START(cqe_fp_type) || CQE_TYPE_STOP(cqe_fp_type))) {
3351                BLOGE(sc, "START/STOP packet while !tpa_enable type (0x%x)\n",
3352                      CQE_TYPE(cqe_fp_type));
3353            }
3354#endif
3355
3356            if (CQE_TYPE_START(cqe_fp_type)) {
3357                bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3358                              bd_cons, bd_prod, cqe_fp);
3359                m = NULL; /* packet not ready yet */
3360                goto next_rx;
3361            }
3362
3363            KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3364                    ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3365
3366            queue = cqe->end_agg_cqe.queue_index;
3367            tpa_info = &fp->rx_tpa_info[queue];
3368
3369            BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3370                  fp->index, queue);
3371
3372            frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3373                         tpa_info->len_on_bd);
3374            pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3375
3376            bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3377                         &cqe->end_agg_cqe, comp_ring_cons);
3378
3379            bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe);
3380
3381            goto next_cqe;
3382        }
3383
3384        /* non TPA */
3385
3386        /* is this an error packet? */
3387        if (__predict_false(cqe_fp_flags &
3388                            ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3389            BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3390            fp->eth_q_stats.rx_soft_errors++;
3391            goto next_rx;
3392        }
3393
3394        len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3395        pad = cqe_fp->placement_offset;
3396
3397        m = rx_buf->m;
3398
3399        if (__predict_false(m == NULL)) {
3400            BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3401                  bd_cons, fp->index);
3402            goto next_rx;
3403        }
3404
3405        /* XXX double copy if packet length under a threshold */
3406
3407        /*
3408         * If all the buffer descriptors are filled with mbufs then fill in
3409         * the current consumer index with a new BD. Else if a maximum Rx
3410         * buffer limit is imposed then fill in the next producer index.
3411         */
3412        rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3413                                  (sc->max_rx_bufs != RX_BD_USABLE) ?
3414                                      bd_prod : bd_cons);
3415        if (rc != 0) {
3416            BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3417                  fp->index, rc);
3418            fp->eth_q_stats.rx_soft_errors++;
3419
3420            if (sc->max_rx_bufs != RX_BD_USABLE) {
3421                /* copy this consumer index to the producer index */
3422                memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3423                       sizeof(struct bxe_sw_rx_bd));
3424                memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3425            }
3426
3427            goto next_rx;
3428        }
3429
3430        /* current mbuf was detached from the bd */
3431        fp->eth_q_stats.mbuf_alloc_rx--;
3432
3433        /* we allocated a replacement mbuf, fixup the current one */
3434        m_adj(m, pad);
3435        m->m_pkthdr.len = m->m_len = len;
3436
3437        /* assign packet to this interface interface */
3438        m->m_pkthdr.rcvif = ifp;
3439
3440        /* assume no hardware checksum has complated */
3441        m->m_pkthdr.csum_flags = 0;
3442
3443        /* validate checksum if offload enabled */
3444        if (ifp->if_capenable & IFCAP_RXCSUM) {
3445            /* check for a valid IP frame */
3446            if (!(cqe->fast_path_cqe.status_flags &
3447                  ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3448                m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3449                if (__predict_false(cqe_fp_flags &
3450                                    ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3451                    fp->eth_q_stats.rx_hw_csum_errors++;
3452                } else {
3453                    fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3454                    m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3455                }
3456            }
3457
3458            /* check for a valid TCP/UDP frame */
3459            if (!(cqe->fast_path_cqe.status_flags &
3460                  ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3461                if (__predict_false(cqe_fp_flags &
3462                                    ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3463                    fp->eth_q_stats.rx_hw_csum_errors++;
3464                } else {
3465                    fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3466                    m->m_pkthdr.csum_data = 0xFFFF;
3467                    m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3468                                               CSUM_PSEUDO_HDR);
3469                }
3470            }
3471        }
3472
3473        /* if there is a VLAN tag then flag that info */
3474        if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_VLAN) {
3475            m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3476            m->m_flags |= M_VLANTAG;
3477        }
3478
3479#if __FreeBSD_version >= 800000
3480        /* specify what RSS queue was used for this flow */
3481        m->m_pkthdr.flowid = fp->index;
3482        m->m_flags |= M_FLOWID;
3483#endif
3484
3485next_rx:
3486
3487        bd_cons    = RX_BD_NEXT(bd_cons);
3488        bd_prod    = RX_BD_NEXT(bd_prod);
3489        bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3490
3491        /* pass the frame to the stack */
3492        if (__predict_true(m != NULL)) {
3493            ifp->if_ipackets++;
3494            rx_pkts++;
3495            (*ifp->if_input)(ifp, m);
3496        }
3497
3498next_cqe:
3499
3500        sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3501        sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3502
3503        /* limit spinning on the queue */
3504        if (rx_pkts == sc->rx_budget) {
3505            fp->eth_q_stats.rx_budget_reached++;
3506            break;
3507        }
3508    } /* while work to do */
3509
3510    fp->rx_bd_cons = bd_cons;
3511    fp->rx_bd_prod = bd_prod_fw;
3512    fp->rx_cq_cons = sw_cq_cons;
3513    fp->rx_cq_prod = sw_cq_prod;
3514
3515    /* Update producers */
3516    bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3517
3518    fp->eth_q_stats.rx_pkts += rx_pkts;
3519    fp->eth_q_stats.rx_calls++;
3520
3521    BXE_FP_RX_UNLOCK(fp);
3522
3523    return (sw_cq_cons != hw_cq_cons);
3524}
3525
3526static uint16_t
3527bxe_free_tx_pkt(struct bxe_softc    *sc,
3528                struct bxe_fastpath *fp,
3529                uint16_t            idx)
3530{
3531    struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3532    struct eth_tx_start_bd *tx_start_bd;
3533    uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3534    uint16_t new_cons;
3535    int nbd;
3536
3537    /* unmap the mbuf from non-paged memory */
3538    bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3539
3540    tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3541    nbd = le16toh(tx_start_bd->nbd) - 1;
3542
3543#if 0
3544    if ((nbd - 1) > (MAX_MBUF_FRAGS + 2)) {
3545        bxe_panic(sc, ("BAD nbd!\n"));
3546    }
3547#endif
3548
3549    new_cons = (tx_buf->first_bd + nbd);
3550
3551#if 0
3552    struct eth_tx_bd *tx_data_bd;
3553
3554    /*
3555     * The following code doesn't do anything but is left here
3556     * for clarity on what the new value of new_cons skipped.
3557     */
3558
3559    /* get the next bd */
3560    bd_idx = TX_BD(TX_BD_NEXT(bd_idx));
3561
3562    /* skip the parse bd */
3563    --nbd;
3564    bd_idx = TX_BD(TX_BD_NEXT(bd_idx));
3565
3566    /* skip the TSO split header bd since they have no mapping */
3567    if (tx_buf->flags & BXE_TSO_SPLIT_BD) {
3568        --nbd;
3569        bd_idx = TX_BD(TX_BD_NEXT(bd_idx));
3570    }
3571
3572    /* now free frags */
3573    while (nbd > 0) {
3574        tx_data_bd = &fp->tx_chain[bd_idx].reg_bd;
3575        if (--nbd) {
3576            bd_idx = TX_BD(TX_BD_NEXT(bd_idx));
3577        }
3578    }
3579#endif
3580
3581    /* free the mbuf */
3582    if (__predict_true(tx_buf->m != NULL)) {
3583        m_freem(tx_buf->m);
3584        fp->eth_q_stats.mbuf_alloc_tx--;
3585    } else {
3586        fp->eth_q_stats.tx_chain_lost_mbuf++;
3587    }
3588
3589    tx_buf->m = NULL;
3590    tx_buf->first_bd = 0;
3591
3592    return (new_cons);
3593}
3594
3595/* transmit timeout watchdog */
3596static int
3597bxe_watchdog(struct bxe_softc    *sc,
3598             struct bxe_fastpath *fp)
3599{
3600    BXE_FP_TX_LOCK(fp);
3601
3602    if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3603        BXE_FP_TX_UNLOCK(fp);
3604        return (0);
3605    }
3606
3607    BXE_FP_TX_UNLOCK(fp);
3608
3609    BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3610
3611    atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3612    taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3613
3614    return (-1);
3615}
3616
3617/* processes transmit completions */
3618static uint8_t
3619bxe_txeof(struct bxe_softc    *sc,
3620          struct bxe_fastpath *fp)
3621{
3622    struct ifnet *ifp = sc->ifnet;
3623    uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3624    uint16_t tx_bd_avail;
3625
3626    BXE_FP_TX_LOCK_ASSERT(fp);
3627
3628    bd_cons = fp->tx_bd_cons;
3629    hw_cons = le16toh(*fp->tx_cons_sb);
3630    sw_cons = fp->tx_pkt_cons;
3631
3632    while (sw_cons != hw_cons) {
3633        pkt_cons = TX_BD(sw_cons);
3634
3635        BLOGD(sc, DBG_TX,
3636              "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3637              fp->index, hw_cons, sw_cons, pkt_cons);
3638
3639        bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3640
3641        sw_cons++;
3642    }
3643
3644    fp->tx_pkt_cons = sw_cons;
3645    fp->tx_bd_cons  = bd_cons;
3646
3647    BLOGD(sc, DBG_TX,
3648          "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3649          fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3650
3651    mb();
3652
3653    tx_bd_avail = bxe_tx_avail(sc, fp);
3654
3655    /* reset the watchdog timer if there are pending transmits */
3656    if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
3657        ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3658
3659        if (tx_bd_avail >= (TX_BD_USABLE - 1)) {
3660            /* clear watchdog if the tx chain is empty */
3661            fp->watchdog_timer = 0;
3662            return (FALSE);
3663        }
3664
3665        /* reset watchdog if there are pending transmits */
3666        fp->watchdog_timer = BXE_TX_TIMEOUT;
3667    }
3668
3669    return (TRUE);
3670}
3671
3672static void
3673bxe_drain_tx_queues(struct bxe_softc *sc)
3674{
3675    struct bxe_fastpath *fp;
3676    int i, count;
3677
3678    /* wait until all TX fastpath tasks have completed */
3679    for (i = 0; i < sc->num_queues; i++) {
3680        fp = &sc->fp[i];
3681
3682        count = 1000;
3683
3684        while (bxe_has_tx_work(fp)) {
3685
3686            BXE_FP_TX_LOCK(fp);
3687            bxe_txeof(sc, fp);
3688            BXE_FP_TX_UNLOCK(fp);
3689
3690            if (count == 0) {
3691                BLOGE(sc, "Timeout waiting for fp[%d] "
3692                          "transmits to complete!\n", i);
3693                bxe_panic(sc, ("tx drain failure\n"));
3694                return;
3695            }
3696
3697            count--;
3698            DELAY(1000);
3699            rmb();
3700        }
3701    }
3702
3703    return;
3704}
3705
3706static int
3707bxe_del_all_macs(struct bxe_softc          *sc,
3708                 struct ecore_vlan_mac_obj *mac_obj,
3709                 int                       mac_type,
3710                 uint8_t                   wait_for_comp)
3711{
3712    unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3713    int rc;
3714
3715    /* wait for completion of requested */
3716    if (wait_for_comp) {
3717        bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3718    }
3719
3720    /* Set the mac type of addresses we want to clear */
3721    bxe_set_bit(mac_type, &vlan_mac_flags);
3722
3723    rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3724    if (rc < 0) {
3725        BLOGE(sc, "Failed to delete MACs (%d)\n", rc);
3726    }
3727
3728    return (rc);
3729}
3730
3731static int
3732bxe_fill_accept_flags(struct bxe_softc *sc,
3733                      uint32_t         rx_mode,
3734                      unsigned long    *rx_accept_flags,
3735                      unsigned long    *tx_accept_flags)
3736{
3737    /* Clear the flags first */
3738    *rx_accept_flags = 0;
3739    *tx_accept_flags = 0;
3740
3741    switch (rx_mode) {
3742    case BXE_RX_MODE_NONE:
3743        /*
3744         * 'drop all' supersedes any accept flags that may have been
3745         * passed to the function.
3746         */
3747        break;
3748
3749    case BXE_RX_MODE_NORMAL:
3750        bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3751        bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3752        bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3753
3754        /* internal switching mode */
3755        bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3756        bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3757        bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3758
3759        break;
3760
3761    case BXE_RX_MODE_ALLMULTI:
3762        bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3763        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3764        bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3765
3766        /* internal switching mode */
3767        bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3768        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3769        bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3770
3771        break;
3772
3773    case BXE_RX_MODE_PROMISC:
3774        /*
3775         * According to deffinition of SI mode, iface in promisc mode
3776         * should receive matched and unmatched (in resolution of port)
3777         * unicast packets.
3778         */
3779        bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3780        bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3781        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3782        bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3783
3784        /* internal switching mode */
3785        bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3786        bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3787
3788        if (IS_MF_SI(sc)) {
3789            bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3790        } else {
3791            bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3792        }
3793
3794        break;
3795
3796    default:
3797        BLOGE(sc, "Unknown rx_mode (%d)\n", rx_mode);
3798        return (-1);
3799    }
3800
3801    /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3802    if (rx_mode != BXE_RX_MODE_NONE) {
3803        bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3804        bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3805    }
3806
3807    return (0);
3808}
3809
3810static int
3811bxe_set_q_rx_mode(struct bxe_softc *sc,
3812                  uint8_t          cl_id,
3813                  unsigned long    rx_mode_flags,
3814                  unsigned long    rx_accept_flags,
3815                  unsigned long    tx_accept_flags,
3816                  unsigned long    ramrod_flags)
3817{
3818    struct ecore_rx_mode_ramrod_params ramrod_param;
3819    int rc;
3820
3821    memset(&ramrod_param, 0, sizeof(ramrod_param));
3822
3823    /* Prepare ramrod parameters */
3824    ramrod_param.cid = 0;
3825    ramrod_param.cl_id = cl_id;
3826    ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3827    ramrod_param.func_id = SC_FUNC(sc);
3828
3829    ramrod_param.pstate = &sc->sp_state;
3830    ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3831
3832    ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3833    ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3834
3835    bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3836
3837    ramrod_param.ramrod_flags = ramrod_flags;
3838    ramrod_param.rx_mode_flags = rx_mode_flags;
3839
3840    ramrod_param.rx_accept_flags = rx_accept_flags;
3841    ramrod_param.tx_accept_flags = tx_accept_flags;
3842
3843    rc = ecore_config_rx_mode(sc, &ramrod_param);
3844    if (rc < 0) {
3845        BLOGE(sc, "Set rx_mode %d failed\n", sc->rx_mode);
3846        return (rc);
3847    }
3848
3849    return (0);
3850}
3851
3852static int
3853bxe_set_storm_rx_mode(struct bxe_softc *sc)
3854{
3855    unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3856    unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3857    int rc;
3858
3859    rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3860                               &tx_accept_flags);
3861    if (rc) {
3862        return (rc);
3863    }
3864
3865    bxe_set_bit(RAMROD_RX, &ramrod_flags);
3866    bxe_set_bit(RAMROD_TX, &ramrod_flags);
3867
3868    /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3869    return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3870                              rx_accept_flags, tx_accept_flags,
3871                              ramrod_flags));
3872}
3873
3874/* returns the "mcp load_code" according to global load_count array */
3875static int
3876bxe_nic_load_no_mcp(struct bxe_softc *sc)
3877{
3878    int path = SC_PATH(sc);
3879    int port = SC_PORT(sc);
3880
3881    BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3882          path, load_count[path][0], load_count[path][1],
3883          load_count[path][2]);
3884    load_count[path][0]++;
3885    load_count[path][1 + port]++;
3886    BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3887          path, load_count[path][0], load_count[path][1],
3888          load_count[path][2]);
3889    if (load_count[path][0] == 1) {
3890        return (FW_MSG_CODE_DRV_LOAD_COMMON);
3891    } else if (load_count[path][1 + port] == 1) {
3892        return (FW_MSG_CODE_DRV_LOAD_PORT);
3893    } else {
3894        return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3895    }
3896}
3897
3898/* returns the "mcp load_code" according to global load_count array */
3899static int
3900bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3901{
3902    int port = SC_PORT(sc);
3903    int path = SC_PATH(sc);
3904
3905    BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3906          path, load_count[path][0], load_count[path][1],
3907          load_count[path][2]);
3908    load_count[path][0]--;
3909    load_count[path][1 + port]--;
3910    BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3911          path, load_count[path][0], load_count[path][1],
3912          load_count[path][2]);
3913    if (load_count[path][0] == 0) {
3914        return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3915    } else if (load_count[path][1 + port] == 0) {
3916        return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3917    } else {
3918        return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3919    }
3920}
3921
3922/* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3923static uint32_t
3924bxe_send_unload_req(struct bxe_softc *sc,
3925                    int              unload_mode)
3926{
3927    uint32_t reset_code = 0;
3928#if 0
3929    int port = SC_PORT(sc);
3930    int path = SC_PATH(sc);
3931#endif
3932
3933    /* Select the UNLOAD request mode */
3934    if (unload_mode == UNLOAD_NORMAL) {
3935        reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3936    }
3937#if 0
3938    else if (sc->flags & BXE_NO_WOL_FLAG) {
3939        reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP;
3940    } else if (sc->wol) {
3941        uint32_t emac_base = port ? GRCBASE_EMAC1 : GRCBASE_EMAC0;
3942        uint8_t *mac_addr = sc->dev->dev_addr;
3943        uint32_t val;
3944        uint16_t pmc;
3945
3946        /*
3947         * The mac address is written to entries 1-4 to
3948         * preserve entry 0 which is used by the PMF
3949         */
3950        uint8_t entry = (SC_VN(sc) + 1)*8;
3951
3952        val = (mac_addr[0] << 8) | mac_addr[1];
3953        EMAC_WR(sc, EMAC_REG_EMAC_MAC_MATCH + entry, val);
3954
3955        val = (mac_addr[2] << 24) | (mac_addr[3] << 16) |
3956              (mac_addr[4] << 8) | mac_addr[5];
3957        EMAC_WR(sc, EMAC_REG_EMAC_MAC_MATCH + entry + 4, val);
3958
3959        /* Enable the PME and clear the status */
3960        pmc = pci_read_config(sc->dev,
3961                              (sc->devinfo.pcie_pm_cap_reg +
3962                               PCIR_POWER_STATUS),
3963                              2);
3964        pmc |= PCIM_PSTAT_PMEENABLE | PCIM_PSTAT_PME;
3965        pci_write_config(sc->dev,
3966                         (sc->devinfo.pcie_pm_cap_reg +
3967                          PCIR_POWER_STATUS),
3968                         pmc, 4);
3969
3970        reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_EN;
3971    }
3972#endif
3973    else {
3974        reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3975    }
3976
3977    /* Send the request to the MCP */
3978    if (!BXE_NOMCP(sc)) {
3979        reset_code = bxe_fw_command(sc, reset_code, 0);
3980    } else {
3981        reset_code = bxe_nic_unload_no_mcp(sc);
3982    }
3983
3984    return (reset_code);
3985}
3986
3987/* send UNLOAD_DONE command to the MCP */
3988static void
3989bxe_send_unload_done(struct bxe_softc *sc,
3990                     uint8_t          keep_link)
3991{
3992    uint32_t reset_param =
3993        keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3994
3995    /* Report UNLOAD_DONE to MCP */
3996    if (!BXE_NOMCP(sc)) {
3997        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3998    }
3999}
4000
4001static int
4002bxe_func_wait_started(struct bxe_softc *sc)
4003{
4004    int tout = 50;
4005
4006    if (!sc->port.pmf) {
4007        return (0);
4008    }
4009
4010    /*
4011     * (assumption: No Attention from MCP at this stage)
4012     * PMF probably in the middle of TX disable/enable transaction
4013     * 1. Sync IRS for default SB
4014     * 2. Sync SP queue - this guarantees us that attention handling started
4015     * 3. Wait, that TX disable/enable transaction completes
4016     *
4017     * 1+2 guarantee that if DCBX attention was scheduled it already changed
4018     * pending bit of transaction from STARTED-->TX_STOPPED, if we already
4019     * received completion for the transaction the state is TX_STOPPED.
4020     * State will return to STARTED after completion of TX_STOPPED-->STARTED
4021     * transaction.
4022     */
4023
4024    /* XXX make sure default SB ISR is done */
4025    /* need a way to synchronize an irq (intr_mtx?) */
4026
4027    /* XXX flush any work queues */
4028
4029    while (ecore_func_get_state(sc, &sc->func_obj) !=
4030           ECORE_F_STATE_STARTED && tout--) {
4031        DELAY(20000);
4032    }
4033
4034    if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
4035        /*
4036         * Failed to complete the transaction in a "good way"
4037         * Force both transactions with CLR bit.
4038         */
4039        struct ecore_func_state_params func_params = { NULL };
4040
4041        BLOGE(sc, "Unexpected function state! "
4042                  "Forcing STARTED-->TX_STOPPED-->STARTED\n");
4043
4044        func_params.f_obj = &sc->func_obj;
4045        bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
4046
4047        /* STARTED-->TX_STOPPED */
4048        func_params.cmd = ECORE_F_CMD_TX_STOP;
4049        ecore_func_state_change(sc, &func_params);
4050
4051        /* TX_STOPPED-->STARTED */
4052        func_params.cmd = ECORE_F_CMD_TX_START;
4053        return (ecore_func_state_change(sc, &func_params));
4054    }
4055
4056    return (0);
4057}
4058
4059static int
4060bxe_stop_queue(struct bxe_softc *sc,
4061               int              index)
4062{
4063    struct bxe_fastpath *fp = &sc->fp[index];
4064    struct ecore_queue_state_params q_params = { NULL };
4065    int rc;
4066
4067    BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
4068
4069    q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
4070    /* We want to wait for completion in this context */
4071    bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
4072
4073    /* Stop the primary connection: */
4074
4075    /* ...halt the connection */
4076    q_params.cmd = ECORE_Q_CMD_HALT;
4077    rc = ecore_queue_state_change(sc, &q_params);
4078    if (rc) {
4079        return (rc);
4080    }
4081
4082    /* ...terminate the connection */
4083    q_params.cmd = ECORE_Q_CMD_TERMINATE;
4084    memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
4085    q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
4086    rc = ecore_queue_state_change(sc, &q_params);
4087    if (rc) {
4088        return (rc);
4089    }
4090
4091    /* ...delete cfc entry */
4092    q_params.cmd = ECORE_Q_CMD_CFC_DEL;
4093    memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
4094    q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
4095    return (ecore_queue_state_change(sc, &q_params));
4096}
4097
4098/* wait for the outstanding SP commands */
4099static inline uint8_t
4100bxe_wait_sp_comp(struct bxe_softc *sc,
4101                 unsigned long    mask)
4102{
4103    unsigned long tmp;
4104    int tout = 5000; /* wait for 5 secs tops */
4105
4106    while (tout--) {
4107        mb();
4108        if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
4109            return (TRUE);
4110        }
4111
4112        DELAY(1000);
4113    }
4114
4115    mb();
4116
4117    tmp = atomic_load_acq_long(&sc->sp_state);
4118    if (tmp & mask) {
4119        BLOGE(sc, "Filtering completion timed out: "
4120                  "sp_state 0x%lx, mask 0x%lx\n",
4121              tmp, mask);
4122        return (FALSE);
4123    }
4124
4125    return (FALSE);
4126}
4127
4128static int
4129bxe_func_stop(struct bxe_softc *sc)
4130{
4131    struct ecore_func_state_params func_params = { NULL };
4132    int rc;
4133
4134    /* prepare parameters for function state transitions */
4135    bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4136    func_params.f_obj = &sc->func_obj;
4137    func_params.cmd = ECORE_F_CMD_STOP;
4138
4139    /*
4140     * Try to stop the function the 'good way'. If it fails (in case
4141     * of a parity error during bxe_chip_cleanup()) and we are
4142     * not in a debug mode, perform a state transaction in order to
4143     * enable further HW_RESET transaction.
4144     */
4145    rc = ecore_func_state_change(sc, &func_params);
4146    if (rc) {
4147        BLOGE(sc, "FUNC_STOP ramrod failed. "
4148                  "Running a dry transaction\n");
4149        bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
4150        return (ecore_func_state_change(sc, &func_params));
4151    }
4152
4153    return (0);
4154}
4155
4156static int
4157bxe_reset_hw(struct bxe_softc *sc,
4158             uint32_t         load_code)
4159{
4160    struct ecore_func_state_params func_params = { NULL };
4161
4162    /* Prepare parameters for function state transitions */
4163    bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4164
4165    func_params.f_obj = &sc->func_obj;
4166    func_params.cmd = ECORE_F_CMD_HW_RESET;
4167
4168    func_params.params.hw_init.load_phase = load_code;
4169
4170    return (ecore_func_state_change(sc, &func_params));
4171}
4172
4173static void
4174bxe_int_disable_sync(struct bxe_softc *sc,
4175                     int              disable_hw)
4176{
4177    if (disable_hw) {
4178        /* prevent the HW from sending interrupts */
4179        bxe_int_disable(sc);
4180    }
4181
4182    /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4183    /* make sure all ISRs are done */
4184
4185    /* XXX make sure sp_task is not running */
4186    /* cancel and flush work queues */
4187}
4188
4189static void
4190bxe_chip_cleanup(struct bxe_softc *sc,
4191                 uint32_t         unload_mode,
4192                 uint8_t          keep_link)
4193{
4194    int port = SC_PORT(sc);
4195    struct ecore_mcast_ramrod_params rparam = { NULL };
4196    uint32_t reset_code;
4197    int i, rc = 0;
4198
4199    bxe_drain_tx_queues(sc);
4200
4201    /* give HW time to discard old tx messages */
4202    DELAY(1000);
4203
4204    /* Clean all ETH MACs */
4205    rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4206    if (rc < 0) {
4207        BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4208    }
4209
4210    /* Clean up UC list  */
4211    rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4212    if (rc < 0) {
4213        BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4214    }
4215
4216    /* Disable LLH */
4217    if (!CHIP_IS_E1(sc)) {
4218        REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4219    }
4220
4221    /* Set "drop all" to stop Rx */
4222
4223    /*
4224     * We need to take the BXE_MCAST_LOCK() here in order to prevent
4225     * a race between the completion code and this code.
4226     */
4227    BXE_MCAST_LOCK(sc);
4228
4229    if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4230        bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4231    } else {
4232        bxe_set_storm_rx_mode(sc);
4233    }
4234
4235    /* Clean up multicast configuration */
4236    rparam.mcast_obj = &sc->mcast_obj;
4237    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4238    if (rc < 0) {
4239        BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4240    }
4241
4242    BXE_MCAST_UNLOCK(sc);
4243
4244    // XXX bxe_iov_chip_cleanup(sc);
4245
4246    /*
4247     * Send the UNLOAD_REQUEST to the MCP. This will return if
4248     * this function should perform FUNCTION, PORT, or COMMON HW
4249     * reset.
4250     */
4251    reset_code = bxe_send_unload_req(sc, unload_mode);
4252
4253    /*
4254     * (assumption: No Attention from MCP at this stage)
4255     * PMF probably in the middle of TX disable/enable transaction
4256     */
4257    rc = bxe_func_wait_started(sc);
4258    if (rc) {
4259        BLOGE(sc, "bxe_func_wait_started failed\n");
4260    }
4261
4262    /*
4263     * Close multi and leading connections
4264     * Completions for ramrods are collected in a synchronous way
4265     */
4266    for (i = 0; i < sc->num_queues; i++) {
4267        if (bxe_stop_queue(sc, i)) {
4268            goto unload_error;
4269        }
4270    }
4271
4272    /*
4273     * If SP settings didn't get completed so far - something
4274     * very wrong has happen.
4275     */
4276    if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4277        BLOGE(sc, "Common slow path ramrods got stuck!\n");
4278    }
4279
4280unload_error:
4281
4282    rc = bxe_func_stop(sc);
4283    if (rc) {
4284        BLOGE(sc, "Function stop failed!\n");
4285    }
4286
4287    /* disable HW interrupts */
4288    bxe_int_disable_sync(sc, TRUE);
4289
4290    /* detach interrupts */
4291    bxe_interrupt_detach(sc);
4292
4293    /* Reset the chip */
4294    rc = bxe_reset_hw(sc, reset_code);
4295    if (rc) {
4296        BLOGE(sc, "Hardware reset failed\n");
4297    }
4298
4299    /* Report UNLOAD_DONE to MCP */
4300    bxe_send_unload_done(sc, keep_link);
4301}
4302
4303static void
4304bxe_disable_close_the_gate(struct bxe_softc *sc)
4305{
4306    uint32_t val;
4307    int port = SC_PORT(sc);
4308
4309    BLOGD(sc, DBG_LOAD,
4310          "Disabling 'close the gates'\n");
4311
4312    if (CHIP_IS_E1(sc)) {
4313        uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4314                               MISC_REG_AEU_MASK_ATTN_FUNC_0;
4315        val = REG_RD(sc, addr);
4316        val &= ~(0x300);
4317        REG_WR(sc, addr, val);
4318    } else {
4319        val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4320        val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4321                 MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4322        REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4323    }
4324}
4325
4326/*
4327 * Cleans the object that have internal lists without sending
4328 * ramrods. Should be run when interrutps are disabled.
4329 */
4330static void
4331bxe_squeeze_objects(struct bxe_softc *sc)
4332{
4333    unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4334    struct ecore_mcast_ramrod_params rparam = { NULL };
4335    struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4336    int rc;
4337
4338    /* Cleanup MACs' object first... */
4339
4340    /* Wait for completion of requested */
4341    bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4342    /* Perform a dry cleanup */
4343    bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4344
4345    /* Clean ETH primary MAC */
4346    bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4347    rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4348                             &ramrod_flags);
4349    if (rc != 0) {
4350        BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4351    }
4352
4353    /* Cleanup UC list */
4354    vlan_mac_flags = 0;
4355    bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4356    rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4357                             &ramrod_flags);
4358    if (rc != 0) {
4359        BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4360    }
4361
4362    /* Now clean mcast object... */
4363
4364    rparam.mcast_obj = &sc->mcast_obj;
4365    bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4366
4367    /* Add a DEL command... */
4368    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4369    if (rc < 0) {
4370        BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4371    }
4372
4373    /* now wait until all pending commands are cleared */
4374
4375    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4376    while (rc != 0) {
4377        if (rc < 0) {
4378            BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4379            return;
4380        }
4381
4382        rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4383    }
4384}
4385
4386/* stop the controller */
4387static __noinline int
4388bxe_nic_unload(struct bxe_softc *sc,
4389               uint32_t         unload_mode,
4390               uint8_t          keep_link)
4391{
4392    uint8_t global = FALSE;
4393    uint32_t val;
4394
4395    BXE_CORE_LOCK_ASSERT(sc);
4396
4397    BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4398
4399    /* mark driver as unloaded in shmem2 */
4400    if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4401        val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4402        SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4403                  val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4404    }
4405
4406    if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4407        (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4408        /*
4409         * We can get here if the driver has been unloaded
4410         * during parity error recovery and is either waiting for a
4411         * leader to complete or for other functions to unload and
4412         * then ifconfig down has been issued. In this case we want to
4413         * unload and let other functions to complete a recovery
4414         * process.
4415         */
4416        sc->recovery_state = BXE_RECOVERY_DONE;
4417        sc->is_leader = 0;
4418        bxe_release_leader_lock(sc);
4419        mb();
4420
4421        BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4422        BLOGE(sc, "Can't unload in closed or error state\n");
4423        return (-1);
4424    }
4425
4426    /*
4427     * Nothing to do during unload if previous bxe_nic_load()
4428     * did not completed succesfully - all resourses are released.
4429     */
4430    if ((sc->state == BXE_STATE_CLOSED) ||
4431        (sc->state == BXE_STATE_ERROR)) {
4432        return (0);
4433    }
4434
4435    sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4436    mb();
4437
4438    /* stop tx */
4439    bxe_tx_disable(sc);
4440
4441    sc->rx_mode = BXE_RX_MODE_NONE;
4442    /* XXX set rx mode ??? */
4443
4444    if (IS_PF(sc)) {
4445        /* set ALWAYS_ALIVE bit in shmem */
4446        sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4447
4448        bxe_drv_pulse(sc);
4449
4450        bxe_stats_handle(sc, STATS_EVENT_STOP);
4451        bxe_save_statistics(sc);
4452    }
4453
4454    /* wait till consumers catch up with producers in all queues */
4455    bxe_drain_tx_queues(sc);
4456
4457    /* if VF indicate to PF this function is going down (PF will delete sp
4458     * elements and clear initializations
4459     */
4460    if (IS_VF(sc)) {
4461        ; /* bxe_vfpf_close_vf(sc); */
4462    } else if (unload_mode != UNLOAD_RECOVERY) {
4463        /* if this is a normal/close unload need to clean up chip */
4464        bxe_chip_cleanup(sc, unload_mode, keep_link);
4465    } else {
4466        /* Send the UNLOAD_REQUEST to the MCP */
4467        bxe_send_unload_req(sc, unload_mode);
4468
4469        /*
4470         * Prevent transactions to host from the functions on the
4471         * engine that doesn't reset global blocks in case of global
4472         * attention once gloabl blocks are reset and gates are opened
4473         * (the engine which leader will perform the recovery
4474         * last).
4475         */
4476        if (!CHIP_IS_E1x(sc)) {
4477            bxe_pf_disable(sc);
4478        }
4479
4480        /* disable HW interrupts */
4481        bxe_int_disable_sync(sc, TRUE);
4482
4483        /* detach interrupts */
4484        bxe_interrupt_detach(sc);
4485
4486        /* Report UNLOAD_DONE to MCP */
4487        bxe_send_unload_done(sc, FALSE);
4488    }
4489
4490    /*
4491     * At this stage no more interrupts will arrive so we may safely clean
4492     * the queue'able objects here in case they failed to get cleaned so far.
4493     */
4494    if (IS_PF(sc)) {
4495        bxe_squeeze_objects(sc);
4496    }
4497
4498    /* There should be no more pending SP commands at this stage */
4499    sc->sp_state = 0;
4500
4501    sc->port.pmf = 0;
4502
4503    bxe_free_fp_buffers(sc);
4504
4505    if (IS_PF(sc)) {
4506        bxe_free_mem(sc);
4507    }
4508
4509    bxe_free_fw_stats_mem(sc);
4510
4511    sc->state = BXE_STATE_CLOSED;
4512
4513    /*
4514     * Check if there are pending parity attentions. If there are - set
4515     * RECOVERY_IN_PROGRESS.
4516     */
4517    if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4518        bxe_set_reset_in_progress(sc);
4519
4520        /* Set RESET_IS_GLOBAL if needed */
4521        if (global) {
4522            bxe_set_reset_global(sc);
4523        }
4524    }
4525
4526    /*
4527     * The last driver must disable a "close the gate" if there is no
4528     * parity attention or "process kill" pending.
4529     */
4530    if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4531        bxe_reset_is_done(sc, SC_PATH(sc))) {
4532        bxe_disable_close_the_gate(sc);
4533    }
4534
4535    BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4536
4537    return (0);
4538}
4539
4540/*
4541 * Called by the OS to set various media options (i.e. link, speed, etc.) when
4542 * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4543 */
4544static int
4545bxe_ifmedia_update(struct ifnet *ifp)
4546{
4547    struct bxe_softc *sc = (struct bxe_softc *)ifp->if_softc;
4548    struct ifmedia *ifm;
4549
4550    ifm = &sc->ifmedia;
4551
4552    /* We only support Ethernet media type. */
4553    if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4554        return (EINVAL);
4555    }
4556
4557    switch (IFM_SUBTYPE(ifm->ifm_media)) {
4558    case IFM_AUTO:
4559         break;
4560    case IFM_10G_CX4:
4561    case IFM_10G_SR:
4562    case IFM_10G_T:
4563    case IFM_10G_TWINAX:
4564    default:
4565        /* We don't support changing the media type. */
4566        BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4567              IFM_SUBTYPE(ifm->ifm_media));
4568        return (EINVAL);
4569    }
4570
4571    return (0);
4572}
4573
4574/*
4575 * Called by the OS to get the current media status (i.e. link, speed, etc.).
4576 */
4577static void
4578bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4579{
4580    struct bxe_softc *sc = ifp->if_softc;
4581
4582    /* Report link down if the driver isn't running. */
4583    if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4584        ifmr->ifm_active |= IFM_NONE;
4585        return;
4586    }
4587
4588    /* Setup the default interface info. */
4589    ifmr->ifm_status = IFM_AVALID;
4590    ifmr->ifm_active = IFM_ETHER;
4591
4592    if (sc->link_vars.link_up) {
4593        ifmr->ifm_status |= IFM_ACTIVE;
4594    } else {
4595        ifmr->ifm_active |= IFM_NONE;
4596        return;
4597    }
4598
4599    ifmr->ifm_active |= sc->media;
4600
4601    if (sc->link_vars.duplex == DUPLEX_FULL) {
4602        ifmr->ifm_active |= IFM_FDX;
4603    } else {
4604        ifmr->ifm_active |= IFM_HDX;
4605    }
4606}
4607
4608static int
4609bxe_ioctl_nvram(struct bxe_softc *sc,
4610                uint32_t         priv_op,
4611                struct ifreq     *ifr)
4612{
4613    struct bxe_nvram_data nvdata_base;
4614    struct bxe_nvram_data *nvdata;
4615    int len;
4616    int error = 0;
4617
4618    copyin(ifr->ifr_data, &nvdata_base, sizeof(nvdata_base));
4619
4620    len = (sizeof(struct bxe_nvram_data) +
4621           nvdata_base.len -
4622           sizeof(uint32_t));
4623
4624    if (len > sizeof(struct bxe_nvram_data)) {
4625        if ((nvdata = (struct bxe_nvram_data *)
4626                 malloc(len, M_DEVBUF,
4627                        (M_NOWAIT | M_ZERO))) == NULL) {
4628            BLOGE(sc, "BXE_IOC_RD_NVRAM malloc failed\n");
4629            return (1);
4630        }
4631        memcpy(nvdata, &nvdata_base, sizeof(struct bxe_nvram_data));
4632    } else {
4633        nvdata = &nvdata_base;
4634    }
4635
4636    if (priv_op == BXE_IOC_RD_NVRAM) {
4637        BLOGD(sc, DBG_IOCTL, "IOC_RD_NVRAM 0x%x %d\n",
4638              nvdata->offset, nvdata->len);
4639        error = bxe_nvram_read(sc,
4640                               nvdata->offset,
4641                               (uint8_t *)nvdata->value,
4642                               nvdata->len);
4643        copyout(nvdata, ifr->ifr_data, len);
4644    } else { /* BXE_IOC_WR_NVRAM */
4645        BLOGD(sc, DBG_IOCTL, "IOC_WR_NVRAM 0x%x %d\n",
4646              nvdata->offset, nvdata->len);
4647        copyin(ifr->ifr_data, nvdata, len);
4648        error = bxe_nvram_write(sc,
4649                                nvdata->offset,
4650                                (uint8_t *)nvdata->value,
4651                                nvdata->len);
4652    }
4653
4654    if (len > sizeof(struct bxe_nvram_data)) {
4655        free(nvdata, M_DEVBUF);
4656    }
4657
4658    return (error);
4659}
4660
4661static int
4662bxe_ioctl_stats_show(struct bxe_softc *sc,
4663                     uint32_t         priv_op,
4664                     struct ifreq     *ifr)
4665{
4666    const size_t str_size   = (BXE_NUM_ETH_STATS * STAT_NAME_LEN);
4667    const size_t stats_size = (BXE_NUM_ETH_STATS * sizeof(uint64_t));
4668    caddr_t p_tmp;
4669    uint32_t *offset;
4670    int i;
4671
4672    switch (priv_op)
4673    {
4674    case BXE_IOC_STATS_SHOW_NUM:
4675        memset(ifr->ifr_data, 0, sizeof(union bxe_stats_show_data));
4676        ((union bxe_stats_show_data *)ifr->ifr_data)->desc.num =
4677            BXE_NUM_ETH_STATS;
4678        ((union bxe_stats_show_data *)ifr->ifr_data)->desc.len =
4679            STAT_NAME_LEN;
4680        return (0);
4681
4682    case BXE_IOC_STATS_SHOW_STR:
4683        memset(ifr->ifr_data, 0, str_size);
4684        p_tmp = ifr->ifr_data;
4685        for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4686            strcpy(p_tmp, bxe_eth_stats_arr[i].string);
4687            p_tmp += STAT_NAME_LEN;
4688        }
4689        return (0);
4690
4691    case BXE_IOC_STATS_SHOW_CNT:
4692        memset(ifr->ifr_data, 0, stats_size);
4693        p_tmp = ifr->ifr_data;
4694        for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4695            offset = ((uint32_t *)&sc->eth_stats +
4696                      bxe_eth_stats_arr[i].offset);
4697            switch (bxe_eth_stats_arr[i].size) {
4698            case 4:
4699                *((uint64_t *)p_tmp) = (uint64_t)*offset;
4700                break;
4701            case 8:
4702                *((uint64_t *)p_tmp) = HILO_U64(*offset, *(offset + 1));
4703                break;
4704            default:
4705                *((uint64_t *)p_tmp) = 0;
4706            }
4707            p_tmp += sizeof(uint64_t);
4708        }
4709        return (0);
4710
4711    default:
4712        return (-1);
4713    }
4714}
4715
4716static void
4717bxe_handle_chip_tq(void *context,
4718                   int  pending)
4719{
4720    struct bxe_softc *sc = (struct bxe_softc *)context;
4721    long work = atomic_load_acq_long(&sc->chip_tq_flags);
4722
4723    switch (work)
4724    {
4725    case CHIP_TQ_START:
4726        if ((sc->ifnet->if_flags & IFF_UP) &&
4727            !(sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
4728            /* start the interface */
4729            BLOGD(sc, DBG_LOAD, "Starting the interface...\n");
4730            BXE_CORE_LOCK(sc);
4731            bxe_init_locked(sc);
4732            BXE_CORE_UNLOCK(sc);
4733        }
4734        break;
4735
4736    case CHIP_TQ_STOP:
4737        if (!(sc->ifnet->if_flags & IFF_UP) &&
4738            (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
4739            /* bring down the interface */
4740            BLOGD(sc, DBG_LOAD, "Stopping the interface...\n");
4741            bxe_periodic_stop(sc);
4742            BXE_CORE_LOCK(sc);
4743            bxe_stop_locked(sc);
4744            BXE_CORE_UNLOCK(sc);
4745        }
4746        break;
4747
4748    case CHIP_TQ_REINIT:
4749        if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
4750            /* restart the interface */
4751            BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4752            bxe_periodic_stop(sc);
4753            BXE_CORE_LOCK(sc);
4754            bxe_stop_locked(sc);
4755            bxe_init_locked(sc);
4756            BXE_CORE_UNLOCK(sc);
4757        }
4758        break;
4759
4760    default:
4761        break;
4762    }
4763}
4764
4765/*
4766 * Handles any IOCTL calls from the operating system.
4767 *
4768 * Returns:
4769 *   0 = Success, >0 Failure
4770 */
4771static int
4772bxe_ioctl(struct ifnet *ifp,
4773          u_long       command,
4774          caddr_t      data)
4775{
4776    struct bxe_softc *sc = ifp->if_softc;
4777    struct ifreq *ifr = (struct ifreq *)data;
4778    struct bxe_nvram_data *nvdata;
4779    uint32_t priv_op;
4780    int mask = 0;
4781    int reinit = 0;
4782    int error = 0;
4783
4784    int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4785    int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4786
4787    switch (command)
4788    {
4789    case SIOCSIFMTU:
4790        BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4791              ifr->ifr_mtu);
4792
4793        if (sc->mtu == ifr->ifr_mtu) {
4794            /* nothing to change */
4795            break;
4796        }
4797
4798        if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4799            BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4800                  ifr->ifr_mtu, mtu_min, mtu_max);
4801            error = EINVAL;
4802            break;
4803        }
4804
4805        atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4806                             (unsigned long)ifr->ifr_mtu);
4807        atomic_store_rel_long((volatile unsigned long *)&ifp->if_mtu,
4808                              (unsigned long)ifr->ifr_mtu);
4809
4810        reinit = 1;
4811        break;
4812
4813    case SIOCSIFFLAGS:
4814        /* toggle the interface state up or down */
4815        BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4816
4817        /* check if the interface is up */
4818        if (ifp->if_flags & IFF_UP) {
4819            if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4820                /* set the receive mode flags */
4821                bxe_set_rx_mode(sc);
4822            } else {
4823                atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_START);
4824                taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
4825            }
4826        } else {
4827            if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4828                atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_STOP);
4829                taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
4830            }
4831        }
4832
4833        break;
4834
4835    case SIOCADDMULTI:
4836    case SIOCDELMULTI:
4837        /* add/delete multicast addresses */
4838        BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4839
4840        /* check if the interface is up */
4841        if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4842            /* set the receive mode flags */
4843            bxe_set_rx_mode(sc);
4844        }
4845
4846        break;
4847
4848    case SIOCSIFCAP:
4849        /* find out which capabilities have changed */
4850        mask = (ifr->ifr_reqcap ^ ifp->if_capenable);
4851
4852        BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4853              mask);
4854
4855        /* toggle the LRO capabilites enable flag */
4856        if (mask & IFCAP_LRO) {
4857            ifp->if_capenable ^= IFCAP_LRO;
4858            BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4859                  (ifp->if_capenable & IFCAP_LRO) ? "ON" : "OFF");
4860            reinit = 1;
4861        }
4862
4863        /* toggle the TXCSUM checksum capabilites enable flag */
4864        if (mask & IFCAP_TXCSUM) {
4865            ifp->if_capenable ^= IFCAP_TXCSUM;
4866            BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4867                  (ifp->if_capenable & IFCAP_TXCSUM) ? "ON" : "OFF");
4868            if (ifp->if_capenable & IFCAP_TXCSUM) {
4869                ifp->if_hwassist = (CSUM_IP       |
4870                                    CSUM_TCP      |
4871                                    CSUM_UDP      |
4872                                    CSUM_TSO      |
4873                                    CSUM_TCP_IPV6 |
4874                                    CSUM_UDP_IPV6);
4875            } else {
4876                ifp->if_hwassist = 0;
4877            }
4878        }
4879
4880        /* toggle the RXCSUM checksum capabilities enable flag */
4881        if (mask & IFCAP_RXCSUM) {
4882            ifp->if_capenable ^= IFCAP_RXCSUM;
4883            BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4884                  (ifp->if_capenable & IFCAP_RXCSUM) ? "ON" : "OFF");
4885            if (ifp->if_capenable & IFCAP_RXCSUM) {
4886                ifp->if_hwassist = (CSUM_IP       |
4887                                    CSUM_TCP      |
4888                                    CSUM_UDP      |
4889                                    CSUM_TSO      |
4890                                    CSUM_TCP_IPV6 |
4891                                    CSUM_UDP_IPV6);
4892            } else {
4893                ifp->if_hwassist = 0;
4894            }
4895        }
4896
4897        /* toggle TSO4 capabilities enabled flag */
4898        if (mask & IFCAP_TSO4) {
4899            ifp->if_capenable ^= IFCAP_TSO4;
4900            BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4901                  (ifp->if_capenable & IFCAP_TSO4) ? "ON" : "OFF");
4902        }
4903
4904        /* toggle TSO6 capabilities enabled flag */
4905        if (mask & IFCAP_TSO6) {
4906            ifp->if_capenable ^= IFCAP_TSO6;
4907            BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4908                  (ifp->if_capenable & IFCAP_TSO6) ? "ON" : "OFF");
4909        }
4910
4911        /* toggle VLAN_HWTSO capabilities enabled flag */
4912        if (mask & IFCAP_VLAN_HWTSO) {
4913            ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
4914            BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4915                  (ifp->if_capenable & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4916        }
4917
4918        /* toggle VLAN_HWCSUM capabilities enabled flag */
4919        if (mask & IFCAP_VLAN_HWCSUM) {
4920            /* XXX investigate this... */
4921            BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4922            error = EINVAL;
4923        }
4924
4925        /* toggle VLAN_MTU capabilities enable flag */
4926        if (mask & IFCAP_VLAN_MTU) {
4927            /* XXX investigate this... */
4928            BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4929            error = EINVAL;
4930        }
4931
4932        /* toggle VLAN_HWTAGGING capabilities enabled flag */
4933        if (mask & IFCAP_VLAN_HWTAGGING) {
4934            /* XXX investigate this... */
4935            BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4936            error = EINVAL;
4937        }
4938
4939        /* toggle VLAN_HWFILTER capabilities enabled flag */
4940        if (mask & IFCAP_VLAN_HWFILTER) {
4941            /* XXX investigate this... */
4942            BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4943            error = EINVAL;
4944        }
4945
4946        /* XXX not yet...
4947         * IFCAP_WOL_MAGIC
4948         */
4949
4950        break;
4951
4952    case SIOCSIFMEDIA:
4953    case SIOCGIFMEDIA:
4954        /* set/get interface media */
4955        BLOGD(sc, DBG_IOCTL,
4956              "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4957              (command & 0xff));
4958        error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4959        break;
4960
4961    case SIOCGPRIVATE_0:
4962        copyin(ifr->ifr_data, &priv_op, sizeof(priv_op));
4963
4964        switch (priv_op)
4965        {
4966        case BXE_IOC_RD_NVRAM:
4967        case BXE_IOC_WR_NVRAM:
4968            nvdata = (struct bxe_nvram_data *)ifr->ifr_data;
4969            BLOGD(sc, DBG_IOCTL,
4970                  "Received Private NVRAM ioctl addr=0x%x size=%u\n",
4971                  nvdata->offset, nvdata->len);
4972            error = bxe_ioctl_nvram(sc, priv_op, ifr);
4973            break;
4974
4975        case BXE_IOC_STATS_SHOW_NUM:
4976        case BXE_IOC_STATS_SHOW_STR:
4977        case BXE_IOC_STATS_SHOW_CNT:
4978            BLOGD(sc, DBG_IOCTL, "Received Private Stats ioctl (%d)\n",
4979                  priv_op);
4980            error = bxe_ioctl_stats_show(sc, priv_op, ifr);
4981            break;
4982
4983        default:
4984            BLOGW(sc, "Received Private Unknown ioctl (%d)\n", priv_op);
4985            error = EINVAL;
4986            break;
4987        }
4988
4989        break;
4990
4991    default:
4992        BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4993              (command & 0xff));
4994        error = ether_ioctl(ifp, command, data);
4995        break;
4996    }
4997
4998    if (reinit && (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
4999        BLOGD(sc, DBG_LOAD | DBG_IOCTL,
5000              "Re-initializing hardware from IOCTL change\n");
5001        atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
5002        taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
5003    }
5004
5005    return (error);
5006}
5007
5008static __noinline void
5009bxe_dump_mbuf(struct bxe_softc *sc,
5010              struct mbuf      *m,
5011              uint8_t          contents)
5012{
5013    char * type;
5014
5015    if (!(sc->debug & DBG_MBUF)) {
5016        return;
5017    }
5018
5019    if (m == NULL) {
5020        BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
5021        return;
5022    }
5023
5024    while (m) {
5025        BLOGD(sc, DBG_MBUF,
5026              "mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
5027              m, m->m_len, m->m_flags,
5028              "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
5029
5030        if (m->m_flags & M_PKTHDR) {
5031             BLOGD(sc, DBG_MBUF,
5032                   "- m_pkthdr: len=%d flags=0x%b csum_flags=%b\n",
5033                   m->m_pkthdr.len, m->m_flags,
5034                   "\20\12M_BCAST\13M_MCAST\14M_FRAG"
5035                   "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
5036                   "\22M_PROMISC\23M_NOFREE",
5037                   (int)m->m_pkthdr.csum_flags,
5038                   "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
5039                   "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
5040                   "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
5041                   "\14CSUM_PSEUDO_HDR");
5042        }
5043
5044        if (m->m_flags & M_EXT) {
5045            switch (m->m_ext.ext_type) {
5046            case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
5047            case EXT_SFBUF:      type = "EXT_SFBUF";      break;
5048            case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
5049            case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
5050            case EXT_PACKET:     type = "EXT_PACKET";     break;
5051            case EXT_MBUF:       type = "EXT_MBUF";       break;
5052            case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
5053            case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
5054            case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
5055            case EXT_EXTREF:     type = "EXT_EXTREF";     break;
5056            default:             type = "UNKNOWN";        break;
5057            }
5058
5059            BLOGD(sc, DBG_MBUF,
5060                  "- m_ext: %p ext_size=%d, type=%s\n",
5061                  m->m_ext.ext_buf, m->m_ext.ext_size, type);
5062        }
5063
5064        if (contents) {
5065            bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
5066        }
5067
5068        m = m->m_next;
5069    }
5070}
5071
5072/*
5073 * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
5074 * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
5075 * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
5076 * The headers comes in a seperate bd in FreeBSD so 13-3=10.
5077 * Returns: 0 if OK to send, 1 if packet needs further defragmentation
5078 */
5079static int
5080bxe_chktso_window(struct bxe_softc  *sc,
5081                  int               nsegs,
5082                  bus_dma_segment_t *segs,
5083                  struct mbuf       *m)
5084{
5085    uint32_t num_wnds, wnd_size, wnd_sum;
5086    int32_t frag_idx, wnd_idx;
5087    unsigned short lso_mss;
5088    int defrag;
5089
5090    defrag = 0;
5091    wnd_sum = 0;
5092    wnd_size = 10;
5093    num_wnds = nsegs - wnd_size;
5094    lso_mss = htole16(m->m_pkthdr.tso_segsz);
5095
5096    /*
5097     * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
5098     * first window sum of data while skipping the first assuming it is the
5099     * header in FreeBSD.
5100     */
5101    for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
5102        wnd_sum += htole16(segs[frag_idx].ds_len);
5103    }
5104
5105    /* check the first 10 bd window size */
5106    if (wnd_sum < lso_mss) {
5107        return (1);
5108    }
5109
5110    /* run through the windows */
5111    for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
5112        /* subtract the first mbuf->m_len of the last wndw(-header) */
5113        wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
5114        /* add the next mbuf len to the len of our new window */
5115        wnd_sum += htole16(segs[frag_idx].ds_len);
5116        if (wnd_sum < lso_mss) {
5117            return (1);
5118        }
5119    }
5120
5121    return (0);
5122}
5123
5124static uint8_t
5125bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
5126                    struct mbuf         *m,
5127                    uint32_t            *parsing_data)
5128{
5129    struct ether_vlan_header *eh = NULL;
5130    struct ip *ip4 = NULL;
5131    struct ip6_hdr *ip6 = NULL;
5132    caddr_t ip = NULL;
5133    struct tcphdr *th = NULL;
5134    int e_hlen, ip_hlen, l4_off;
5135    uint16_t proto;
5136
5137    if (m->m_pkthdr.csum_flags == CSUM_IP) {
5138        /* no L4 checksum offload needed */
5139        return (0);
5140    }
5141
5142    /* get the Ethernet header */
5143    eh = mtod(m, struct ether_vlan_header *);
5144
5145    /* handle VLAN encapsulation if present */
5146    if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
5147        e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
5148        proto  = ntohs(eh->evl_proto);
5149    } else {
5150        e_hlen = ETHER_HDR_LEN;
5151        proto  = ntohs(eh->evl_encap_proto);
5152    }
5153
5154    switch (proto) {
5155    case ETHERTYPE_IP:
5156        /* get the IP header, if mbuf len < 20 then header in next mbuf */
5157        ip4 = (m->m_len < sizeof(struct ip)) ?
5158                  (struct ip *)m->m_next->m_data :
5159                  (struct ip *)(m->m_data + e_hlen);
5160        /* ip_hl is number of 32-bit words */
5161        ip_hlen = (ip4->ip_hl << 2);
5162        ip = (caddr_t)ip4;
5163        break;
5164    case ETHERTYPE_IPV6:
5165        /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
5166        ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
5167                  (struct ip6_hdr *)m->m_next->m_data :
5168                  (struct ip6_hdr *)(m->m_data + e_hlen);
5169        /* XXX cannot support offload with IPv6 extensions */
5170        ip_hlen = sizeof(struct ip6_hdr);
5171        ip = (caddr_t)ip6;
5172        break;
5173    default:
5174        /* We can't offload in this case... */
5175        /* XXX error stat ??? */
5176        return (0);
5177    }
5178
5179    /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5180    l4_off = (e_hlen + ip_hlen);
5181
5182    *parsing_data |=
5183        (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
5184         ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
5185
5186    if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5187                                  CSUM_TSO |
5188                                  CSUM_TCP_IPV6)) {
5189        fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5190        th = (struct tcphdr *)(ip + ip_hlen);
5191        /* th_off is number of 32-bit words */
5192        *parsing_data |= ((th->th_off <<
5193                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
5194                          ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
5195        return (l4_off + (th->th_off << 2)); /* entire header length */
5196    } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5197                                         CSUM_UDP_IPV6)) {
5198        fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5199        return (l4_off + sizeof(struct udphdr)); /* entire header length */
5200    } else {
5201        /* XXX error stat ??? */
5202        return (0);
5203    }
5204}
5205
5206static uint8_t
5207bxe_set_pbd_csum(struct bxe_fastpath        *fp,
5208                 struct mbuf                *m,
5209                 struct eth_tx_parse_bd_e1x *pbd)
5210{
5211    struct ether_vlan_header *eh = NULL;
5212    struct ip *ip4 = NULL;
5213    struct ip6_hdr *ip6 = NULL;
5214    caddr_t ip = NULL;
5215    struct tcphdr *th = NULL;
5216    struct udphdr *uh = NULL;
5217    int e_hlen, ip_hlen;
5218    uint16_t proto;
5219    uint8_t hlen;
5220    uint16_t tmp_csum;
5221    uint32_t *tmp_uh;
5222
5223    /* get the Ethernet header */
5224    eh = mtod(m, struct ether_vlan_header *);
5225
5226    /* handle VLAN encapsulation if present */
5227    if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
5228        e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
5229        proto  = ntohs(eh->evl_proto);
5230    } else {
5231        e_hlen = ETHER_HDR_LEN;
5232        proto  = ntohs(eh->evl_encap_proto);
5233    }
5234
5235    switch (proto) {
5236    case ETHERTYPE_IP:
5237        /* get the IP header, if mbuf len < 20 then header in next mbuf */
5238        ip4 = (m->m_len < sizeof(struct ip)) ?
5239                  (struct ip *)m->m_next->m_data :
5240                  (struct ip *)(m->m_data + e_hlen);
5241        /* ip_hl is number of 32-bit words */
5242        ip_hlen = (ip4->ip_hl << 1);
5243        ip = (caddr_t)ip4;
5244        break;
5245    case ETHERTYPE_IPV6:
5246        /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
5247        ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
5248                  (struct ip6_hdr *)m->m_next->m_data :
5249                  (struct ip6_hdr *)(m->m_data + e_hlen);
5250        /* XXX cannot support offload with IPv6 extensions */
5251        ip_hlen = (sizeof(struct ip6_hdr) >> 1);
5252        ip = (caddr_t)ip6;
5253        break;
5254    default:
5255        /* We can't offload in this case... */
5256        /* XXX error stat ??? */
5257        return (0);
5258    }
5259
5260    hlen = (e_hlen >> 1);
5261
5262    /* note that rest of global_data is indirectly zeroed here */
5263    if (m->m_flags & M_VLANTAG) {
5264        pbd->global_data =
5265            htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
5266    } else {
5267        pbd->global_data = htole16(hlen);
5268    }
5269
5270    pbd->ip_hlen_w = ip_hlen;
5271
5272    hlen += pbd->ip_hlen_w;
5273
5274    /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5275
5276    if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5277                                  CSUM_TSO |
5278                                  CSUM_TCP_IPV6)) {
5279        th = (struct tcphdr *)(ip + (ip_hlen << 1));
5280        /* th_off is number of 32-bit words */
5281        hlen += (uint16_t)(th->th_off << 1);
5282    } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5283                                         CSUM_UDP_IPV6)) {
5284        uh = (struct udphdr *)(ip + (ip_hlen << 1));
5285        hlen += (sizeof(struct udphdr) / 2);
5286    } else {
5287        /* valid case as only CSUM_IP was set */
5288        return (0);
5289    }
5290
5291    pbd->total_hlen_w = htole16(hlen);
5292
5293    if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5294                                  CSUM_TSO |
5295                                  CSUM_TCP_IPV6)) {
5296        fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5297        pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5298    } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5299                                         CSUM_UDP_IPV6)) {
5300        fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5301
5302        /*
5303         * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5304         * checksums and does not know anything about the UDP header and where
5305         * the checksum field is located. It only knows about TCP. Therefore
5306         * we "lie" to the hardware for outgoing UDP packets w/ checksum
5307         * offload. Since the checksum field offset for TCP is 16 bytes and
5308         * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5309         * bytes less than the start of the UDP header. This allows the
5310         * hardware to write the checksum in the correct spot. But the
5311         * hardware will compute a checksum which includes the last 10 bytes
5312         * of the IP header. To correct this we tweak the stack computed
5313         * pseudo checksum by folding in the calculation of the inverse
5314         * checksum for those final 10 bytes of the IP header. This allows
5315         * the correct checksum to be computed by the hardware.
5316         */
5317
5318        /* set pointer 10 bytes before UDP header */
5319        tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5320
5321        /* calculate a pseudo header checksum over the first 10 bytes */
5322        tmp_csum = in_pseudo(*tmp_uh,
5323                             *(tmp_uh + 1),
5324                             *(uint16_t *)(tmp_uh + 2));
5325
5326        pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5327    }
5328
5329    return (hlen * 2); /* entire header length, number of bytes */
5330}
5331
5332static void
5333bxe_set_pbd_lso_e2(struct mbuf *m,
5334                   uint32_t    *parsing_data)
5335{
5336    *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5337                       ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5338                      ETH_TX_PARSE_BD_E2_LSO_MSS);
5339
5340    /* XXX test for IPv6 with extension header... */
5341#if 0
5342    struct ip6_hdr *ip6;
5343    if (ip6 && ip6->ip6_nxt == 'some ipv6 extension header')
5344        *parsing_data |= ETH_TX_PARSE_BD_E2_IPV6_WITH_EXT_HDR;
5345#endif
5346}
5347
5348static void
5349bxe_set_pbd_lso(struct mbuf                *m,
5350                struct eth_tx_parse_bd_e1x *pbd)
5351{
5352    struct ether_vlan_header *eh = NULL;
5353    struct ip *ip = NULL;
5354    struct tcphdr *th = NULL;
5355    int e_hlen;
5356
5357    /* get the Ethernet header */
5358    eh = mtod(m, struct ether_vlan_header *);
5359
5360    /* handle VLAN encapsulation if present */
5361    e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5362                 (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5363
5364    /* get the IP and TCP header, with LSO entire header in first mbuf */
5365    /* XXX assuming IPv4 */
5366    ip = (struct ip *)(m->m_data + e_hlen);
5367    th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5368
5369    pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5370    pbd->tcp_send_seq = ntohl(th->th_seq);
5371    pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5372
5373#if 1
5374        /* XXX IPv4 */
5375        pbd->ip_id = ntohs(ip->ip_id);
5376        pbd->tcp_pseudo_csum =
5377            ntohs(in_pseudo(ip->ip_src.s_addr,
5378                            ip->ip_dst.s_addr,
5379                            htons(IPPROTO_TCP)));
5380#else
5381        /* XXX IPv6 */
5382        pbd->tcp_pseudo_csum =
5383            ntohs(in_pseudo(&ip6->ip6_src,
5384                            &ip6->ip6_dst,
5385                            htons(IPPROTO_TCP)));
5386#endif
5387
5388    pbd->global_data |=
5389        htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5390}
5391
5392/*
5393 * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5394 * visible to the controller.
5395 *
5396 * If an mbuf is submitted to this routine and cannot be given to the
5397 * controller (e.g. it has too many fragments) then the function may free
5398 * the mbuf and return to the caller.
5399 *
5400 * Returns:
5401 *   0 = Success, !0 = Failure
5402 *   Note the side effect that an mbuf may be freed if it causes a problem.
5403 */
5404static int
5405bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5406{
5407    bus_dma_segment_t segs[32];
5408    struct mbuf *m0;
5409    struct bxe_sw_tx_bd *tx_buf;
5410    struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5411    struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5412    /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5413    struct eth_tx_bd *tx_data_bd;
5414    struct eth_tx_bd *tx_total_pkt_size_bd;
5415    struct eth_tx_start_bd *tx_start_bd;
5416    uint16_t bd_prod, pkt_prod, total_pkt_size;
5417    uint8_t mac_type;
5418    int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5419    struct bxe_softc *sc;
5420    uint16_t tx_bd_avail;
5421    struct ether_vlan_header *eh;
5422    uint32_t pbd_e2_parsing_data = 0;
5423    uint8_t hlen = 0;
5424    int tmp_bd;
5425    int i;
5426
5427    sc = fp->sc;
5428
5429    M_ASSERTPKTHDR(*m_head);
5430
5431    m0 = *m_head;
5432    rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5433    tx_start_bd = NULL;
5434    tx_data_bd = NULL;
5435    tx_total_pkt_size_bd = NULL;
5436
5437    /* get the H/W pointer for packets and BDs */
5438    pkt_prod = fp->tx_pkt_prod;
5439    bd_prod = fp->tx_bd_prod;
5440
5441    mac_type = UNICAST_ADDRESS;
5442
5443    /* map the mbuf into the next open DMAable memory */
5444    tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5445    error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5446                                    tx_buf->m_map, m0,
5447                                    segs, &nsegs, BUS_DMA_NOWAIT);
5448
5449    /* mapping errors */
5450    if(__predict_false(error != 0)) {
5451        fp->eth_q_stats.tx_dma_mapping_failure++;
5452        if (error == ENOMEM) {
5453            /* resource issue, try again later */
5454            rc = ENOMEM;
5455        } else if (error == EFBIG) {
5456            /* possibly recoverable with defragmentation */
5457            fp->eth_q_stats.mbuf_defrag_attempts++;
5458            m0 = m_defrag(*m_head, M_DONTWAIT);
5459            if (m0 == NULL) {
5460                fp->eth_q_stats.mbuf_defrag_failures++;
5461                rc = ENOBUFS;
5462            } else {
5463                /* defrag successful, try mapping again */
5464                *m_head = m0;
5465                error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5466                                                tx_buf->m_map, m0,
5467                                                segs, &nsegs, BUS_DMA_NOWAIT);
5468                if (error) {
5469                    fp->eth_q_stats.tx_dma_mapping_failure++;
5470                    rc = error;
5471                }
5472            }
5473        } else {
5474            /* unknown, unrecoverable mapping error */
5475            BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5476            bxe_dump_mbuf(sc, m0, FALSE);
5477            rc = error;
5478        }
5479
5480        goto bxe_tx_encap_continue;
5481    }
5482
5483    tx_bd_avail = bxe_tx_avail(sc, fp);
5484
5485    /* make sure there is enough room in the send queue */
5486    if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5487        /* Recoverable, try again later. */
5488        fp->eth_q_stats.tx_hw_queue_full++;
5489        bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5490        rc = ENOMEM;
5491        goto bxe_tx_encap_continue;
5492    }
5493
5494    /* capture the current H/W TX chain high watermark */
5495    if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5496                        (TX_BD_USABLE - tx_bd_avail))) {
5497        fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5498    }
5499
5500    /* make sure it fits in the packet window */
5501    if (__predict_false(nsegs > 12)) {
5502        /*
5503         * The mbuf may be to big for the controller to handle. If the frame
5504         * is a TSO frame we'll need to do an additional check.
5505         */
5506        if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5507            if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5508                goto bxe_tx_encap_continue; /* OK to send */
5509            } else {
5510                fp->eth_q_stats.tx_window_violation_tso++;
5511            }
5512        } else {
5513            fp->eth_q_stats.tx_window_violation_std++;
5514        }
5515
5516        /* XXX I don't like this, change to double copy packet */
5517
5518        /* no sense trying to defrag again, just drop the frame */
5519        rc = ENODEV;
5520    }
5521
5522bxe_tx_encap_continue:
5523
5524    /* Check for errors */
5525    if (rc) {
5526        if (rc == ENOMEM) {
5527            /* recoverable try again later  */
5528        } else {
5529            fp->eth_q_stats.tx_soft_errors++;
5530            fp->eth_q_stats.mbuf_alloc_tx--;
5531            m_freem(*m_head);
5532            *m_head = NULL;
5533        }
5534
5535        return (rc);
5536    }
5537
5538    /* set flag according to packet type (UNICAST_ADDRESS is default) */
5539    if (m0->m_flags & M_BCAST) {
5540        mac_type = BROADCAST_ADDRESS;
5541    } else if (m0->m_flags & M_MCAST) {
5542        mac_type = MULTICAST_ADDRESS;
5543    }
5544
5545    /* store the mbuf into the mbuf ring */
5546    tx_buf->m        = m0;
5547    tx_buf->first_bd = fp->tx_bd_prod;
5548    tx_buf->flags    = 0;
5549
5550    /* prepare the first transmit (start) BD for the mbuf */
5551    tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5552
5553    BLOGD(sc, DBG_TX,
5554          "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5555          pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5556
5557    tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5558    tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5559    tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5560    total_pkt_size += tx_start_bd->nbytes;
5561    tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5562
5563    tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5564
5565    /* all frames have at least Start BD + Parsing BD */
5566    nbds = nsegs + 1;
5567    tx_start_bd->nbd = htole16(nbds);
5568
5569    if (m0->m_flags & M_VLANTAG) {
5570        tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5571        tx_start_bd->bd_flags.as_bitfield |=
5572            (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5573    } else {
5574        /* vf tx, start bd must hold the ethertype for fw to enforce it */
5575        if (IS_VF(sc)) {
5576            /* map ethernet header to find type and header length */
5577            eh = mtod(m0, struct ether_vlan_header *);
5578            tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5579        } else {
5580            /* used by FW for packet accounting */
5581            tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5582#if 0
5583            /*
5584             * If NPAR-SD is active then FW should do the tagging regardless
5585             * of value of priority. Otherwise, if priority indicates this is
5586             * a control packet we need to indicate to FW to avoid tagging.
5587             */
5588            if (!IS_MF_AFEX(sc) && (mbuf priority == PRIO_CONTROL)) {
5589                SET_FLAG(tx_start_bd->general_data,
5590                         ETH_TX_START_BD_FORCE_VLAN_MODE, 1);
5591            }
5592#endif
5593        }
5594    }
5595
5596    /*
5597     * add a parsing BD from the chain. The parsing BD is always added
5598     * though it is only used for TSO and chksum
5599     */
5600    bd_prod = TX_BD_NEXT(bd_prod);
5601
5602    if (m0->m_pkthdr.csum_flags) {
5603        if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5604            fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5605            tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5606        }
5607
5608        if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5609            tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5610                                                  ETH_TX_BD_FLAGS_L4_CSUM);
5611        } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5612            tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5613                                                  ETH_TX_BD_FLAGS_IS_UDP |
5614                                                  ETH_TX_BD_FLAGS_L4_CSUM);
5615        } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5616                   (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5617            tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5618        } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5619            tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5620                                                  ETH_TX_BD_FLAGS_IS_UDP);
5621        }
5622    }
5623
5624    if (!CHIP_IS_E1x(sc)) {
5625        pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5626        memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5627
5628        if (m0->m_pkthdr.csum_flags) {
5629            hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5630        }
5631
5632#if 0
5633        /*
5634         * Add the MACs to the parsing BD if the module param was
5635         * explicitly set, if this is a vf, or in switch independent
5636         * mode.
5637         */
5638        if (sc->flags & BXE_TX_SWITCHING || IS_VF(sc) || IS_MF_SI(sc)) {
5639            eh = mtod(m0, struct ether_vlan_header *);
5640            bxe_set_fw_mac_addr(&pbd_e2->data.mac_addr.src_hi,
5641                                &pbd_e2->data.mac_addr.src_mid,
5642                                &pbd_e2->data.mac_addr.src_lo,
5643                                eh->evl_shost);
5644            bxe_set_fw_mac_addr(&pbd_e2->data.mac_addr.dst_hi,
5645                                &pbd_e2->data.mac_addr.dst_mid,
5646                                &pbd_e2->data.mac_addr.dst_lo,
5647                                eh->evl_dhost);
5648        }
5649#endif
5650
5651        SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5652                 mac_type);
5653    } else {
5654        uint16_t global_data = 0;
5655
5656        pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5657        memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5658
5659        if (m0->m_pkthdr.csum_flags) {
5660            hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5661        }
5662
5663        SET_FLAG(global_data,
5664                 ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5665        pbd_e1x->global_data |= htole16(global_data);
5666    }
5667
5668    /* setup the parsing BD with TSO specific info */
5669    if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5670        fp->eth_q_stats.tx_ofld_frames_lso++;
5671        tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5672
5673        if (__predict_false(tx_start_bd->nbytes > hlen)) {
5674            fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5675
5676            /* split the first BD into header/data making the fw job easy */
5677            nbds++;
5678            tx_start_bd->nbd = htole16(nbds);
5679
5680            bd_prod = TX_BD_NEXT(bd_prod);
5681
5682            /* new transmit BD after the tx_parse_bd */
5683            tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5684            tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5685            tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5686            tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5687            if (tx_total_pkt_size_bd == NULL) {
5688                tx_total_pkt_size_bd = tx_data_bd;
5689            }
5690
5691            BLOGD(sc, DBG_TX,
5692                  "TSO split header size is %d (%x:%x) nbds %d\n",
5693                  le16toh(tx_start_bd->nbytes),
5694                  le32toh(tx_start_bd->addr_hi),
5695                  le32toh(tx_start_bd->addr_lo),
5696                  nbds);
5697        }
5698
5699        if (!CHIP_IS_E1x(sc)) {
5700            bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5701        } else {
5702            bxe_set_pbd_lso(m0, pbd_e1x);
5703        }
5704    }
5705
5706    if (pbd_e2_parsing_data) {
5707        pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5708    }
5709
5710    /* prepare remaining BDs, start tx bd contains first seg/frag */
5711    for (i = 1; i < nsegs ; i++) {
5712        bd_prod = TX_BD_NEXT(bd_prod);
5713        tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5714        tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5715        tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5716        tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5717        if (tx_total_pkt_size_bd == NULL) {
5718            tx_total_pkt_size_bd = tx_data_bd;
5719        }
5720        total_pkt_size += tx_data_bd->nbytes;
5721    }
5722
5723    BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5724
5725    if (tx_total_pkt_size_bd != NULL) {
5726        tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5727    }
5728
5729    if (__predict_false(sc->debug & DBG_TX)) {
5730        tmp_bd = tx_buf->first_bd;
5731        for (i = 0; i < nbds; i++)
5732        {
5733            if (i == 0) {
5734                BLOGD(sc, DBG_TX,
5735                      "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5736                      "bd_flags=0x%x hdr_nbds=%d\n",
5737                      tx_start_bd,
5738                      tmp_bd,
5739                      le16toh(tx_start_bd->nbd),
5740                      le16toh(tx_start_bd->vlan_or_ethertype),
5741                      tx_start_bd->bd_flags.as_bitfield,
5742                      (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5743            } else if (i == 1) {
5744                if (pbd_e1x) {
5745                    BLOGD(sc, DBG_TX,
5746                          "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5747                          "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5748                          "tcp_seq=%u total_hlen_w=%u\n",
5749                          pbd_e1x,
5750                          tmp_bd,
5751                          pbd_e1x->global_data,
5752                          pbd_e1x->ip_hlen_w,
5753                          pbd_e1x->ip_id,
5754                          pbd_e1x->lso_mss,
5755                          pbd_e1x->tcp_flags,
5756                          pbd_e1x->tcp_pseudo_csum,
5757                          pbd_e1x->tcp_send_seq,
5758                          le16toh(pbd_e1x->total_hlen_w));
5759                } else { /* if (pbd_e2) */
5760                    BLOGD(sc, DBG_TX,
5761                          "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5762                          "src=%02x:%02x:%02x parsing_data=0x%x\n",
5763                          pbd_e2,
5764                          tmp_bd,
5765                          pbd_e2->data.mac_addr.dst_hi,
5766                          pbd_e2->data.mac_addr.dst_mid,
5767                          pbd_e2->data.mac_addr.dst_lo,
5768                          pbd_e2->data.mac_addr.src_hi,
5769                          pbd_e2->data.mac_addr.src_mid,
5770                          pbd_e2->data.mac_addr.src_lo,
5771                          pbd_e2->parsing_data);
5772                }
5773            }
5774
5775            if (i != 1) { /* skip parse db as it doesn't hold data */
5776                tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5777                BLOGD(sc, DBG_TX,
5778                      "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5779                      tx_data_bd,
5780                      tmp_bd,
5781                      le16toh(tx_data_bd->nbytes),
5782                      le32toh(tx_data_bd->addr_hi),
5783                      le32toh(tx_data_bd->addr_lo));
5784            }
5785
5786            tmp_bd = TX_BD_NEXT(tmp_bd);
5787        }
5788    }
5789
5790    BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5791
5792    /* update TX BD producer index value for next TX */
5793    bd_prod = TX_BD_NEXT(bd_prod);
5794
5795    /*
5796     * If the chain of tx_bd's describing this frame is adjacent to or spans
5797     * an eth_tx_next_bd element then we need to increment the nbds value.
5798     */
5799    if (TX_BD_IDX(bd_prod) < nbds) {
5800        nbds++;
5801    }
5802
5803    /* don't allow reordering of writes for nbd and packets */
5804    mb();
5805
5806    fp->tx_db.data.prod += nbds;
5807
5808    /* producer points to the next free tx_bd at this point */
5809    fp->tx_pkt_prod++;
5810    fp->tx_bd_prod = bd_prod;
5811
5812    DOORBELL(sc, fp->index, fp->tx_db.raw);
5813
5814    fp->eth_q_stats.tx_pkts++;
5815
5816    /* Prevent speculative reads from getting ahead of the status block. */
5817    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5818                      0, 0, BUS_SPACE_BARRIER_READ);
5819
5820    /* Prevent speculative reads from getting ahead of the doorbell. */
5821    bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5822                      0, 0, BUS_SPACE_BARRIER_READ);
5823
5824    return (0);
5825}
5826
5827static void
5828bxe_tx_start_locked(struct bxe_softc    *sc,
5829                    struct ifnet        *ifp,
5830                    struct bxe_fastpath *fp)
5831{
5832    struct mbuf *m = NULL;
5833    int tx_count = 0;
5834    uint16_t tx_bd_avail;
5835
5836    BXE_FP_TX_LOCK_ASSERT(fp);
5837
5838    /* keep adding entries while there are frames to send */
5839    while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
5840
5841        /*
5842         * check for any frames to send
5843         * dequeue can still be NULL even if queue is not empty
5844         */
5845        IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
5846        if (__predict_false(m == NULL)) {
5847            break;
5848        }
5849
5850        /* the mbuf now belongs to us */
5851        fp->eth_q_stats.mbuf_alloc_tx++;
5852
5853        /*
5854         * Put the frame into the transmit ring. If we don't have room,
5855         * place the mbuf back at the head of the TX queue, set the
5856         * OACTIVE flag, and wait for the NIC to drain the chain.
5857         */
5858        if (__predict_false(bxe_tx_encap(fp, &m))) {
5859            fp->eth_q_stats.tx_encap_failures++;
5860            if (m != NULL) {
5861                /* mark the TX queue as full and return the frame */
5862                ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5863                IFQ_DRV_PREPEND(&ifp->if_snd, m);
5864                fp->eth_q_stats.mbuf_alloc_tx--;
5865                fp->eth_q_stats.tx_queue_xoff++;
5866            }
5867
5868            /* stop looking for more work */
5869            break;
5870        }
5871
5872        /* the frame was enqueued successfully */
5873        tx_count++;
5874
5875        /* send a copy of the frame to any BPF listeners. */
5876        BPF_MTAP(ifp, m);
5877
5878        tx_bd_avail = bxe_tx_avail(sc, fp);
5879
5880        /* handle any completions if we're running low */
5881        if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5882            bxe_txeof(sc, fp);
5883        }
5884
5885        /* close TX if we're still running low */
5886        if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5887            ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5888            break;
5889        }
5890    }
5891
5892    /* all TX packets were dequeued and/or the tx ring is full */
5893    if (tx_count > 0) {
5894        /* reset the TX watchdog timeout timer */
5895        fp->watchdog_timer = BXE_TX_TIMEOUT;
5896    }
5897}
5898
5899/* Legacy (non-RSS) dispatch routine */
5900static void
5901bxe_tx_start(struct ifnet *ifp)
5902{
5903    struct bxe_softc *sc;
5904    struct bxe_fastpath *fp;
5905
5906    sc = ifp->if_softc;
5907
5908    if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5909        BLOGW(sc, "Interface not running, ignoring transmit request\n");
5910        return;
5911    }
5912
5913    if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5914        BLOGW(sc, "Interface TX queue is full, ignoring transmit request\n");
5915        return;
5916    }
5917
5918    if (!sc->link_vars.link_up) {
5919        BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5920        return;
5921    }
5922
5923    fp = &sc->fp[0];
5924
5925    BXE_FP_TX_LOCK(fp);
5926    bxe_tx_start_locked(sc, ifp, fp);
5927    BXE_FP_TX_UNLOCK(fp);
5928}
5929
5930#if __FreeBSD_version >= 800000
5931
5932static int
5933bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5934                       struct ifnet        *ifp,
5935                       struct bxe_fastpath *fp,
5936                       struct mbuf         *m)
5937{
5938    struct buf_ring *tx_br = fp->tx_br;
5939    struct mbuf *next;
5940    int depth, rc, tx_count;
5941    uint16_t tx_bd_avail;
5942
5943    rc = tx_count = 0;
5944
5945    if (!tx_br) {
5946        BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5947        return (EINVAL);
5948    }
5949
5950    /* fetch the depth of the driver queue */
5951    depth = drbr_inuse(ifp, tx_br);
5952    if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5953        fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5954    }
5955
5956    BXE_FP_TX_LOCK_ASSERT(fp);
5957
5958    if (m == NULL) {
5959        /* no new work, check for pending frames */
5960        next = drbr_dequeue(ifp, tx_br);
5961    } else if (drbr_needs_enqueue(ifp, tx_br)) {
5962        /* have both new and pending work, maintain packet order */
5963        rc = drbr_enqueue(ifp, tx_br, m);
5964        if (rc != 0) {
5965            fp->eth_q_stats.tx_soft_errors++;
5966            goto bxe_tx_mq_start_locked_exit;
5967        }
5968        next = drbr_dequeue(ifp, tx_br);
5969    } else {
5970        /* new work only and nothing pending */
5971        next = m;
5972    }
5973
5974    /* keep adding entries while there are frames to send */
5975    while (next != NULL) {
5976
5977        /* the mbuf now belongs to us */
5978        fp->eth_q_stats.mbuf_alloc_tx++;
5979
5980        /*
5981         * Put the frame into the transmit ring. If we don't have room,
5982         * place the mbuf back at the head of the TX queue, set the
5983         * OACTIVE flag, and wait for the NIC to drain the chain.
5984         */
5985        rc = bxe_tx_encap(fp, &next);
5986        if (__predict_false(rc != 0)) {
5987            fp->eth_q_stats.tx_encap_failures++;
5988            if (next != NULL) {
5989                /* mark the TX queue as full and save the frame */
5990                ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5991                /* XXX this may reorder the frame */
5992                rc = drbr_enqueue(ifp, tx_br, next);
5993                fp->eth_q_stats.mbuf_alloc_tx--;
5994                fp->eth_q_stats.tx_frames_deferred++;
5995            }
5996
5997            /* stop looking for more work */
5998            break;
5999        }
6000
6001        /* the transmit frame was enqueued successfully */
6002        tx_count++;
6003
6004        /* send a copy of the frame to any BPF listeners */
6005        BPF_MTAP(ifp, next);
6006
6007        tx_bd_avail = bxe_tx_avail(sc, fp);
6008
6009        /* handle any completions if we're running low */
6010        if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
6011            bxe_txeof(sc, fp);
6012        }
6013
6014        /* close TX if we're still running low */
6015        if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
6016            ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
6017            break;
6018        }
6019
6020        next = drbr_dequeue(ifp, tx_br);
6021    }
6022
6023    /* all TX packets were dequeued and/or the tx ring is full */
6024    if (tx_count > 0) {
6025        /* reset the TX watchdog timeout timer */
6026        fp->watchdog_timer = BXE_TX_TIMEOUT;
6027    }
6028
6029bxe_tx_mq_start_locked_exit:
6030
6031    return (rc);
6032}
6033
6034/* Multiqueue (TSS) dispatch routine. */
6035static int
6036bxe_tx_mq_start(struct ifnet *ifp,
6037                struct mbuf  *m)
6038{
6039    struct bxe_softc *sc = ifp->if_softc;
6040    struct bxe_fastpath *fp;
6041    int fp_index, rc;
6042
6043    fp_index = 0; /* default is the first queue */
6044
6045    /* change the queue if using flow ID */
6046    if ((m->m_flags & M_FLOWID) != 0) {
6047        fp_index = (m->m_pkthdr.flowid % sc->num_queues);
6048    }
6049
6050    fp = &sc->fp[fp_index];
6051
6052    if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
6053        BLOGW(sc, "Interface not running, ignoring transmit request\n");
6054        return (ENETDOWN);
6055    }
6056
6057    if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
6058        BLOGW(sc, "Interface TX queue is full, ignoring transmit request\n");
6059        return (EBUSY);
6060    }
6061
6062    if (!sc->link_vars.link_up) {
6063        BLOGW(sc, "Interface link is down, ignoring transmit request\n");
6064        return (ENETDOWN);
6065    }
6066
6067    /* XXX change to TRYLOCK here and if failed then schedule taskqueue */
6068
6069    BXE_FP_TX_LOCK(fp);
6070    rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
6071    BXE_FP_TX_UNLOCK(fp);
6072
6073    return (rc);
6074}
6075
6076static void
6077bxe_mq_flush(struct ifnet *ifp)
6078{
6079    struct bxe_softc *sc = ifp->if_softc;
6080    struct bxe_fastpath *fp;
6081    struct mbuf *m;
6082    int i;
6083
6084    for (i = 0; i < sc->num_queues; i++) {
6085        fp = &sc->fp[i];
6086
6087        if (fp->state != BXE_FP_STATE_OPEN) {
6088            BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
6089                  fp->index, fp->state);
6090            continue;
6091        }
6092
6093        if (fp->tx_br != NULL) {
6094            BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
6095            BXE_FP_TX_LOCK(fp);
6096            while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
6097                m_freem(m);
6098            }
6099            BXE_FP_TX_UNLOCK(fp);
6100        }
6101    }
6102
6103    if_qflush(ifp);
6104}
6105
6106#endif /* FreeBSD_version >= 800000 */
6107
6108static uint16_t
6109bxe_cid_ilt_lines(struct bxe_softc *sc)
6110{
6111    if (IS_SRIOV(sc)) {
6112        return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
6113    }
6114    return (L2_ILT_LINES(sc));
6115}
6116
6117static void
6118bxe_ilt_set_info(struct bxe_softc *sc)
6119{
6120    struct ilt_client_info *ilt_client;
6121    struct ecore_ilt *ilt = sc->ilt;
6122    uint16_t line = 0;
6123
6124    ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
6125    BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
6126
6127    /* CDU */
6128    ilt_client = &ilt->clients[ILT_CLIENT_CDU];
6129    ilt_client->client_num = ILT_CLIENT_CDU;
6130    ilt_client->page_size = CDU_ILT_PAGE_SZ;
6131    ilt_client->flags = ILT_CLIENT_SKIP_MEM;
6132    ilt_client->start = line;
6133    line += bxe_cid_ilt_lines(sc);
6134
6135    if (CNIC_SUPPORT(sc)) {
6136        line += CNIC_ILT_LINES;
6137    }
6138
6139    ilt_client->end = (line - 1);
6140
6141    BLOGD(sc, DBG_LOAD,
6142          "ilt client[CDU]: start %d, end %d, "
6143          "psz 0x%x, flags 0x%x, hw psz %d\n",
6144          ilt_client->start, ilt_client->end,
6145          ilt_client->page_size,
6146          ilt_client->flags,
6147          ilog2(ilt_client->page_size >> 12));
6148
6149    /* QM */
6150    if (QM_INIT(sc->qm_cid_count)) {
6151        ilt_client = &ilt->clients[ILT_CLIENT_QM];
6152        ilt_client->client_num = ILT_CLIENT_QM;
6153        ilt_client->page_size = QM_ILT_PAGE_SZ;
6154        ilt_client->flags = 0;
6155        ilt_client->start = line;
6156
6157        /* 4 bytes for each cid */
6158        line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
6159                             QM_ILT_PAGE_SZ);
6160
6161        ilt_client->end = (line - 1);
6162
6163        BLOGD(sc, DBG_LOAD,
6164              "ilt client[QM]: start %d, end %d, "
6165              "psz 0x%x, flags 0x%x, hw psz %d\n",
6166              ilt_client->start, ilt_client->end,
6167              ilt_client->page_size, ilt_client->flags,
6168              ilog2(ilt_client->page_size >> 12));
6169    }
6170
6171    if (CNIC_SUPPORT(sc)) {
6172        /* SRC */
6173        ilt_client = &ilt->clients[ILT_CLIENT_SRC];
6174        ilt_client->client_num = ILT_CLIENT_SRC;
6175        ilt_client->page_size = SRC_ILT_PAGE_SZ;
6176        ilt_client->flags = 0;
6177        ilt_client->start = line;
6178        line += SRC_ILT_LINES;
6179        ilt_client->end = (line - 1);
6180
6181        BLOGD(sc, DBG_LOAD,
6182              "ilt client[SRC]: start %d, end %d, "
6183              "psz 0x%x, flags 0x%x, hw psz %d\n",
6184              ilt_client->start, ilt_client->end,
6185              ilt_client->page_size, ilt_client->flags,
6186              ilog2(ilt_client->page_size >> 12));
6187
6188        /* TM */
6189        ilt_client = &ilt->clients[ILT_CLIENT_TM];
6190        ilt_client->client_num = ILT_CLIENT_TM;
6191        ilt_client->page_size = TM_ILT_PAGE_SZ;
6192        ilt_client->flags = 0;
6193        ilt_client->start = line;
6194        line += TM_ILT_LINES;
6195        ilt_client->end = (line - 1);
6196
6197        BLOGD(sc, DBG_LOAD,
6198              "ilt client[TM]: start %d, end %d, "
6199              "psz 0x%x, flags 0x%x, hw psz %d\n",
6200              ilt_client->start, ilt_client->end,
6201              ilt_client->page_size, ilt_client->flags,
6202              ilog2(ilt_client->page_size >> 12));
6203    }
6204
6205    KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
6206}
6207
6208static void
6209bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
6210{
6211    int i;
6212
6213    BLOGD(sc, DBG_LOAD, "mtu = %d\n", sc->mtu);
6214
6215    for (i = 0; i < sc->num_queues; i++) {
6216        /* get the Rx buffer size for RX frames */
6217        sc->fp[i].rx_buf_size =
6218            (IP_HEADER_ALIGNMENT_PADDING +
6219             ETH_OVERHEAD +
6220             sc->mtu);
6221
6222        BLOGD(sc, DBG_LOAD, "rx_buf_size for fp[%02d] = %d\n",
6223              i, sc->fp[i].rx_buf_size);
6224
6225        /* get the mbuf allocation size for RX frames */
6226        if (sc->fp[i].rx_buf_size <= MCLBYTES) {
6227            sc->fp[i].mbuf_alloc_size = MCLBYTES;
6228        } else if (sc->fp[i].rx_buf_size <= BCM_PAGE_SIZE) {
6229            sc->fp[i].mbuf_alloc_size = PAGE_SIZE;
6230        } else {
6231            sc->fp[i].mbuf_alloc_size = MJUM9BYTES;
6232        }
6233
6234        BLOGD(sc, DBG_LOAD, "mbuf_alloc_size for fp[%02d] = %d\n",
6235              i, sc->fp[i].mbuf_alloc_size);
6236    }
6237}
6238
6239static int
6240bxe_alloc_ilt_mem(struct bxe_softc *sc)
6241{
6242    int rc = 0;
6243
6244    if ((sc->ilt =
6245         (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
6246                                    M_BXE_ILT,
6247                                    (M_NOWAIT | M_ZERO))) == NULL) {
6248        rc = 1;
6249    }
6250
6251    return (rc);
6252}
6253
6254static int
6255bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
6256{
6257    int rc = 0;
6258
6259    if ((sc->ilt->lines =
6260         (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6261                                    M_BXE_ILT,
6262                                    (M_NOWAIT | M_ZERO))) == NULL) {
6263        rc = 1;
6264    }
6265
6266    return (rc);
6267}
6268
6269static void
6270bxe_free_ilt_mem(struct bxe_softc *sc)
6271{
6272    if (sc->ilt != NULL) {
6273        free(sc->ilt, M_BXE_ILT);
6274        sc->ilt = NULL;
6275    }
6276}
6277
6278static void
6279bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6280{
6281    if (sc->ilt->lines != NULL) {
6282        free(sc->ilt->lines, M_BXE_ILT);
6283        sc->ilt->lines = NULL;
6284    }
6285}
6286
6287static void
6288bxe_free_mem(struct bxe_softc *sc)
6289{
6290    int i;
6291
6292#if 0
6293    if (!CONFIGURE_NIC_MODE(sc)) {
6294        /* free searcher T2 table */
6295        bxe_dma_free(sc, &sc->t2);
6296    }
6297#endif
6298
6299    for (i = 0; i < L2_ILT_LINES(sc); i++) {
6300        bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6301        sc->context[i].vcxt = NULL;
6302        sc->context[i].size = 0;
6303    }
6304
6305    ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6306
6307    bxe_free_ilt_lines_mem(sc);
6308
6309#if 0
6310    bxe_iov_free_mem(sc);
6311#endif
6312}
6313
6314static int
6315bxe_alloc_mem(struct bxe_softc *sc)
6316{
6317    int context_size;
6318    int allocated;
6319    int i;
6320
6321#if 0
6322    if (!CONFIGURE_NIC_MODE(sc)) {
6323        /* allocate searcher T2 table */
6324        if (bxe_dma_alloc(sc, SRC_T2_SZ,
6325                          &sc->t2, "searcher t2 table") != 0) {
6326            return (-1);
6327        }
6328    }
6329#endif
6330
6331    /*
6332     * Allocate memory for CDU context:
6333     * This memory is allocated separately and not in the generic ILT
6334     * functions because CDU differs in few aspects:
6335     * 1. There can be multiple entities allocating memory for context -
6336     * regular L2, CNIC, and SRIOV drivers. Each separately controls
6337     * its own ILT lines.
6338     * 2. Since CDU page-size is not a single 4KB page (which is the case
6339     * for the other ILT clients), to be efficient we want to support
6340     * allocation of sub-page-size in the last entry.
6341     * 3. Context pointers are used by the driver to pass to FW / update
6342     * the context (for the other ILT clients the pointers are used just to
6343     * free the memory during unload).
6344     */
6345    context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6346    for (i = 0, allocated = 0; allocated < context_size; i++) {
6347        sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6348                                  (context_size - allocated));
6349
6350        if (bxe_dma_alloc(sc, sc->context[i].size,
6351                          &sc->context[i].vcxt_dma,
6352                          "cdu context") != 0) {
6353            bxe_free_mem(sc);
6354            return (-1);
6355        }
6356
6357        sc->context[i].vcxt =
6358            (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6359
6360        allocated += sc->context[i].size;
6361    }
6362
6363    bxe_alloc_ilt_lines_mem(sc);
6364
6365    BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6366          sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6367    {
6368        for (i = 0; i < 4; i++) {
6369            BLOGD(sc, DBG_LOAD,
6370                  "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6371                  i,
6372                  sc->ilt->clients[i].page_size,
6373                  sc->ilt->clients[i].start,
6374                  sc->ilt->clients[i].end,
6375                  sc->ilt->clients[i].client_num,
6376                  sc->ilt->clients[i].flags);
6377        }
6378    }
6379    if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6380        BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6381        bxe_free_mem(sc);
6382        return (-1);
6383    }
6384
6385#if 0
6386    if (bxe_iov_alloc_mem(sc)) {
6387        BLOGE(sc, "Failed to allocate memory for SRIOV\n");
6388        bxe_free_mem(sc);
6389        return (-1);
6390    }
6391#endif
6392
6393    return (0);
6394}
6395
6396static void
6397bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6398{
6399    struct bxe_softc *sc;
6400    int i;
6401
6402    sc = fp->sc;
6403
6404    if (fp->rx_mbuf_tag == NULL) {
6405        return;
6406    }
6407
6408    /* free all mbufs and unload all maps */
6409    for (i = 0; i < RX_BD_TOTAL; i++) {
6410        if (fp->rx_mbuf_chain[i].m_map != NULL) {
6411            bus_dmamap_sync(fp->rx_mbuf_tag,
6412                            fp->rx_mbuf_chain[i].m_map,
6413                            BUS_DMASYNC_POSTREAD);
6414            bus_dmamap_unload(fp->rx_mbuf_tag,
6415                              fp->rx_mbuf_chain[i].m_map);
6416        }
6417
6418        if (fp->rx_mbuf_chain[i].m != NULL) {
6419            m_freem(fp->rx_mbuf_chain[i].m);
6420            fp->rx_mbuf_chain[i].m = NULL;
6421            fp->eth_q_stats.mbuf_alloc_rx--;
6422        }
6423    }
6424}
6425
6426static void
6427bxe_free_tpa_pool(struct bxe_fastpath *fp)
6428{
6429    struct bxe_softc *sc;
6430    int i, max_agg_queues;
6431
6432    sc = fp->sc;
6433
6434    if (fp->rx_mbuf_tag == NULL) {
6435        return;
6436    }
6437
6438    max_agg_queues = MAX_AGG_QS(sc);
6439
6440    /* release all mbufs and unload all DMA maps in the TPA pool */
6441    for (i = 0; i < max_agg_queues; i++) {
6442        if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6443            bus_dmamap_sync(fp->rx_mbuf_tag,
6444                            fp->rx_tpa_info[i].bd.m_map,
6445                            BUS_DMASYNC_POSTREAD);
6446            bus_dmamap_unload(fp->rx_mbuf_tag,
6447                              fp->rx_tpa_info[i].bd.m_map);
6448        }
6449
6450        if (fp->rx_tpa_info[i].bd.m != NULL) {
6451            m_freem(fp->rx_tpa_info[i].bd.m);
6452            fp->rx_tpa_info[i].bd.m = NULL;
6453            fp->eth_q_stats.mbuf_alloc_tpa--;
6454        }
6455    }
6456}
6457
6458static void
6459bxe_free_sge_chain(struct bxe_fastpath *fp)
6460{
6461    struct bxe_softc *sc;
6462    int i;
6463
6464    sc = fp->sc;
6465
6466    if (fp->rx_sge_mbuf_tag == NULL) {
6467        return;
6468    }
6469
6470    /* rree all mbufs and unload all maps */
6471    for (i = 0; i < RX_SGE_TOTAL; i++) {
6472        if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6473            bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6474                            fp->rx_sge_mbuf_chain[i].m_map,
6475                            BUS_DMASYNC_POSTREAD);
6476            bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6477                              fp->rx_sge_mbuf_chain[i].m_map);
6478        }
6479
6480        if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6481            m_freem(fp->rx_sge_mbuf_chain[i].m);
6482            fp->rx_sge_mbuf_chain[i].m = NULL;
6483            fp->eth_q_stats.mbuf_alloc_sge--;
6484        }
6485    }
6486}
6487
6488static void
6489bxe_free_fp_buffers(struct bxe_softc *sc)
6490{
6491    struct bxe_fastpath *fp;
6492    int i;
6493
6494    for (i = 0; i < sc->num_queues; i++) {
6495        fp = &sc->fp[i];
6496
6497#if __FreeBSD_version >= 800000
6498        if (fp->tx_br != NULL) {
6499            struct mbuf *m;
6500            /* just in case bxe_mq_flush() wasn't called */
6501            while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
6502                m_freem(m);
6503            }
6504            buf_ring_free(fp->tx_br, M_DEVBUF);
6505            fp->tx_br = NULL;
6506        }
6507#endif
6508
6509        /* free all RX buffers */
6510        bxe_free_rx_bd_chain(fp);
6511        bxe_free_tpa_pool(fp);
6512        bxe_free_sge_chain(fp);
6513
6514        if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6515            BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6516                  fp->eth_q_stats.mbuf_alloc_rx);
6517        }
6518
6519        if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6520            BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6521                  fp->eth_q_stats.mbuf_alloc_sge);
6522        }
6523
6524        if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6525            BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6526                  fp->eth_q_stats.mbuf_alloc_tpa);
6527        }
6528
6529        if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6530            BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6531                  fp->eth_q_stats.mbuf_alloc_tx);
6532        }
6533
6534        /* XXX verify all mbufs were reclaimed */
6535
6536        if (mtx_initialized(&fp->tx_mtx)) {
6537            mtx_destroy(&fp->tx_mtx);
6538        }
6539
6540        if (mtx_initialized(&fp->rx_mtx)) {
6541            mtx_destroy(&fp->rx_mtx);
6542        }
6543    }
6544}
6545
6546static int
6547bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6548                     uint16_t            prev_index,
6549                     uint16_t            index)
6550{
6551    struct bxe_sw_rx_bd *rx_buf;
6552    struct eth_rx_bd *rx_bd;
6553    bus_dma_segment_t segs[1];
6554    bus_dmamap_t map;
6555    struct mbuf *m;
6556    int nsegs, rc;
6557
6558    rc = 0;
6559
6560    /* allocate the new RX BD mbuf */
6561    m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6562    if (__predict_false(m == NULL)) {
6563        fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6564        return (ENOBUFS);
6565    }
6566
6567    fp->eth_q_stats.mbuf_alloc_rx++;
6568
6569    /* initialize the mbuf buffer length */
6570    m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6571
6572    /* map the mbuf into non-paged pool */
6573    rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6574                                 fp->rx_mbuf_spare_map,
6575                                 m, segs, &nsegs, BUS_DMA_NOWAIT);
6576    if (__predict_false(rc != 0)) {
6577        fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6578        m_freem(m);
6579        fp->eth_q_stats.mbuf_alloc_rx--;
6580        return (rc);
6581    }
6582
6583    /* all mbufs must map to a single segment */
6584    KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6585
6586    /* release any existing RX BD mbuf mappings */
6587
6588    if (prev_index != index) {
6589        rx_buf = &fp->rx_mbuf_chain[prev_index];
6590
6591        if (rx_buf->m_map != NULL) {
6592            bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6593                            BUS_DMASYNC_POSTREAD);
6594            bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6595        }
6596
6597        /*
6598         * We only get here from bxe_rxeof() when the maximum number
6599         * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6600         * holds the mbuf in the prev_index so it's OK to NULL it out
6601         * here without concern of a memory leak.
6602         */
6603        fp->rx_mbuf_chain[prev_index].m = NULL;
6604    }
6605
6606    rx_buf = &fp->rx_mbuf_chain[index];
6607
6608    if (rx_buf->m_map != NULL) {
6609        bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6610                        BUS_DMASYNC_POSTREAD);
6611        bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6612    }
6613
6614    /* save the mbuf and mapping info for a future packet */
6615    map = (prev_index != index) ?
6616              fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6617    rx_buf->m_map = fp->rx_mbuf_spare_map;
6618    fp->rx_mbuf_spare_map = map;
6619    bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6620                    BUS_DMASYNC_PREREAD);
6621    rx_buf->m = m;
6622
6623    rx_bd = &fp->rx_chain[index];
6624    rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6625    rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6626
6627    return (rc);
6628}
6629
6630static int
6631bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6632                      int                 queue)
6633{
6634    struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6635    bus_dma_segment_t segs[1];
6636    bus_dmamap_t map;
6637    struct mbuf *m;
6638    int nsegs;
6639    int rc = 0;
6640
6641    /* allocate the new TPA mbuf */
6642    m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6643    if (__predict_false(m == NULL)) {
6644        fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6645        return (ENOBUFS);
6646    }
6647
6648    fp->eth_q_stats.mbuf_alloc_tpa++;
6649
6650    /* initialize the mbuf buffer length */
6651    m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6652
6653    /* map the mbuf into non-paged pool */
6654    rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6655                                 fp->rx_tpa_info_mbuf_spare_map,
6656                                 m, segs, &nsegs, BUS_DMA_NOWAIT);
6657    if (__predict_false(rc != 0)) {
6658        fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6659        m_free(m);
6660        fp->eth_q_stats.mbuf_alloc_tpa--;
6661        return (rc);
6662    }
6663
6664    /* all mbufs must map to a single segment */
6665    KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6666
6667    /* release any existing TPA mbuf mapping */
6668    if (tpa_info->bd.m_map != NULL) {
6669        bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6670                        BUS_DMASYNC_POSTREAD);
6671        bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6672    }
6673
6674    /* save the mbuf and mapping info for the TPA mbuf */
6675    map = tpa_info->bd.m_map;
6676    tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6677    fp->rx_tpa_info_mbuf_spare_map = map;
6678    bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6679                    BUS_DMASYNC_PREREAD);
6680    tpa_info->bd.m = m;
6681    tpa_info->seg = segs[0];
6682
6683    return (rc);
6684}
6685
6686/*
6687 * Allocate an mbuf and assign it to the receive scatter gather chain. The
6688 * caller must take care to save a copy of the existing mbuf in the SG mbuf
6689 * chain.
6690 */
6691static int
6692bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6693                      uint16_t            index)
6694{
6695    struct bxe_sw_rx_bd *sge_buf;
6696    struct eth_rx_sge *sge;
6697    bus_dma_segment_t segs[1];
6698    bus_dmamap_t map;
6699    struct mbuf *m;
6700    int nsegs;
6701    int rc = 0;
6702
6703    /* allocate a new SGE mbuf */
6704    m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6705    if (__predict_false(m == NULL)) {
6706        fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6707        return (ENOMEM);
6708    }
6709
6710    fp->eth_q_stats.mbuf_alloc_sge++;
6711
6712    /* initialize the mbuf buffer length */
6713    m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6714
6715    /* map the SGE mbuf into non-paged pool */
6716    rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6717                                 fp->rx_sge_mbuf_spare_map,
6718                                 m, segs, &nsegs, BUS_DMA_NOWAIT);
6719    if (__predict_false(rc != 0)) {
6720        fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6721        m_freem(m);
6722        fp->eth_q_stats.mbuf_alloc_sge--;
6723        return (rc);
6724    }
6725
6726    /* all mbufs must map to a single segment */
6727    KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6728
6729    sge_buf = &fp->rx_sge_mbuf_chain[index];
6730
6731    /* release any existing SGE mbuf mapping */
6732    if (sge_buf->m_map != NULL) {
6733        bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6734                        BUS_DMASYNC_POSTREAD);
6735        bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6736    }
6737
6738    /* save the mbuf and mapping info for a future packet */
6739    map = sge_buf->m_map;
6740    sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6741    fp->rx_sge_mbuf_spare_map = map;
6742    bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6743                    BUS_DMASYNC_PREREAD);
6744    sge_buf->m = m;
6745
6746    sge = &fp->rx_sge_chain[index];
6747    sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6748    sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6749
6750    return (rc);
6751}
6752
6753static __noinline int
6754bxe_alloc_fp_buffers(struct bxe_softc *sc)
6755{
6756    struct bxe_fastpath *fp;
6757    int i, j, rc = 0;
6758    int ring_prod, cqe_ring_prod;
6759    int max_agg_queues;
6760
6761    for (i = 0; i < sc->num_queues; i++) {
6762        fp = &sc->fp[i];
6763
6764#if __FreeBSD_version >= 800000
6765        fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
6766                                   M_DONTWAIT, &fp->tx_mtx);
6767        if (fp->tx_br == NULL) {
6768            BLOGE(sc, "buf_ring alloc fail for fp[%02d]\n", i);
6769            goto bxe_alloc_fp_buffers_error;
6770        }
6771#endif
6772
6773        ring_prod = cqe_ring_prod = 0;
6774        fp->rx_bd_cons = 0;
6775        fp->rx_cq_cons = 0;
6776
6777        /* allocate buffers for the RX BDs in RX BD chain */
6778        for (j = 0; j < sc->max_rx_bufs; j++) {
6779            rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6780            if (rc != 0) {
6781                BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6782                      i, rc);
6783                goto bxe_alloc_fp_buffers_error;
6784            }
6785
6786            ring_prod     = RX_BD_NEXT(ring_prod);
6787            cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6788        }
6789
6790        fp->rx_bd_prod = ring_prod;
6791        fp->rx_cq_prod = cqe_ring_prod;
6792        fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6793
6794        if (sc->ifnet->if_capenable & IFCAP_LRO) {
6795            max_agg_queues = MAX_AGG_QS(sc);
6796
6797            fp->tpa_enable = TRUE;
6798
6799            /* fill the TPA pool */
6800            for (j = 0; j < max_agg_queues; j++) {
6801                rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6802                if (rc != 0) {
6803                    BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6804                          i, j);
6805                    fp->tpa_enable = FALSE;
6806                    goto bxe_alloc_fp_buffers_error;
6807                }
6808
6809                fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6810            }
6811
6812            if (fp->tpa_enable) {
6813                /* fill the RX SGE chain */
6814                ring_prod = 0;
6815                for (j = 0; j < RX_SGE_USABLE; j++) {
6816                    rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6817                    if (rc != 0) {
6818                        BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6819                              i, ring_prod);
6820                        fp->tpa_enable = FALSE;
6821                        ring_prod = 0;
6822                        goto bxe_alloc_fp_buffers_error;
6823                    }
6824
6825                    ring_prod = RX_SGE_NEXT(ring_prod);
6826                }
6827
6828                fp->rx_sge_prod = ring_prod;
6829            }
6830        }
6831    }
6832
6833    return (0);
6834
6835bxe_alloc_fp_buffers_error:
6836
6837    /* unwind what was already allocated */
6838    bxe_free_rx_bd_chain(fp);
6839    bxe_free_tpa_pool(fp);
6840    bxe_free_sge_chain(fp);
6841
6842    return (ENOBUFS);
6843}
6844
6845static void
6846bxe_free_fw_stats_mem(struct bxe_softc *sc)
6847{
6848    bxe_dma_free(sc, &sc->fw_stats_dma);
6849
6850    sc->fw_stats_num = 0;
6851
6852    sc->fw_stats_req_size = 0;
6853    sc->fw_stats_req = NULL;
6854    sc->fw_stats_req_mapping = 0;
6855
6856    sc->fw_stats_data_size = 0;
6857    sc->fw_stats_data = NULL;
6858    sc->fw_stats_data_mapping = 0;
6859}
6860
6861static int
6862bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6863{
6864    uint8_t num_queue_stats;
6865    int num_groups;
6866
6867    /* number of queues for statistics is number of eth queues */
6868    num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6869
6870    /*
6871     * Total number of FW statistics requests =
6872     *   1 for port stats + 1 for PF stats + num of queues
6873     */
6874    sc->fw_stats_num = (2 + num_queue_stats);
6875
6876    /*
6877     * Request is built from stats_query_header and an array of
6878     * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6879     * rules. The real number or requests is configured in the
6880     * stats_query_header.
6881     */
6882    num_groups =
6883        ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6884         ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6885
6886    BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6887          sc->fw_stats_num, num_groups);
6888
6889    sc->fw_stats_req_size =
6890        (sizeof(struct stats_query_header) +
6891         (num_groups * sizeof(struct stats_query_cmd_group)));
6892
6893    /*
6894     * Data for statistics requests + stats_counter.
6895     * stats_counter holds per-STORM counters that are incremented when
6896     * STORM has finished with the current request. Memory for FCoE
6897     * offloaded statistics are counted anyway, even if they will not be sent.
6898     * VF stats are not accounted for here as the data of VF stats is stored
6899     * in memory allocated by the VF, not here.
6900     */
6901    sc->fw_stats_data_size =
6902        (sizeof(struct stats_counter) +
6903         sizeof(struct per_port_stats) +
6904         sizeof(struct per_pf_stats) +
6905         /* sizeof(struct fcoe_statistics_params) + */
6906         (sizeof(struct per_queue_stats) * num_queue_stats));
6907
6908    if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6909                      &sc->fw_stats_dma, "fw stats") != 0) {
6910        bxe_free_fw_stats_mem(sc);
6911        return (-1);
6912    }
6913
6914    /* set up the shortcuts */
6915
6916    sc->fw_stats_req =
6917        (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6918    sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6919
6920    sc->fw_stats_data =
6921        (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6922                                     sc->fw_stats_req_size);
6923    sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6924                                 sc->fw_stats_req_size);
6925
6926    BLOGD(sc, DBG_LOAD, "statistics request base address set to %p\n",
6927          (void *)sc->fw_stats_req_mapping);
6928
6929    BLOGD(sc, DBG_LOAD, "statistics data base address set to %p\n",
6930          (void *)sc->fw_stats_data_mapping);
6931
6932    return (0);
6933}
6934
6935/*
6936 * Bits map:
6937 * 0-7  - Engine0 load counter.
6938 * 8-15 - Engine1 load counter.
6939 * 16   - Engine0 RESET_IN_PROGRESS bit.
6940 * 17   - Engine1 RESET_IN_PROGRESS bit.
6941 * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6942 *        function on the engine
6943 * 19   - Engine1 ONE_IS_LOADED.
6944 * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6945 *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6946 *        for just the one belonging to its engine).
6947 */
6948#define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6949#define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6950#define BXE_PATH0_LOAD_CNT_SHIFT  0
6951#define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6952#define BXE_PATH1_LOAD_CNT_SHIFT  8
6953#define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6954#define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6955#define BXE_GLOBAL_RESET_BIT      0x00040000
6956
6957/* set the GLOBAL_RESET bit, should be run under rtnl lock */
6958static void
6959bxe_set_reset_global(struct bxe_softc *sc)
6960{
6961    uint32_t val;
6962    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6963    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6964    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6965    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6966}
6967
6968/* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6969static void
6970bxe_clear_reset_global(struct bxe_softc *sc)
6971{
6972    uint32_t val;
6973    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6974    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6975    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6976    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6977}
6978
6979/* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6980static uint8_t
6981bxe_reset_is_global(struct bxe_softc *sc)
6982{
6983    uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6984    BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6985    return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6986}
6987
6988/* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6989static void
6990bxe_set_reset_done(struct bxe_softc *sc)
6991{
6992    uint32_t val;
6993    uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6994                                 BXE_PATH0_RST_IN_PROG_BIT;
6995
6996    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6997
6998    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6999    /* Clear the bit */
7000    val &= ~bit;
7001    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
7002
7003    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7004}
7005
7006/* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
7007static void
7008bxe_set_reset_in_progress(struct bxe_softc *sc)
7009{
7010    uint32_t val;
7011    uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
7012                                 BXE_PATH0_RST_IN_PROG_BIT;
7013
7014    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7015
7016    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
7017    /* Set the bit */
7018    val |= bit;
7019    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
7020
7021    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7022}
7023
7024/* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
7025static uint8_t
7026bxe_reset_is_done(struct bxe_softc *sc,
7027                  int              engine)
7028{
7029    uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
7030    uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
7031                            BXE_PATH0_RST_IN_PROG_BIT;
7032
7033    /* return false if bit is set */
7034    return (val & bit) ? FALSE : TRUE;
7035}
7036
7037/* get the load status for an engine, should be run under rtnl lock */
7038static uint8_t
7039bxe_get_load_status(struct bxe_softc *sc,
7040                    int              engine)
7041{
7042    uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
7043                             BXE_PATH0_LOAD_CNT_MASK;
7044    uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
7045                              BXE_PATH0_LOAD_CNT_SHIFT;
7046    uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
7047
7048    BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
7049
7050    val = ((val & mask) >> shift);
7051
7052    BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
7053
7054    return (val != 0);
7055}
7056
7057/* set pf load mark */
7058/* XXX needs to be under rtnl lock */
7059static void
7060bxe_set_pf_load(struct bxe_softc *sc)
7061{
7062    uint32_t val;
7063    uint32_t val1;
7064    uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
7065                                  BXE_PATH0_LOAD_CNT_MASK;
7066    uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
7067                                   BXE_PATH0_LOAD_CNT_SHIFT;
7068
7069    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7070
7071    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
7072    BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
7073
7074    /* get the current counter value */
7075    val1 = ((val & mask) >> shift);
7076
7077    /* set bit of this PF */
7078    val1 |= (1 << SC_ABS_FUNC(sc));
7079
7080    /* clear the old value */
7081    val &= ~mask;
7082
7083    /* set the new one */
7084    val |= ((val1 << shift) & mask);
7085
7086    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
7087
7088    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7089}
7090
7091/* clear pf load mark */
7092/* XXX needs to be under rtnl lock */
7093static uint8_t
7094bxe_clear_pf_load(struct bxe_softc *sc)
7095{
7096    uint32_t val1, val;
7097    uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
7098                                  BXE_PATH0_LOAD_CNT_MASK;
7099    uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
7100                                   BXE_PATH0_LOAD_CNT_SHIFT;
7101
7102    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7103    val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
7104    BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
7105
7106    /* get the current counter value */
7107    val1 = (val & mask) >> shift;
7108
7109    /* clear bit of that PF */
7110    val1 &= ~(1 << SC_ABS_FUNC(sc));
7111
7112    /* clear the old value */
7113    val &= ~mask;
7114
7115    /* set the new one */
7116    val |= ((val1 << shift) & mask);
7117
7118    REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
7119    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
7120    return (val1 != 0);
7121}
7122
7123/* send load requrest to mcp and analyze response */
7124static int
7125bxe_nic_load_request(struct bxe_softc *sc,
7126                     uint32_t         *load_code)
7127{
7128    /* init fw_seq */
7129    sc->fw_seq =
7130        (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
7131         DRV_MSG_SEQ_NUMBER_MASK);
7132
7133    BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
7134
7135    /* get the current FW pulse sequence */
7136    sc->fw_drv_pulse_wr_seq =
7137        (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
7138         DRV_PULSE_SEQ_MASK);
7139
7140    BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
7141          sc->fw_drv_pulse_wr_seq);
7142
7143    /* load request */
7144    (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
7145                                  DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
7146
7147    /* if the MCP fails to respond we must abort */
7148    if (!(*load_code)) {
7149        BLOGE(sc, "MCP response failure!\n");
7150        return (-1);
7151    }
7152
7153    /* if MCP refused then must abort */
7154    if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
7155        BLOGE(sc, "MCP refused load request\n");
7156        return (-1);
7157    }
7158
7159    return (0);
7160}
7161
7162/*
7163 * Check whether another PF has already loaded FW to chip. In virtualized
7164 * environments a pf from anoth VM may have already initialized the device
7165 * including loading FW.
7166 */
7167static int
7168bxe_nic_load_analyze_req(struct bxe_softc *sc,
7169                         uint32_t         load_code)
7170{
7171    uint32_t my_fw, loaded_fw;
7172
7173    /* is another pf loaded on this engine? */
7174    if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
7175        (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
7176        /* build my FW version dword */
7177        my_fw = (BCM_5710_FW_MAJOR_VERSION +
7178                 (BCM_5710_FW_MINOR_VERSION << 8 ) +
7179                 (BCM_5710_FW_REVISION_VERSION << 16) +
7180                 (BCM_5710_FW_ENGINEERING_VERSION << 24));
7181
7182        /* read loaded FW from chip */
7183        loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
7184        BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
7185              loaded_fw, my_fw);
7186
7187        /* abort nic load if version mismatch */
7188        if (my_fw != loaded_fw) {
7189            BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
7190                  loaded_fw, my_fw);
7191            return (-1);
7192        }
7193    }
7194
7195    return (0);
7196}
7197
7198/* mark PMF if applicable */
7199static void
7200bxe_nic_load_pmf(struct bxe_softc *sc,
7201                 uint32_t         load_code)
7202{
7203    uint32_t ncsi_oem_data_addr;
7204
7205    if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
7206        (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
7207        (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
7208        /*
7209         * Barrier here for ordering between the writing to sc->port.pmf here
7210         * and reading it from the periodic task.
7211         */
7212        sc->port.pmf = 1;
7213        mb();
7214    } else {
7215        sc->port.pmf = 0;
7216    }
7217
7218    BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
7219
7220    /* XXX needed? */
7221    if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
7222        if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
7223            ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
7224            if (ncsi_oem_data_addr) {
7225                REG_WR(sc,
7226                       (ncsi_oem_data_addr +
7227                        offsetof(struct glob_ncsi_oem_data, driver_version)),
7228                       0);
7229            }
7230        }
7231    }
7232}
7233
7234static void
7235bxe_read_mf_cfg(struct bxe_softc *sc)
7236{
7237    int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
7238    int abs_func;
7239    int vn;
7240
7241    if (BXE_NOMCP(sc)) {
7242        return; /* what should be the default bvalue in this case */
7243    }
7244
7245    /*
7246     * The formula for computing the absolute function number is...
7247     * For 2 port configuration (4 functions per port):
7248     *   abs_func = 2 * vn + SC_PORT + SC_PATH
7249     * For 4 port configuration (2 functions per port):
7250     *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
7251     */
7252    for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
7253        abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
7254        if (abs_func >= E1H_FUNC_MAX) {
7255            break;
7256        }
7257        sc->devinfo.mf_info.mf_config[vn] =
7258            MFCFG_RD(sc, func_mf_config[abs_func].config);
7259    }
7260
7261    if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
7262        FUNC_MF_CFG_FUNC_DISABLED) {
7263        BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
7264        sc->flags |= BXE_MF_FUNC_DIS;
7265    } else {
7266        BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
7267        sc->flags &= ~BXE_MF_FUNC_DIS;
7268    }
7269}
7270
7271/* acquire split MCP access lock register */
7272static int bxe_acquire_alr(struct bxe_softc *sc)
7273{
7274    uint32_t j, val;
7275
7276    for (j = 0; j < 1000; j++) {
7277        val = (1UL << 31);
7278        REG_WR(sc, GRCBASE_MCP + 0x9c, val);
7279        val = REG_RD(sc, GRCBASE_MCP + 0x9c);
7280        if (val & (1L << 31))
7281            break;
7282
7283        DELAY(5000);
7284    }
7285
7286    if (!(val & (1L << 31))) {
7287        BLOGE(sc, "Cannot acquire MCP access lock register\n");
7288        return (-1);
7289    }
7290
7291    return (0);
7292}
7293
7294/* release split MCP access lock register */
7295static void bxe_release_alr(struct bxe_softc *sc)
7296{
7297    REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
7298}
7299
7300static void
7301bxe_fan_failure(struct bxe_softc *sc)
7302{
7303    int port = SC_PORT(sc);
7304    uint32_t ext_phy_config;
7305
7306    /* mark the failure */
7307    ext_phy_config =
7308        SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7309
7310    ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7311    ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7312    SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7313             ext_phy_config);
7314
7315    /* log the failure */
7316    BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7317              "the card to prevent permanent damage. "
7318              "Please contact OEM Support for assistance\n");
7319
7320    /* XXX */
7321#if 1
7322    bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7323#else
7324    /*
7325     * Schedule device reset (unload)
7326     * This is due to some boards consuming sufficient power when driver is
7327     * up to overheat if fan fails.
7328     */
7329    bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7330    schedule_delayed_work(&sc->sp_rtnl_task, 0);
7331#endif
7332}
7333
7334/* this function is called upon a link interrupt */
7335static void
7336bxe_link_attn(struct bxe_softc *sc)
7337{
7338    uint32_t pause_enabled = 0;
7339    struct host_port_stats *pstats;
7340    int cmng_fns;
7341
7342    /* Make sure that we are synced with the current statistics */
7343    bxe_stats_handle(sc, STATS_EVENT_STOP);
7344
7345    elink_link_update(&sc->link_params, &sc->link_vars);
7346
7347    if (sc->link_vars.link_up) {
7348
7349        /* dropless flow control */
7350        if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7351            pause_enabled = 0;
7352
7353            if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7354                pause_enabled = 1;
7355            }
7356
7357            REG_WR(sc,
7358                   (BAR_USTRORM_INTMEM +
7359                    USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7360                   pause_enabled);
7361        }
7362
7363        if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7364            pstats = BXE_SP(sc, port_stats);
7365            /* reset old mac stats */
7366            memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7367        }
7368
7369        if (sc->state == BXE_STATE_OPEN) {
7370            bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7371        }
7372    }
7373
7374    if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7375        cmng_fns = bxe_get_cmng_fns_mode(sc);
7376
7377        if (cmng_fns != CMNG_FNS_NONE) {
7378            bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7379            storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7380        } else {
7381            /* rate shaping and fairness are disabled */
7382            BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7383        }
7384    }
7385
7386    bxe_link_report_locked(sc);
7387
7388    if (IS_MF(sc)) {
7389        ; // XXX bxe_link_sync_notify(sc);
7390    }
7391}
7392
7393static void
7394bxe_attn_int_asserted(struct bxe_softc *sc,
7395                      uint32_t         asserted)
7396{
7397    int port = SC_PORT(sc);
7398    uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7399                               MISC_REG_AEU_MASK_ATTN_FUNC_0;
7400    uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7401                                        NIG_REG_MASK_INTERRUPT_PORT0;
7402    uint32_t aeu_mask;
7403    uint32_t nig_mask = 0;
7404    uint32_t reg_addr;
7405    uint32_t igu_acked;
7406    uint32_t cnt;
7407
7408    if (sc->attn_state & asserted) {
7409        BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7410    }
7411
7412    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7413
7414    aeu_mask = REG_RD(sc, aeu_addr);
7415
7416    BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7417          aeu_mask, asserted);
7418
7419    aeu_mask &= ~(asserted & 0x3ff);
7420
7421    BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7422
7423    REG_WR(sc, aeu_addr, aeu_mask);
7424
7425    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7426
7427    BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7428    sc->attn_state |= asserted;
7429    BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7430
7431    if (asserted & ATTN_HARD_WIRED_MASK) {
7432        if (asserted & ATTN_NIG_FOR_FUNC) {
7433
7434            BXE_PHY_LOCK(sc);
7435
7436            /* save nig interrupt mask */
7437            nig_mask = REG_RD(sc, nig_int_mask_addr);
7438
7439            /* If nig_mask is not set, no need to call the update function */
7440            if (nig_mask) {
7441                REG_WR(sc, nig_int_mask_addr, 0);
7442
7443                bxe_link_attn(sc);
7444            }
7445
7446            /* handle unicore attn? */
7447        }
7448
7449        if (asserted & ATTN_SW_TIMER_4_FUNC) {
7450            BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7451        }
7452
7453        if (asserted & GPIO_2_FUNC) {
7454            BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7455        }
7456
7457        if (asserted & GPIO_3_FUNC) {
7458            BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7459        }
7460
7461        if (asserted & GPIO_4_FUNC) {
7462            BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7463        }
7464
7465        if (port == 0) {
7466            if (asserted & ATTN_GENERAL_ATTN_1) {
7467                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7468                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7469            }
7470            if (asserted & ATTN_GENERAL_ATTN_2) {
7471                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7472                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7473            }
7474            if (asserted & ATTN_GENERAL_ATTN_3) {
7475                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7476                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7477            }
7478        } else {
7479            if (asserted & ATTN_GENERAL_ATTN_4) {
7480                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7481                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7482            }
7483            if (asserted & ATTN_GENERAL_ATTN_5) {
7484                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7485                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7486            }
7487            if (asserted & ATTN_GENERAL_ATTN_6) {
7488                BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7489                REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7490            }
7491        }
7492    } /* hardwired */
7493
7494    if (sc->devinfo.int_block == INT_BLOCK_HC) {
7495        reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7496    } else {
7497        reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7498    }
7499
7500    BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7501          asserted,
7502          (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7503    REG_WR(sc, reg_addr, asserted);
7504
7505    /* now set back the mask */
7506    if (asserted & ATTN_NIG_FOR_FUNC) {
7507        /*
7508         * Verify that IGU ack through BAR was written before restoring
7509         * NIG mask. This loop should exit after 2-3 iterations max.
7510         */
7511        if (sc->devinfo.int_block != INT_BLOCK_HC) {
7512            cnt = 0;
7513
7514            do {
7515                igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7516            } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7517                     (++cnt < MAX_IGU_ATTN_ACK_TO));
7518
7519            if (!igu_acked) {
7520                BLOGE(sc, "Failed to verify IGU ack on time\n");
7521            }
7522
7523            mb();
7524        }
7525
7526        REG_WR(sc, nig_int_mask_addr, nig_mask);
7527
7528        BXE_PHY_UNLOCK(sc);
7529    }
7530}
7531
7532static void
7533bxe_print_next_block(struct bxe_softc *sc,
7534                     int              idx,
7535                     const char       *blk)
7536{
7537    BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7538}
7539
7540static int
7541bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7542                              uint32_t         sig,
7543                              int              par_num,
7544                              uint8_t          print)
7545{
7546    uint32_t cur_bit = 0;
7547    int i = 0;
7548
7549    for (i = 0; sig; i++) {
7550        cur_bit = ((uint32_t)0x1 << i);
7551        if (sig & cur_bit) {
7552            switch (cur_bit) {
7553            case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7554                if (print)
7555                    bxe_print_next_block(sc, par_num++, "BRB");
7556                break;
7557            case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7558                if (print)
7559                    bxe_print_next_block(sc, par_num++, "PARSER");
7560                break;
7561            case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7562                if (print)
7563                    bxe_print_next_block(sc, par_num++, "TSDM");
7564                break;
7565            case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7566                if (print)
7567                    bxe_print_next_block(sc, par_num++, "SEARCHER");
7568                break;
7569            case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7570                if (print)
7571                    bxe_print_next_block(sc, par_num++, "TCM");
7572                break;
7573            case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7574                if (print)
7575                    bxe_print_next_block(sc, par_num++, "TSEMI");
7576                break;
7577            case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7578                if (print)
7579                    bxe_print_next_block(sc, par_num++, "XPB");
7580                break;
7581            }
7582
7583            /* Clear the bit */
7584            sig &= ~cur_bit;
7585        }
7586    }
7587
7588    return (par_num);
7589}
7590
7591static int
7592bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7593                              uint32_t         sig,
7594                              int              par_num,
7595                              uint8_t          *global,
7596                              uint8_t          print)
7597{
7598    int i = 0;
7599    uint32_t cur_bit = 0;
7600    for (i = 0; sig; i++) {
7601        cur_bit = ((uint32_t)0x1 << i);
7602        if (sig & cur_bit) {
7603            switch (cur_bit) {
7604            case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7605                if (print)
7606                    bxe_print_next_block(sc, par_num++, "PBF");
7607                break;
7608            case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7609                if (print)
7610                    bxe_print_next_block(sc, par_num++, "QM");
7611                break;
7612            case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7613                if (print)
7614                    bxe_print_next_block(sc, par_num++, "TM");
7615                break;
7616            case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7617                if (print)
7618                    bxe_print_next_block(sc, par_num++, "XSDM");
7619                break;
7620            case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7621                if (print)
7622                    bxe_print_next_block(sc, par_num++, "XCM");
7623                break;
7624            case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7625                if (print)
7626                    bxe_print_next_block(sc, par_num++, "XSEMI");
7627                break;
7628            case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7629                if (print)
7630                    bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7631                break;
7632            case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7633                if (print)
7634                    bxe_print_next_block(sc, par_num++, "NIG");
7635                break;
7636            case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7637                if (print)
7638                    bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7639                *global = TRUE;
7640                break;
7641            case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7642                if (print)
7643                    bxe_print_next_block(sc, par_num++, "DEBUG");
7644                break;
7645            case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7646                if (print)
7647                    bxe_print_next_block(sc, par_num++, "USDM");
7648                break;
7649            case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7650                if (print)
7651                    bxe_print_next_block(sc, par_num++, "UCM");
7652                break;
7653            case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7654                if (print)
7655                    bxe_print_next_block(sc, par_num++, "USEMI");
7656                break;
7657            case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7658                if (print)
7659                    bxe_print_next_block(sc, par_num++, "UPB");
7660                break;
7661            case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7662                if (print)
7663                    bxe_print_next_block(sc, par_num++, "CSDM");
7664                break;
7665            case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7666                if (print)
7667                    bxe_print_next_block(sc, par_num++, "CCM");
7668                break;
7669            }
7670
7671            /* Clear the bit */
7672            sig &= ~cur_bit;
7673        }
7674    }
7675
7676    return (par_num);
7677}
7678
7679static int
7680bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7681                              uint32_t         sig,
7682                              int              par_num,
7683                              uint8_t          print)
7684{
7685    uint32_t cur_bit = 0;
7686    int i = 0;
7687
7688    for (i = 0; sig; i++) {
7689        cur_bit = ((uint32_t)0x1 << i);
7690        if (sig & cur_bit) {
7691            switch (cur_bit) {
7692            case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7693                if (print)
7694                    bxe_print_next_block(sc, par_num++, "CSEMI");
7695                break;
7696            case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7697                if (print)
7698                    bxe_print_next_block(sc, par_num++, "PXP");
7699                break;
7700            case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7701                if (print)
7702                    bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7703                break;
7704            case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7705                if (print)
7706                    bxe_print_next_block(sc, par_num++, "CFC");
7707                break;
7708            case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7709                if (print)
7710                    bxe_print_next_block(sc, par_num++, "CDU");
7711                break;
7712            case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7713                if (print)
7714                    bxe_print_next_block(sc, par_num++, "DMAE");
7715                break;
7716            case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7717                if (print)
7718                    bxe_print_next_block(sc, par_num++, "IGU");
7719                break;
7720            case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7721                if (print)
7722                    bxe_print_next_block(sc, par_num++, "MISC");
7723                break;
7724            }
7725
7726            /* Clear the bit */
7727            sig &= ~cur_bit;
7728        }
7729    }
7730
7731    return (par_num);
7732}
7733
7734static int
7735bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7736                              uint32_t         sig,
7737                              int              par_num,
7738                              uint8_t          *global,
7739                              uint8_t          print)
7740{
7741    uint32_t cur_bit = 0;
7742    int i = 0;
7743
7744    for (i = 0; sig; i++) {
7745        cur_bit = ((uint32_t)0x1 << i);
7746        if (sig & cur_bit) {
7747            switch (cur_bit) {
7748            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7749                if (print)
7750                    bxe_print_next_block(sc, par_num++, "MCP ROM");
7751                *global = TRUE;
7752                break;
7753            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7754                if (print)
7755                    bxe_print_next_block(sc, par_num++,
7756                              "MCP UMP RX");
7757                *global = TRUE;
7758                break;
7759            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7760                if (print)
7761                    bxe_print_next_block(sc, par_num++,
7762                              "MCP UMP TX");
7763                *global = TRUE;
7764                break;
7765            case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7766                if (print)
7767                    bxe_print_next_block(sc, par_num++,
7768                              "MCP SCPAD");
7769                *global = TRUE;
7770                break;
7771            }
7772
7773            /* Clear the bit */
7774            sig &= ~cur_bit;
7775        }
7776    }
7777
7778    return (par_num);
7779}
7780
7781static int
7782bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7783                              uint32_t         sig,
7784                              int              par_num,
7785                              uint8_t          print)
7786{
7787    uint32_t cur_bit = 0;
7788    int i = 0;
7789
7790    for (i = 0; sig; i++) {
7791        cur_bit = ((uint32_t)0x1 << i);
7792        if (sig & cur_bit) {
7793            switch (cur_bit) {
7794            case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7795                if (print)
7796                    bxe_print_next_block(sc, par_num++, "PGLUE_B");
7797                break;
7798            case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7799                if (print)
7800                    bxe_print_next_block(sc, par_num++, "ATC");
7801                break;
7802            }
7803
7804            /* Clear the bit */
7805            sig &= ~cur_bit;
7806        }
7807    }
7808
7809    return (par_num);
7810}
7811
7812static uint8_t
7813bxe_parity_attn(struct bxe_softc *sc,
7814                uint8_t          *global,
7815                uint8_t          print,
7816                uint32_t         *sig)
7817{
7818    int par_num = 0;
7819
7820    if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7821        (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7822        (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7823        (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7824        (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7825        BLOGE(sc, "Parity error: HW block parity attention:\n"
7826                  "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7827              (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7828              (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7829              (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7830              (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7831              (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7832
7833        if (print)
7834            BLOGI(sc, "Parity errors detected in blocks: ");
7835
7836        par_num =
7837            bxe_check_blocks_with_parity0(sc, sig[0] &
7838                                          HW_PRTY_ASSERT_SET_0,
7839                                          par_num, print);
7840        par_num =
7841            bxe_check_blocks_with_parity1(sc, sig[1] &
7842                                          HW_PRTY_ASSERT_SET_1,
7843                                          par_num, global, print);
7844        par_num =
7845            bxe_check_blocks_with_parity2(sc, sig[2] &
7846                                          HW_PRTY_ASSERT_SET_2,
7847                                          par_num, print);
7848        par_num =
7849            bxe_check_blocks_with_parity3(sc, sig[3] &
7850                                          HW_PRTY_ASSERT_SET_3,
7851                                          par_num, global, print);
7852        par_num =
7853            bxe_check_blocks_with_parity4(sc, sig[4] &
7854                                          HW_PRTY_ASSERT_SET_4,
7855                                          par_num, print);
7856
7857        if (print)
7858            BLOGI(sc, "\n");
7859
7860        return (TRUE);
7861    }
7862
7863    return (FALSE);
7864}
7865
7866static uint8_t
7867bxe_chk_parity_attn(struct bxe_softc *sc,
7868                    uint8_t          *global,
7869                    uint8_t          print)
7870{
7871    struct attn_route attn = { {0} };
7872    int port = SC_PORT(sc);
7873
7874    attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7875    attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7876    attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7877    attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7878
7879    if (!CHIP_IS_E1x(sc))
7880        attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7881
7882    return (bxe_parity_attn(sc, global, print, attn.sig));
7883}
7884
7885static void
7886bxe_attn_int_deasserted4(struct bxe_softc *sc,
7887                         uint32_t         attn)
7888{
7889    uint32_t val;
7890
7891    if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7892        val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7893        BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7894        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7895            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7896        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7897            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7898        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7899            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7900        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7901            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7902        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7903            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7904        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7905            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7906        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7907            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7908        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7909            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7910        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7911            BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7912    }
7913
7914    if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7915        val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7916        BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7917        if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7918            BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7919        if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7920            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7921        if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7922            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7923        if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7924            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7925        if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7926            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7927        if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7928            BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7929    }
7930
7931    if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7932                AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7933        BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7934              (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7935                                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7936    }
7937}
7938
7939static void
7940bxe_e1h_disable(struct bxe_softc *sc)
7941{
7942    int port = SC_PORT(sc);
7943
7944    bxe_tx_disable(sc);
7945
7946    REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7947}
7948
7949static void
7950bxe_e1h_enable(struct bxe_softc *sc)
7951{
7952    int port = SC_PORT(sc);
7953
7954    REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7955
7956    // XXX bxe_tx_enable(sc);
7957}
7958
7959/*
7960 * called due to MCP event (on pmf):
7961 *   reread new bandwidth configuration
7962 *   configure FW
7963 *   notify others function about the change
7964 */
7965static void
7966bxe_config_mf_bw(struct bxe_softc *sc)
7967{
7968    if (sc->link_vars.link_up) {
7969        bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7970        // XXX bxe_link_sync_notify(sc);
7971    }
7972
7973    storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7974}
7975
7976static void
7977bxe_set_mf_bw(struct bxe_softc *sc)
7978{
7979    bxe_config_mf_bw(sc);
7980    bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7981}
7982
7983static void
7984bxe_handle_eee_event(struct bxe_softc *sc)
7985{
7986    BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7987    bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7988}
7989
7990#define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7991
7992static void
7993bxe_drv_info_ether_stat(struct bxe_softc *sc)
7994{
7995    struct eth_stats_info *ether_stat =
7996        &sc->sp->drv_info_to_mcp.ether_stat;
7997
7998    strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7999            ETH_STAT_INFO_VERSION_LEN);
8000
8001    /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
8002    sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
8003                                          DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
8004                                          ether_stat->mac_local + MAC_PAD,
8005                                          MAC_PAD, ETH_ALEN);
8006
8007    ether_stat->mtu_size = sc->mtu;
8008
8009    ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
8010    if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
8011        ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
8012    }
8013
8014    // XXX ether_stat->feature_flags |= ???;
8015
8016    ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
8017
8018    ether_stat->txq_size = sc->tx_ring_size;
8019    ether_stat->rxq_size = sc->rx_ring_size;
8020}
8021
8022static void
8023bxe_handle_drv_info_req(struct bxe_softc *sc)
8024{
8025    enum drv_info_opcode op_code;
8026    uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
8027
8028    /* if drv_info version supported by MFW doesn't match - send NACK */
8029    if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
8030        bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
8031        return;
8032    }
8033
8034    op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
8035               DRV_INFO_CONTROL_OP_CODE_SHIFT);
8036
8037    memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
8038
8039    switch (op_code) {
8040    case ETH_STATS_OPCODE:
8041        bxe_drv_info_ether_stat(sc);
8042        break;
8043    case FCOE_STATS_OPCODE:
8044    case ISCSI_STATS_OPCODE:
8045    default:
8046        /* if op code isn't supported - send NACK */
8047        bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
8048        return;
8049    }
8050
8051    /*
8052     * If we got drv_info attn from MFW then these fields are defined in
8053     * shmem2 for sure
8054     */
8055    SHMEM2_WR(sc, drv_info_host_addr_lo,
8056              U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
8057    SHMEM2_WR(sc, drv_info_host_addr_hi,
8058              U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
8059
8060    bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
8061}
8062
8063static void
8064bxe_dcc_event(struct bxe_softc *sc,
8065              uint32_t         dcc_event)
8066{
8067    BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
8068
8069    if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
8070        /*
8071         * This is the only place besides the function initialization
8072         * where the sc->flags can change so it is done without any
8073         * locks
8074         */
8075        if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
8076            BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
8077            sc->flags |= BXE_MF_FUNC_DIS;
8078            bxe_e1h_disable(sc);
8079        } else {
8080            BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
8081            sc->flags &= ~BXE_MF_FUNC_DIS;
8082            bxe_e1h_enable(sc);
8083        }
8084        dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
8085    }
8086
8087    if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
8088        bxe_config_mf_bw(sc);
8089        dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
8090    }
8091
8092    /* Report results to MCP */
8093    if (dcc_event)
8094        bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
8095    else
8096        bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
8097}
8098
8099static void
8100bxe_pmf_update(struct bxe_softc *sc)
8101{
8102    int port = SC_PORT(sc);
8103    uint32_t val;
8104
8105    sc->port.pmf = 1;
8106    BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
8107
8108    /*
8109     * We need the mb() to ensure the ordering between the writing to
8110     * sc->port.pmf here and reading it from the bxe_periodic_task().
8111     */
8112    mb();
8113
8114    /* queue a periodic task */
8115    // XXX schedule task...
8116
8117    // XXX bxe_dcbx_pmf_update(sc);
8118
8119    /* enable nig attention */
8120    val = (0xff0f | (1 << (SC_VN(sc) + 4)));
8121    if (sc->devinfo.int_block == INT_BLOCK_HC) {
8122        REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
8123        REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
8124    } else if (!CHIP_IS_E1x(sc)) {
8125        REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
8126        REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
8127    }
8128
8129    bxe_stats_handle(sc, STATS_EVENT_PMF);
8130}
8131
8132static int
8133bxe_mc_assert(struct bxe_softc *sc)
8134{
8135    char last_idx;
8136    int i, rc = 0;
8137    uint32_t row0, row1, row2, row3;
8138
8139    /* XSTORM */
8140    last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
8141    if (last_idx)
8142        BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
8143
8144    /* print the asserts */
8145    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
8146
8147        row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
8148        row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
8149        row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
8150        row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
8151
8152        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
8153            BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
8154                  i, row3, row2, row1, row0);
8155            rc++;
8156        } else {
8157            break;
8158        }
8159    }
8160
8161    /* TSTORM */
8162    last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
8163    if (last_idx) {
8164        BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
8165    }
8166
8167    /* print the asserts */
8168    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
8169
8170        row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
8171        row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
8172        row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
8173        row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
8174
8175        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
8176            BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
8177                  i, row3, row2, row1, row0);
8178            rc++;
8179        } else {
8180            break;
8181        }
8182    }
8183
8184    /* CSTORM */
8185    last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
8186    if (last_idx) {
8187        BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
8188    }
8189
8190    /* print the asserts */
8191    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
8192
8193        row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
8194        row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
8195        row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
8196        row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
8197
8198        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
8199            BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
8200                  i, row3, row2, row1, row0);
8201            rc++;
8202        } else {
8203            break;
8204        }
8205    }
8206
8207    /* USTORM */
8208    last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
8209    if (last_idx) {
8210        BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
8211    }
8212
8213    /* print the asserts */
8214    for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
8215
8216        row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
8217        row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
8218        row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
8219        row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
8220
8221        if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
8222            BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
8223                  i, row3, row2, row1, row0);
8224            rc++;
8225        } else {
8226            break;
8227        }
8228    }
8229
8230    return (rc);
8231}
8232
8233static void
8234bxe_attn_int_deasserted3(struct bxe_softc *sc,
8235                         uint32_t         attn)
8236{
8237    int func = SC_FUNC(sc);
8238    uint32_t val;
8239
8240    if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
8241
8242        if (attn & BXE_PMF_LINK_ASSERT(sc)) {
8243
8244            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
8245            bxe_read_mf_cfg(sc);
8246            sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
8247                MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
8248            val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
8249
8250            if (val & DRV_STATUS_DCC_EVENT_MASK)
8251                bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
8252
8253            if (val & DRV_STATUS_SET_MF_BW)
8254                bxe_set_mf_bw(sc);
8255
8256            if (val & DRV_STATUS_DRV_INFO_REQ)
8257                bxe_handle_drv_info_req(sc);
8258
8259#if 0
8260            if (val & DRV_STATUS_VF_DISABLED)
8261                bxe_vf_handle_flr_event(sc);
8262#endif
8263
8264            if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
8265                bxe_pmf_update(sc);
8266
8267#if 0
8268            if (sc->port.pmf &&
8269                (val & DRV_STATUS_DCBX_NEGOTIATION_RESULTS) &&
8270                (sc->dcbx_enabled > 0))
8271                /* start dcbx state machine */
8272                bxe_dcbx_set_params(sc, BXE_DCBX_STATE_NEG_RECEIVED);
8273#endif
8274
8275#if 0
8276            if (val & DRV_STATUS_AFEX_EVENT_MASK)
8277                bxe_handle_afex_cmd(sc, val & DRV_STATUS_AFEX_EVENT_MASK);
8278#endif
8279
8280            if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
8281                bxe_handle_eee_event(sc);
8282
8283            if (sc->link_vars.periodic_flags &
8284                ELINK_PERIODIC_FLAGS_LINK_EVENT) {
8285                /* sync with link */
8286                BXE_PHY_LOCK(sc);
8287                sc->link_vars.periodic_flags &=
8288                    ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
8289                BXE_PHY_UNLOCK(sc);
8290                if (IS_MF(sc))
8291                    ; // XXX bxe_link_sync_notify(sc);
8292                bxe_link_report(sc);
8293            }
8294
8295            /*
8296             * Always call it here: bxe_link_report() will
8297             * prevent the link indication duplication.
8298             */
8299            bxe_link_status_update(sc);
8300
8301        } else if (attn & BXE_MC_ASSERT_BITS) {
8302
8303            BLOGE(sc, "MC assert!\n");
8304            bxe_mc_assert(sc);
8305            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8306            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8307            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8308            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8309            bxe_panic(sc, ("MC assert!\n"));
8310
8311        } else if (attn & BXE_MCP_ASSERT) {
8312
8313            BLOGE(sc, "MCP assert!\n");
8314            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8315            // XXX bxe_fw_dump(sc);
8316
8317        } else {
8318            BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8319        }
8320    }
8321
8322    if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8323        BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8324        if (attn & BXE_GRC_TIMEOUT) {
8325            val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8326            BLOGE(sc, "GRC time-out 0x%08x\n", val);
8327        }
8328        if (attn & BXE_GRC_RSV) {
8329            val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8330            BLOGE(sc, "GRC reserved 0x%08x\n", val);
8331        }
8332        REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8333    }
8334}
8335
8336static void
8337bxe_attn_int_deasserted2(struct bxe_softc *sc,
8338                         uint32_t         attn)
8339{
8340    int port = SC_PORT(sc);
8341    int reg_offset;
8342    uint32_t val0, mask0, val1, mask1;
8343    uint32_t val;
8344
8345    if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8346        val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8347        BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8348        /* CFC error attention */
8349        if (val & 0x2) {
8350            BLOGE(sc, "FATAL error from CFC\n");
8351        }
8352    }
8353
8354    if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8355        val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8356        BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8357        /* RQ_USDMDP_FIFO_OVERFLOW */
8358        if (val & 0x18000) {
8359            BLOGE(sc, "FATAL error from PXP\n");
8360        }
8361
8362        if (!CHIP_IS_E1x(sc)) {
8363            val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8364            BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8365        }
8366    }
8367
8368#define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8369#define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8370
8371    if (attn & AEU_PXP2_HW_INT_BIT) {
8372        /*  CQ47854 workaround do not panic on
8373         *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8374         */
8375        if (!CHIP_IS_E1x(sc)) {
8376            mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8377            val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8378            mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8379            val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8380            /*
8381             * If the olny PXP2_EOP_ERROR_BIT is set in
8382             * STS0 and STS1 - clear it
8383             *
8384             * probably we lose additional attentions between
8385             * STS0 and STS_CLR0, in this case user will not
8386             * be notified about them
8387             */
8388            if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8389                !(val1 & mask1))
8390                val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8391
8392            /* print the register, since no one can restore it */
8393            BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8394
8395            /*
8396             * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8397             * then notify
8398             */
8399            if (val0 & PXP2_EOP_ERROR_BIT) {
8400                BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8401
8402                /*
8403                 * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8404                 * set then clear attention from PXP2 block without panic
8405                 */
8406                if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8407                    ((val1 & mask1) == 0))
8408                    attn &= ~AEU_PXP2_HW_INT_BIT;
8409            }
8410        }
8411    }
8412
8413    if (attn & HW_INTERRUT_ASSERT_SET_2) {
8414        reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8415                             MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8416
8417        val = REG_RD(sc, reg_offset);
8418        val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8419        REG_WR(sc, reg_offset, val);
8420
8421        BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8422              (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8423        bxe_panic(sc, ("HW block attention set2\n"));
8424    }
8425}
8426
8427static void
8428bxe_attn_int_deasserted1(struct bxe_softc *sc,
8429                         uint32_t         attn)
8430{
8431    int port = SC_PORT(sc);
8432    int reg_offset;
8433    uint32_t val;
8434
8435    if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8436        val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8437        BLOGE(sc, "DB hw attention 0x%08x\n", val);
8438        /* DORQ discard attention */
8439        if (val & 0x2) {
8440            BLOGE(sc, "FATAL error from DORQ\n");
8441        }
8442    }
8443
8444    if (attn & HW_INTERRUT_ASSERT_SET_1) {
8445        reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8446                             MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8447
8448        val = REG_RD(sc, reg_offset);
8449        val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8450        REG_WR(sc, reg_offset, val);
8451
8452        BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8453              (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8454        bxe_panic(sc, ("HW block attention set1\n"));
8455    }
8456}
8457
8458static void
8459bxe_attn_int_deasserted0(struct bxe_softc *sc,
8460                         uint32_t         attn)
8461{
8462    int port = SC_PORT(sc);
8463    int reg_offset;
8464    uint32_t val;
8465
8466    reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8467                          MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8468
8469    if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8470        val = REG_RD(sc, reg_offset);
8471        val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8472        REG_WR(sc, reg_offset, val);
8473
8474        BLOGW(sc, "SPIO5 hw attention\n");
8475
8476        /* Fan failure attention */
8477        elink_hw_reset_phy(&sc->link_params);
8478        bxe_fan_failure(sc);
8479    }
8480
8481    if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8482        BXE_PHY_LOCK(sc);
8483        elink_handle_module_detect_int(&sc->link_params);
8484        BXE_PHY_UNLOCK(sc);
8485    }
8486
8487    if (attn & HW_INTERRUT_ASSERT_SET_0) {
8488        val = REG_RD(sc, reg_offset);
8489        val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8490        REG_WR(sc, reg_offset, val);
8491
8492        bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8493                       (attn & HW_INTERRUT_ASSERT_SET_0)));
8494    }
8495}
8496
8497static void
8498bxe_attn_int_deasserted(struct bxe_softc *sc,
8499                        uint32_t         deasserted)
8500{
8501    struct attn_route attn;
8502    struct attn_route *group_mask;
8503    int port = SC_PORT(sc);
8504    int index;
8505    uint32_t reg_addr;
8506    uint32_t val;
8507    uint32_t aeu_mask;
8508    uint8_t global = FALSE;
8509
8510    /*
8511     * Need to take HW lock because MCP or other port might also
8512     * try to handle this event.
8513     */
8514    bxe_acquire_alr(sc);
8515
8516    if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8517        /* XXX
8518         * In case of parity errors don't handle attentions so that
8519         * other function would "see" parity errors.
8520         */
8521        sc->recovery_state = BXE_RECOVERY_INIT;
8522        // XXX schedule a recovery task...
8523        /* disable HW interrupts */
8524        bxe_int_disable(sc);
8525        bxe_release_alr(sc);
8526        return;
8527    }
8528
8529    attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8530    attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8531    attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8532    attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8533    if (!CHIP_IS_E1x(sc)) {
8534        attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8535    } else {
8536        attn.sig[4] = 0;
8537    }
8538
8539    BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8540          attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8541
8542    for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8543        if (deasserted & (1 << index)) {
8544            group_mask = &sc->attn_group[index];
8545
8546            BLOGD(sc, DBG_INTR,
8547                  "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8548                  group_mask->sig[0], group_mask->sig[1],
8549                  group_mask->sig[2], group_mask->sig[3],
8550                  group_mask->sig[4]);
8551
8552            bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8553            bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8554            bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8555            bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8556            bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8557        }
8558    }
8559
8560    bxe_release_alr(sc);
8561
8562    if (sc->devinfo.int_block == INT_BLOCK_HC) {
8563        reg_addr = (HC_REG_COMMAND_REG + port*32 +
8564                    COMMAND_REG_ATTN_BITS_CLR);
8565    } else {
8566        reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8567    }
8568
8569    val = ~deasserted;
8570    BLOGD(sc, DBG_INTR,
8571          "about to mask 0x%08x at %s addr 0x%08x\n", val,
8572          (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8573    REG_WR(sc, reg_addr, val);
8574
8575    if (~sc->attn_state & deasserted) {
8576        BLOGE(sc, "IGU error\n");
8577    }
8578
8579    reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8580                      MISC_REG_AEU_MASK_ATTN_FUNC_0;
8581
8582    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8583
8584    aeu_mask = REG_RD(sc, reg_addr);
8585
8586    BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8587          aeu_mask, deasserted);
8588    aeu_mask |= (deasserted & 0x3ff);
8589    BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8590
8591    REG_WR(sc, reg_addr, aeu_mask);
8592    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8593
8594    BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8595    sc->attn_state &= ~deasserted;
8596    BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8597}
8598
8599static void
8600bxe_attn_int(struct bxe_softc *sc)
8601{
8602    /* read local copy of bits */
8603    uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8604    uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8605    uint32_t attn_state = sc->attn_state;
8606
8607    /* look for changed bits */
8608    uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8609    uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8610
8611    BLOGD(sc, DBG_INTR,
8612          "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8613          attn_bits, attn_ack, asserted, deasserted);
8614
8615    if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8616        BLOGE(sc, "BAD attention state\n");
8617    }
8618
8619    /* handle bits that were raised */
8620    if (asserted) {
8621        bxe_attn_int_asserted(sc, asserted);
8622    }
8623
8624    if (deasserted) {
8625        bxe_attn_int_deasserted(sc, deasserted);
8626    }
8627}
8628
8629static uint16_t
8630bxe_update_dsb_idx(struct bxe_softc *sc)
8631{
8632    struct host_sp_status_block *def_sb = sc->def_sb;
8633    uint16_t rc = 0;
8634
8635    mb(); /* status block is written to by the chip */
8636
8637    if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8638        sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8639        rc |= BXE_DEF_SB_ATT_IDX;
8640    }
8641
8642    if (sc->def_idx != def_sb->sp_sb.running_index) {
8643        sc->def_idx = def_sb->sp_sb.running_index;
8644        rc |= BXE_DEF_SB_IDX;
8645    }
8646
8647    mb();
8648
8649    return (rc);
8650}
8651
8652static inline struct ecore_queue_sp_obj *
8653bxe_cid_to_q_obj(struct bxe_softc *sc,
8654                 uint32_t         cid)
8655{
8656    BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8657    return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8658}
8659
8660static void
8661bxe_handle_mcast_eqe(struct bxe_softc *sc)
8662{
8663    struct ecore_mcast_ramrod_params rparam;
8664    int rc;
8665
8666    memset(&rparam, 0, sizeof(rparam));
8667
8668    rparam.mcast_obj = &sc->mcast_obj;
8669
8670    BXE_MCAST_LOCK(sc);
8671
8672    /* clear pending state for the last command */
8673    sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8674
8675    /* if there are pending mcast commands - send them */
8676    if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8677        rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8678        if (rc < 0) {
8679            BLOGD(sc, DBG_SP,
8680                  "ERROR: Failed to send pending mcast commands (%d)\n",
8681                  rc);
8682        }
8683    }
8684
8685    BXE_MCAST_UNLOCK(sc);
8686}
8687
8688static void
8689bxe_handle_classification_eqe(struct bxe_softc      *sc,
8690                              union event_ring_elem *elem)
8691{
8692    unsigned long ramrod_flags = 0;
8693    int rc = 0;
8694    uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8695    struct ecore_vlan_mac_obj *vlan_mac_obj;
8696
8697    /* always push next commands out, don't wait here */
8698    bit_set(&ramrod_flags, RAMROD_CONT);
8699
8700    switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8701    case ECORE_FILTER_MAC_PENDING:
8702        BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8703        vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8704        break;
8705
8706    case ECORE_FILTER_MCAST_PENDING:
8707        BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8708        /*
8709         * This is only relevant for 57710 where multicast MACs are
8710         * configured as unicast MACs using the same ramrod.
8711         */
8712        bxe_handle_mcast_eqe(sc);
8713        return;
8714
8715    default:
8716        BLOGE(sc, "Unsupported classification command: %d\n",
8717              elem->message.data.eth_event.echo);
8718        return;
8719    }
8720
8721    rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8722
8723    if (rc < 0) {
8724        BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8725    } else if (rc > 0) {
8726        BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8727    }
8728}
8729
8730static void
8731bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8732                       union event_ring_elem *elem)
8733{
8734    bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8735
8736    /* send rx_mode command again if was requested */
8737    if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8738                               &sc->sp_state)) {
8739        bxe_set_storm_rx_mode(sc);
8740    }
8741#if 0
8742    else if (bxe_test_and_clear_bit(ECORE_FILTER_ISCSI_ETH_START_SCHED,
8743                                    &sc->sp_state)) {
8744        bxe_set_iscsi_eth_rx_mode(sc, TRUE);
8745    }
8746    else if (bxe_test_and_clear_bit(ECORE_FILTER_ISCSI_ETH_STOP_SCHED,
8747                                    &sc->sp_state)) {
8748        bxe_set_iscsi_eth_rx_mode(sc, FALSE);
8749    }
8750#endif
8751}
8752
8753static void
8754bxe_update_eq_prod(struct bxe_softc *sc,
8755                   uint16_t         prod)
8756{
8757    storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8758    wmb(); /* keep prod updates ordered */
8759}
8760
8761static void
8762bxe_eq_int(struct bxe_softc *sc)
8763{
8764    uint16_t hw_cons, sw_cons, sw_prod;
8765    union event_ring_elem *elem;
8766    uint8_t echo;
8767    uint32_t cid;
8768    uint8_t opcode;
8769    int spqe_cnt = 0;
8770    struct ecore_queue_sp_obj *q_obj;
8771    struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8772    struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8773
8774    hw_cons = le16toh(*sc->eq_cons_sb);
8775
8776    /*
8777     * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8778     * when we get to the next-page we need to adjust so the loop
8779     * condition below will be met. The next element is the size of a
8780     * regular element and hence incrementing by 1
8781     */
8782    if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8783        hw_cons++;
8784    }
8785
8786    /*
8787     * This function may never run in parallel with itself for a
8788     * specific sc and no need for a read memory barrier here.
8789     */
8790    sw_cons = sc->eq_cons;
8791    sw_prod = sc->eq_prod;
8792
8793    BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8794          hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8795
8796    for (;
8797         sw_cons != hw_cons;
8798         sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8799
8800        elem = &sc->eq[EQ_DESC(sw_cons)];
8801
8802#if 0
8803        int rc;
8804        rc = bxe_iov_eq_sp_event(sc, elem);
8805        if (!rc) {
8806            BLOGE(sc, "bxe_iov_eq_sp_event returned %d\n", rc);
8807            goto next_spqe;
8808        }
8809#endif
8810
8811        /* elem CID originates from FW, actually LE */
8812        cid = SW_CID(elem->message.data.cfc_del_event.cid);
8813        opcode = elem->message.opcode;
8814
8815        /* handle eq element */
8816        switch (opcode) {
8817#if 0
8818        case EVENT_RING_OPCODE_VF_PF_CHANNEL:
8819            BLOGD(sc, DBG_SP, "vf/pf channel element on eq\n");
8820            bxe_vf_mbx(sc, &elem->message.data.vf_pf_event);
8821            continue;
8822#endif
8823
8824        case EVENT_RING_OPCODE_STAT_QUERY:
8825            BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8826                  sc->stats_comp++);
8827            /* nothing to do with stats comp */
8828            goto next_spqe;
8829
8830        case EVENT_RING_OPCODE_CFC_DEL:
8831            /* handle according to cid range */
8832            /* we may want to verify here that the sc state is HALTING */
8833            BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8834            q_obj = bxe_cid_to_q_obj(sc, cid);
8835            if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8836                break;
8837            }
8838            goto next_spqe;
8839
8840        case EVENT_RING_OPCODE_STOP_TRAFFIC:
8841            BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8842            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8843                break;
8844            }
8845            // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8846            goto next_spqe;
8847
8848        case EVENT_RING_OPCODE_START_TRAFFIC:
8849            BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8850            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8851                break;
8852            }
8853            // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8854            goto next_spqe;
8855
8856        case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8857            echo = elem->message.data.function_update_event.echo;
8858            if (echo == SWITCH_UPDATE) {
8859                BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8860                if (f_obj->complete_cmd(sc, f_obj,
8861                                        ECORE_F_CMD_SWITCH_UPDATE)) {
8862                    break;
8863                }
8864            }
8865            else {
8866                BLOGD(sc, DBG_SP,
8867                      "AFEX: ramrod completed FUNCTION_UPDATE\n");
8868#if 0
8869                f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_AFEX_UPDATE);
8870                /*
8871                 * We will perform the queues update from the sp_core_task as
8872                 * all queue SP operations should run with CORE_LOCK.
8873                 */
8874                bxe_set_bit(BXE_SP_CORE_AFEX_F_UPDATE, &sc->sp_core_state);
8875                taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8876#endif
8877            }
8878            goto next_spqe;
8879
8880#if 0
8881        case EVENT_RING_OPCODE_AFEX_VIF_LISTS:
8882            f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_AFEX_VIFLISTS);
8883            bxe_after_afex_vif_lists(sc, elem);
8884            goto next_spqe;
8885#endif
8886
8887        case EVENT_RING_OPCODE_FORWARD_SETUP:
8888            q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8889            if (q_obj->complete_cmd(sc, q_obj,
8890                                    ECORE_Q_CMD_SETUP_TX_ONLY)) {
8891                break;
8892            }
8893            goto next_spqe;
8894
8895        case EVENT_RING_OPCODE_FUNCTION_START:
8896            BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8897            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8898                break;
8899            }
8900            goto next_spqe;
8901
8902        case EVENT_RING_OPCODE_FUNCTION_STOP:
8903            BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8904            if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8905                break;
8906            }
8907            goto next_spqe;
8908        }
8909
8910        switch (opcode | sc->state) {
8911        case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8912        case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8913            cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8914            BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8915            rss_raw->clear_pending(rss_raw);
8916            break;
8917
8918        case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8919        case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8920        case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8921        case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8922        case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8923        case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8924            BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8925            bxe_handle_classification_eqe(sc, elem);
8926            break;
8927
8928        case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8929        case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8930        case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8931            BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8932            bxe_handle_mcast_eqe(sc);
8933            break;
8934
8935        case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8936        case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8937        case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8938            BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8939            bxe_handle_rx_mode_eqe(sc, elem);
8940            break;
8941
8942        default:
8943            /* unknown event log error and continue */
8944            BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8945                  elem->message.opcode, sc->state);
8946        }
8947
8948next_spqe:
8949        spqe_cnt++;
8950    } /* for */
8951
8952    mb();
8953    atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8954
8955    sc->eq_cons = sw_cons;
8956    sc->eq_prod = sw_prod;
8957
8958    /* make sure that above mem writes were issued towards the memory */
8959    wmb();
8960
8961    /* update producer */
8962    bxe_update_eq_prod(sc, sc->eq_prod);
8963}
8964
8965static void
8966bxe_handle_sp_tq(void *context,
8967                 int  pending)
8968{
8969    struct bxe_softc *sc = (struct bxe_softc *)context;
8970    uint16_t status;
8971
8972    BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8973
8974    /* what work needs to be performed? */
8975    status = bxe_update_dsb_idx(sc);
8976
8977    BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8978
8979    /* HW attentions */
8980    if (status & BXE_DEF_SB_ATT_IDX) {
8981        BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8982        bxe_attn_int(sc);
8983        status &= ~BXE_DEF_SB_ATT_IDX;
8984    }
8985
8986    /* SP events: STAT_QUERY and others */
8987    if (status & BXE_DEF_SB_IDX) {
8988        /* handle EQ completions */
8989        BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8990        bxe_eq_int(sc);
8991        bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8992                   le16toh(sc->def_idx), IGU_INT_NOP, 1);
8993        status &= ~BXE_DEF_SB_IDX;
8994    }
8995
8996    /* if status is non zero then something went wrong */
8997    if (__predict_false(status)) {
8998        BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8999    }
9000
9001    /* ack status block only if something was actually handled */
9002    bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
9003               le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
9004
9005    /*
9006     * Must be called after the EQ processing (since eq leads to sriov
9007     * ramrod completion flows).
9008     * This flow may have been scheduled by the arrival of a ramrod
9009     * completion, or by the sriov code rescheduling itself.
9010     */
9011    // XXX bxe_iov_sp_task(sc);
9012
9013#if 0
9014    /* AFEX - poll to check if VIFSET_ACK should be sent to MFW */
9015    if (bxe_test_and_clear_bit(ECORE_AFEX_PENDING_VIFSET_MCP_ACK,
9016                               &sc->sp_state)) {
9017        bxe_link_report(sc);
9018        bxe_fw_command(sc, DRV_MSG_CODE_AFEX_VIFSET_ACK, 0);
9019    }
9020#endif
9021}
9022
9023static void
9024bxe_handle_fp_tq(void *context,
9025                 int  pending)
9026{
9027    struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
9028    struct bxe_softc *sc = fp->sc;
9029    uint8_t more_tx = FALSE;
9030    uint8_t more_rx = FALSE;
9031
9032    BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
9033
9034    /* XXX
9035     * IFF_DRV_RUNNING state can't be checked here since we process
9036     * slowpath events on a client queue during setup. Instead
9037     * we need to add a "process/continue" flag here that the driver
9038     * can use to tell the task here not to do anything.
9039     */
9040#if 0
9041    if (!(sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
9042        return;
9043    }
9044#endif
9045
9046    /* update the fastpath index */
9047    bxe_update_fp_sb_idx(fp);
9048
9049    /* XXX add loop here if ever support multiple tx CoS */
9050    /* fp->txdata[cos] */
9051    if (bxe_has_tx_work(fp)) {
9052        BXE_FP_TX_LOCK(fp);
9053        more_tx = bxe_txeof(sc, fp);
9054        BXE_FP_TX_UNLOCK(fp);
9055    }
9056
9057    if (bxe_has_rx_work(fp)) {
9058        more_rx = bxe_rxeof(sc, fp);
9059    }
9060
9061    if (more_rx /*|| more_tx*/) {
9062        /* still more work to do */
9063        taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
9064        return;
9065    }
9066
9067    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
9068               le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
9069}
9070
9071static void
9072bxe_task_fp(struct bxe_fastpath *fp)
9073{
9074    struct bxe_softc *sc = fp->sc;
9075    uint8_t more_tx = FALSE;
9076    uint8_t more_rx = FALSE;
9077
9078    BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
9079
9080    /* update the fastpath index */
9081    bxe_update_fp_sb_idx(fp);
9082
9083    /* XXX add loop here if ever support multiple tx CoS */
9084    /* fp->txdata[cos] */
9085    if (bxe_has_tx_work(fp)) {
9086        BXE_FP_TX_LOCK(fp);
9087        more_tx = bxe_txeof(sc, fp);
9088        BXE_FP_TX_UNLOCK(fp);
9089    }
9090
9091    if (bxe_has_rx_work(fp)) {
9092        more_rx = bxe_rxeof(sc, fp);
9093    }
9094
9095    if (more_rx /*|| more_tx*/) {
9096        /* still more work to do, bail out if this ISR and process later */
9097        taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
9098        return;
9099    }
9100
9101    /*
9102     * Here we write the fastpath index taken before doing any tx or rx work.
9103     * It is very well possible other hw events occurred up to this point and
9104     * they were actually processed accordingly above. Since we're going to
9105     * write an older fastpath index, an interrupt is coming which we might
9106     * not do any work in.
9107     */
9108    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
9109               le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
9110}
9111
9112/*
9113 * Legacy interrupt entry point.
9114 *
9115 * Verifies that the controller generated the interrupt and
9116 * then calls a separate routine to handle the various
9117 * interrupt causes: link, RX, and TX.
9118 */
9119static void
9120bxe_intr_legacy(void *xsc)
9121{
9122    struct bxe_softc *sc = (struct bxe_softc *)xsc;
9123    struct bxe_fastpath *fp;
9124    uint16_t status, mask;
9125    int i;
9126
9127    BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
9128
9129#if 0
9130    /* Don't handle any interrupts if we're not ready. */
9131    if (__predict_false(sc->intr_sem != 0)) {
9132        return;
9133    }
9134#endif
9135
9136    /*
9137     * 0 for ustorm, 1 for cstorm
9138     * the bits returned from ack_int() are 0-15
9139     * bit 0 = attention status block
9140     * bit 1 = fast path status block
9141     * a mask of 0x2 or more = tx/rx event
9142     * a mask of 1 = slow path event
9143     */
9144
9145    status = bxe_ack_int(sc);
9146
9147    /* the interrupt is not for us */
9148    if (__predict_false(status == 0)) {
9149        BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
9150        return;
9151    }
9152
9153    BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
9154
9155    FOR_EACH_ETH_QUEUE(sc, i) {
9156        fp = &sc->fp[i];
9157        mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
9158        if (status & mask) {
9159            /* acknowledge and disable further fastpath interrupts */
9160            bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
9161            bxe_task_fp(fp);
9162            status &= ~mask;
9163        }
9164    }
9165
9166#if 0
9167    if (CNIC_SUPPORT(sc)) {
9168        mask = 0x2;
9169        if (status & (mask | 0x1)) {
9170            ...
9171            status &= ~mask;
9172        }
9173    }
9174#endif
9175
9176    if (__predict_false(status & 0x1)) {
9177        /* acknowledge and disable further slowpath interrupts */
9178        bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
9179
9180        /* schedule slowpath handler */
9181        taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
9182
9183        status &= ~0x1;
9184    }
9185
9186    if (__predict_false(status)) {
9187        BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
9188    }
9189}
9190
9191/* slowpath interrupt entry point */
9192static void
9193bxe_intr_sp(void *xsc)
9194{
9195    struct bxe_softc *sc = (struct bxe_softc *)xsc;
9196
9197    BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
9198
9199    /* acknowledge and disable further slowpath interrupts */
9200    bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
9201
9202    /* schedule slowpath handler */
9203    taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
9204}
9205
9206/* fastpath interrupt entry point */
9207static void
9208bxe_intr_fp(void *xfp)
9209{
9210    struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
9211    struct bxe_softc *sc = fp->sc;
9212
9213    BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
9214
9215    BLOGD(sc, DBG_INTR,
9216          "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
9217          curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
9218
9219#if 0
9220    /* Don't handle any interrupts if we're not ready. */
9221    if (__predict_false(sc->intr_sem != 0)) {
9222        return;
9223    }
9224#endif
9225
9226    /* acknowledge and disable further fastpath interrupts */
9227    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
9228
9229    bxe_task_fp(fp);
9230}
9231
9232/* Release all interrupts allocated by the driver. */
9233static void
9234bxe_interrupt_free(struct bxe_softc *sc)
9235{
9236    int i;
9237
9238    switch (sc->interrupt_mode) {
9239    case INTR_MODE_INTX:
9240        BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
9241        if (sc->intr[0].resource != NULL) {
9242            bus_release_resource(sc->dev,
9243                                 SYS_RES_IRQ,
9244                                 sc->intr[0].rid,
9245                                 sc->intr[0].resource);
9246        }
9247        break;
9248    case INTR_MODE_MSI:
9249        for (i = 0; i < sc->intr_count; i++) {
9250            BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
9251            if (sc->intr[i].resource && sc->intr[i].rid) {
9252                bus_release_resource(sc->dev,
9253                                     SYS_RES_IRQ,
9254                                     sc->intr[i].rid,
9255                                     sc->intr[i].resource);
9256            }
9257        }
9258        pci_release_msi(sc->dev);
9259        break;
9260    case INTR_MODE_MSIX:
9261        for (i = 0; i < sc->intr_count; i++) {
9262            BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
9263            if (sc->intr[i].resource && sc->intr[i].rid) {
9264                bus_release_resource(sc->dev,
9265                                     SYS_RES_IRQ,
9266                                     sc->intr[i].rid,
9267                                     sc->intr[i].resource);
9268            }
9269        }
9270        pci_release_msi(sc->dev);
9271        break;
9272    default:
9273        /* nothing to do as initial allocation failed */
9274        break;
9275    }
9276}
9277
9278/*
9279 * This function determines and allocates the appropriate
9280 * interrupt based on system capabilites and user request.
9281 *
9282 * The user may force a particular interrupt mode, specify
9283 * the number of receive queues, specify the method for
9284 * distribuitng received frames to receive queues, or use
9285 * the default settings which will automatically select the
9286 * best supported combination.  In addition, the OS may or
9287 * may not support certain combinations of these settings.
9288 * This routine attempts to reconcile the settings requested
9289 * by the user with the capabilites available from the system
9290 * to select the optimal combination of features.
9291 *
9292 * Returns:
9293 *   0 = Success, !0 = Failure.
9294 */
9295static int
9296bxe_interrupt_alloc(struct bxe_softc *sc)
9297{
9298    int msix_count = 0;
9299    int msi_count = 0;
9300    int num_requested = 0;
9301    int num_allocated = 0;
9302    int rid, i, j;
9303    int rc;
9304
9305    /* get the number of available MSI/MSI-X interrupts from the OS */
9306    if (sc->interrupt_mode > 0) {
9307        if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
9308            msix_count = pci_msix_count(sc->dev);
9309        }
9310
9311        if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
9312            msi_count = pci_msi_count(sc->dev);
9313        }
9314
9315        BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
9316              msi_count, msix_count);
9317    }
9318
9319    do { /* try allocating MSI-X interrupt resources (at least 2) */
9320        if (sc->interrupt_mode != INTR_MODE_MSIX) {
9321            break;
9322        }
9323
9324        if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
9325            (msix_count < 2)) {
9326            sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9327            break;
9328        }
9329
9330        /* ask for the necessary number of MSI-X vectors */
9331        num_requested = min((sc->num_queues + 1), msix_count);
9332
9333        BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
9334
9335        num_allocated = num_requested;
9336        if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
9337            BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
9338            sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9339            break;
9340        }
9341
9342        if (num_allocated < 2) { /* possible? */
9343            BLOGE(sc, "MSI-X allocation less than 2!\n");
9344            sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9345            pci_release_msi(sc->dev);
9346            break;
9347        }
9348
9349        BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
9350              num_requested, num_allocated);
9351
9352        /* best effort so use the number of vectors allocated to us */
9353        sc->intr_count = num_allocated;
9354        sc->num_queues = num_allocated - 1;
9355
9356        rid = 1; /* initial resource identifier */
9357
9358        /* allocate the MSI-X vectors */
9359        for (i = 0; i < num_allocated; i++) {
9360            sc->intr[i].rid = (rid + i);
9361
9362            if ((sc->intr[i].resource =
9363                 bus_alloc_resource_any(sc->dev,
9364                                        SYS_RES_IRQ,
9365                                        &sc->intr[i].rid,
9366                                        RF_ACTIVE)) == NULL) {
9367                BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
9368                      i, (rid + i));
9369
9370                for (j = (i - 1); j >= 0; j--) {
9371                    bus_release_resource(sc->dev,
9372                                         SYS_RES_IRQ,
9373                                         sc->intr[j].rid,
9374                                         sc->intr[j].resource);
9375                }
9376
9377                sc->intr_count = 0;
9378                sc->num_queues = 0;
9379                sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9380                pci_release_msi(sc->dev);
9381                break;
9382            }
9383
9384            BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9385        }
9386    } while (0);
9387
9388    do { /* try allocating MSI vector resources (at least 2) */
9389        if (sc->interrupt_mode != INTR_MODE_MSI) {
9390            break;
9391        }
9392
9393        if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9394            (msi_count < 2)) {
9395            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9396            break;
9397        }
9398
9399        /* ask for the necessary number of MSI vectors */
9400        num_requested = min((sc->num_queues + 1), msi_count);
9401
9402        BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9403
9404        num_allocated = num_requested;
9405        if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9406            BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9407            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9408            break;
9409        }
9410
9411        if (num_allocated < 2) { /* possible? */
9412            BLOGE(sc, "MSI allocation less than 2!\n");
9413            sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9414            pci_release_msi(sc->dev);
9415            break;
9416        }
9417
9418        BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9419              num_requested, num_allocated);
9420
9421        /* best effort so use the number of vectors allocated to us */
9422        sc->intr_count = num_allocated;
9423        sc->num_queues = num_allocated - 1;
9424
9425        rid = 1; /* initial resource identifier */
9426
9427        /* allocate the MSI vectors */
9428        for (i = 0; i < num_allocated; i++) {
9429            sc->intr[i].rid = (rid + i);
9430
9431            if ((sc->intr[i].resource =
9432                 bus_alloc_resource_any(sc->dev,
9433                                        SYS_RES_IRQ,
9434                                        &sc->intr[i].rid,
9435                                        RF_ACTIVE)) == NULL) {
9436                BLOGE(sc, "Failed to map MSI[%d] (rid=%d)!\n",
9437                      i, (rid + i));
9438
9439                for (j = (i - 1); j >= 0; j--) {
9440                    bus_release_resource(sc->dev,
9441                                         SYS_RES_IRQ,
9442                                         sc->intr[j].rid,
9443                                         sc->intr[j].resource);
9444                }
9445
9446                sc->intr_count = 0;
9447                sc->num_queues = 0;
9448                sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9449                pci_release_msi(sc->dev);
9450                break;
9451            }
9452
9453            BLOGD(sc, DBG_LOAD, "Mapped MSI[%d] (rid=%d)\n", i, (rid + i));
9454        }
9455    } while (0);
9456
9457    do { /* try allocating INTx vector resources */
9458        if (sc->interrupt_mode != INTR_MODE_INTX) {
9459            break;
9460        }
9461
9462        BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9463
9464        /* only one vector for INTx */
9465        sc->intr_count = 1;
9466        sc->num_queues = 1;
9467
9468        rid = 0; /* initial resource identifier */
9469
9470        sc->intr[0].rid = rid;
9471
9472        if ((sc->intr[0].resource =
9473             bus_alloc_resource_any(sc->dev,
9474                                    SYS_RES_IRQ,
9475                                    &sc->intr[0].rid,
9476                                    (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9477            BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9478            sc->intr_count = 0;
9479            sc->num_queues = 0;
9480            sc->interrupt_mode = -1; /* Failed! */
9481            break;
9482        }
9483
9484        BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9485    } while (0);
9486
9487    if (sc->interrupt_mode == -1) {
9488        BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9489        rc = 1;
9490    } else {
9491        BLOGD(sc, DBG_LOAD,
9492              "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9493              sc->interrupt_mode, sc->num_queues);
9494        rc = 0;
9495    }
9496
9497    return (rc);
9498}
9499
9500static void
9501bxe_interrupt_detach(struct bxe_softc *sc)
9502{
9503    struct bxe_fastpath *fp;
9504    int i;
9505
9506    /* release interrupt resources */
9507    for (i = 0; i < sc->intr_count; i++) {
9508        if (sc->intr[i].resource && sc->intr[i].tag) {
9509            BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9510            bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9511        }
9512    }
9513
9514    for (i = 0; i < sc->num_queues; i++) {
9515        fp = &sc->fp[i];
9516        if (fp->tq) {
9517            taskqueue_drain(fp->tq, &fp->tq_task);
9518            taskqueue_free(fp->tq);
9519            fp->tq = NULL;
9520        }
9521    }
9522
9523    if (sc->rx_mode_tq) {
9524        taskqueue_drain(sc->rx_mode_tq, &sc->rx_mode_tq_task);
9525        taskqueue_free(sc->rx_mode_tq);
9526        sc->rx_mode_tq = NULL;
9527    }
9528
9529    if (sc->sp_tq) {
9530        taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9531        taskqueue_free(sc->sp_tq);
9532        sc->sp_tq = NULL;
9533    }
9534}
9535
9536/*
9537 * Enables interrupts and attach to the ISR.
9538 *
9539 * When using multiple MSI/MSI-X vectors the first vector
9540 * is used for slowpath operations while all remaining
9541 * vectors are used for fastpath operations.  If only a
9542 * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9543 * ISR must look for both slowpath and fastpath completions.
9544 */
9545static int
9546bxe_interrupt_attach(struct bxe_softc *sc)
9547{
9548    struct bxe_fastpath *fp;
9549    int rc = 0;
9550    int i;
9551
9552    snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9553             "bxe%d_sp_tq", sc->unit);
9554    TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9555    sc->sp_tq = taskqueue_create_fast(sc->sp_tq_name, M_NOWAIT,
9556                                      taskqueue_thread_enqueue,
9557                                      &sc->sp_tq);
9558    taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9559                            "%s", sc->sp_tq_name);
9560
9561    snprintf(sc->rx_mode_tq_name, sizeof(sc->rx_mode_tq_name),
9562             "bxe%d_rx_mode_tq", sc->unit);
9563    TASK_INIT(&sc->rx_mode_tq_task, 0, bxe_handle_rx_mode_tq, sc);
9564    sc->rx_mode_tq = taskqueue_create_fast(sc->rx_mode_tq_name, M_NOWAIT,
9565                                           taskqueue_thread_enqueue,
9566                                           &sc->rx_mode_tq);
9567    taskqueue_start_threads(&sc->rx_mode_tq, 1, PWAIT, /* lower priority */
9568                            "%s", sc->rx_mode_tq_name);
9569
9570    for (i = 0; i < sc->num_queues; i++) {
9571        fp = &sc->fp[i];
9572        snprintf(fp->tq_name, sizeof(fp->tq_name),
9573                 "bxe%d_fp%d_tq", sc->unit, i);
9574        TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9575        fp->tq = taskqueue_create_fast(fp->tq_name, M_NOWAIT,
9576                                       taskqueue_thread_enqueue,
9577                                       &fp->tq);
9578        taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9579                                "%s", fp->tq_name);
9580    }
9581
9582    /* setup interrupt handlers */
9583    if (sc->interrupt_mode == INTR_MODE_MSIX) {
9584        BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9585
9586        /*
9587         * Setup the interrupt handler. Note that we pass the driver instance
9588         * to the interrupt handler for the slowpath.
9589         */
9590        if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9591                                 (INTR_TYPE_NET | INTR_MPSAFE),
9592                                 NULL, bxe_intr_sp, sc,
9593                                 &sc->intr[0].tag)) != 0) {
9594            BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9595            goto bxe_interrupt_attach_exit;
9596        }
9597
9598        bus_describe_intr(sc->dev, sc->intr[0].resource,
9599                          sc->intr[0].tag, "sp");
9600
9601        /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9602
9603        /* initialize the fastpath vectors (note the first was used for sp) */
9604        for (i = 0; i < sc->num_queues; i++) {
9605            fp = &sc->fp[i];
9606            BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9607
9608            /*
9609             * Setup the interrupt handler. Note that we pass the
9610             * fastpath context to the interrupt handler in this
9611             * case.
9612             */
9613            if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9614                                     (INTR_TYPE_NET | INTR_MPSAFE),
9615                                     NULL, bxe_intr_fp, fp,
9616                                     &sc->intr[i + 1].tag)) != 0) {
9617                BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9618                      (i + 1), rc);
9619                goto bxe_interrupt_attach_exit;
9620            }
9621
9622            bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9623                              sc->intr[i + 1].tag, "fp%02d", i);
9624
9625            /* bind the fastpath instance to a cpu */
9626            if (sc->num_queues > 1) {
9627                bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9628            }
9629
9630            fp->state = BXE_FP_STATE_IRQ;
9631        }
9632    } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9633        BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI[0] vector.\n");
9634
9635        /*
9636         * Setup the interrupt handler. Note that we pass the driver instance
9637         * to the interrupt handler for the slowpath.
9638         */
9639        if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9640                                 (INTR_TYPE_NET | INTR_MPSAFE),
9641                                 NULL, bxe_intr_sp, sc,
9642                                 &sc->intr[0].tag)) != 0) {
9643            BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9644            goto bxe_interrupt_attach_exit;
9645        }
9646
9647        bus_describe_intr(sc->dev, sc->intr[0].resource,
9648                          sc->intr[0].tag, "sp");
9649
9650        /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9651
9652        /* initialize the fastpath vectors (note the first was used for sp) */
9653        for (i = 0; i < sc->num_queues; i++) {
9654            fp = &sc->fp[i];
9655            BLOGD(sc, DBG_LOAD, "Enabling MSI[%d] vector\n", (i + 1));
9656
9657            /*
9658             * Setup the interrupt handler. Note that we pass the
9659             * fastpath context to the interrupt handler in this
9660             * case.
9661             */
9662            if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9663                                     (INTR_TYPE_NET | INTR_MPSAFE),
9664                                     NULL, bxe_intr_fp, fp,
9665                                     &sc->intr[i + 1].tag)) != 0) {
9666                BLOGE(sc, "Failed to allocate MSI[%d] vector (%d)\n",
9667                      (i + 1), rc);
9668                goto bxe_interrupt_attach_exit;
9669            }
9670
9671            bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9672                              sc->intr[i + 1].tag, "fp%02d", i);
9673
9674            /* bind the fastpath instance to a cpu */
9675            if (sc->num_queues > 1) {
9676                bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9677            }
9678
9679            fp->state = BXE_FP_STATE_IRQ;
9680        }
9681    } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9682        BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9683
9684        /*
9685         * Setup the interrupt handler. Note that we pass the
9686         * driver instance to the interrupt handler which
9687         * will handle both the slowpath and fastpath.
9688         */
9689        if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9690                                 (INTR_TYPE_NET | INTR_MPSAFE),
9691                                 NULL, bxe_intr_legacy, sc,
9692                                 &sc->intr[0].tag)) != 0) {
9693            BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9694            goto bxe_interrupt_attach_exit;
9695        }
9696    }
9697
9698bxe_interrupt_attach_exit:
9699
9700    return (rc);
9701}
9702
9703static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9704static int  bxe_init_hw_common(struct bxe_softc *sc);
9705static int  bxe_init_hw_port(struct bxe_softc *sc);
9706static int  bxe_init_hw_func(struct bxe_softc *sc);
9707static void bxe_reset_common(struct bxe_softc *sc);
9708static void bxe_reset_port(struct bxe_softc *sc);
9709static void bxe_reset_func(struct bxe_softc *sc);
9710static int  bxe_gunzip_init(struct bxe_softc *sc);
9711static void bxe_gunzip_end(struct bxe_softc *sc);
9712static int  bxe_init_firmware(struct bxe_softc *sc);
9713static void bxe_release_firmware(struct bxe_softc *sc);
9714
9715static struct
9716ecore_func_sp_drv_ops bxe_func_sp_drv = {
9717    .init_hw_cmn_chip = bxe_init_hw_common_chip,
9718    .init_hw_cmn      = bxe_init_hw_common,
9719    .init_hw_port     = bxe_init_hw_port,
9720    .init_hw_func     = bxe_init_hw_func,
9721
9722    .reset_hw_cmn     = bxe_reset_common,
9723    .reset_hw_port    = bxe_reset_port,
9724    .reset_hw_func    = bxe_reset_func,
9725
9726    .gunzip_init      = bxe_gunzip_init,
9727    .gunzip_end       = bxe_gunzip_end,
9728
9729    .init_fw          = bxe_init_firmware,
9730    .release_fw       = bxe_release_firmware,
9731};
9732
9733static void
9734bxe_init_func_obj(struct bxe_softc *sc)
9735{
9736    sc->dmae_ready = 0;
9737
9738    ecore_init_func_obj(sc,
9739                        &sc->func_obj,
9740                        BXE_SP(sc, func_rdata),
9741                        BXE_SP_MAPPING(sc, func_rdata),
9742                        BXE_SP(sc, func_afex_rdata),
9743                        BXE_SP_MAPPING(sc, func_afex_rdata),
9744                        &bxe_func_sp_drv);
9745}
9746
9747static int
9748bxe_init_hw(struct bxe_softc *sc,
9749            uint32_t         load_code)
9750{
9751    struct ecore_func_state_params func_params = { NULL };
9752    int rc;
9753
9754    /* prepare the parameters for function state transitions */
9755    bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9756
9757    func_params.f_obj = &sc->func_obj;
9758    func_params.cmd = ECORE_F_CMD_HW_INIT;
9759
9760    func_params.params.hw_init.load_phase = load_code;
9761
9762    /*
9763     * Via a plethora of function pointers, we will eventually reach
9764     * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9765     */
9766    rc = ecore_func_state_change(sc, &func_params);
9767
9768    return (rc);
9769}
9770
9771static void
9772bxe_fill(struct bxe_softc *sc,
9773         uint32_t         addr,
9774         int              fill,
9775         uint32_t         len)
9776{
9777    uint32_t i;
9778
9779    if (!(len % 4) && !(addr % 4)) {
9780        for (i = 0; i < len; i += 4) {
9781            REG_WR(sc, (addr + i), fill);
9782        }
9783    } else {
9784        for (i = 0; i < len; i++) {
9785            REG_WR8(sc, (addr + i), fill);
9786        }
9787    }
9788}
9789
9790/* writes FP SP data to FW - data_size in dwords */
9791static void
9792bxe_wr_fp_sb_data(struct bxe_softc *sc,
9793                  int              fw_sb_id,
9794                  uint32_t         *sb_data_p,
9795                  uint32_t         data_size)
9796{
9797    int index;
9798
9799    for (index = 0; index < data_size; index++) {
9800        REG_WR(sc,
9801               (BAR_CSTRORM_INTMEM +
9802                CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9803                (sizeof(uint32_t) * index)),
9804               *(sb_data_p + index));
9805    }
9806}
9807
9808static void
9809bxe_zero_fp_sb(struct bxe_softc *sc,
9810               int              fw_sb_id)
9811{
9812    struct hc_status_block_data_e2 sb_data_e2;
9813    struct hc_status_block_data_e1x sb_data_e1x;
9814    uint32_t *sb_data_p;
9815    uint32_t data_size = 0;
9816
9817    if (!CHIP_IS_E1x(sc)) {
9818        memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9819        sb_data_e2.common.state = SB_DISABLED;
9820        sb_data_e2.common.p_func.vf_valid = FALSE;
9821        sb_data_p = (uint32_t *)&sb_data_e2;
9822        data_size = (sizeof(struct hc_status_block_data_e2) /
9823                     sizeof(uint32_t));
9824    } else {
9825        memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9826        sb_data_e1x.common.state = SB_DISABLED;
9827        sb_data_e1x.common.p_func.vf_valid = FALSE;
9828        sb_data_p = (uint32_t *)&sb_data_e1x;
9829        data_size = (sizeof(struct hc_status_block_data_e1x) /
9830                     sizeof(uint32_t));
9831    }
9832
9833    bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9834
9835    bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9836             0, CSTORM_STATUS_BLOCK_SIZE);
9837    bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9838             0, CSTORM_SYNC_BLOCK_SIZE);
9839}
9840
9841static void
9842bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9843                  struct hc_sp_status_block_data *sp_sb_data)
9844{
9845    int i;
9846
9847    for (i = 0;
9848         i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9849         i++) {
9850        REG_WR(sc,
9851               (BAR_CSTRORM_INTMEM +
9852                CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9853                (i * sizeof(uint32_t))),
9854               *((uint32_t *)sp_sb_data + i));
9855    }
9856}
9857
9858static void
9859bxe_zero_sp_sb(struct bxe_softc *sc)
9860{
9861    struct hc_sp_status_block_data sp_sb_data;
9862
9863    memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9864
9865    sp_sb_data.state           = SB_DISABLED;
9866    sp_sb_data.p_func.vf_valid = FALSE;
9867
9868    bxe_wr_sp_sb_data(sc, &sp_sb_data);
9869
9870    bxe_fill(sc,
9871             (BAR_CSTRORM_INTMEM +
9872              CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9873              0, CSTORM_SP_STATUS_BLOCK_SIZE);
9874    bxe_fill(sc,
9875             (BAR_CSTRORM_INTMEM +
9876              CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9877              0, CSTORM_SP_SYNC_BLOCK_SIZE);
9878}
9879
9880static void
9881bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9882                             int                       igu_sb_id,
9883                             int                       igu_seg_id)
9884{
9885    hc_sm->igu_sb_id      = igu_sb_id;
9886    hc_sm->igu_seg_id     = igu_seg_id;
9887    hc_sm->timer_value    = 0xFF;
9888    hc_sm->time_to_expire = 0xFFFFFFFF;
9889}
9890
9891static void
9892bxe_map_sb_state_machines(struct hc_index_data *index_data)
9893{
9894    /* zero out state machine indices */
9895
9896    /* rx indices */
9897    index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9898
9899    /* tx indices */
9900    index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9901    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9902    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9903    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9904
9905    /* map indices */
9906
9907    /* rx indices */
9908    index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9909        (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9910
9911    /* tx indices */
9912    index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9913        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9914    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9915        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9916    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9917        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9918    index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9919        (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9920}
9921
9922static void
9923bxe_init_sb(struct bxe_softc *sc,
9924            bus_addr_t       busaddr,
9925            int              vfid,
9926            uint8_t          vf_valid,
9927            int              fw_sb_id,
9928            int              igu_sb_id)
9929{
9930    struct hc_status_block_data_e2  sb_data_e2;
9931    struct hc_status_block_data_e1x sb_data_e1x;
9932    struct hc_status_block_sm       *hc_sm_p;
9933    uint32_t *sb_data_p;
9934    int igu_seg_id;
9935    int data_size;
9936
9937    if (CHIP_INT_MODE_IS_BC(sc)) {
9938        igu_seg_id = HC_SEG_ACCESS_NORM;
9939    } else {
9940        igu_seg_id = IGU_SEG_ACCESS_NORM;
9941    }
9942
9943    bxe_zero_fp_sb(sc, fw_sb_id);
9944
9945    if (!CHIP_IS_E1x(sc)) {
9946        memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9947        sb_data_e2.common.state = SB_ENABLED;
9948        sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9949        sb_data_e2.common.p_func.vf_id = vfid;
9950        sb_data_e2.common.p_func.vf_valid = vf_valid;
9951        sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9952        sb_data_e2.common.same_igu_sb_1b = TRUE;
9953        sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9954        sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9955        hc_sm_p = sb_data_e2.common.state_machine;
9956        sb_data_p = (uint32_t *)&sb_data_e2;
9957        data_size = (sizeof(struct hc_status_block_data_e2) /
9958                     sizeof(uint32_t));
9959        bxe_map_sb_state_machines(sb_data_e2.index_data);
9960    } else {
9961        memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9962        sb_data_e1x.common.state = SB_ENABLED;
9963        sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9964        sb_data_e1x.common.p_func.vf_id = 0xff;
9965        sb_data_e1x.common.p_func.vf_valid = FALSE;
9966        sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9967        sb_data_e1x.common.same_igu_sb_1b = TRUE;
9968        sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9969        sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9970        hc_sm_p = sb_data_e1x.common.state_machine;
9971        sb_data_p = (uint32_t *)&sb_data_e1x;
9972        data_size = (sizeof(struct hc_status_block_data_e1x) /
9973                     sizeof(uint32_t));
9974        bxe_map_sb_state_machines(sb_data_e1x.index_data);
9975    }
9976
9977    bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9978    bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9979
9980    BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9981
9982    /* write indices to HW - PCI guarantees endianity of regpairs */
9983    bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9984}
9985
9986static inline uint8_t
9987bxe_fp_qzone_id(struct bxe_fastpath *fp)
9988{
9989    if (CHIP_IS_E1x(fp->sc)) {
9990        return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9991    } else {
9992        return (fp->cl_id);
9993    }
9994}
9995
9996static inline uint32_t
9997bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9998                           struct bxe_fastpath *fp)
9999{
10000    uint32_t offset = BAR_USTRORM_INTMEM;
10001
10002#if 0
10003    if (IS_VF(sc)) {
10004        return (PXP_VF_ADDR_USDM_QUEUES_START +
10005                (sc->acquire_resp.resc.hw_qid[fp->index] *
10006                 sizeof(struct ustorm_queue_zone_data)));
10007    } else
10008#endif
10009    if (!CHIP_IS_E1x(sc)) {
10010        offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
10011    } else {
10012        offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
10013    }
10014
10015    return (offset);
10016}
10017
10018static void
10019bxe_init_eth_fp(struct bxe_softc *sc,
10020                int              idx)
10021{
10022    struct bxe_fastpath *fp = &sc->fp[idx];
10023    uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
10024    unsigned long q_type = 0;
10025    int cos;
10026
10027    fp->sc    = sc;
10028    fp->index = idx;
10029
10030    snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
10031             "bxe%d_fp%d_tx_lock", sc->unit, idx);
10032    mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
10033
10034    snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
10035             "bxe%d_fp%d_rx_lock", sc->unit, idx);
10036    mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
10037
10038    fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
10039    fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
10040
10041    fp->cl_id = (CHIP_IS_E1x(sc)) ?
10042                    (SC_L_ID(sc) + idx) :
10043                    /* want client ID same as IGU SB ID for non-E1 */
10044                    fp->igu_sb_id;
10045    fp->cl_qzone_id = bxe_fp_qzone_id(fp);
10046
10047    /* setup sb indices */
10048    if (!CHIP_IS_E1x(sc)) {
10049        fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
10050        fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
10051    } else {
10052        fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
10053        fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
10054    }
10055
10056    /* init shortcut */
10057    fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
10058
10059    fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
10060
10061    /*
10062     * XXX If multiple CoS is ever supported then each fastpath structure
10063     * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
10064     */
10065    for (cos = 0; cos < sc->max_cos; cos++) {
10066        cids[cos] = idx;
10067    }
10068    fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
10069
10070    /* nothing more for a VF to do */
10071    if (IS_VF(sc)) {
10072        return;
10073    }
10074
10075    bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
10076                fp->fw_sb_id, fp->igu_sb_id);
10077
10078    bxe_update_fp_sb_idx(fp);
10079
10080    /* Configure Queue State object */
10081    bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
10082    bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
10083
10084    ecore_init_queue_obj(sc,
10085                         &sc->sp_objs[idx].q_obj,
10086                         fp->cl_id,
10087                         cids,
10088                         sc->max_cos,
10089                         SC_FUNC(sc),
10090                         BXE_SP(sc, q_rdata),
10091                         BXE_SP_MAPPING(sc, q_rdata),
10092                         q_type);
10093
10094    /* configure classification DBs */
10095    ecore_init_mac_obj(sc,
10096                       &sc->sp_objs[idx].mac_obj,
10097                       fp->cl_id,
10098                       idx,
10099                       SC_FUNC(sc),
10100                       BXE_SP(sc, mac_rdata),
10101                       BXE_SP_MAPPING(sc, mac_rdata),
10102                       ECORE_FILTER_MAC_PENDING,
10103                       &sc->sp_state,
10104                       ECORE_OBJ_TYPE_RX_TX,
10105                       &sc->macs_pool);
10106
10107    BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
10108          idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
10109}
10110
10111static inline void
10112bxe_update_rx_prod(struct bxe_softc    *sc,
10113                   struct bxe_fastpath *fp,
10114                   uint16_t            rx_bd_prod,
10115                   uint16_t            rx_cq_prod,
10116                   uint16_t            rx_sge_prod)
10117{
10118    struct ustorm_eth_rx_producers rx_prods = { 0 };
10119    uint32_t i;
10120
10121    /* update producers */
10122    rx_prods.bd_prod  = rx_bd_prod;
10123    rx_prods.cqe_prod = rx_cq_prod;
10124    rx_prods.sge_prod = rx_sge_prod;
10125
10126    /*
10127     * Make sure that the BD and SGE data is updated before updating the
10128     * producers since FW might read the BD/SGE right after the producer
10129     * is updated.
10130     * This is only applicable for weak-ordered memory model archs such
10131     * as IA-64. The following barrier is also mandatory since FW will
10132     * assumes BDs must have buffers.
10133     */
10134    wmb();
10135
10136    for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
10137        REG_WR(sc,
10138               (fp->ustorm_rx_prods_offset + (i * 4)),
10139               ((uint32_t *)&rx_prods)[i]);
10140    }
10141
10142    wmb(); /* keep prod updates ordered */
10143
10144    BLOGD(sc, DBG_RX,
10145          "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
10146          fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
10147}
10148
10149static void
10150bxe_init_rx_rings(struct bxe_softc *sc)
10151{
10152    struct bxe_fastpath *fp;
10153    int i;
10154
10155    for (i = 0; i < sc->num_queues; i++) {
10156        fp = &sc->fp[i];
10157
10158        fp->rx_bd_cons = 0;
10159
10160        /*
10161         * Activate the BD ring...
10162         * Warning, this will generate an interrupt (to the TSTORM)
10163         * so this can only be done after the chip is initialized
10164         */
10165        bxe_update_rx_prod(sc, fp,
10166                           fp->rx_bd_prod,
10167                           fp->rx_cq_prod,
10168                           fp->rx_sge_prod);
10169
10170        if (i != 0) {
10171            continue;
10172        }
10173
10174        if (CHIP_IS_E1(sc)) {
10175            REG_WR(sc,
10176                   (BAR_USTRORM_INTMEM +
10177                    USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
10178                   U64_LO(fp->rcq_dma.paddr));
10179            REG_WR(sc,
10180                   (BAR_USTRORM_INTMEM +
10181                    USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
10182                   U64_HI(fp->rcq_dma.paddr));
10183        }
10184    }
10185}
10186
10187static void
10188bxe_init_tx_ring_one(struct bxe_fastpath *fp)
10189{
10190    SET_FLAG(fp->tx_db.data.header.header, DOORBELL_HDR_DB_TYPE, 1);
10191    fp->tx_db.data.zero_fill1 = 0;
10192    fp->tx_db.data.prod = 0;
10193
10194    fp->tx_pkt_prod = 0;
10195    fp->tx_pkt_cons = 0;
10196    fp->tx_bd_prod = 0;
10197    fp->tx_bd_cons = 0;
10198    fp->eth_q_stats.tx_pkts = 0;
10199}
10200
10201static inline void
10202bxe_init_tx_rings(struct bxe_softc *sc)
10203{
10204    int i;
10205
10206    for (i = 0; i < sc->num_queues; i++) {
10207#if 0
10208        uint8_t cos;
10209        for (cos = 0; cos < sc->max_cos; cos++) {
10210            bxe_init_tx_ring_one(&sc->fp[i].txdata[cos]);
10211        }
10212#else
10213        bxe_init_tx_ring_one(&sc->fp[i]);
10214#endif
10215    }
10216}
10217
10218static void
10219bxe_init_def_sb(struct bxe_softc *sc)
10220{
10221    struct host_sp_status_block *def_sb = sc->def_sb;
10222    bus_addr_t mapping = sc->def_sb_dma.paddr;
10223    int igu_sp_sb_index;
10224    int igu_seg_id;
10225    int port = SC_PORT(sc);
10226    int func = SC_FUNC(sc);
10227    int reg_offset, reg_offset_en5;
10228    uint64_t section;
10229    int index, sindex;
10230    struct hc_sp_status_block_data sp_sb_data;
10231
10232    memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
10233
10234    if (CHIP_INT_MODE_IS_BC(sc)) {
10235        igu_sp_sb_index = DEF_SB_IGU_ID;
10236        igu_seg_id = HC_SEG_ACCESS_DEF;
10237    } else {
10238        igu_sp_sb_index = sc->igu_dsb_id;
10239        igu_seg_id = IGU_SEG_ACCESS_DEF;
10240    }
10241
10242    /* attentions */
10243    section = ((uint64_t)mapping +
10244               offsetof(struct host_sp_status_block, atten_status_block));
10245    def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
10246    sc->attn_state = 0;
10247
10248    reg_offset = (port) ?
10249                     MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
10250                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
10251    reg_offset_en5 = (port) ?
10252                         MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
10253                         MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
10254
10255    for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
10256        /* take care of sig[0]..sig[4] */
10257        for (sindex = 0; sindex < 4; sindex++) {
10258            sc->attn_group[index].sig[sindex] =
10259                REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
10260        }
10261
10262        if (!CHIP_IS_E1x(sc)) {
10263            /*
10264             * enable5 is separate from the rest of the registers,
10265             * and the address skip is 4 and not 16 between the
10266             * different groups
10267             */
10268            sc->attn_group[index].sig[4] =
10269                REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
10270        } else {
10271            sc->attn_group[index].sig[4] = 0;
10272        }
10273    }
10274
10275    if (sc->devinfo.int_block == INT_BLOCK_HC) {
10276        reg_offset = (port) ?
10277                         HC_REG_ATTN_MSG1_ADDR_L :
10278                         HC_REG_ATTN_MSG0_ADDR_L;
10279        REG_WR(sc, reg_offset, U64_LO(section));
10280        REG_WR(sc, (reg_offset + 4), U64_HI(section));
10281    } else if (!CHIP_IS_E1x(sc)) {
10282        REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
10283        REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
10284    }
10285
10286    section = ((uint64_t)mapping +
10287               offsetof(struct host_sp_status_block, sp_sb));
10288
10289    bxe_zero_sp_sb(sc);
10290
10291    /* PCI guarantees endianity of regpair */
10292    sp_sb_data.state           = SB_ENABLED;
10293    sp_sb_data.host_sb_addr.lo = U64_LO(section);
10294    sp_sb_data.host_sb_addr.hi = U64_HI(section);
10295    sp_sb_data.igu_sb_id       = igu_sp_sb_index;
10296    sp_sb_data.igu_seg_id      = igu_seg_id;
10297    sp_sb_data.p_func.pf_id    = func;
10298    sp_sb_data.p_func.vnic_id  = SC_VN(sc);
10299    sp_sb_data.p_func.vf_id    = 0xff;
10300
10301    bxe_wr_sp_sb_data(sc, &sp_sb_data);
10302
10303    bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
10304}
10305
10306static void
10307bxe_init_sp_ring(struct bxe_softc *sc)
10308{
10309    atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
10310    sc->spq_prod_idx = 0;
10311    sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
10312    sc->spq_prod_bd = sc->spq;
10313    sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
10314}
10315
10316static void
10317bxe_init_eq_ring(struct bxe_softc *sc)
10318{
10319    union event_ring_elem *elem;
10320    int i;
10321
10322    for (i = 1; i <= NUM_EQ_PAGES; i++) {
10323        elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
10324
10325        elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
10326                                                 BCM_PAGE_SIZE *
10327                                                 (i % NUM_EQ_PAGES)));
10328        elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
10329                                                 BCM_PAGE_SIZE *
10330                                                 (i % NUM_EQ_PAGES)));
10331    }
10332
10333    sc->eq_cons    = 0;
10334    sc->eq_prod    = NUM_EQ_DESC;
10335    sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
10336
10337    atomic_store_rel_long(&sc->eq_spq_left,
10338                          (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
10339                               NUM_EQ_DESC) - 1));
10340}
10341
10342static void
10343bxe_init_internal_common(struct bxe_softc *sc)
10344{
10345    int i;
10346
10347    if (IS_MF_SI(sc)) {
10348        /*
10349         * In switch independent mode, the TSTORM needs to accept
10350         * packets that failed classification, since approximate match
10351         * mac addresses aren't written to NIG LLH.
10352         */
10353        REG_WR8(sc,
10354                (BAR_TSTRORM_INTMEM + TSTORM_ACCEPT_CLASSIFY_FAILED_OFFSET),
10355                2);
10356    } else if (!CHIP_IS_E1(sc)) { /* 57710 doesn't support MF */
10357        REG_WR8(sc,
10358                (BAR_TSTRORM_INTMEM + TSTORM_ACCEPT_CLASSIFY_FAILED_OFFSET),
10359                0);
10360    }
10361
10362    /*
10363     * Zero this manually as its initialization is currently missing
10364     * in the initTool.
10365     */
10366    for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
10367        REG_WR(sc,
10368               (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
10369               0);
10370    }
10371
10372    if (!CHIP_IS_E1x(sc)) {
10373        REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
10374                CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
10375    }
10376}
10377
10378static void
10379bxe_init_internal(struct bxe_softc *sc,
10380                  uint32_t         load_code)
10381{
10382    switch (load_code) {
10383    case FW_MSG_CODE_DRV_LOAD_COMMON:
10384    case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
10385        bxe_init_internal_common(sc);
10386        /* no break */
10387
10388    case FW_MSG_CODE_DRV_LOAD_PORT:
10389        /* nothing to do */
10390        /* no break */
10391
10392    case FW_MSG_CODE_DRV_LOAD_FUNCTION:
10393        /* internal memory per function is initialized inside bxe_pf_init */
10394        break;
10395
10396    default:
10397        BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
10398        break;
10399    }
10400}
10401
10402static void
10403storm_memset_func_cfg(struct bxe_softc                         *sc,
10404                      struct tstorm_eth_function_common_config *tcfg,
10405                      uint16_t                                  abs_fid)
10406{
10407    uint32_t addr;
10408    size_t size;
10409
10410    addr = (BAR_TSTRORM_INTMEM +
10411            TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
10412    size = sizeof(struct tstorm_eth_function_common_config);
10413    ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
10414}
10415
10416static void
10417bxe_func_init(struct bxe_softc            *sc,
10418              struct bxe_func_init_params *p)
10419{
10420    struct tstorm_eth_function_common_config tcfg = { 0 };
10421
10422    if (CHIP_IS_E1x(sc)) {
10423        storm_memset_func_cfg(sc, &tcfg, p->func_id);
10424    }
10425
10426    /* Enable the function in the FW */
10427    storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
10428    storm_memset_func_en(sc, p->func_id, 1);
10429
10430    /* spq */
10431    if (p->func_flgs & FUNC_FLG_SPQ) {
10432        storm_memset_spq_addr(sc, p->spq_map, p->func_id);
10433        REG_WR(sc,
10434               (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
10435               p->spq_prod);
10436    }
10437}
10438
10439/*
10440 * Calculates the sum of vn_min_rates.
10441 * It's needed for further normalizing of the min_rates.
10442 * Returns:
10443 *   sum of vn_min_rates.
10444 *     or
10445 *   0 - if all the min_rates are 0.
10446 * In the later case fainess algorithm should be deactivated.
10447 * If all min rates are not zero then those that are zeroes will be set to 1.
10448 */
10449static void
10450bxe_calc_vn_min(struct bxe_softc       *sc,
10451                struct cmng_init_input *input)
10452{
10453    uint32_t vn_cfg;
10454    uint32_t vn_min_rate;
10455    int all_zero = 1;
10456    int vn;
10457
10458    for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10459        vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10460        vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
10461                        FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
10462
10463        if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10464            /* skip hidden VNs */
10465            vn_min_rate = 0;
10466        } else if (!vn_min_rate) {
10467            /* If min rate is zero - set it to 100 */
10468            vn_min_rate = DEF_MIN_RATE;
10469        } else {
10470            all_zero = 0;
10471        }
10472
10473        input->vnic_min_rate[vn] = vn_min_rate;
10474    }
10475
10476    /* if ETS or all min rates are zeros - disable fairness */
10477    if (BXE_IS_ETS_ENABLED(sc)) {
10478        input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10479        BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10480    } else if (all_zero) {
10481        input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10482        BLOGD(sc, DBG_LOAD,
10483              "Fariness disabled (all MIN values are zeroes)\n");
10484    } else {
10485        input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10486    }
10487}
10488
10489static inline uint16_t
10490bxe_extract_max_cfg(struct bxe_softc *sc,
10491                    uint32_t         mf_cfg)
10492{
10493    uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10494                        FUNC_MF_CFG_MAX_BW_SHIFT);
10495
10496    if (!max_cfg) {
10497        BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10498        max_cfg = 100;
10499    }
10500
10501    return (max_cfg);
10502}
10503
10504static void
10505bxe_calc_vn_max(struct bxe_softc       *sc,
10506                int                    vn,
10507                struct cmng_init_input *input)
10508{
10509    uint16_t vn_max_rate;
10510    uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10511    uint32_t max_cfg;
10512
10513    if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10514        vn_max_rate = 0;
10515    } else {
10516        max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10517
10518        if (IS_MF_SI(sc)) {
10519            /* max_cfg in percents of linkspeed */
10520            vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10521        } else { /* SD modes */
10522            /* max_cfg is absolute in 100Mb units */
10523            vn_max_rate = (max_cfg * 100);
10524        }
10525    }
10526
10527    BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10528
10529    input->vnic_max_rate[vn] = vn_max_rate;
10530}
10531
10532static void
10533bxe_cmng_fns_init(struct bxe_softc *sc,
10534                  uint8_t          read_cfg,
10535                  uint8_t          cmng_type)
10536{
10537    struct cmng_init_input input;
10538    int vn;
10539
10540    memset(&input, 0, sizeof(struct cmng_init_input));
10541
10542    input.port_rate = sc->link_vars.line_speed;
10543
10544    if (cmng_type == CMNG_FNS_MINMAX) {
10545        /* read mf conf from shmem */
10546        if (read_cfg) {
10547            bxe_read_mf_cfg(sc);
10548        }
10549
10550        /* get VN min rate and enable fairness if not 0 */
10551        bxe_calc_vn_min(sc, &input);
10552
10553        /* get VN max rate */
10554        if (sc->port.pmf) {
10555            for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10556                bxe_calc_vn_max(sc, vn, &input);
10557            }
10558        }
10559
10560        /* always enable rate shaping and fairness */
10561        input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10562
10563        ecore_init_cmng(&input, &sc->cmng);
10564        return;
10565    }
10566
10567    /* rate shaping and fairness are disabled */
10568    BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10569}
10570
10571static int
10572bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10573{
10574    if (CHIP_REV_IS_SLOW(sc)) {
10575        return (CMNG_FNS_NONE);
10576    }
10577
10578    if (IS_MF(sc)) {
10579        return (CMNG_FNS_MINMAX);
10580    }
10581
10582    return (CMNG_FNS_NONE);
10583}
10584
10585static void
10586storm_memset_cmng(struct bxe_softc *sc,
10587                  struct cmng_init *cmng,
10588                  uint8_t          port)
10589{
10590    int vn;
10591    int func;
10592    uint32_t addr;
10593    size_t size;
10594
10595    addr = (BAR_XSTRORM_INTMEM +
10596            XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10597    size = sizeof(struct cmng_struct_per_port);
10598    ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10599
10600    for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10601        func = func_by_vn(sc, vn);
10602
10603        addr = (BAR_XSTRORM_INTMEM +
10604                XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10605        size = sizeof(struct rate_shaping_vars_per_vn);
10606        ecore_storm_memset_struct(sc, addr, size,
10607                                  (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10608
10609        addr = (BAR_XSTRORM_INTMEM +
10610                XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10611        size = sizeof(struct fairness_vars_per_vn);
10612        ecore_storm_memset_struct(sc, addr, size,
10613                                  (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10614    }
10615}
10616
10617static void
10618bxe_pf_init(struct bxe_softc *sc)
10619{
10620    struct bxe_func_init_params func_init = { 0 };
10621    struct event_ring_data eq_data = { { 0 } };
10622    uint16_t flags;
10623
10624    if (!CHIP_IS_E1x(sc)) {
10625        /* reset IGU PF statistics: MSIX + ATTN */
10626        /* PF */
10627        REG_WR(sc,
10628               (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10629                (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10630                ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10631               0);
10632        /* ATTN */
10633        REG_WR(sc,
10634               (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10635                (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10636                (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10637                ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10638               0);
10639    }
10640
10641    /* function setup flags */
10642    flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10643
10644    /*
10645     * This flag is relevant for E1x only.
10646     * E2 doesn't have a TPA configuration in a function level.
10647     */
10648    flags |= (sc->ifnet->if_capenable & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10649
10650    func_init.func_flgs = flags;
10651    func_init.pf_id     = SC_FUNC(sc);
10652    func_init.func_id   = SC_FUNC(sc);
10653    func_init.spq_map   = sc->spq_dma.paddr;
10654    func_init.spq_prod  = sc->spq_prod_idx;
10655
10656    bxe_func_init(sc, &func_init);
10657
10658    memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10659
10660    /*
10661     * Congestion management values depend on the link rate.
10662     * There is no active link so initial link rate is set to 10Gbps.
10663     * When the link comes up the congestion management values are
10664     * re-calculated according to the actual link rate.
10665     */
10666    sc->link_vars.line_speed = SPEED_10000;
10667    bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10668
10669    /* Only the PMF sets the HW */
10670    if (sc->port.pmf) {
10671        storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10672    }
10673
10674    /* init Event Queue - PCI bus guarantees correct endainity */
10675    eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10676    eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10677    eq_data.producer     = sc->eq_prod;
10678    eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10679    eq_data.sb_id        = DEF_SB_ID;
10680    storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10681}
10682
10683static void
10684bxe_hc_int_enable(struct bxe_softc *sc)
10685{
10686    int port = SC_PORT(sc);
10687    uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10688    uint32_t val = REG_RD(sc, addr);
10689    uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10690    uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10691                           (sc->intr_count == 1)) ? TRUE : FALSE;
10692    uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10693
10694    if (msix) {
10695        val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10696                 HC_CONFIG_0_REG_INT_LINE_EN_0);
10697        val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10698                HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10699        if (single_msix) {
10700            val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10701        }
10702    } else if (msi) {
10703        val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10704        val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10705                HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10706                HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10707    } else {
10708        val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10709                HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10710                HC_CONFIG_0_REG_INT_LINE_EN_0 |
10711                HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10712
10713        if (!CHIP_IS_E1(sc)) {
10714            BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10715                  val, port, addr);
10716
10717            REG_WR(sc, addr, val);
10718
10719            val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10720        }
10721    }
10722
10723    if (CHIP_IS_E1(sc)) {
10724        REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10725    }
10726
10727    BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10728          val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10729
10730    REG_WR(sc, addr, val);
10731
10732    /* ensure that HC_CONFIG is written before leading/trailing edge config */
10733    mb();
10734
10735    if (!CHIP_IS_E1(sc)) {
10736        /* init leading/trailing edge */
10737        if (IS_MF(sc)) {
10738            val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10739            if (sc->port.pmf) {
10740                /* enable nig and gpio3 attention */
10741                val |= 0x1100;
10742            }
10743        } else {
10744            val = 0xffff;
10745        }
10746
10747        REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10748        REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10749    }
10750
10751    /* make sure that interrupts are indeed enabled from here on */
10752    mb();
10753}
10754
10755static void
10756bxe_igu_int_enable(struct bxe_softc *sc)
10757{
10758    uint32_t val;
10759    uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10760    uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10761                           (sc->intr_count == 1)) ? TRUE : FALSE;
10762    uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10763
10764    val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10765
10766    if (msix) {
10767        val &= ~(IGU_PF_CONF_INT_LINE_EN |
10768                 IGU_PF_CONF_SINGLE_ISR_EN);
10769        val |= (IGU_PF_CONF_MSI_MSIX_EN |
10770                IGU_PF_CONF_ATTN_BIT_EN);
10771        if (single_msix) {
10772            val |= IGU_PF_CONF_SINGLE_ISR_EN;
10773        }
10774    } else if (msi) {
10775        val &= ~IGU_PF_CONF_INT_LINE_EN;
10776        val |= (IGU_PF_CONF_MSI_MSIX_EN |
10777                IGU_PF_CONF_ATTN_BIT_EN |
10778                IGU_PF_CONF_SINGLE_ISR_EN);
10779    } else {
10780        val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10781        val |= (IGU_PF_CONF_INT_LINE_EN |
10782                IGU_PF_CONF_ATTN_BIT_EN |
10783                IGU_PF_CONF_SINGLE_ISR_EN);
10784    }
10785
10786    /* clean previous status - need to configure igu prior to ack*/
10787    if ((!msix) || single_msix) {
10788        REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10789        bxe_ack_int(sc);
10790    }
10791
10792    val |= IGU_PF_CONF_FUNC_EN;
10793
10794    BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10795          val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10796
10797    REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10798
10799    mb();
10800
10801    /* init leading/trailing edge */
10802    if (IS_MF(sc)) {
10803        val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10804        if (sc->port.pmf) {
10805            /* enable nig and gpio3 attention */
10806            val |= 0x1100;
10807        }
10808    } else {
10809        val = 0xffff;
10810    }
10811
10812    REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10813    REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10814
10815    /* make sure that interrupts are indeed enabled from here on */
10816    mb();
10817}
10818
10819static void
10820bxe_int_enable(struct bxe_softc *sc)
10821{
10822    if (sc->devinfo.int_block == INT_BLOCK_HC) {
10823        bxe_hc_int_enable(sc);
10824    } else {
10825        bxe_igu_int_enable(sc);
10826    }
10827}
10828
10829static void
10830bxe_hc_int_disable(struct bxe_softc *sc)
10831{
10832    int port = SC_PORT(sc);
10833    uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10834    uint32_t val = REG_RD(sc, addr);
10835
10836    /*
10837     * In E1 we must use only PCI configuration space to disable MSI/MSIX
10838     * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10839     * block
10840     */
10841    if (CHIP_IS_E1(sc)) {
10842        /*
10843         * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10844         * to prevent from HC sending interrupts after we exit the function
10845         */
10846        REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10847
10848        val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10849                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10850                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10851    } else {
10852        val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10853                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10854                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10855                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10856    }
10857
10858    BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10859
10860    /* flush all outstanding writes */
10861    mb();
10862
10863    REG_WR(sc, addr, val);
10864    if (REG_RD(sc, addr) != val) {
10865        BLOGE(sc, "proper val not read from HC IGU!\n");
10866    }
10867}
10868
10869static void
10870bxe_igu_int_disable(struct bxe_softc *sc)
10871{
10872    uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10873
10874    val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10875             IGU_PF_CONF_INT_LINE_EN |
10876             IGU_PF_CONF_ATTN_BIT_EN);
10877
10878    BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10879
10880    /* flush all outstanding writes */
10881    mb();
10882
10883    REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10884    if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10885        BLOGE(sc, "proper val not read from IGU!\n");
10886    }
10887}
10888
10889static void
10890bxe_int_disable(struct bxe_softc *sc)
10891{
10892    if (sc->devinfo.int_block == INT_BLOCK_HC) {
10893        bxe_hc_int_disable(sc);
10894    } else {
10895        bxe_igu_int_disable(sc);
10896    }
10897}
10898
10899static void
10900bxe_nic_init(struct bxe_softc *sc,
10901             int              load_code)
10902{
10903    int i;
10904
10905    for (i = 0; i < sc->num_queues; i++) {
10906        bxe_init_eth_fp(sc, i);
10907    }
10908
10909    rmb(); /* ensure status block indices were read */
10910
10911    bxe_init_rx_rings(sc);
10912    bxe_init_tx_rings(sc);
10913
10914    if (IS_VF(sc)) {
10915        return;
10916    }
10917
10918    /* initialize MOD_ABS interrupts */
10919    elink_init_mod_abs_int(sc, &sc->link_vars,
10920                           sc->devinfo.chip_id,
10921                           sc->devinfo.shmem_base,
10922                           sc->devinfo.shmem2_base,
10923                           SC_PORT(sc));
10924
10925    bxe_init_def_sb(sc);
10926    bxe_update_dsb_idx(sc);
10927    bxe_init_sp_ring(sc);
10928    bxe_init_eq_ring(sc);
10929    bxe_init_internal(sc, load_code);
10930    bxe_pf_init(sc);
10931    bxe_stats_init(sc);
10932
10933    /* flush all before enabling interrupts */
10934    mb();
10935
10936    bxe_int_enable(sc);
10937
10938    /* check for SPIO5 */
10939    bxe_attn_int_deasserted0(sc,
10940                             REG_RD(sc,
10941                                    (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10942                                     SC_PORT(sc)*4)) &
10943                             AEU_INPUTS_ATTN_BITS_SPIO5);
10944}
10945
10946static inline void
10947bxe_init_objs(struct bxe_softc *sc)
10948{
10949    /* mcast rules must be added to tx if tx switching is enabled */
10950    ecore_obj_type o_type =
10951        (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10952                                         ECORE_OBJ_TYPE_RX;
10953
10954    /* RX_MODE controlling object */
10955    ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10956
10957    /* multicast configuration controlling object */
10958    ecore_init_mcast_obj(sc,
10959                         &sc->mcast_obj,
10960                         sc->fp[0].cl_id,
10961                         sc->fp[0].index,
10962                         SC_FUNC(sc),
10963                         SC_FUNC(sc),
10964                         BXE_SP(sc, mcast_rdata),
10965                         BXE_SP_MAPPING(sc, mcast_rdata),
10966                         ECORE_FILTER_MCAST_PENDING,
10967                         &sc->sp_state,
10968                         o_type);
10969
10970    /* Setup CAM credit pools */
10971    ecore_init_mac_credit_pool(sc,
10972                               &sc->macs_pool,
10973                               SC_FUNC(sc),
10974                               CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10975                                                 VNICS_PER_PATH(sc));
10976
10977    ecore_init_vlan_credit_pool(sc,
10978                                &sc->vlans_pool,
10979                                SC_ABS_FUNC(sc) >> 1,
10980                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10981                                                  VNICS_PER_PATH(sc));
10982
10983    /* RSS configuration object */
10984    ecore_init_rss_config_obj(sc,
10985                              &sc->rss_conf_obj,
10986                              sc->fp[0].cl_id,
10987                              sc->fp[0].index,
10988                              SC_FUNC(sc),
10989                              SC_FUNC(sc),
10990                              BXE_SP(sc, rss_rdata),
10991                              BXE_SP_MAPPING(sc, rss_rdata),
10992                              ECORE_FILTER_RSS_CONF_PENDING,
10993                              &sc->sp_state, ECORE_OBJ_TYPE_RX);
10994}
10995
10996/*
10997 * Initialize the function. This must be called before sending CLIENT_SETUP
10998 * for the first client.
10999 */
11000static inline int
11001bxe_func_start(struct bxe_softc *sc)
11002{
11003    struct ecore_func_state_params func_params = { NULL };
11004    struct ecore_func_start_params *start_params = &func_params.params.start;
11005
11006    /* Prepare parameters for function state transitions */
11007    bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
11008
11009    func_params.f_obj = &sc->func_obj;
11010    func_params.cmd = ECORE_F_CMD_START;
11011
11012    /* Function parameters */
11013    start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
11014    start_params->sd_vlan_tag = OVLAN(sc);
11015
11016    if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
11017        start_params->network_cos_mode = STATIC_COS;
11018    } else { /* CHIP_IS_E1X */
11019        start_params->network_cos_mode = FW_WRR;
11020    }
11021
11022    start_params->gre_tunnel_mode = 0;
11023    start_params->gre_tunnel_rss  = 0;
11024
11025    return (ecore_func_state_change(sc, &func_params));
11026}
11027
11028static int
11029bxe_set_power_state(struct bxe_softc *sc,
11030                    uint8_t          state)
11031{
11032    uint16_t pmcsr;
11033
11034    /* If there is no power capability, silently succeed */
11035    if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
11036        BLOGW(sc, "No power capability\n");
11037        return (0);
11038    }
11039
11040    pmcsr = pci_read_config(sc->dev,
11041                            (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
11042                            2);
11043
11044    switch (state) {
11045    case PCI_PM_D0:
11046        pci_write_config(sc->dev,
11047                         (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
11048                         ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
11049
11050        if (pmcsr & PCIM_PSTAT_DMASK) {
11051            /* delay required during transition out of D3hot */
11052            DELAY(20000);
11053        }
11054
11055        break;
11056
11057    case PCI_PM_D3hot:
11058        /* XXX if there are other clients above don't shut down the power */
11059
11060        /* don't shut down the power for emulation and FPGA */
11061        if (CHIP_REV_IS_SLOW(sc)) {
11062            return (0);
11063        }
11064
11065        pmcsr &= ~PCIM_PSTAT_DMASK;
11066        pmcsr |= PCIM_PSTAT_D3;
11067
11068        if (sc->wol) {
11069            pmcsr |= PCIM_PSTAT_PMEENABLE;
11070        }
11071
11072        pci_write_config(sc->dev,
11073                         (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
11074                         pmcsr, 4);
11075
11076        /*
11077         * No more memory access after this point until device is brought back
11078         * to D0 state.
11079         */
11080        break;
11081
11082    default:
11083        BLOGE(sc, "Can't support PCI power state = %d\n", state);
11084        return (-1);
11085    }
11086
11087    return (0);
11088}
11089
11090
11091/* return true if succeeded to acquire the lock */
11092static uint8_t
11093bxe_trylock_hw_lock(struct bxe_softc *sc,
11094                    uint32_t         resource)
11095{
11096    uint32_t lock_status;
11097    uint32_t resource_bit = (1 << resource);
11098    int func = SC_FUNC(sc);
11099    uint32_t hw_lock_control_reg;
11100
11101    BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
11102
11103    /* Validating that the resource is within range */
11104    if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
11105        BLOGD(sc, DBG_LOAD,
11106              "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
11107              resource, HW_LOCK_MAX_RESOURCE_VALUE);
11108        return (FALSE);
11109    }
11110
11111    if (func <= 5) {
11112        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
11113    } else {
11114        hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
11115    }
11116
11117    /* try to acquire the lock */
11118    REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
11119    lock_status = REG_RD(sc, hw_lock_control_reg);
11120    if (lock_status & resource_bit) {
11121        return (TRUE);
11122    }
11123
11124    BLOGE(sc, "Failed to get a resource lock 0x%x\n", resource);
11125
11126    return (FALSE);
11127}
11128
11129/*
11130 * Get the recovery leader resource id according to the engine this function
11131 * belongs to. Currently only only 2 engines is supported.
11132 */
11133static int
11134bxe_get_leader_lock_resource(struct bxe_softc *sc)
11135{
11136    if (SC_PATH(sc)) {
11137        return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
11138    } else {
11139        return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
11140    }
11141}
11142
11143/* try to acquire a leader lock for current engine */
11144static uint8_t
11145bxe_trylock_leader_lock(struct bxe_softc *sc)
11146{
11147    return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
11148}
11149
11150static int
11151bxe_release_leader_lock(struct bxe_softc *sc)
11152{
11153    return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
11154}
11155
11156/* close gates #2, #3 and #4 */
11157static void
11158bxe_set_234_gates(struct bxe_softc *sc,
11159                  uint8_t          close)
11160{
11161    uint32_t val;
11162
11163    /* gates #2 and #4a are closed/opened for "not E1" only */
11164    if (!CHIP_IS_E1(sc)) {
11165        /* #4 */
11166        REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
11167        /* #2 */
11168        REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
11169    }
11170
11171    /* #3 */
11172    if (CHIP_IS_E1x(sc)) {
11173        /* prevent interrupts from HC on both ports */
11174        val = REG_RD(sc, HC_REG_CONFIG_1);
11175        REG_WR(sc, HC_REG_CONFIG_1,
11176               (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
11177               (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
11178
11179        val = REG_RD(sc, HC_REG_CONFIG_0);
11180        REG_WR(sc, HC_REG_CONFIG_0,
11181               (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
11182               (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
11183    } else {
11184        /* Prevent incomming interrupts in IGU */
11185        val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
11186
11187        REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
11188               (!close) ?
11189               (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
11190               (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
11191    }
11192
11193    BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
11194          close ? "closing" : "opening");
11195
11196    wmb();
11197}
11198
11199/* poll for pending writes bit, it should get cleared in no more than 1s */
11200static int
11201bxe_er_poll_igu_vq(struct bxe_softc *sc)
11202{
11203    uint32_t cnt = 1000;
11204    uint32_t pend_bits = 0;
11205
11206    do {
11207        pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
11208
11209        if (pend_bits == 0) {
11210            break;
11211        }
11212
11213        DELAY(1000);
11214    } while (--cnt > 0);
11215
11216    if (cnt == 0) {
11217        BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
11218        return (-1);
11219    }
11220
11221    return (0);
11222}
11223
11224#define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
11225
11226static void
11227bxe_clp_reset_prep(struct bxe_softc *sc,
11228                   uint32_t         *magic_val)
11229{
11230    /* Do some magic... */
11231    uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
11232    *magic_val = val & SHARED_MF_CLP_MAGIC;
11233    MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
11234}
11235
11236/* restore the value of the 'magic' bit */
11237static void
11238bxe_clp_reset_done(struct bxe_softc *sc,
11239                   uint32_t         magic_val)
11240{
11241    /* Restore the 'magic' bit value... */
11242    uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
11243    MFCFG_WR(sc, shared_mf_config.clp_mb,
11244              (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
11245}
11246
11247/* prepare for MCP reset, takes care of CLP configurations */
11248static void
11249bxe_reset_mcp_prep(struct bxe_softc *sc,
11250                   uint32_t         *magic_val)
11251{
11252    uint32_t shmem;
11253    uint32_t validity_offset;
11254
11255    /* set `magic' bit in order to save MF config */
11256    if (!CHIP_IS_E1(sc)) {
11257        bxe_clp_reset_prep(sc, magic_val);
11258    }
11259
11260    /* get shmem offset */
11261    shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
11262    validity_offset =
11263        offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
11264
11265    /* Clear validity map flags */
11266    if (shmem > 0) {
11267        REG_WR(sc, shmem + validity_offset, 0);
11268    }
11269}
11270
11271#define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
11272#define MCP_ONE_TIMEOUT  100    /* 100 ms */
11273
11274static void
11275bxe_mcp_wait_one(struct bxe_softc *sc)
11276{
11277    /* special handling for emulation and FPGA (10 times longer) */
11278    if (CHIP_REV_IS_SLOW(sc)) {
11279        DELAY((MCP_ONE_TIMEOUT*10) * 1000);
11280    } else {
11281        DELAY((MCP_ONE_TIMEOUT) * 1000);
11282    }
11283}
11284
11285/* initialize shmem_base and waits for validity signature to appear */
11286static int
11287bxe_init_shmem(struct bxe_softc *sc)
11288{
11289    int cnt = 0;
11290    uint32_t val = 0;
11291
11292    do {
11293        sc->devinfo.shmem_base     =
11294        sc->link_params.shmem_base =
11295            REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
11296
11297        if (sc->devinfo.shmem_base) {
11298            val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
11299            if (val & SHR_MEM_VALIDITY_MB)
11300                return (0);
11301        }
11302
11303        bxe_mcp_wait_one(sc);
11304
11305    } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
11306
11307    BLOGE(sc, "BAD MCP validity signature\n");
11308
11309    return (-1);
11310}
11311
11312static int
11313bxe_reset_mcp_comp(struct bxe_softc *sc,
11314                   uint32_t         magic_val)
11315{
11316    int rc = bxe_init_shmem(sc);
11317
11318    /* Restore the `magic' bit value */
11319    if (!CHIP_IS_E1(sc)) {
11320        bxe_clp_reset_done(sc, magic_val);
11321    }
11322
11323    return (rc);
11324}
11325
11326static void
11327bxe_pxp_prep(struct bxe_softc *sc)
11328{
11329    if (!CHIP_IS_E1(sc)) {
11330        REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
11331        REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
11332        wmb();
11333    }
11334}
11335
11336/*
11337 * Reset the whole chip except for:
11338 *      - PCIE core
11339 *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
11340 *      - IGU
11341 *      - MISC (including AEU)
11342 *      - GRC
11343 *      - RBCN, RBCP
11344 */
11345static void
11346bxe_process_kill_chip_reset(struct bxe_softc *sc,
11347                            uint8_t          global)
11348{
11349    uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
11350    uint32_t global_bits2, stay_reset2;
11351
11352    /*
11353     * Bits that have to be set in reset_mask2 if we want to reset 'global'
11354     * (per chip) blocks.
11355     */
11356    global_bits2 =
11357        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
11358        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
11359
11360    /*
11361     * Don't reset the following blocks.
11362     * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
11363     *            reset, as in 4 port device they might still be owned
11364     *            by the MCP (there is only one leader per path).
11365     */
11366    not_reset_mask1 =
11367        MISC_REGISTERS_RESET_REG_1_RST_HC |
11368        MISC_REGISTERS_RESET_REG_1_RST_PXPV |
11369        MISC_REGISTERS_RESET_REG_1_RST_PXP;
11370
11371    not_reset_mask2 =
11372        MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
11373        MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
11374        MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
11375        MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
11376        MISC_REGISTERS_RESET_REG_2_RST_RBCN |
11377        MISC_REGISTERS_RESET_REG_2_RST_GRC  |
11378        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
11379        MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
11380        MISC_REGISTERS_RESET_REG_2_RST_ATC |
11381        MISC_REGISTERS_RESET_REG_2_PGLC |
11382        MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
11383        MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
11384        MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
11385        MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
11386        MISC_REGISTERS_RESET_REG_2_UMAC0 |
11387        MISC_REGISTERS_RESET_REG_2_UMAC1;
11388
11389    /*
11390     * Keep the following blocks in reset:
11391     *  - all xxMACs are handled by the elink code.
11392     */
11393    stay_reset2 =
11394        MISC_REGISTERS_RESET_REG_2_XMAC |
11395        MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
11396
11397    /* Full reset masks according to the chip */
11398    reset_mask1 = 0xffffffff;
11399
11400    if (CHIP_IS_E1(sc))
11401        reset_mask2 = 0xffff;
11402    else if (CHIP_IS_E1H(sc))
11403        reset_mask2 = 0x1ffff;
11404    else if (CHIP_IS_E2(sc))
11405        reset_mask2 = 0xfffff;
11406    else /* CHIP_IS_E3 */
11407        reset_mask2 = 0x3ffffff;
11408
11409    /* Don't reset global blocks unless we need to */
11410    if (!global)
11411        reset_mask2 &= ~global_bits2;
11412
11413    /*
11414     * In case of attention in the QM, we need to reset PXP
11415     * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
11416     * because otherwise QM reset would release 'close the gates' shortly
11417     * before resetting the PXP, then the PSWRQ would send a write
11418     * request to PGLUE. Then when PXP is reset, PGLUE would try to
11419     * read the payload data from PSWWR, but PSWWR would not
11420     * respond. The write queue in PGLUE would stuck, dmae commands
11421     * would not return. Therefore it's important to reset the second
11422     * reset register (containing the
11423     * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
11424     * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
11425     * bit).
11426     */
11427    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
11428           reset_mask2 & (~not_reset_mask2));
11429
11430    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
11431           reset_mask1 & (~not_reset_mask1));
11432
11433    mb();
11434    wmb();
11435
11436    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
11437           reset_mask2 & (~stay_reset2));
11438
11439    mb();
11440    wmb();
11441
11442    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
11443    wmb();
11444}
11445
11446static int
11447bxe_process_kill(struct bxe_softc *sc,
11448                 uint8_t          global)
11449{
11450    int cnt = 1000;
11451    uint32_t val = 0;
11452    uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
11453    uint32_t tags_63_32 = 0;
11454
11455    /* Empty the Tetris buffer, wait for 1s */
11456    do {
11457        sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
11458        blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
11459        port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
11460        port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
11461        pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
11462        if (CHIP_IS_E3(sc)) {
11463            tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
11464        }
11465
11466        if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11467            ((port_is_idle_0 & 0x1) == 0x1) &&
11468            ((port_is_idle_1 & 0x1) == 0x1) &&
11469            (pgl_exp_rom2 == 0xffffffff) &&
11470            (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11471            break;
11472        DELAY(1000);
11473    } while (cnt-- > 0);
11474
11475    if (cnt <= 0) {
11476        BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11477                  "are still outstanding read requests after 1s! "
11478                  "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11479                  "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11480              sr_cnt, blk_cnt, port_is_idle_0,
11481              port_is_idle_1, pgl_exp_rom2);
11482        return (-1);
11483    }
11484
11485    mb();
11486
11487    /* Close gates #2, #3 and #4 */
11488    bxe_set_234_gates(sc, TRUE);
11489
11490    /* Poll for IGU VQs for 57712 and newer chips */
11491    if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11492        return (-1);
11493    }
11494
11495    /* XXX indicate that "process kill" is in progress to MCP */
11496
11497    /* clear "unprepared" bit */
11498    REG_WR(sc, MISC_REG_UNPREPARED, 0);
11499    mb();
11500
11501    /* Make sure all is written to the chip before the reset */
11502    wmb();
11503
11504    /*
11505     * Wait for 1ms to empty GLUE and PCI-E core queues,
11506     * PSWHST, GRC and PSWRD Tetris buffer.
11507     */
11508    DELAY(1000);
11509
11510    /* Prepare to chip reset: */
11511    /* MCP */
11512    if (global) {
11513        bxe_reset_mcp_prep(sc, &val);
11514    }
11515
11516    /* PXP */
11517    bxe_pxp_prep(sc);
11518    mb();
11519
11520    /* reset the chip */
11521    bxe_process_kill_chip_reset(sc, global);
11522    mb();
11523
11524    /* Recover after reset: */
11525    /* MCP */
11526    if (global && bxe_reset_mcp_comp(sc, val)) {
11527        return (-1);
11528    }
11529
11530    /* XXX add resetting the NO_MCP mode DB here */
11531
11532    /* Open the gates #2, #3 and #4 */
11533    bxe_set_234_gates(sc, FALSE);
11534
11535    /* XXX
11536     * IGU/AEU preparation bring back the AEU/IGU to a reset state
11537     * re-enable attentions
11538     */
11539
11540    return (0);
11541}
11542
11543static int
11544bxe_leader_reset(struct bxe_softc *sc)
11545{
11546    int rc = 0;
11547    uint8_t global = bxe_reset_is_global(sc);
11548    uint32_t load_code;
11549
11550    /*
11551     * If not going to reset MCP, load "fake" driver to reset HW while
11552     * driver is owner of the HW.
11553     */
11554    if (!global && !BXE_NOMCP(sc)) {
11555        load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11556                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11557        if (!load_code) {
11558            BLOGE(sc, "MCP response failure, aborting\n");
11559            rc = -1;
11560            goto exit_leader_reset;
11561        }
11562
11563        if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11564            (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11565            BLOGE(sc, "MCP unexpected response, aborting\n");
11566            rc = -1;
11567            goto exit_leader_reset2;
11568        }
11569
11570        load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11571        if (!load_code) {
11572            BLOGE(sc, "MCP response failure, aborting\n");
11573            rc = -1;
11574            goto exit_leader_reset2;
11575        }
11576    }
11577
11578    /* try to recover after the failure */
11579    if (bxe_process_kill(sc, global)) {
11580        BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11581        rc = -1;
11582        goto exit_leader_reset2;
11583    }
11584
11585    /*
11586     * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11587     * state.
11588     */
11589    bxe_set_reset_done(sc);
11590    if (global) {
11591        bxe_clear_reset_global(sc);
11592    }
11593
11594exit_leader_reset2:
11595
11596    /* unload "fake driver" if it was loaded */
11597    if (!global && !BXE_NOMCP(sc)) {
11598        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11599        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11600    }
11601
11602exit_leader_reset:
11603
11604    sc->is_leader = 0;
11605    bxe_release_leader_lock(sc);
11606
11607    mb();
11608    return (rc);
11609}
11610
11611/*
11612 * prepare INIT transition, parameters configured:
11613 *   - HC configuration
11614 *   - Queue's CDU context
11615 */
11616static void
11617bxe_pf_q_prep_init(struct bxe_softc               *sc,
11618                   struct bxe_fastpath            *fp,
11619                   struct ecore_queue_init_params *init_params)
11620{
11621    uint8_t cos;
11622    int cxt_index, cxt_offset;
11623
11624    bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11625    bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11626
11627    bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11628    bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11629
11630    /* HC rate */
11631    init_params->rx.hc_rate =
11632        sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11633    init_params->tx.hc_rate =
11634        sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11635
11636    /* FW SB ID */
11637    init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11638
11639    /* CQ index among the SB indices */
11640    init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11641    init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11642
11643    /* set maximum number of COSs supported by this queue */
11644    init_params->max_cos = sc->max_cos;
11645
11646    BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11647          fp->index, init_params->max_cos);
11648
11649    /* set the context pointers queue object */
11650    for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11651        /* XXX change index/cid here if ever support multiple tx CoS */
11652        /* fp->txdata[cos]->cid */
11653        cxt_index = fp->index / ILT_PAGE_CIDS;
11654        cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11655        init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11656    }
11657}
11658
11659/* set flags that are common for the Tx-only and not normal connections */
11660static unsigned long
11661bxe_get_common_flags(struct bxe_softc    *sc,
11662                     struct bxe_fastpath *fp,
11663                     uint8_t             zero_stats)
11664{
11665    unsigned long flags = 0;
11666
11667    /* PF driver will always initialize the Queue to an ACTIVE state */
11668    bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11669
11670    /*
11671     * tx only connections collect statistics (on the same index as the
11672     * parent connection). The statistics are zeroed when the parent
11673     * connection is initialized.
11674     */
11675
11676    bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11677    if (zero_stats) {
11678        bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11679    }
11680
11681    /*
11682     * tx only connections can support tx-switching, though their
11683     * CoS-ness doesn't survive the loopback
11684     */
11685    if (sc->flags & BXE_TX_SWITCHING) {
11686        bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11687    }
11688
11689    bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11690
11691    return (flags);
11692}
11693
11694static unsigned long
11695bxe_get_q_flags(struct bxe_softc    *sc,
11696                struct bxe_fastpath *fp,
11697                uint8_t             leading)
11698{
11699    unsigned long flags = 0;
11700
11701    if (IS_MF_SD(sc)) {
11702        bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11703    }
11704
11705    if (sc->ifnet->if_capenable & IFCAP_LRO) {
11706        bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11707        bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11708#if 0
11709        if (fp->mode == TPA_MODE_GRO)
11710            __set_bit(ECORE_Q_FLG_TPA_GRO, &flags);
11711#endif
11712    }
11713
11714    if (leading) {
11715        bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11716        bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11717    }
11718
11719    bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11720
11721#if 0
11722    /* configure silent vlan removal */
11723    if (IS_MF_AFEX(sc)) {
11724        bxe_set_bit(ECORE_Q_FLG_SILENT_VLAN_REM, &flags);
11725    }
11726#endif
11727
11728    /* merge with common flags */
11729    return (flags | bxe_get_common_flags(sc, fp, TRUE));
11730}
11731
11732static void
11733bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11734                      struct bxe_fastpath               *fp,
11735                      struct ecore_general_setup_params *gen_init,
11736                      uint8_t                           cos)
11737{
11738    gen_init->stat_id = bxe_stats_id(fp);
11739    gen_init->spcl_id = fp->cl_id;
11740    gen_init->mtu = sc->mtu;
11741    gen_init->cos = cos;
11742}
11743
11744static void
11745bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11746                 struct bxe_fastpath           *fp,
11747                 struct rxq_pause_params       *pause,
11748                 struct ecore_rxq_setup_params *rxq_init)
11749{
11750    uint8_t max_sge = 0;
11751    uint16_t sge_sz = 0;
11752    uint16_t tpa_agg_size = 0;
11753
11754    if (sc->ifnet->if_capenable & IFCAP_LRO) {
11755        pause->sge_th_lo = SGE_TH_LO(sc);
11756        pause->sge_th_hi = SGE_TH_HI(sc);
11757
11758        /* validate SGE ring has enough to cross high threshold */
11759        if (sc->dropless_fc &&
11760            (pause->sge_th_hi + FW_PREFETCH_CNT) >
11761            (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11762            BLOGW(sc, "sge ring threshold limit\n");
11763        }
11764
11765        /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11766        tpa_agg_size = (2 * sc->mtu);
11767        if (tpa_agg_size < sc->max_aggregation_size) {
11768            tpa_agg_size = sc->max_aggregation_size;
11769        }
11770
11771        max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11772        max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11773                   (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11774        sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11775    }
11776
11777    /* pause - not for e1 */
11778    if (!CHIP_IS_E1(sc)) {
11779        pause->bd_th_lo = BD_TH_LO(sc);
11780        pause->bd_th_hi = BD_TH_HI(sc);
11781
11782        pause->rcq_th_lo = RCQ_TH_LO(sc);
11783        pause->rcq_th_hi = RCQ_TH_HI(sc);
11784
11785        /* validate rings have enough entries to cross high thresholds */
11786        if (sc->dropless_fc &&
11787            pause->bd_th_hi + FW_PREFETCH_CNT >
11788            sc->rx_ring_size) {
11789            BLOGW(sc, "rx bd ring threshold limit\n");
11790        }
11791
11792        if (sc->dropless_fc &&
11793            pause->rcq_th_hi + FW_PREFETCH_CNT >
11794            RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11795            BLOGW(sc, "rcq ring threshold limit\n");
11796        }
11797
11798        pause->pri_map = 1;
11799    }
11800
11801    /* rxq setup */
11802    rxq_init->dscr_map   = fp->rx_dma.paddr;
11803    rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11804    rxq_init->rcq_map    = fp->rcq_dma.paddr;
11805    rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11806
11807    /*
11808     * This should be a maximum number of data bytes that may be
11809     * placed on the BD (not including paddings).
11810     */
11811    rxq_init->buf_sz = (fp->rx_buf_size -
11812                        IP_HEADER_ALIGNMENT_PADDING);
11813
11814    rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11815    rxq_init->tpa_agg_sz      = tpa_agg_size;
11816    rxq_init->sge_buf_sz      = sge_sz;
11817    rxq_init->max_sges_pkt    = max_sge;
11818    rxq_init->rss_engine_id   = SC_FUNC(sc);
11819    rxq_init->mcast_engine_id = SC_FUNC(sc);
11820
11821    /*
11822     * Maximum number or simultaneous TPA aggregation for this Queue.
11823     * For PF Clients it should be the maximum available number.
11824     * VF driver(s) may want to define it to a smaller value.
11825     */
11826    rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11827
11828    rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11829    rxq_init->fw_sb_id = fp->fw_sb_id;
11830
11831    rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11832
11833    /*
11834     * configure silent vlan removal
11835     * if multi function mode is afex, then mask default vlan
11836     */
11837    if (IS_MF_AFEX(sc)) {
11838        rxq_init->silent_removal_value =
11839            sc->devinfo.mf_info.afex_def_vlan_tag;
11840        rxq_init->silent_removal_mask = EVL_VLID_MASK;
11841    }
11842}
11843
11844static void
11845bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11846                 struct bxe_fastpath           *fp,
11847                 struct ecore_txq_setup_params *txq_init,
11848                 uint8_t                       cos)
11849{
11850    /*
11851     * XXX If multiple CoS is ever supported then each fastpath structure
11852     * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11853     * fp->txdata[cos]->tx_dma.paddr;
11854     */
11855    txq_init->dscr_map     = fp->tx_dma.paddr;
11856    txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11857    txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11858    txq_init->fw_sb_id     = fp->fw_sb_id;
11859
11860    /*
11861     * set the TSS leading client id for TX classfication to the
11862     * leading RSS client id
11863     */
11864    txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11865}
11866
11867/*
11868 * This function performs 2 steps in a queue state machine:
11869 *   1) RESET->INIT
11870 *   2) INIT->SETUP
11871 */
11872static int
11873bxe_setup_queue(struct bxe_softc    *sc,
11874                struct bxe_fastpath *fp,
11875                uint8_t             leading)
11876{
11877    struct ecore_queue_state_params q_params = { NULL };
11878    struct ecore_queue_setup_params *setup_params =
11879                        &q_params.params.setup;
11880#if 0
11881    struct ecore_queue_setup_tx_only_params *tx_only_params =
11882                        &q_params.params.tx_only;
11883    uint8_t tx_index;
11884#endif
11885    int rc;
11886
11887    BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11888
11889    bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11890
11891    q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11892
11893    /* we want to wait for completion in this context */
11894    bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11895
11896    /* prepare the INIT parameters */
11897    bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11898
11899    /* Set the command */
11900    q_params.cmd = ECORE_Q_CMD_INIT;
11901
11902    /* Change the state to INIT */
11903    rc = ecore_queue_state_change(sc, &q_params);
11904    if (rc) {
11905        BLOGE(sc, "Queue(%d) INIT failed\n", fp->index);
11906        return (rc);
11907    }
11908
11909    BLOGD(sc, DBG_LOAD, "init complete\n");
11910
11911    /* now move the Queue to the SETUP state */
11912    memset(setup_params, 0, sizeof(*setup_params));
11913
11914    /* set Queue flags */
11915    setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11916
11917    /* set general SETUP parameters */
11918    bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11919                          FIRST_TX_COS_INDEX);
11920
11921    bxe_pf_rx_q_prep(sc, fp,
11922                     &setup_params->pause_params,
11923                     &setup_params->rxq_params);
11924
11925    bxe_pf_tx_q_prep(sc, fp,
11926                     &setup_params->txq_params,
11927                     FIRST_TX_COS_INDEX);
11928
11929    /* Set the command */
11930    q_params.cmd = ECORE_Q_CMD_SETUP;
11931
11932    /* change the state to SETUP */
11933    rc = ecore_queue_state_change(sc, &q_params);
11934    if (rc) {
11935        BLOGE(sc, "Queue(%d) SETUP failed\n", fp->index);
11936        return (rc);
11937    }
11938
11939#if 0
11940    /* loop through the relevant tx-only indices */
11941    for (tx_index = FIRST_TX_ONLY_COS_INDEX;
11942         tx_index < sc->max_cos;
11943         tx_index++) {
11944        /* prepare and send tx-only ramrod*/
11945        rc = bxe_setup_tx_only(sc, fp, &q_params,
11946                               tx_only_params, tx_index, leading);
11947        if (rc) {
11948            BLOGE(sc, "Queue(%d.%d) TX_ONLY_SETUP failed\n",
11949                  fp->index, tx_index);
11950            return (rc);
11951        }
11952    }
11953#endif
11954
11955    return (rc);
11956}
11957
11958static int
11959bxe_setup_leading(struct bxe_softc *sc)
11960{
11961    return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11962}
11963
11964static int
11965bxe_config_rss_pf(struct bxe_softc            *sc,
11966                  struct ecore_rss_config_obj *rss_obj,
11967                  uint8_t                     config_hash)
11968{
11969    struct ecore_config_rss_params params = { NULL };
11970    int i;
11971
11972    /*
11973     * Although RSS is meaningless when there is a single HW queue we
11974     * still need it enabled in order to have HW Rx hash generated.
11975     */
11976
11977    params.rss_obj = rss_obj;
11978
11979    bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11980
11981    bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11982
11983    /* RSS configuration */
11984    bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11985    bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11986    bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11987    bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11988    if (rss_obj->udp_rss_v4) {
11989        bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11990    }
11991    if (rss_obj->udp_rss_v6) {
11992        bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11993    }
11994
11995    /* Hash bits */
11996    params.rss_result_mask = MULTI_MASK;
11997
11998    memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11999
12000    if (config_hash) {
12001        /* RSS keys */
12002        for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
12003            params.rss_key[i] = arc4random();
12004        }
12005
12006        bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
12007    }
12008
12009    return (ecore_config_rss(sc, &params));
12010}
12011
12012static int
12013bxe_config_rss_eth(struct bxe_softc *sc,
12014                   uint8_t          config_hash)
12015{
12016    return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
12017}
12018
12019static int
12020bxe_init_rss_pf(struct bxe_softc *sc)
12021{
12022    uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
12023    int i;
12024
12025    /*
12026     * Prepare the initial contents of the indirection table if
12027     * RSS is enabled
12028     */
12029    for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
12030        sc->rss_conf_obj.ind_table[i] =
12031            (sc->fp->cl_id + (i % num_eth_queues));
12032    }
12033
12034    if (sc->udp_rss) {
12035        sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
12036    }
12037
12038    /*
12039     * For 57710 and 57711 SEARCHER configuration (rss_keys) is
12040     * per-port, so if explicit configuration is needed, do it only
12041     * for a PMF.
12042     *
12043     * For 57712 and newer it's a per-function configuration.
12044     */
12045    return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
12046}
12047
12048static int
12049bxe_set_mac_one(struct bxe_softc          *sc,
12050                uint8_t                   *mac,
12051                struct ecore_vlan_mac_obj *obj,
12052                uint8_t                   set,
12053                int                       mac_type,
12054                unsigned long             *ramrod_flags)
12055{
12056    struct ecore_vlan_mac_ramrod_params ramrod_param;
12057    int rc;
12058
12059    memset(&ramrod_param, 0, sizeof(ramrod_param));
12060
12061    /* fill in general parameters */
12062    ramrod_param.vlan_mac_obj = obj;
12063    ramrod_param.ramrod_flags = *ramrod_flags;
12064
12065    /* fill a user request section if needed */
12066    if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
12067        memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
12068
12069        bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
12070
12071        /* Set the command: ADD or DEL */
12072        ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
12073                                            ECORE_VLAN_MAC_DEL;
12074    }
12075
12076    rc = ecore_config_vlan_mac(sc, &ramrod_param);
12077
12078    if (rc == ECORE_EXISTS) {
12079        BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12080        /* do not treat adding same MAC as error */
12081        rc = 0;
12082    } else if (rc < 0) {
12083        BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
12084    }
12085
12086    return (rc);
12087}
12088
12089static int
12090bxe_set_eth_mac(struct bxe_softc *sc,
12091                uint8_t          set)
12092{
12093    unsigned long ramrod_flags = 0;
12094
12095    BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
12096
12097    bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
12098
12099    /* Eth MAC is set on RSS leading client (fp[0]) */
12100    return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
12101                            &sc->sp_objs->mac_obj,
12102                            set, ECORE_ETH_MAC, &ramrod_flags));
12103}
12104
12105#if 0
12106static void
12107bxe_update_max_mf_config(struct bxe_softc *sc,
12108                         uint32_t         value)
12109{
12110    /* load old values */
12111    uint32_t mf_cfg = sc->devinfo.mf_info.mf_config[SC_VN(sc)];
12112
12113    if (value != bxe_extract_max_cfg(sc, mf_cfg)) {
12114        /* leave all but MAX value */
12115        mf_cfg &= ~FUNC_MF_CFG_MAX_BW_MASK;
12116
12117        /* set new MAX value */
12118        mf_cfg |= ((value << FUNC_MF_CFG_MAX_BW_SHIFT) &
12119                   FUNC_MF_CFG_MAX_BW_MASK);
12120
12121        bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW, mf_cfg);
12122    }
12123}
12124#endif
12125
12126static int
12127bxe_get_cur_phy_idx(struct bxe_softc *sc)
12128{
12129    uint32_t sel_phy_idx = 0;
12130
12131    if (sc->link_params.num_phys <= 1) {
12132        return (ELINK_INT_PHY);
12133    }
12134
12135    if (sc->link_vars.link_up) {
12136        sel_phy_idx = ELINK_EXT_PHY1;
12137        /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
12138        if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
12139            (sc->link_params.phy[ELINK_EXT_PHY2].supported &
12140             ELINK_SUPPORTED_FIBRE))
12141            sel_phy_idx = ELINK_EXT_PHY2;
12142    } else {
12143        switch (elink_phy_selection(&sc->link_params)) {
12144        case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
12145        case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
12146        case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
12147               sel_phy_idx = ELINK_EXT_PHY1;
12148               break;
12149        case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
12150        case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
12151               sel_phy_idx = ELINK_EXT_PHY2;
12152               break;
12153        }
12154    }
12155
12156    return (sel_phy_idx);
12157}
12158
12159static int
12160bxe_get_link_cfg_idx(struct bxe_softc *sc)
12161{
12162    uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
12163
12164    /*
12165     * The selected activated PHY is always after swapping (in case PHY
12166     * swapping is enabled). So when swapping is enabled, we need to reverse
12167     * the configuration
12168     */
12169
12170    if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
12171        if (sel_phy_idx == ELINK_EXT_PHY1)
12172            sel_phy_idx = ELINK_EXT_PHY2;
12173        else if (sel_phy_idx == ELINK_EXT_PHY2)
12174            sel_phy_idx = ELINK_EXT_PHY1;
12175    }
12176
12177    return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
12178}
12179
12180static void
12181bxe_set_requested_fc(struct bxe_softc *sc)
12182{
12183    /*
12184     * Initialize link parameters structure variables
12185     * It is recommended to turn off RX FC for jumbo frames
12186     * for better performance
12187     */
12188    if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
12189        sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
12190    } else {
12191        sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
12192    }
12193}
12194
12195static void
12196bxe_calc_fc_adv(struct bxe_softc *sc)
12197{
12198    uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
12199    switch (sc->link_vars.ieee_fc &
12200            MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
12201    case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
12202    default:
12203        sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
12204                                           ADVERTISED_Pause);
12205        break;
12206
12207    case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
12208        sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
12209                                          ADVERTISED_Pause);
12210        break;
12211
12212    case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
12213        sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
12214        break;
12215    }
12216}
12217
12218static uint16_t
12219bxe_get_mf_speed(struct bxe_softc *sc)
12220{
12221    uint16_t line_speed = sc->link_vars.line_speed;
12222    if (IS_MF(sc)) {
12223        uint16_t maxCfg =
12224            bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
12225
12226        /* calculate the current MAX line speed limit for the MF devices */
12227        if (IS_MF_SI(sc)) {
12228            line_speed = (line_speed * maxCfg) / 100;
12229        } else { /* SD mode */
12230            uint16_t vn_max_rate = maxCfg * 100;
12231
12232            if (vn_max_rate < line_speed) {
12233                line_speed = vn_max_rate;
12234            }
12235        }
12236    }
12237
12238    return (line_speed);
12239}
12240
12241static void
12242bxe_fill_report_data(struct bxe_softc            *sc,
12243                     struct bxe_link_report_data *data)
12244{
12245    uint16_t line_speed = bxe_get_mf_speed(sc);
12246
12247    memset(data, 0, sizeof(*data));
12248
12249    /* fill the report data with the effective line speed */
12250    data->line_speed = line_speed;
12251
12252    /* Link is down */
12253    if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
12254        bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
12255    }
12256
12257    /* Full DUPLEX */
12258    if (sc->link_vars.duplex == DUPLEX_FULL) {
12259        bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
12260    }
12261
12262    /* Rx Flow Control is ON */
12263    if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
12264        bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
12265    }
12266
12267    /* Tx Flow Control is ON */
12268    if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
12269        bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
12270    }
12271}
12272
12273/* report link status to OS, should be called under phy_lock */
12274static void
12275bxe_link_report_locked(struct bxe_softc *sc)
12276{
12277    struct bxe_link_report_data cur_data;
12278
12279    /* reread mf_cfg */
12280    if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
12281        bxe_read_mf_cfg(sc);
12282    }
12283
12284    /* Read the current link report info */
12285    bxe_fill_report_data(sc, &cur_data);
12286
12287    /* Don't report link down or exactly the same link status twice */
12288    if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
12289        (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
12290                      &sc->last_reported_link.link_report_flags) &&
12291         bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
12292                      &cur_data.link_report_flags))) {
12293        return;
12294    }
12295
12296    sc->link_cnt++;
12297
12298    /* report new link params and remember the state for the next time */
12299    memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
12300
12301    if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
12302                     &cur_data.link_report_flags)) {
12303        if_link_state_change(sc->ifnet, LINK_STATE_DOWN);
12304        BLOGI(sc, "NIC Link is Down\n");
12305    } else {
12306        const char *duplex;
12307        const char *flow;
12308
12309        if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
12310                                   &cur_data.link_report_flags)) {
12311            duplex = "full";
12312        } else {
12313            duplex = "half";
12314        }
12315
12316        /*
12317         * Handle the FC at the end so that only these flags would be
12318         * possibly set. This way we may easily check if there is no FC
12319         * enabled.
12320         */
12321        if (cur_data.link_report_flags) {
12322            if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
12323                             &cur_data.link_report_flags) &&
12324                bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
12325                             &cur_data.link_report_flags)) {
12326                flow = "ON - receive & transmit";
12327            } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
12328                                    &cur_data.link_report_flags) &&
12329                       !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
12330                                     &cur_data.link_report_flags)) {
12331                flow = "ON - receive";
12332            } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
12333                                     &cur_data.link_report_flags) &&
12334                       bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
12335                                    &cur_data.link_report_flags)) {
12336                flow = "ON - transmit";
12337            } else {
12338                flow = "none"; /* possible? */
12339            }
12340        } else {
12341            flow = "none";
12342        }
12343
12344        if_link_state_change(sc->ifnet, LINK_STATE_UP);
12345        BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
12346              cur_data.line_speed, duplex, flow);
12347    }
12348}
12349
12350static void
12351bxe_link_report(struct bxe_softc *sc)
12352{
12353    BXE_PHY_LOCK(sc);
12354    bxe_link_report_locked(sc);
12355    BXE_PHY_UNLOCK(sc);
12356}
12357
12358static void
12359bxe_link_status_update(struct bxe_softc *sc)
12360{
12361    if (sc->state != BXE_STATE_OPEN) {
12362        return;
12363    }
12364
12365#if 0
12366    /* read updated dcb configuration */
12367    if (IS_PF(sc))
12368        bxe_dcbx_pmf_update(sc);
12369#endif
12370
12371    if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
12372        elink_link_status_update(&sc->link_params, &sc->link_vars);
12373    } else {
12374        sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
12375                                  ELINK_SUPPORTED_10baseT_Full |
12376                                  ELINK_SUPPORTED_100baseT_Half |
12377                                  ELINK_SUPPORTED_100baseT_Full |
12378                                  ELINK_SUPPORTED_1000baseT_Full |
12379                                  ELINK_SUPPORTED_2500baseX_Full |
12380                                  ELINK_SUPPORTED_10000baseT_Full |
12381                                  ELINK_SUPPORTED_TP |
12382                                  ELINK_SUPPORTED_FIBRE |
12383                                  ELINK_SUPPORTED_Autoneg |
12384                                  ELINK_SUPPORTED_Pause |
12385                                  ELINK_SUPPORTED_Asym_Pause);
12386        sc->port.advertising[0] = sc->port.supported[0];
12387
12388        sc->link_params.sc                = sc;
12389        sc->link_params.port              = SC_PORT(sc);
12390        sc->link_params.req_duplex[0]     = DUPLEX_FULL;
12391        sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
12392        sc->link_params.req_line_speed[0] = SPEED_10000;
12393        sc->link_params.speed_cap_mask[0] = 0x7f0000;
12394        sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
12395
12396        if (CHIP_REV_IS_FPGA(sc)) {
12397            sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
12398            sc->link_vars.line_speed  = ELINK_SPEED_1000;
12399            sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
12400                                         LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
12401        } else {
12402            sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
12403            sc->link_vars.line_speed  = ELINK_SPEED_10000;
12404            sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
12405                                         LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
12406        }
12407
12408        sc->link_vars.link_up = 1;
12409
12410        sc->link_vars.duplex    = DUPLEX_FULL;
12411        sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
12412
12413        if (IS_PF(sc)) {
12414            REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
12415            bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12416            bxe_link_report(sc);
12417        }
12418    }
12419
12420    if (IS_PF(sc)) {
12421        if (sc->link_vars.link_up) {
12422            bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12423        } else {
12424            bxe_stats_handle(sc, STATS_EVENT_STOP);
12425        }
12426        bxe_link_report(sc);
12427    } else {
12428        bxe_link_report(sc);
12429        bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12430    }
12431}
12432
12433static int
12434bxe_initial_phy_init(struct bxe_softc *sc,
12435                     int              load_mode)
12436{
12437    int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
12438    uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
12439    struct elink_params *lp = &sc->link_params;
12440
12441    bxe_set_requested_fc(sc);
12442
12443    if (CHIP_REV_IS_SLOW(sc)) {
12444        uint32_t bond = CHIP_BOND_ID(sc);
12445        uint32_t feat = 0;
12446
12447        if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
12448            feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
12449        } else if (bond & 0x4) {
12450            if (CHIP_IS_E3(sc)) {
12451                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
12452            } else {
12453                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
12454            }
12455        } else if (bond & 0x8) {
12456            if (CHIP_IS_E3(sc)) {
12457                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
12458            } else {
12459                feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12460            }
12461        }
12462
12463        /* disable EMAC for E3 and above */
12464        if (bond & 0x2) {
12465            feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12466        }
12467
12468        sc->link_params.feature_config_flags |= feat;
12469    }
12470
12471    BXE_PHY_LOCK(sc);
12472
12473    if (load_mode == LOAD_DIAG) {
12474        lp->loopback_mode = ELINK_LOOPBACK_XGXS;
12475        /* Prefer doing PHY loopback at 10G speed, if possible */
12476        if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
12477            if (lp->speed_cap_mask[cfg_idx] &
12478                PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
12479                lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
12480            } else {
12481                lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
12482            }
12483        }
12484    }
12485
12486    if (load_mode == LOAD_LOOPBACK_EXT) {
12487        lp->loopback_mode = ELINK_LOOPBACK_EXT;
12488    }
12489
12490    rc = elink_phy_init(&sc->link_params, &sc->link_vars);
12491
12492    BXE_PHY_UNLOCK(sc);
12493
12494    bxe_calc_fc_adv(sc);
12495
12496    if (sc->link_vars.link_up) {
12497        bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12498        bxe_link_report(sc);
12499    }
12500
12501    if (!CHIP_REV_IS_SLOW(sc)) {
12502        bxe_periodic_start(sc);
12503    }
12504
12505    sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
12506    return (rc);
12507}
12508
12509/* must be called under IF_ADDR_LOCK */
12510static int
12511bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
12512                         struct ecore_mcast_ramrod_params *p)
12513{
12514    struct ifnet *ifp = sc->ifnet;
12515    int mc_count = 0;
12516    struct ifmultiaddr *ifma;
12517    struct ecore_mcast_list_elem *mc_mac;
12518
12519    TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12520        if (ifma->ifma_addr->sa_family != AF_LINK) {
12521            continue;
12522        }
12523
12524        mc_count++;
12525    }
12526
12527    ECORE_LIST_INIT(&p->mcast_list);
12528    p->mcast_list_len = 0;
12529
12530    if (!mc_count) {
12531        return (0);
12532    }
12533
12534    mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12535                    (M_NOWAIT | M_ZERO));
12536    if (!mc_mac) {
12537        BLOGE(sc, "Failed to allocate temp mcast list\n");
12538        return (-1);
12539    }
12540
12541    TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12542        if (ifma->ifma_addr->sa_family != AF_LINK) {
12543            continue;
12544        }
12545
12546        mc_mac->mac = (uint8_t *)LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
12547        ECORE_LIST_PUSH_TAIL(&mc_mac->link, &p->mcast_list);
12548
12549        BLOGD(sc, DBG_LOAD,
12550              "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
12551              mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12552              mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
12553
12554        mc_mac++;
12555    }
12556
12557    p->mcast_list_len = mc_count;
12558
12559    return (0);
12560}
12561
12562static void
12563bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12564{
12565    struct ecore_mcast_list_elem *mc_mac =
12566        ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12567                               struct ecore_mcast_list_elem,
12568                               link);
12569
12570    if (mc_mac) {
12571        /* only a single free as all mc_macs are in the same heap array */
12572        free(mc_mac, M_DEVBUF);
12573    }
12574}
12575
12576static int
12577bxe_set_mc_list(struct bxe_softc *sc)
12578{
12579    struct ecore_mcast_ramrod_params rparam = { NULL };
12580    int rc = 0;
12581
12582    rparam.mcast_obj = &sc->mcast_obj;
12583
12584    BXE_MCAST_LOCK(sc);
12585
12586    /* first, clear all configured multicast MACs */
12587    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12588    if (rc < 0) {
12589        BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12590        return (rc);
12591    }
12592
12593    /* configure a new MACs list */
12594    rc = bxe_init_mcast_macs_list(sc, &rparam);
12595    if (rc) {
12596        BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12597        BXE_MCAST_UNLOCK(sc);
12598        return (rc);
12599    }
12600
12601    /* Now add the new MACs */
12602    rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12603    if (rc < 0) {
12604        BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12605    }
12606
12607    bxe_free_mcast_macs_list(&rparam);
12608
12609    BXE_MCAST_UNLOCK(sc);
12610
12611    return (rc);
12612}
12613
12614static int
12615bxe_set_uc_list(struct bxe_softc *sc)
12616{
12617    struct ifnet *ifp = sc->ifnet;
12618    struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12619    struct ifaddr *ifa;
12620    unsigned long ramrod_flags = 0;
12621    int rc;
12622
12623#if __FreeBSD_version < 800000
12624    IF_ADDR_LOCK(ifp);
12625#else
12626    if_addr_rlock(ifp);
12627#endif
12628
12629    /* first schedule a cleanup up of old configuration */
12630    rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12631    if (rc < 0) {
12632        BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12633#if __FreeBSD_version < 800000
12634        IF_ADDR_UNLOCK(ifp);
12635#else
12636        if_addr_runlock(ifp);
12637#endif
12638        return (rc);
12639    }
12640
12641    ifa = ifp->if_addr;
12642    while (ifa) {
12643        if (ifa->ifa_addr->sa_family != AF_LINK) {
12644            ifa = TAILQ_NEXT(ifa, ifa_link);
12645            continue;
12646        }
12647
12648        rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12649                             mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12650        if (rc == -EEXIST) {
12651            BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12652            /* do not treat adding same MAC as an error */
12653            rc = 0;
12654        } else if (rc < 0) {
12655            BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12656#if __FreeBSD_version < 800000
12657            IF_ADDR_UNLOCK(ifp);
12658#else
12659            if_addr_runlock(ifp);
12660#endif
12661            return (rc);
12662        }
12663
12664        ifa = TAILQ_NEXT(ifa, ifa_link);
12665    }
12666
12667#if __FreeBSD_version < 800000
12668    IF_ADDR_UNLOCK(ifp);
12669#else
12670    if_addr_runlock(ifp);
12671#endif
12672
12673    /* Execute the pending commands */
12674    bit_set(&ramrod_flags, RAMROD_CONT);
12675    return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12676                            ECORE_UC_LIST_MAC, &ramrod_flags));
12677}
12678
12679static void
12680bxe_handle_rx_mode_tq(void *context,
12681                      int  pending)
12682{
12683    struct bxe_softc *sc = (struct bxe_softc *)context;
12684    struct ifnet *ifp = sc->ifnet;
12685    uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12686
12687    BXE_CORE_LOCK(sc);
12688
12689    if (sc->state != BXE_STATE_OPEN) {
12690        BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12691        BXE_CORE_UNLOCK(sc);
12692        return;
12693    }
12694
12695    BLOGD(sc, DBG_SP, "ifp->if_flags=0x%x\n", ifp->if_flags);
12696
12697    if (ifp->if_flags & IFF_PROMISC) {
12698        rx_mode = BXE_RX_MODE_PROMISC;
12699    } else if ((ifp->if_flags & IFF_ALLMULTI) ||
12700               ((ifp->if_amcount > BXE_MAX_MULTICAST) &&
12701                CHIP_IS_E1(sc))) {
12702        rx_mode = BXE_RX_MODE_ALLMULTI;
12703    } else {
12704        if (IS_PF(sc)) {
12705            /* some multicasts */
12706            if (bxe_set_mc_list(sc) < 0) {
12707                rx_mode = BXE_RX_MODE_ALLMULTI;
12708            }
12709            if (bxe_set_uc_list(sc) < 0) {
12710                rx_mode = BXE_RX_MODE_PROMISC;
12711            }
12712        }
12713#if 0
12714        else {
12715            /*
12716             * Configuring mcast to a VF involves sleeping (when we
12717             * wait for the PF's response). Since this function is
12718             * called from a non sleepable context we must schedule
12719             * a work item for this purpose
12720             */
12721            bxe_set_bit(BXE_SP_RTNL_VFPF_MCAST, &sc->sp_rtnl_state);
12722            schedule_delayed_work(&sc->sp_rtnl_task, 0);
12723        }
12724#endif
12725    }
12726
12727    sc->rx_mode = rx_mode;
12728
12729    /* schedule the rx_mode command */
12730    if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12731        BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12732        bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12733        BXE_CORE_UNLOCK(sc);
12734        return;
12735    }
12736
12737    if (IS_PF(sc)) {
12738        bxe_set_storm_rx_mode(sc);
12739    }
12740#if 0
12741    else {
12742        /*
12743         * Configuring mcast to a VF involves sleeping (when we
12744         * wait for the PF's response). Since this function is
12745         * called from a non sleepable context we must schedule
12746         * a work item for this purpose
12747         */
12748        bxe_set_bit(BXE_SP_RTNL_VFPF_STORM_RX_MODE, &sc->sp_rtnl_state);
12749        schedule_delayed_work(&sc->sp_rtnl_task, 0);
12750    }
12751#endif
12752
12753    BXE_CORE_UNLOCK(sc);
12754}
12755
12756static void
12757bxe_set_rx_mode(struct bxe_softc *sc)
12758{
12759    taskqueue_enqueue(sc->rx_mode_tq, &sc->rx_mode_tq_task);
12760}
12761
12762/* update flags in shmem */
12763static void
12764bxe_update_drv_flags(struct bxe_softc *sc,
12765                     uint32_t         flags,
12766                     uint32_t         set)
12767{
12768    uint32_t drv_flags;
12769
12770    if (SHMEM2_HAS(sc, drv_flags)) {
12771        bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12772        drv_flags = SHMEM2_RD(sc, drv_flags);
12773
12774        if (set) {
12775            SET_FLAGS(drv_flags, flags);
12776        } else {
12777            RESET_FLAGS(drv_flags, flags);
12778        }
12779
12780        SHMEM2_WR(sc, drv_flags, drv_flags);
12781        BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12782
12783        bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12784    }
12785}
12786
12787/* periodic timer callout routine, only runs when the interface is up */
12788
12789static void
12790bxe_periodic_callout_func(void *xsc)
12791{
12792    struct bxe_softc *sc = (struct bxe_softc *)xsc;
12793    int i;
12794
12795    if (!BXE_CORE_TRYLOCK(sc)) {
12796        /* just bail and try again next time */
12797
12798        if ((sc->state == BXE_STATE_OPEN) &&
12799            (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12800            /* schedule the next periodic callout */
12801            callout_reset(&sc->periodic_callout, hz,
12802                          bxe_periodic_callout_func, sc);
12803        }
12804
12805        return;
12806    }
12807
12808    if ((sc->state != BXE_STATE_OPEN) ||
12809        (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12810        BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12811        BXE_CORE_UNLOCK(sc);
12812        return;
12813    }
12814
12815    /* Check for TX timeouts on any fastpath. */
12816    FOR_EACH_QUEUE(sc, i) {
12817        if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12818            /* Ruh-Roh, chip was reset! */
12819            break;
12820        }
12821    }
12822
12823    if (!CHIP_REV_IS_SLOW(sc)) {
12824        /*
12825         * This barrier is needed to ensure the ordering between the writing
12826         * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12827         * the reading here.
12828         */
12829        mb();
12830        if (sc->port.pmf) {
12831            BXE_PHY_LOCK(sc);
12832            elink_period_func(&sc->link_params, &sc->link_vars);
12833            BXE_PHY_UNLOCK(sc);
12834        }
12835    }
12836
12837    if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12838        int mb_idx = SC_FW_MB_IDX(sc);
12839        uint32_t drv_pulse;
12840        uint32_t mcp_pulse;
12841
12842        ++sc->fw_drv_pulse_wr_seq;
12843        sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12844
12845        drv_pulse = sc->fw_drv_pulse_wr_seq;
12846        bxe_drv_pulse(sc);
12847
12848        mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12849                     MCP_PULSE_SEQ_MASK);
12850
12851        /*
12852         * The delta between driver pulse and mcp response should
12853         * be 1 (before mcp response) or 0 (after mcp response).
12854         */
12855        if ((drv_pulse != mcp_pulse) &&
12856            (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12857            /* someone lost a heartbeat... */
12858            BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12859                  drv_pulse, mcp_pulse);
12860        }
12861    }
12862
12863    /* state is BXE_STATE_OPEN */
12864    bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12865
12866#if 0
12867    /* sample VF bulletin board for new posts from PF */
12868    if (IS_VF(sc)) {
12869        bxe_sample_bulletin(sc);
12870    }
12871#endif
12872
12873    BXE_CORE_UNLOCK(sc);
12874
12875    if ((sc->state == BXE_STATE_OPEN) &&
12876        (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12877        /* schedule the next periodic callout */
12878        callout_reset(&sc->periodic_callout, hz,
12879                      bxe_periodic_callout_func, sc);
12880    }
12881}
12882
12883static void
12884bxe_periodic_start(struct bxe_softc *sc)
12885{
12886    atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12887    callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12888}
12889
12890static void
12891bxe_periodic_stop(struct bxe_softc *sc)
12892{
12893    atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12894    callout_drain(&sc->periodic_callout);
12895}
12896
12897/* start the controller */
12898static __noinline int
12899bxe_nic_load(struct bxe_softc *sc,
12900             int              load_mode)
12901{
12902    uint32_t val;
12903    int load_code = 0;
12904    int i, rc = 0;
12905
12906    BXE_CORE_LOCK_ASSERT(sc);
12907
12908    BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12909
12910    sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12911
12912    if (IS_PF(sc)) {
12913        /* must be called before memory allocation and HW init */
12914        bxe_ilt_set_info(sc);
12915    }
12916
12917    sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12918
12919    bxe_set_fp_rx_buf_size(sc);
12920
12921    if (bxe_alloc_fp_buffers(sc) != 0) {
12922        BLOGE(sc, "Failed to allocate fastpath memory\n");
12923        sc->state = BXE_STATE_CLOSED;
12924        rc = ENOMEM;
12925        goto bxe_nic_load_error0;
12926    }
12927
12928    if (bxe_alloc_mem(sc) != 0) {
12929        sc->state = BXE_STATE_CLOSED;
12930        rc = ENOMEM;
12931        goto bxe_nic_load_error0;
12932    }
12933
12934    if (bxe_alloc_fw_stats_mem(sc) != 0) {
12935        sc->state = BXE_STATE_CLOSED;
12936        rc = ENOMEM;
12937        goto bxe_nic_load_error0;
12938    }
12939
12940    if (IS_PF(sc)) {
12941        /* set pf load just before approaching the MCP */
12942        bxe_set_pf_load(sc);
12943
12944        /* if MCP exists send load request and analyze response */
12945        if (!BXE_NOMCP(sc)) {
12946            /* attempt to load pf */
12947            if (bxe_nic_load_request(sc, &load_code) != 0) {
12948                sc->state = BXE_STATE_CLOSED;
12949                rc = ENXIO;
12950                goto bxe_nic_load_error1;
12951            }
12952
12953            /* what did the MCP say? */
12954            if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12955                bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12956                sc->state = BXE_STATE_CLOSED;
12957                rc = ENXIO;
12958                goto bxe_nic_load_error2;
12959            }
12960        } else {
12961            BLOGI(sc, "Device has no MCP!\n");
12962            load_code = bxe_nic_load_no_mcp(sc);
12963        }
12964
12965        /* mark PMF if applicable */
12966        bxe_nic_load_pmf(sc, load_code);
12967
12968        /* Init Function state controlling object */
12969        bxe_init_func_obj(sc);
12970
12971        /* Initialize HW */
12972        if (bxe_init_hw(sc, load_code) != 0) {
12973            BLOGE(sc, "HW init failed\n");
12974            bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12975            sc->state = BXE_STATE_CLOSED;
12976            rc = ENXIO;
12977            goto bxe_nic_load_error2;
12978        }
12979    }
12980
12981    /* attach interrupts */
12982    if (bxe_interrupt_attach(sc) != 0) {
12983        sc->state = BXE_STATE_CLOSED;
12984        rc = ENXIO;
12985        goto bxe_nic_load_error2;
12986    }
12987
12988    bxe_nic_init(sc, load_code);
12989
12990    /* Init per-function objects */
12991    if (IS_PF(sc)) {
12992        bxe_init_objs(sc);
12993        // XXX bxe_iov_nic_init(sc);
12994
12995        /* set AFEX default VLAN tag to an invalid value */
12996        sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12997        // XXX bxe_nic_load_afex_dcc(sc, load_code);
12998
12999        sc->state = BXE_STATE_OPENING_WAITING_PORT;
13000        rc = bxe_func_start(sc);
13001        if (rc) {
13002            BLOGE(sc, "Function start failed!\n");
13003            bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
13004            sc->state = BXE_STATE_ERROR;
13005            goto bxe_nic_load_error3;
13006        }
13007
13008        /* send LOAD_DONE command to MCP */
13009        if (!BXE_NOMCP(sc)) {
13010            load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
13011            if (!load_code) {
13012                BLOGE(sc, "MCP response failure, aborting\n");
13013                sc->state = BXE_STATE_ERROR;
13014                rc = ENXIO;
13015                goto bxe_nic_load_error3;
13016            }
13017        }
13018
13019        rc = bxe_setup_leading(sc);
13020        if (rc) {
13021            BLOGE(sc, "Setup leading failed!\n");
13022            sc->state = BXE_STATE_ERROR;
13023            goto bxe_nic_load_error3;
13024        }
13025
13026        FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
13027            rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
13028            if (rc) {
13029                BLOGE(sc, "Queue(%d) setup failed\n", i);
13030                sc->state = BXE_STATE_ERROR;
13031                goto bxe_nic_load_error3;
13032            }
13033        }
13034
13035        rc = bxe_init_rss_pf(sc);
13036        if (rc) {
13037            BLOGE(sc, "PF RSS init failed\n");
13038            sc->state = BXE_STATE_ERROR;
13039            goto bxe_nic_load_error3;
13040        }
13041    }
13042    /* XXX VF */
13043#if 0
13044    else { /* VF */
13045        FOR_EACH_ETH_QUEUE(sc, i) {
13046            rc = bxe_vfpf_setup_q(sc, i);
13047            if (rc) {
13048                BLOGE(sc, "Queue(%d) setup failed\n", i);
13049                sc->state = BXE_STATE_ERROR;
13050                goto bxe_nic_load_error3;
13051            }
13052        }
13053    }
13054#endif
13055
13056    /* now when Clients are configured we are ready to work */
13057    sc->state = BXE_STATE_OPEN;
13058
13059    /* Configure a ucast MAC */
13060    if (IS_PF(sc)) {
13061        rc = bxe_set_eth_mac(sc, TRUE);
13062    }
13063#if 0
13064    else { /* IS_VF(sc) */
13065        rc = bxe_vfpf_set_mac(sc);
13066    }
13067#endif
13068    if (rc) {
13069        BLOGE(sc, "Setting Ethernet MAC failed\n");
13070        sc->state = BXE_STATE_ERROR;
13071        goto bxe_nic_load_error3;
13072    }
13073
13074#if 0
13075    if (IS_PF(sc) && sc->pending_max) {
13076        /* for AFEX */
13077        bxe_update_max_mf_config(sc, sc->pending_max);
13078        sc->pending_max = 0;
13079    }
13080#endif
13081
13082    if (sc->port.pmf) {
13083        rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
13084        if (rc) {
13085            sc->state = BXE_STATE_ERROR;
13086            goto bxe_nic_load_error3;
13087        }
13088    }
13089
13090    sc->link_params.feature_config_flags &=
13091        ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
13092
13093    /* start fast path */
13094
13095    /* Initialize Rx filter */
13096    bxe_set_rx_mode(sc);
13097
13098    /* start the Tx */
13099    switch (/* XXX load_mode */LOAD_OPEN) {
13100    case LOAD_NORMAL:
13101    case LOAD_OPEN:
13102        break;
13103
13104    case LOAD_DIAG:
13105    case LOAD_LOOPBACK_EXT:
13106        sc->state = BXE_STATE_DIAG;
13107        break;
13108
13109    default:
13110        break;
13111    }
13112
13113    if (sc->port.pmf) {
13114        bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
13115    } else {
13116        bxe_link_status_update(sc);
13117    }
13118
13119    /* start the periodic timer callout */
13120    bxe_periodic_start(sc);
13121
13122    if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
13123        /* mark driver is loaded in shmem2 */
13124        val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
13125        SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
13126                  (val |
13127                   DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
13128                   DRV_FLAGS_CAPABILITIES_LOADED_L2));
13129    }
13130
13131    /* wait for all pending SP commands to complete */
13132    if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
13133        BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
13134        bxe_periodic_stop(sc);
13135        bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
13136        return (ENXIO);
13137    }
13138
13139#if 0
13140    /* If PMF - send ADMIN DCBX msg to MFW to initiate DCBX FSM */
13141    if (sc->port.pmf && (sc->state != BXE_STATE_DIAG)) {
13142        bxe_dcbx_init(sc, FALSE);
13143    }
13144#endif
13145
13146    /* Tell the stack the driver is running! */
13147    sc->ifnet->if_drv_flags = IFF_DRV_RUNNING;
13148
13149    BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
13150
13151    return (0);
13152
13153bxe_nic_load_error3:
13154
13155    if (IS_PF(sc)) {
13156        bxe_int_disable_sync(sc, 1);
13157
13158        /* clean out queued objects */
13159        bxe_squeeze_objects(sc);
13160    }
13161
13162    bxe_interrupt_detach(sc);
13163
13164bxe_nic_load_error2:
13165
13166    if (IS_PF(sc) && !BXE_NOMCP(sc)) {
13167        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
13168        bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
13169    }
13170
13171    sc->port.pmf = 0;
13172
13173bxe_nic_load_error1:
13174
13175    /* clear pf_load status, as it was already set */
13176    if (IS_PF(sc)) {
13177        bxe_clear_pf_load(sc);
13178    }
13179
13180bxe_nic_load_error0:
13181
13182    bxe_free_fw_stats_mem(sc);
13183    bxe_free_fp_buffers(sc);
13184    bxe_free_mem(sc);
13185
13186    return (rc);
13187}
13188
13189static int
13190bxe_init_locked(struct bxe_softc *sc)
13191{
13192    int other_engine = SC_PATH(sc) ? 0 : 1;
13193    uint8_t other_load_status, load_status;
13194    uint8_t global = FALSE;
13195    int rc;
13196
13197    BXE_CORE_LOCK_ASSERT(sc);
13198
13199    /* check if the driver is already running */
13200    if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
13201        BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
13202        return (0);
13203    }
13204
13205    bxe_set_power_state(sc, PCI_PM_D0);
13206
13207    /*
13208     * If parity occurred during the unload, then attentions and/or
13209     * RECOVERY_IN_PROGRES may still be set. If so we want the first function
13210     * loaded on the current engine to complete the recovery. Parity recovery
13211     * is only relevant for PF driver.
13212     */
13213    if (IS_PF(sc)) {
13214        other_load_status = bxe_get_load_status(sc, other_engine);
13215        load_status = bxe_get_load_status(sc, SC_PATH(sc));
13216
13217        if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
13218            bxe_chk_parity_attn(sc, &global, TRUE)) {
13219            do {
13220                /*
13221                 * If there are attentions and they are in global blocks, set
13222                 * the GLOBAL_RESET bit regardless whether it will be this
13223                 * function that will complete the recovery or not.
13224                 */
13225                if (global) {
13226                    bxe_set_reset_global(sc);
13227                }
13228
13229                /*
13230                 * Only the first function on the current engine should try
13231                 * to recover in open. In case of attentions in global blocks
13232                 * only the first in the chip should try to recover.
13233                 */
13234                if ((!load_status && (!global || !other_load_status)) &&
13235                    bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
13236                    BLOGI(sc, "Recovered during init\n");
13237                    break;
13238                }
13239
13240                /* recovery has failed... */
13241                bxe_set_power_state(sc, PCI_PM_D3hot);
13242                sc->recovery_state = BXE_RECOVERY_FAILED;
13243
13244                BLOGE(sc, "Recovery flow hasn't properly "
13245                          "completed yet, try again later. "
13246                          "If you still see this message after a "
13247                          "few retries then power cycle is required.\n");
13248
13249                rc = ENXIO;
13250                goto bxe_init_locked_done;
13251            } while (0);
13252        }
13253    }
13254
13255    sc->recovery_state = BXE_RECOVERY_DONE;
13256
13257    rc = bxe_nic_load(sc, LOAD_OPEN);
13258
13259bxe_init_locked_done:
13260
13261    if (rc) {
13262        /* Tell the stack the driver is NOT running! */
13263        BLOGE(sc, "Initialization failed, "
13264                  "stack notified driver is NOT running!\n");
13265        sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
13266    }
13267
13268    return (rc);
13269}
13270
13271static int
13272bxe_stop_locked(struct bxe_softc *sc)
13273{
13274    BXE_CORE_LOCK_ASSERT(sc);
13275    return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
13276}
13277
13278/*
13279 * Handles controller initialization when called from an unlocked routine.
13280 * ifconfig calls this function.
13281 *
13282 * Returns:
13283 *   void
13284 */
13285static void
13286bxe_init(void *xsc)
13287{
13288    struct bxe_softc *sc = (struct bxe_softc *)xsc;
13289
13290    BXE_CORE_LOCK(sc);
13291    bxe_init_locked(sc);
13292    BXE_CORE_UNLOCK(sc);
13293}
13294
13295static int
13296bxe_init_ifnet(struct bxe_softc *sc)
13297{
13298    struct ifnet *ifp;
13299
13300    /* ifconfig entrypoint for media type/status reporting */
13301    ifmedia_init(&sc->ifmedia, IFM_IMASK,
13302                 bxe_ifmedia_update,
13303                 bxe_ifmedia_status);
13304
13305    /* set the default interface values */
13306    ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
13307    ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
13308    ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
13309
13310    sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
13311
13312    /* allocate the ifnet structure */
13313    if ((ifp = if_alloc(IFT_ETHER)) == NULL) {
13314        BLOGE(sc, "Interface allocation failed!\n");
13315        return (ENXIO);
13316    }
13317
13318    ifp->if_softc = sc;
13319    if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
13320    ifp->if_flags = (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
13321    ifp->if_ioctl = bxe_ioctl;
13322    ifp->if_start = bxe_tx_start;
13323#if __FreeBSD_version >= 800000
13324    ifp->if_transmit = bxe_tx_mq_start;
13325    ifp->if_qflush = bxe_mq_flush;
13326#endif
13327#ifdef FreeBSD8_0
13328    ifp->if_timer = 0;
13329#endif
13330    ifp->if_init = bxe_init;
13331    ifp->if_mtu = sc->mtu;
13332    ifp->if_hwassist = (CSUM_IP       |
13333                        CSUM_TCP      |
13334                        CSUM_UDP      |
13335                        CSUM_TSO      |
13336                        CSUM_TCP_IPV6 |
13337                        CSUM_UDP_IPV6);
13338    ifp->if_capabilities =
13339#if __FreeBSD_version < 700000
13340        (IFCAP_VLAN_MTU       |
13341         IFCAP_VLAN_HWTAGGING |
13342         IFCAP_HWCSUM         |
13343         IFCAP_JUMBO_MTU      |
13344         IFCAP_LRO);
13345#else
13346        (IFCAP_VLAN_MTU       |
13347         IFCAP_VLAN_HWTAGGING |
13348         IFCAP_VLAN_HWTSO     |
13349         IFCAP_VLAN_HWFILTER  |
13350         IFCAP_VLAN_HWCSUM    |
13351         IFCAP_HWCSUM         |
13352         IFCAP_JUMBO_MTU      |
13353         IFCAP_LRO            |
13354         IFCAP_TSO4           |
13355         IFCAP_TSO6           |
13356         IFCAP_WOL_MAGIC);
13357#endif
13358    ifp->if_capenable = ifp->if_capabilities;
13359    ifp->if_capenable &= ~IFCAP_WOL_MAGIC; /* XXX not yet... */
13360#if __FreeBSD_version < 1000025
13361    ifp->if_baudrate = 1000000000;
13362#else
13363    if_initbaudrate(ifp, IF_Gbps(10));
13364#endif
13365    ifp->if_snd.ifq_drv_maxlen = sc->tx_ring_size;
13366
13367    IFQ_SET_MAXLEN(&ifp->if_snd, ifp->if_snd.ifq_drv_maxlen);
13368    IFQ_SET_READY(&ifp->if_snd);
13369
13370    sc->ifnet = ifp;
13371
13372    /* attach to the Ethernet interface list */
13373    ether_ifattach(ifp, sc->link_params.mac_addr);
13374
13375    return (0);
13376}
13377
13378static void
13379bxe_deallocate_bars(struct bxe_softc *sc)
13380{
13381    int i;
13382
13383    for (i = 0; i < MAX_BARS; i++) {
13384        if (sc->bar[i].resource != NULL) {
13385            bus_release_resource(sc->dev,
13386                                 SYS_RES_MEMORY,
13387                                 sc->bar[i].rid,
13388                                 sc->bar[i].resource);
13389            BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
13390                  i, PCIR_BAR(i));
13391        }
13392    }
13393}
13394
13395static int
13396bxe_allocate_bars(struct bxe_softc *sc)
13397{
13398    u_int flags;
13399    int i;
13400
13401    memset(sc->bar, 0, sizeof(sc->bar));
13402
13403    for (i = 0; i < MAX_BARS; i++) {
13404
13405        /* memory resources reside at BARs 0, 2, 4 */
13406        /* Run `pciconf -lb` to see mappings */
13407        if ((i != 0) && (i != 2) && (i != 4)) {
13408            continue;
13409        }
13410
13411        sc->bar[i].rid = PCIR_BAR(i);
13412
13413        flags = RF_ACTIVE;
13414        if (i == 0) {
13415            flags |= RF_SHAREABLE;
13416        }
13417
13418        if ((sc->bar[i].resource =
13419             bus_alloc_resource_any(sc->dev,
13420                                    SYS_RES_MEMORY,
13421                                    &sc->bar[i].rid,
13422                                    flags)) == NULL) {
13423#if 0
13424            /* BAR4 doesn't exist for E1 */
13425            BLOGE(sc, "PCI BAR%d [%02x] memory allocation failed\n",
13426                  i, PCIR_BAR(i));
13427#endif
13428            return (0);
13429        }
13430
13431        sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
13432        sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
13433        sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
13434
13435        BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%ld) -> %p\n",
13436              i, PCIR_BAR(i),
13437              (void *)rman_get_start(sc->bar[i].resource),
13438              (void *)rman_get_end(sc->bar[i].resource),
13439              rman_get_size(sc->bar[i].resource),
13440              (void *)sc->bar[i].kva);
13441    }
13442
13443    return (0);
13444}
13445
13446static void
13447bxe_get_function_num(struct bxe_softc *sc)
13448{
13449    uint32_t val = 0;
13450
13451    /*
13452     * Read the ME register to get the function number. The ME register
13453     * holds the relative-function number and absolute-function number. The
13454     * absolute-function number appears only in E2 and above. Before that
13455     * these bits always contained zero, therefore we cannot blindly use them.
13456     */
13457
13458    val = REG_RD(sc, BAR_ME_REGISTER);
13459
13460    sc->pfunc_rel =
13461        (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
13462    sc->path_id =
13463        (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
13464
13465    if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13466        sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
13467    } else {
13468        sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
13469    }
13470
13471    BLOGD(sc, DBG_LOAD,
13472          "Relative function %d, Absolute function %d, Path %d\n",
13473          sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
13474}
13475
13476static uint32_t
13477bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
13478{
13479    uint32_t shmem2_size;
13480    uint32_t offset;
13481    uint32_t mf_cfg_offset_value;
13482
13483    /* Non 57712 */
13484    offset = (SHMEM_RD(sc, func_mb) +
13485              (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
13486
13487    /* 57712 plus */
13488    if (sc->devinfo.shmem2_base != 0) {
13489        shmem2_size = SHMEM2_RD(sc, size);
13490        if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
13491            mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
13492            if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
13493                offset = mf_cfg_offset_value;
13494            }
13495        }
13496    }
13497
13498    return (offset);
13499}
13500
13501static uint32_t
13502bxe_pcie_capability_read(struct bxe_softc *sc,
13503                         int    reg,
13504                         int    width)
13505{
13506    int pcie_reg;
13507
13508    /* ensure PCIe capability is enabled */
13509    if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
13510        if (pcie_reg != 0) {
13511            BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
13512            return (pci_read_config(sc->dev, (pcie_reg + reg), width));
13513        }
13514    }
13515
13516    BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
13517
13518    return (0);
13519}
13520
13521static uint8_t
13522bxe_is_pcie_pending(struct bxe_softc *sc)
13523{
13524    return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
13525            PCIM_EXP_STA_TRANSACTION_PND);
13526}
13527
13528/*
13529 * Walk the PCI capabiites list for the device to find what features are
13530 * supported. These capabilites may be enabled/disabled by firmware so it's
13531 * best to walk the list rather than make assumptions.
13532 */
13533static void
13534bxe_probe_pci_caps(struct bxe_softc *sc)
13535{
13536    uint16_t link_status;
13537    int reg;
13538
13539    /* check if PCI Power Management is enabled */
13540    if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
13541        if (reg != 0) {
13542            BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
13543
13544            sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
13545            sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
13546        }
13547    }
13548
13549    link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
13550
13551    /* handle PCIe 2.0 workarounds for 57710 */
13552    if (CHIP_IS_E1(sc)) {
13553        /* workaround for 57710 errata E4_57710_27462 */
13554        sc->devinfo.pcie_link_speed =
13555            (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
13556
13557        /* workaround for 57710 errata E4_57710_27488 */
13558        sc->devinfo.pcie_link_width =
13559            ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13560        if (sc->devinfo.pcie_link_speed > 1) {
13561            sc->devinfo.pcie_link_width =
13562                ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
13563        }
13564    } else {
13565        sc->devinfo.pcie_link_speed =
13566            (link_status & PCIM_LINK_STA_SPEED);
13567        sc->devinfo.pcie_link_width =
13568            ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13569    }
13570
13571    BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
13572          sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
13573
13574    sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
13575    sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
13576
13577    /* check if MSI capability is enabled */
13578    if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
13579        if (reg != 0) {
13580            BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13581
13582            sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13583            sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13584        }
13585    }
13586
13587    /* check if MSI-X capability is enabled */
13588    if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13589        if (reg != 0) {
13590            BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13591
13592            sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13593            sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13594        }
13595    }
13596}
13597
13598static int
13599bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13600{
13601    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13602    uint32_t val;
13603
13604    /* get the outer vlan if we're in switch-dependent mode */
13605
13606    val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13607    mf_info->ext_id = (uint16_t)val;
13608
13609    mf_info->multi_vnics_mode = 1;
13610
13611    if (!VALID_OVLAN(mf_info->ext_id)) {
13612        BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13613        return (1);
13614    }
13615
13616    /* get the capabilities */
13617    if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13618        FUNC_MF_CFG_PROTOCOL_ISCSI) {
13619        mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13620    } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13621               FUNC_MF_CFG_PROTOCOL_FCOE) {
13622        mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13623    } else {
13624        mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13625    }
13626
13627    mf_info->vnics_per_port =
13628        (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13629
13630    return (0);
13631}
13632
13633static uint32_t
13634bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13635{
13636    uint32_t retval = 0;
13637    uint32_t val;
13638
13639    val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13640
13641    if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13642        if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13643            retval |= MF_PROTO_SUPPORT_ETHERNET;
13644        }
13645        if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13646            retval |= MF_PROTO_SUPPORT_ISCSI;
13647        }
13648        if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13649            retval |= MF_PROTO_SUPPORT_FCOE;
13650        }
13651    }
13652
13653    return (retval);
13654}
13655
13656static int
13657bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13658{
13659    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13660    uint32_t val;
13661
13662    /*
13663     * There is no outer vlan if we're in switch-independent mode.
13664     * If the mac is valid then assume multi-function.
13665     */
13666
13667    val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13668
13669    mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13670
13671    mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13672
13673    mf_info->vnics_per_port =
13674        (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13675
13676    return (0);
13677}
13678
13679static int
13680bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13681{
13682    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13683    uint32_t e1hov_tag;
13684    uint32_t func_config;
13685    uint32_t niv_config;
13686
13687    mf_info->multi_vnics_mode = 1;
13688
13689    e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13690    func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13691    niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13692
13693    mf_info->ext_id =
13694        (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13695                   FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13696
13697    mf_info->default_vlan =
13698        (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13699                   FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13700
13701    mf_info->niv_allowed_priorities =
13702        (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13703                  FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13704
13705    mf_info->niv_default_cos =
13706        (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13707                  FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13708
13709    mf_info->afex_vlan_mode =
13710        ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13711         FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13712
13713    mf_info->niv_mba_enabled =
13714        ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13715         FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13716
13717    mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13718
13719    mf_info->vnics_per_port =
13720        (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13721
13722    return (0);
13723}
13724
13725static int
13726bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13727{
13728    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13729    uint32_t mf_cfg1;
13730    uint32_t mf_cfg2;
13731    uint32_t ovlan1;
13732    uint32_t ovlan2;
13733    uint8_t i, j;
13734
13735    BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13736          SC_PORT(sc));
13737    BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13738          mf_info->mf_config[SC_VN(sc)]);
13739    BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13740          mf_info->multi_vnics_mode);
13741    BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13742          mf_info->vnics_per_port);
13743    BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13744          mf_info->ext_id);
13745    BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13746          mf_info->min_bw[0], mf_info->min_bw[1],
13747          mf_info->min_bw[2], mf_info->min_bw[3]);
13748    BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13749          mf_info->max_bw[0], mf_info->max_bw[1],
13750          mf_info->max_bw[2], mf_info->max_bw[3]);
13751    BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13752          sc->mac_addr_str);
13753
13754    /* various MF mode sanity checks... */
13755
13756    if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13757        BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13758              SC_PORT(sc));
13759        return (1);
13760    }
13761
13762    if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13763        BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13764              mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13765        return (1);
13766    }
13767
13768    if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13769        /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13770        if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13771            BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13772                  SC_VN(sc), OVLAN(sc));
13773            return (1);
13774        }
13775
13776        if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13777            BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13778                  mf_info->multi_vnics_mode, OVLAN(sc));
13779            return (1);
13780        }
13781
13782        /*
13783         * Verify all functions are either MF or SF mode. If MF, make sure
13784         * sure that all non-hidden functions have a valid ovlan. If SF,
13785         * make sure that all non-hidden functions have an invalid ovlan.
13786         */
13787        FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13788            mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13789            ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13790            if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13791                (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13792                 ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13793                BLOGE(sc, "mf_mode=SD function %d MF config "
13794                          "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13795                      i, mf_info->multi_vnics_mode, ovlan1);
13796                return (1);
13797            }
13798        }
13799
13800        /* Verify all funcs on the same port each have a different ovlan. */
13801        FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13802            mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13803            ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13804            /* iterate from the next function on the port to the max func */
13805            for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13806                mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13807                ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13808                if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13809                    VALID_OVLAN(ovlan1) &&
13810                    !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13811                    VALID_OVLAN(ovlan2) &&
13812                    (ovlan1 == ovlan2)) {
13813                    BLOGE(sc, "mf_mode=SD functions %d and %d "
13814                              "have the same ovlan (%d)\n",
13815                          i, j, ovlan1);
13816                    return (1);
13817                }
13818            }
13819        }
13820    } /* MULTI_FUNCTION_SD */
13821
13822    return (0);
13823}
13824
13825static int
13826bxe_get_mf_cfg_info(struct bxe_softc *sc)
13827{
13828    struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13829    uint32_t val, mac_upper;
13830    uint8_t i, vnic;
13831
13832    /* initialize mf_info defaults */
13833    mf_info->vnics_per_port   = 1;
13834    mf_info->multi_vnics_mode = FALSE;
13835    mf_info->path_has_ovlan   = FALSE;
13836    mf_info->mf_mode          = SINGLE_FUNCTION;
13837
13838    if (!CHIP_IS_MF_CAP(sc)) {
13839        return (0);
13840    }
13841
13842    if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13843        BLOGE(sc, "Invalid mf_cfg_base!\n");
13844        return (1);
13845    }
13846
13847    /* get the MF mode (switch dependent / independent / single-function) */
13848
13849    val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13850
13851    switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13852    {
13853    case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13854
13855        mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13856
13857        /* check for legal upper mac bytes */
13858        if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13859            mf_info->mf_mode = MULTI_FUNCTION_SI;
13860        } else {
13861            BLOGE(sc, "Invalid config for Switch Independent mode\n");
13862        }
13863
13864        break;
13865
13866    case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13867    case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13868
13869        /* get outer vlan configuration */
13870        val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13871
13872        if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13873            FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13874            mf_info->mf_mode = MULTI_FUNCTION_SD;
13875        } else {
13876            BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13877        }
13878
13879        break;
13880
13881    case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13882
13883        /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13884        return (0);
13885
13886    case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13887
13888        /*
13889         * Mark MF mode as NIV if MCP version includes NPAR-SD support
13890         * and the MAC address is valid.
13891         */
13892        mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13893
13894        if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13895            (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13896            mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13897        } else {
13898            BLOGE(sc, "Invalid config for AFEX mode\n");
13899        }
13900
13901        break;
13902
13903    default:
13904
13905        BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13906              (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13907
13908        return (1);
13909    }
13910
13911    /* set path mf_mode (which could be different than function mf_mode) */
13912    if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13913        mf_info->path_has_ovlan = TRUE;
13914    } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13915        /*
13916         * Decide on path multi vnics mode. If we're not in MF mode and in
13917         * 4-port mode, this is good enough to check vnic-0 of the other port
13918         * on the same path
13919         */
13920        if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13921            uint8_t other_port = !(PORT_ID(sc) & 1);
13922            uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13923
13924            val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13925
13926            mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13927        }
13928    }
13929
13930    if (mf_info->mf_mode == SINGLE_FUNCTION) {
13931        /* invalid MF config */
13932        if (SC_VN(sc) >= 1) {
13933            BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13934            return (1);
13935        }
13936
13937        return (0);
13938    }
13939
13940    /* get the MF configuration */
13941    mf_info->mf_config[SC_VN(sc)] =
13942        MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13943
13944    switch(mf_info->mf_mode)
13945    {
13946    case MULTI_FUNCTION_SD:
13947
13948        bxe_get_shmem_mf_cfg_info_sd(sc);
13949        break;
13950
13951    case MULTI_FUNCTION_SI:
13952
13953        bxe_get_shmem_mf_cfg_info_si(sc);
13954        break;
13955
13956    case MULTI_FUNCTION_AFEX:
13957
13958        bxe_get_shmem_mf_cfg_info_niv(sc);
13959        break;
13960
13961    default:
13962
13963        BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13964              mf_info->mf_mode);
13965        return (1);
13966    }
13967
13968    /* get the congestion management parameters */
13969
13970    vnic = 0;
13971    FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13972        /* get min/max bw */
13973        val = MFCFG_RD(sc, func_mf_config[i].config);
13974        mf_info->min_bw[vnic] =
13975            ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13976        mf_info->max_bw[vnic] =
13977            ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13978        vnic++;
13979    }
13980
13981    return (bxe_check_valid_mf_cfg(sc));
13982}
13983
13984static int
13985bxe_get_shmem_info(struct bxe_softc *sc)
13986{
13987    int port;
13988    uint32_t mac_hi, mac_lo, val;
13989
13990    port = SC_PORT(sc);
13991    mac_hi = mac_lo = 0;
13992
13993    sc->link_params.sc   = sc;
13994    sc->link_params.port = port;
13995
13996    /* get the hardware config info */
13997    sc->devinfo.hw_config =
13998        SHMEM_RD(sc, dev_info.shared_hw_config.config);
13999    sc->devinfo.hw_config2 =
14000        SHMEM_RD(sc, dev_info.shared_hw_config.config2);
14001
14002    sc->link_params.hw_led_mode =
14003        ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
14004         SHARED_HW_CFG_LED_MODE_SHIFT);
14005
14006    /* get the port feature config */
14007    sc->port.config =
14008        SHMEM_RD(sc, dev_info.port_feature_config[port].config),
14009
14010    /* get the link params */
14011    sc->link_params.speed_cap_mask[0] =
14012        SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
14013    sc->link_params.speed_cap_mask[1] =
14014        SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
14015
14016    /* get the lane config */
14017    sc->link_params.lane_config =
14018        SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
14019
14020    /* get the link config */
14021    val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
14022    sc->port.link_config[ELINK_INT_PHY] = val;
14023    sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
14024    sc->port.link_config[ELINK_EXT_PHY1] =
14025        SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
14026
14027    /* get the override preemphasis flag and enable it or turn it off */
14028    val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
14029    if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
14030        sc->link_params.feature_config_flags |=
14031            ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
14032    } else {
14033        sc->link_params.feature_config_flags &=
14034            ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
14035    }
14036
14037    /* get the initial value of the link params */
14038    sc->link_params.multi_phy_config =
14039        SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
14040
14041    /* get external phy info */
14042    sc->port.ext_phy_config =
14043        SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
14044
14045    /* get the multifunction configuration */
14046    bxe_get_mf_cfg_info(sc);
14047
14048    /* get the mac address */
14049    if (IS_MF(sc)) {
14050        mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
14051        mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
14052    } else {
14053        mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
14054        mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
14055    }
14056
14057    if ((mac_lo == 0) && (mac_hi == 0)) {
14058        *sc->mac_addr_str = 0;
14059        BLOGE(sc, "No Ethernet address programmed!\n");
14060    } else {
14061        sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
14062        sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
14063        sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
14064        sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
14065        sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
14066        sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
14067        snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
14068                 "%02x:%02x:%02x:%02x:%02x:%02x",
14069                 sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
14070                 sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
14071                 sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
14072        BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
14073    }
14074
14075#if 0
14076    if (!IS_MF(sc) &&
14077        ((sc->port.config & PORT_FEAT_CFG_STORAGE_PERSONALITY_MASK) ==
14078         PORT_FEAT_CFG_STORAGE_PERSONALITY_FCOE)) {
14079        sc->flags |= BXE_NO_ISCSI;
14080    }
14081    if (!IS_MF(sc) &&
14082        ((sc->port.config & PORT_FEAT_CFG_STORAGE_PERSONALITY_MASK) ==
14083         PORT_FEAT_CFG_STORAGE_PERSONALITY_ISCSI)) {
14084        sc->flags |= BXE_NO_FCOE_FLAG;
14085    }
14086#endif
14087
14088    return (0);
14089}
14090
14091static void
14092bxe_get_tunable_params(struct bxe_softc *sc)
14093{
14094    /* sanity checks */
14095
14096    if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
14097        (bxe_interrupt_mode != INTR_MODE_MSI)  &&
14098        (bxe_interrupt_mode != INTR_MODE_MSIX)) {
14099        BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
14100        bxe_interrupt_mode = INTR_MODE_MSIX;
14101    }
14102
14103    if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
14104        BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
14105        bxe_queue_count = 0;
14106    }
14107
14108    if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
14109        if (bxe_max_rx_bufs == 0) {
14110            bxe_max_rx_bufs = RX_BD_USABLE;
14111        } else {
14112            BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
14113            bxe_max_rx_bufs = 2048;
14114        }
14115    }
14116
14117    if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
14118        BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
14119        bxe_hc_rx_ticks = 25;
14120    }
14121
14122    if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
14123        BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
14124        bxe_hc_tx_ticks = 50;
14125    }
14126
14127    if (bxe_max_aggregation_size == 0) {
14128        bxe_max_aggregation_size = TPA_AGG_SIZE;
14129    }
14130
14131    if (bxe_max_aggregation_size > 0xffff) {
14132        BLOGW(sc, "invalid max_aggregation_size (%d)\n",
14133              bxe_max_aggregation_size);
14134        bxe_max_aggregation_size = TPA_AGG_SIZE;
14135    }
14136
14137    if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
14138        BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
14139        bxe_mrrs = -1;
14140    }
14141
14142    if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
14143        BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
14144        bxe_autogreeen = 0;
14145    }
14146
14147    if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
14148        BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
14149        bxe_udp_rss = 0;
14150    }
14151
14152    /* pull in user settings */
14153
14154    sc->interrupt_mode       = bxe_interrupt_mode;
14155    sc->max_rx_bufs          = bxe_max_rx_bufs;
14156    sc->hc_rx_ticks          = bxe_hc_rx_ticks;
14157    sc->hc_tx_ticks          = bxe_hc_tx_ticks;
14158    sc->max_aggregation_size = bxe_max_aggregation_size;
14159    sc->mrrs                 = bxe_mrrs;
14160    sc->autogreeen           = bxe_autogreeen;
14161    sc->udp_rss              = bxe_udp_rss;
14162
14163    if (bxe_interrupt_mode == INTR_MODE_INTX) {
14164        sc->num_queues = 1;
14165    } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
14166        sc->num_queues =
14167            min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
14168                MAX_RSS_CHAINS);
14169        if (sc->num_queues > mp_ncpus) {
14170            sc->num_queues = mp_ncpus;
14171        }
14172    }
14173
14174    BLOGD(sc, DBG_LOAD,
14175          "User Config: "
14176          "debug=0x%x "
14177          "interrupt_mode=%d "
14178          "queue_count=%d "
14179          "hc_rx_ticks=%d "
14180          "hc_tx_ticks=%d "
14181          "rx_budget=%d "
14182          "max_aggregation_size=%d "
14183          "mrrs=%d "
14184          "autogreeen=%d "
14185          "udp_rss=%d\n",
14186          bxe_debug,
14187          sc->interrupt_mode,
14188          sc->num_queues,
14189          sc->hc_rx_ticks,
14190          sc->hc_tx_ticks,
14191          bxe_rx_budget,
14192          sc->max_aggregation_size,
14193          sc->mrrs,
14194          sc->autogreeen,
14195          sc->udp_rss);
14196}
14197
14198static void
14199bxe_media_detect(struct bxe_softc *sc)
14200{
14201    uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
14202    switch (sc->link_params.phy[phy_idx].media_type) {
14203    case ELINK_ETH_PHY_SFPP_10G_FIBER:
14204    case ELINK_ETH_PHY_SFP_1G_FIBER:
14205    case ELINK_ETH_PHY_XFP_FIBER:
14206    case ELINK_ETH_PHY_KR:
14207    case ELINK_ETH_PHY_CX4:
14208        BLOGI(sc, "Found 10GBase-CX4 media.\n");
14209        sc->media = IFM_10G_CX4;
14210        break;
14211    case ELINK_ETH_PHY_DA_TWINAX:
14212        BLOGI(sc, "Found 10Gb Twinax media.\n");
14213        sc->media = IFM_10G_TWINAX;
14214        break;
14215    case ELINK_ETH_PHY_BASE_T:
14216        BLOGI(sc, "Found 10GBase-T media.\n");
14217        sc->media = IFM_10G_T;
14218        break;
14219    case ELINK_ETH_PHY_NOT_PRESENT:
14220        BLOGI(sc, "Media not present.\n");
14221        sc->media = 0;
14222        break;
14223    case ELINK_ETH_PHY_UNSPECIFIED:
14224    default:
14225        BLOGI(sc, "Unknown media!\n");
14226        sc->media = 0;
14227        break;
14228    }
14229}
14230
14231#define GET_FIELD(value, fname)                     \
14232    (((value) & (fname##_MASK)) >> (fname##_SHIFT))
14233#define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
14234#define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
14235
14236static int
14237bxe_get_igu_cam_info(struct bxe_softc *sc)
14238{
14239    int pfid = SC_FUNC(sc);
14240    int igu_sb_id;
14241    uint32_t val;
14242    uint8_t fid, igu_sb_cnt = 0;
14243
14244    sc->igu_base_sb = 0xff;
14245
14246    if (CHIP_INT_MODE_IS_BC(sc)) {
14247        int vn = SC_VN(sc);
14248        igu_sb_cnt = sc->igu_sb_cnt;
14249        sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
14250                           FP_SB_MAX_E1x);
14251        sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
14252                          (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
14253        return (0);
14254    }
14255
14256    /* IGU in normal mode - read CAM */
14257    for (igu_sb_id = 0;
14258         igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
14259         igu_sb_id++) {
14260        val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
14261        if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
14262            continue;
14263        }
14264        fid = IGU_FID(val);
14265        if ((fid & IGU_FID_ENCODE_IS_PF)) {
14266            if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
14267                continue;
14268            }
14269            if (IGU_VEC(val) == 0) {
14270                /* default status block */
14271                sc->igu_dsb_id = igu_sb_id;
14272            } else {
14273                if (sc->igu_base_sb == 0xff) {
14274                    sc->igu_base_sb = igu_sb_id;
14275                }
14276                igu_sb_cnt++;
14277            }
14278        }
14279    }
14280
14281    /*
14282     * Due to new PF resource allocation by MFW T7.4 and above, it's optional
14283     * that number of CAM entries will not be equal to the value advertised in
14284     * PCI. Driver should use the minimal value of both as the actual status
14285     * block count
14286     */
14287    sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
14288
14289    if (igu_sb_cnt == 0) {
14290        BLOGE(sc, "CAM configuration error\n");
14291        return (-1);
14292    }
14293
14294    return (0);
14295}
14296
14297/*
14298 * Gather various information from the device config space, the device itself,
14299 * shmem, and the user input.
14300 */
14301static int
14302bxe_get_device_info(struct bxe_softc *sc)
14303{
14304    uint32_t val;
14305    int rc;
14306
14307    /* Get the data for the device */
14308    sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
14309    sc->devinfo.device_id    = pci_get_device(sc->dev);
14310    sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
14311    sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
14312
14313    /* get the chip revision (chip metal comes from pci config space) */
14314    sc->devinfo.chip_id     =
14315    sc->link_params.chip_id =
14316        (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
14317         ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
14318         (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
14319         ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
14320
14321    /* force 57811 according to MISC register */
14322    if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
14323        if (CHIP_IS_57810(sc)) {
14324            sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
14325                                   (sc->devinfo.chip_id & 0x0000ffff));
14326        } else if (CHIP_IS_57810_MF(sc)) {
14327            sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
14328                                   (sc->devinfo.chip_id & 0x0000ffff));
14329        }
14330        sc->devinfo.chip_id |= 0x1;
14331    }
14332
14333    BLOGD(sc, DBG_LOAD,
14334          "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
14335          sc->devinfo.chip_id,
14336          ((sc->devinfo.chip_id >> 16) & 0xffff),
14337          ((sc->devinfo.chip_id >> 12) & 0xf),
14338          ((sc->devinfo.chip_id >>  4) & 0xff),
14339          ((sc->devinfo.chip_id >>  0) & 0xf));
14340
14341    val = (REG_RD(sc, 0x2874) & 0x55);
14342    if ((sc->devinfo.chip_id & 0x1) ||
14343        (CHIP_IS_E1(sc) && val) ||
14344        (CHIP_IS_E1H(sc) && (val == 0x55))) {
14345        sc->flags |= BXE_ONE_PORT_FLAG;
14346        BLOGD(sc, DBG_LOAD, "single port device\n");
14347    }
14348
14349    /* set the doorbell size */
14350    sc->doorbell_size = (1 << BXE_DB_SHIFT);
14351
14352    /* determine whether the device is in 2 port or 4 port mode */
14353    sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
14354    if (CHIP_IS_E2E3(sc)) {
14355        /*
14356         * Read port4mode_en_ovwr[0]:
14357         *   If 1, four port mode is in port4mode_en_ovwr[1].
14358         *   If 0, four port mode is in port4mode_en[0].
14359         */
14360        val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
14361        if (val & 1) {
14362            val = ((val >> 1) & 1);
14363        } else {
14364            val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
14365        }
14366
14367        sc->devinfo.chip_port_mode =
14368            (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
14369
14370        BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
14371    }
14372
14373    /* get the function and path info for the device */
14374    bxe_get_function_num(sc);
14375
14376    /* get the shared memory base address */
14377    sc->devinfo.shmem_base     =
14378    sc->link_params.shmem_base =
14379        REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
14380    sc->devinfo.shmem2_base =
14381        REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
14382                                  MISC_REG_GENERIC_CR_0));
14383
14384    BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
14385          sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
14386
14387    if (!sc->devinfo.shmem_base) {
14388        /* this should ONLY prevent upcoming shmem reads */
14389        BLOGI(sc, "MCP not active\n");
14390        sc->flags |= BXE_NO_MCP_FLAG;
14391        return (0);
14392    }
14393
14394    /* make sure the shared memory contents are valid */
14395    val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
14396    if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
14397        (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
14398        BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
14399        return (0);
14400    }
14401    BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
14402
14403    /* get the bootcode version */
14404    sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
14405    snprintf(sc->devinfo.bc_ver_str,
14406             sizeof(sc->devinfo.bc_ver_str),
14407             "%d.%d.%d",
14408             ((sc->devinfo.bc_ver >> 24) & 0xff),
14409             ((sc->devinfo.bc_ver >> 16) & 0xff),
14410             ((sc->devinfo.bc_ver >>  8) & 0xff));
14411    BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
14412
14413    /* get the bootcode shmem address */
14414    sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
14415    BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
14416
14417    /* clean indirect addresses as they're not used */
14418    pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
14419    if (IS_PF(sc)) {
14420        REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
14421        REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
14422        REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
14423        REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
14424        if (CHIP_IS_E1x(sc)) {
14425            REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
14426            REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
14427            REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
14428            REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
14429        }
14430
14431        /*
14432         * Enable internal target-read (in case we are probed after PF
14433         * FLR). Must be done prior to any BAR read access. Only for
14434         * 57712 and up
14435         */
14436        if (!CHIP_IS_E1x(sc)) {
14437            REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
14438        }
14439    }
14440
14441    /* get the nvram size */
14442    val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
14443    sc->devinfo.flash_size =
14444        (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
14445    BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
14446
14447    /* get PCI capabilites */
14448    bxe_probe_pci_caps(sc);
14449
14450    bxe_set_power_state(sc, PCI_PM_D0);
14451
14452    /* get various configuration parameters from shmem */
14453    bxe_get_shmem_info(sc);
14454
14455    if (sc->devinfo.pcie_msix_cap_reg != 0) {
14456        val = pci_read_config(sc->dev,
14457                              (sc->devinfo.pcie_msix_cap_reg +
14458                               PCIR_MSIX_CTRL),
14459                              2);
14460        sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
14461    } else {
14462        sc->igu_sb_cnt = 1;
14463    }
14464
14465    sc->igu_base_addr = BAR_IGU_INTMEM;
14466
14467    /* initialize IGU parameters */
14468    if (CHIP_IS_E1x(sc)) {
14469        sc->devinfo.int_block = INT_BLOCK_HC;
14470        sc->igu_dsb_id = DEF_SB_IGU_ID;
14471        sc->igu_base_sb = 0;
14472    } else {
14473        sc->devinfo.int_block = INT_BLOCK_IGU;
14474
14475        /* do not allow device reset during IGU info preocessing */
14476        bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14477
14478        val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
14479
14480        if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
14481            int tout = 5000;
14482
14483            BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
14484
14485            val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
14486            REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
14487            REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
14488
14489            while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14490                tout--;
14491                DELAY(1000);
14492            }
14493
14494            if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14495                BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
14496                bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14497                return (-1);
14498            }
14499        }
14500
14501        if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
14502            BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
14503            sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
14504        } else {
14505            BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
14506        }
14507
14508        rc = bxe_get_igu_cam_info(sc);
14509
14510        bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14511
14512        if (rc) {
14513            return (rc);
14514        }
14515    }
14516
14517    /*
14518     * Get base FW non-default (fast path) status block ID. This value is
14519     * used to initialize the fw_sb_id saved on the fp/queue structure to
14520     * determine the id used by the FW.
14521     */
14522    if (CHIP_IS_E1x(sc)) {
14523        sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
14524    } else {
14525        /*
14526         * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
14527         * the same queue are indicated on the same IGU SB). So we prefer
14528         * FW and IGU SBs to be the same value.
14529         */
14530        sc->base_fw_ndsb = sc->igu_base_sb;
14531    }
14532
14533    BLOGD(sc, DBG_LOAD,
14534          "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
14535          sc->igu_dsb_id, sc->igu_base_sb,
14536          sc->igu_sb_cnt, sc->base_fw_ndsb);
14537
14538    elink_phy_probe(&sc->link_params);
14539
14540    return (0);
14541}
14542
14543static void
14544bxe_link_settings_supported(struct bxe_softc *sc,
14545                            uint32_t         switch_cfg)
14546{
14547    uint32_t cfg_size = 0;
14548    uint32_t idx;
14549    uint8_t port = SC_PORT(sc);
14550
14551    /* aggregation of supported attributes of all external phys */
14552    sc->port.supported[0] = 0;
14553    sc->port.supported[1] = 0;
14554
14555    switch (sc->link_params.num_phys) {
14556    case 1:
14557        sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
14558        cfg_size = 1;
14559        break;
14560    case 2:
14561        sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
14562        cfg_size = 1;
14563        break;
14564    case 3:
14565        if (sc->link_params.multi_phy_config &
14566            PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
14567            sc->port.supported[1] =
14568                sc->link_params.phy[ELINK_EXT_PHY1].supported;
14569            sc->port.supported[0] =
14570                sc->link_params.phy[ELINK_EXT_PHY2].supported;
14571        } else {
14572            sc->port.supported[0] =
14573                sc->link_params.phy[ELINK_EXT_PHY1].supported;
14574            sc->port.supported[1] =
14575                sc->link_params.phy[ELINK_EXT_PHY2].supported;
14576        }
14577        cfg_size = 2;
14578        break;
14579    }
14580
14581    if (!(sc->port.supported[0] || sc->port.supported[1])) {
14582        BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14583              SHMEM_RD(sc,
14584                       dev_info.port_hw_config[port].external_phy_config),
14585              SHMEM_RD(sc,
14586                       dev_info.port_hw_config[port].external_phy_config2));
14587        return;
14588    }
14589
14590    if (CHIP_IS_E3(sc))
14591        sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14592    else {
14593        switch (switch_cfg) {
14594        case ELINK_SWITCH_CFG_1G:
14595            sc->port.phy_addr =
14596                REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14597            break;
14598        case ELINK_SWITCH_CFG_10G:
14599            sc->port.phy_addr =
14600                REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14601            break;
14602        default:
14603            BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14604                  sc->port.link_config[0]);
14605            return;
14606        }
14607    }
14608
14609    BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14610
14611    /* mask what we support according to speed_cap_mask per configuration */
14612    for (idx = 0; idx < cfg_size; idx++) {
14613        if (!(sc->link_params.speed_cap_mask[idx] &
14614              PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14615            sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14616        }
14617
14618        if (!(sc->link_params.speed_cap_mask[idx] &
14619              PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14620            sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14621        }
14622
14623        if (!(sc->link_params.speed_cap_mask[idx] &
14624              PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14625            sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14626        }
14627
14628        if (!(sc->link_params.speed_cap_mask[idx] &
14629              PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14630            sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14631        }
14632
14633        if (!(sc->link_params.speed_cap_mask[idx] &
14634              PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14635            sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14636        }
14637
14638        if (!(sc->link_params.speed_cap_mask[idx] &
14639              PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14640            sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14641        }
14642
14643        if (!(sc->link_params.speed_cap_mask[idx] &
14644              PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14645            sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14646        }
14647
14648        if (!(sc->link_params.speed_cap_mask[idx] &
14649              PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14650            sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14651        }
14652    }
14653
14654    BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14655          sc->port.supported[0], sc->port.supported[1]);
14656}
14657
14658static void
14659bxe_link_settings_requested(struct bxe_softc *sc)
14660{
14661    uint32_t link_config;
14662    uint32_t idx;
14663    uint32_t cfg_size = 0;
14664
14665    sc->port.advertising[0] = 0;
14666    sc->port.advertising[1] = 0;
14667
14668    switch (sc->link_params.num_phys) {
14669    case 1:
14670    case 2:
14671        cfg_size = 1;
14672        break;
14673    case 3:
14674        cfg_size = 2;
14675        break;
14676    }
14677
14678    for (idx = 0; idx < cfg_size; idx++) {
14679        sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14680        link_config = sc->port.link_config[idx];
14681
14682        switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14683        case PORT_FEATURE_LINK_SPEED_AUTO:
14684            if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14685                sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14686                sc->port.advertising[idx] |= sc->port.supported[idx];
14687                if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14688                    PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14689                    sc->port.advertising[idx] |=
14690                        (ELINK_SUPPORTED_100baseT_Half |
14691                         ELINK_SUPPORTED_100baseT_Full);
14692            } else {
14693                /* force 10G, no AN */
14694                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14695                sc->port.advertising[idx] |=
14696                    (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14697                continue;
14698            }
14699            break;
14700
14701        case PORT_FEATURE_LINK_SPEED_10M_FULL:
14702            if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14703                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14704                sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14705                                              ADVERTISED_TP);
14706            } else {
14707                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14708                          "speed_cap_mask=0x%08x\n",
14709                      link_config, sc->link_params.speed_cap_mask[idx]);
14710                return;
14711            }
14712            break;
14713
14714        case PORT_FEATURE_LINK_SPEED_10M_HALF:
14715            if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14716                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14717                sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14718                sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14719                                              ADVERTISED_TP);
14720            } else {
14721                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14722                          "speed_cap_mask=0x%08x\n",
14723                      link_config, sc->link_params.speed_cap_mask[idx]);
14724                return;
14725            }
14726            break;
14727
14728        case PORT_FEATURE_LINK_SPEED_100M_FULL:
14729            if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14730                sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14731                sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14732                                              ADVERTISED_TP);
14733            } else {
14734                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14735                          "speed_cap_mask=0x%08x\n",
14736                      link_config, sc->link_params.speed_cap_mask[idx]);
14737                return;
14738            }
14739            break;
14740
14741        case PORT_FEATURE_LINK_SPEED_100M_HALF:
14742            if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14743                sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14744                sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14745                sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14746                                              ADVERTISED_TP);
14747            } else {
14748                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14749                          "speed_cap_mask=0x%08x\n",
14750                      link_config, sc->link_params.speed_cap_mask[idx]);
14751                return;
14752            }
14753            break;
14754
14755        case PORT_FEATURE_LINK_SPEED_1G:
14756            if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14757                sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14758                sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14759                                              ADVERTISED_TP);
14760            } else {
14761                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14762                          "speed_cap_mask=0x%08x\n",
14763                      link_config, sc->link_params.speed_cap_mask[idx]);
14764                return;
14765            }
14766            break;
14767
14768        case PORT_FEATURE_LINK_SPEED_2_5G:
14769            if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14770                sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14771                sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14772                                              ADVERTISED_TP);
14773            } else {
14774                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14775                          "speed_cap_mask=0x%08x\n",
14776                      link_config, sc->link_params.speed_cap_mask[idx]);
14777                return;
14778            }
14779            break;
14780
14781        case PORT_FEATURE_LINK_SPEED_10G_CX4:
14782            if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14783                sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14784                sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14785                                              ADVERTISED_FIBRE);
14786            } else {
14787                BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14788                          "speed_cap_mask=0x%08x\n",
14789                      link_config, sc->link_params.speed_cap_mask[idx]);
14790                return;
14791            }
14792            break;
14793
14794        case PORT_FEATURE_LINK_SPEED_20G:
14795            sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14796            break;
14797
14798        default:
14799            BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14800                      "speed_cap_mask=0x%08x\n",
14801                  link_config, sc->link_params.speed_cap_mask[idx]);
14802            sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14803            sc->port.advertising[idx] = sc->port.supported[idx];
14804            break;
14805        }
14806
14807        sc->link_params.req_flow_ctrl[idx] =
14808            (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14809
14810        if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14811            if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14812                sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14813            } else {
14814                bxe_set_requested_fc(sc);
14815            }
14816        }
14817
14818        BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14819                            "req_flow_ctrl=0x%x advertising=0x%x\n",
14820              sc->link_params.req_line_speed[idx],
14821              sc->link_params.req_duplex[idx],
14822              sc->link_params.req_flow_ctrl[idx],
14823              sc->port.advertising[idx]);
14824    }
14825}
14826
14827static void
14828bxe_get_phy_info(struct bxe_softc *sc)
14829{
14830    uint8_t port = SC_PORT(sc);
14831    uint32_t config = sc->port.config;
14832    uint32_t eee_mode;
14833
14834    /* shmem data already read in bxe_get_shmem_info() */
14835
14836    BLOGD(sc, DBG_LOAD, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14837                        "link_config0=0x%08x\n",
14838               sc->link_params.lane_config,
14839               sc->link_params.speed_cap_mask[0],
14840               sc->port.link_config[0]);
14841
14842    bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14843    bxe_link_settings_requested(sc);
14844
14845    if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14846        sc->link_params.feature_config_flags |=
14847            ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14848    } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14849        sc->link_params.feature_config_flags &=
14850            ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14851    } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14852        sc->link_params.feature_config_flags |=
14853            ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14854    }
14855
14856    /* configure link feature according to nvram value */
14857    eee_mode =
14858        (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14859          PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14860         PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14861    if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14862        sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14863                                    ELINK_EEE_MODE_ENABLE_LPI |
14864                                    ELINK_EEE_MODE_OUTPUT_TIME);
14865    } else {
14866        sc->link_params.eee_mode = 0;
14867    }
14868
14869    /* get the media type */
14870    bxe_media_detect(sc);
14871}
14872
14873static void
14874bxe_get_params(struct bxe_softc *sc)
14875{
14876    /* get user tunable params */
14877    bxe_get_tunable_params(sc);
14878
14879    /* select the RX and TX ring sizes */
14880    sc->tx_ring_size = TX_BD_USABLE;
14881    sc->rx_ring_size = RX_BD_USABLE;
14882
14883    /* XXX disable WoL */
14884    sc->wol = 0;
14885}
14886
14887static void
14888bxe_set_modes_bitmap(struct bxe_softc *sc)
14889{
14890    uint32_t flags = 0;
14891
14892    if (CHIP_REV_IS_FPGA(sc)) {
14893        SET_FLAGS(flags, MODE_FPGA);
14894    } else if (CHIP_REV_IS_EMUL(sc)) {
14895        SET_FLAGS(flags, MODE_EMUL);
14896    } else {
14897        SET_FLAGS(flags, MODE_ASIC);
14898    }
14899
14900    if (CHIP_IS_MODE_4_PORT(sc)) {
14901        SET_FLAGS(flags, MODE_PORT4);
14902    } else {
14903        SET_FLAGS(flags, MODE_PORT2);
14904    }
14905
14906    if (CHIP_IS_E2(sc)) {
14907        SET_FLAGS(flags, MODE_E2);
14908    } else if (CHIP_IS_E3(sc)) {
14909        SET_FLAGS(flags, MODE_E3);
14910        if (CHIP_REV(sc) == CHIP_REV_Ax) {
14911            SET_FLAGS(flags, MODE_E3_A0);
14912        } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14913            SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14914        }
14915    }
14916
14917    if (IS_MF(sc)) {
14918        SET_FLAGS(flags, MODE_MF);
14919        switch (sc->devinfo.mf_info.mf_mode) {
14920        case MULTI_FUNCTION_SD:
14921            SET_FLAGS(flags, MODE_MF_SD);
14922            break;
14923        case MULTI_FUNCTION_SI:
14924            SET_FLAGS(flags, MODE_MF_SI);
14925            break;
14926        case MULTI_FUNCTION_AFEX:
14927            SET_FLAGS(flags, MODE_MF_AFEX);
14928            break;
14929        }
14930    } else {
14931        SET_FLAGS(flags, MODE_SF);
14932    }
14933
14934#if defined(__LITTLE_ENDIAN)
14935    SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14936#else /* __BIG_ENDIAN */
14937    SET_FLAGS(flags, MODE_BIG_ENDIAN);
14938#endif
14939
14940    INIT_MODE_FLAGS(sc) = flags;
14941}
14942
14943static int
14944bxe_alloc_hsi_mem(struct bxe_softc *sc)
14945{
14946    struct bxe_fastpath *fp;
14947    bus_addr_t busaddr;
14948    int max_agg_queues;
14949    int max_segments;
14950    bus_size_t max_size;
14951    bus_size_t max_seg_size;
14952    char buf[32];
14953    int rc;
14954    int i, j;
14955
14956    /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14957
14958    /* allocate the parent bus DMA tag */
14959    rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14960                            1,                        /* alignment */
14961                            0,                        /* boundary limit */
14962                            BUS_SPACE_MAXADDR,        /* restricted low */
14963                            BUS_SPACE_MAXADDR,        /* restricted hi */
14964                            NULL,                     /* addr filter() */
14965                            NULL,                     /* addr filter() arg */
14966                            BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14967                            BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14968                            BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14969                            0,                        /* flags */
14970                            NULL,                     /* lock() */
14971                            NULL,                     /* lock() arg */
14972                            &sc->parent_dma_tag);     /* returned dma tag */
14973    if (rc != 0) {
14974        BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14975        return (1);
14976    }
14977
14978    /************************/
14979    /* DEFAULT STATUS BLOCK */
14980    /************************/
14981
14982    if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14983                      &sc->def_sb_dma, "default status block") != 0) {
14984        /* XXX */
14985        bus_dma_tag_destroy(sc->parent_dma_tag);
14986        return (1);
14987    }
14988
14989    sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14990
14991    /***************/
14992    /* EVENT QUEUE */
14993    /***************/
14994
14995    if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14996                      &sc->eq_dma, "event queue") != 0) {
14997        /* XXX */
14998        bxe_dma_free(sc, &sc->def_sb_dma);
14999        sc->def_sb = NULL;
15000        bus_dma_tag_destroy(sc->parent_dma_tag);
15001        return (1);
15002    }
15003
15004    sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
15005
15006    /*************/
15007    /* SLOW PATH */
15008    /*************/
15009
15010    if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
15011                      &sc->sp_dma, "slow path") != 0) {
15012        /* XXX */
15013        bxe_dma_free(sc, &sc->eq_dma);
15014        sc->eq = NULL;
15015        bxe_dma_free(sc, &sc->def_sb_dma);
15016        sc->def_sb = NULL;
15017        bus_dma_tag_destroy(sc->parent_dma_tag);
15018        return (1);
15019    }
15020
15021    sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
15022
15023    /*******************/
15024    /* SLOW PATH QUEUE */
15025    /*******************/
15026
15027    if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
15028                      &sc->spq_dma, "slow path queue") != 0) {
15029        /* XXX */
15030        bxe_dma_free(sc, &sc->sp_dma);
15031        sc->sp = NULL;
15032        bxe_dma_free(sc, &sc->eq_dma);
15033        sc->eq = NULL;
15034        bxe_dma_free(sc, &sc->def_sb_dma);
15035        sc->def_sb = NULL;
15036        bus_dma_tag_destroy(sc->parent_dma_tag);
15037        return (1);
15038    }
15039
15040    sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
15041
15042    /***************************/
15043    /* FW DECOMPRESSION BUFFER */
15044    /***************************/
15045
15046    if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
15047                      "fw decompression buffer") != 0) {
15048        /* XXX */
15049        bxe_dma_free(sc, &sc->spq_dma);
15050        sc->spq = NULL;
15051        bxe_dma_free(sc, &sc->sp_dma);
15052        sc->sp = NULL;
15053        bxe_dma_free(sc, &sc->eq_dma);
15054        sc->eq = NULL;
15055        bxe_dma_free(sc, &sc->def_sb_dma);
15056        sc->def_sb = NULL;
15057        bus_dma_tag_destroy(sc->parent_dma_tag);
15058        return (1);
15059    }
15060
15061    sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
15062
15063    if ((sc->gz_strm =
15064         malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
15065        /* XXX */
15066        bxe_dma_free(sc, &sc->gz_buf_dma);
15067        sc->gz_buf = NULL;
15068        bxe_dma_free(sc, &sc->spq_dma);
15069        sc->spq = NULL;
15070        bxe_dma_free(sc, &sc->sp_dma);
15071        sc->sp = NULL;
15072        bxe_dma_free(sc, &sc->eq_dma);
15073        sc->eq = NULL;
15074        bxe_dma_free(sc, &sc->def_sb_dma);
15075        sc->def_sb = NULL;
15076        bus_dma_tag_destroy(sc->parent_dma_tag);
15077        return (1);
15078    }
15079
15080    /*************/
15081    /* FASTPATHS */
15082    /*************/
15083
15084    /* allocate DMA memory for each fastpath structure */
15085    for (i = 0; i < sc->num_queues; i++) {
15086        fp = &sc->fp[i];
15087        fp->sc    = sc;
15088        fp->index = i;
15089
15090        /*******************/
15091        /* FP STATUS BLOCK */
15092        /*******************/
15093
15094        snprintf(buf, sizeof(buf), "fp %d status block", i);
15095        if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
15096                          &fp->sb_dma, buf) != 0) {
15097            /* XXX unwind and free previous fastpath allocations */
15098            BLOGE(sc, "Failed to alloc %s\n", buf);
15099            return (1);
15100        } else {
15101            if (CHIP_IS_E2E3(sc)) {
15102                fp->status_block.e2_sb =
15103                    (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
15104            } else {
15105                fp->status_block.e1x_sb =
15106                    (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
15107            }
15108        }
15109
15110        /******************/
15111        /* FP TX BD CHAIN */
15112        /******************/
15113
15114        snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
15115        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
15116                          &fp->tx_dma, buf) != 0) {
15117            /* XXX unwind and free previous fastpath allocations */
15118            BLOGE(sc, "Failed to alloc %s\n", buf);
15119            return (1);
15120        } else {
15121            fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
15122        }
15123
15124        /* link together the tx bd chain pages */
15125        for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
15126            /* index into the tx bd chain array to last entry per page */
15127            struct eth_tx_next_bd *tx_next_bd =
15128                &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
15129            /* point to the next page and wrap from last page */
15130            busaddr = (fp->tx_dma.paddr +
15131                       (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
15132            tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
15133            tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
15134        }
15135
15136        /******************/
15137        /* FP RX BD CHAIN */
15138        /******************/
15139
15140        snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
15141        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
15142                          &fp->rx_dma, buf) != 0) {
15143            /* XXX unwind and free previous fastpath allocations */
15144            BLOGE(sc, "Failed to alloc %s\n", buf);
15145            return (1);
15146        } else {
15147            fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
15148        }
15149
15150        /* link together the rx bd chain pages */
15151        for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
15152            /* index into the rx bd chain array to last entry per page */
15153            struct eth_rx_bd *rx_bd =
15154                &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
15155            /* point to the next page and wrap from last page */
15156            busaddr = (fp->rx_dma.paddr +
15157                       (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
15158            rx_bd->addr_hi = htole32(U64_HI(busaddr));
15159            rx_bd->addr_lo = htole32(U64_LO(busaddr));
15160        }
15161
15162        /*******************/
15163        /* FP RX RCQ CHAIN */
15164        /*******************/
15165
15166        snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
15167        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
15168                          &fp->rcq_dma, buf) != 0) {
15169            /* XXX unwind and free previous fastpath allocations */
15170            BLOGE(sc, "Failed to alloc %s\n", buf);
15171            return (1);
15172        } else {
15173            fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
15174        }
15175
15176        /* link together the rcq chain pages */
15177        for (j = 1; j <= RCQ_NUM_PAGES; j++) {
15178            /* index into the rcq chain array to last entry per page */
15179            struct eth_rx_cqe_next_page *rx_cqe_next =
15180                (struct eth_rx_cqe_next_page *)
15181                &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
15182            /* point to the next page and wrap from last page */
15183            busaddr = (fp->rcq_dma.paddr +
15184                       (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
15185            rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
15186            rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
15187        }
15188
15189        /*******************/
15190        /* FP RX SGE CHAIN */
15191        /*******************/
15192
15193        snprintf(buf, sizeof(buf), "fp %d sge chain", i);
15194        if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
15195                          &fp->rx_sge_dma, buf) != 0) {
15196            /* XXX unwind and free previous fastpath allocations */
15197            BLOGE(sc, "Failed to alloc %s\n", buf);
15198            return (1);
15199        } else {
15200            fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
15201        }
15202
15203        /* link together the sge chain pages */
15204        for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
15205            /* index into the rcq chain array to last entry per page */
15206            struct eth_rx_sge *rx_sge =
15207                &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
15208            /* point to the next page and wrap from last page */
15209            busaddr = (fp->rx_sge_dma.paddr +
15210                       (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
15211            rx_sge->addr_hi = htole32(U64_HI(busaddr));
15212            rx_sge->addr_lo = htole32(U64_LO(busaddr));
15213        }
15214
15215        /***********************/
15216        /* FP TX MBUF DMA MAPS */
15217        /***********************/
15218
15219        /* set required sizes before mapping to conserve resources */
15220        if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
15221            max_size     = BXE_TSO_MAX_SIZE;
15222            max_segments = BXE_TSO_MAX_SEGMENTS;
15223            max_seg_size = BXE_TSO_MAX_SEG_SIZE;
15224        } else {
15225            max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
15226            max_segments = BXE_MAX_SEGMENTS;
15227            max_seg_size = MCLBYTES;
15228        }
15229
15230        /* create a dma tag for the tx mbufs */
15231        rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15232                                1,                  /* alignment */
15233                                0,                  /* boundary limit */
15234                                BUS_SPACE_MAXADDR,  /* restricted low */
15235                                BUS_SPACE_MAXADDR,  /* restricted hi */
15236                                NULL,               /* addr filter() */
15237                                NULL,               /* addr filter() arg */
15238                                max_size,           /* max map size */
15239                                max_segments,       /* num discontinuous */
15240                                max_seg_size,       /* max seg size */
15241                                0,                  /* flags */
15242                                NULL,               /* lock() */
15243                                NULL,               /* lock() arg */
15244                                &fp->tx_mbuf_tag);  /* returned dma tag */
15245        if (rc != 0) {
15246            /* XXX unwind and free previous fastpath allocations */
15247            BLOGE(sc, "Failed to create dma tag for "
15248                      "'fp %d tx mbufs' (%d)\n",
15249                  i, rc);
15250            return (1);
15251        }
15252
15253        /* create dma maps for each of the tx mbuf clusters */
15254        for (j = 0; j < TX_BD_TOTAL; j++) {
15255            if (bus_dmamap_create(fp->tx_mbuf_tag,
15256                                  BUS_DMA_NOWAIT,
15257                                  &fp->tx_mbuf_chain[j].m_map)) {
15258                /* XXX unwind and free previous fastpath allocations */
15259                BLOGE(sc, "Failed to create dma map for "
15260                          "'fp %d tx mbuf %d' (%d)\n",
15261                      i, j, rc);
15262                return (1);
15263            }
15264        }
15265
15266        /***********************/
15267        /* FP RX MBUF DMA MAPS */
15268        /***********************/
15269
15270        /* create a dma tag for the rx mbufs */
15271        rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15272                                1,                  /* alignment */
15273                                0,                  /* boundary limit */
15274                                BUS_SPACE_MAXADDR,  /* restricted low */
15275                                BUS_SPACE_MAXADDR,  /* restricted hi */
15276                                NULL,               /* addr filter() */
15277                                NULL,               /* addr filter() arg */
15278                                MJUM9BYTES,         /* max map size */
15279                                1,                  /* num discontinuous */
15280                                MJUM9BYTES,         /* max seg size */
15281                                0,                  /* flags */
15282                                NULL,               /* lock() */
15283                                NULL,               /* lock() arg */
15284                                &fp->rx_mbuf_tag);  /* returned dma tag */
15285        if (rc != 0) {
15286            /* XXX unwind and free previous fastpath allocations */
15287            BLOGE(sc, "Failed to create dma tag for "
15288                      "'fp %d rx mbufs' (%d)\n",
15289                  i, rc);
15290            return (1);
15291        }
15292
15293        /* create dma maps for each of the rx mbuf clusters */
15294        for (j = 0; j < RX_BD_TOTAL; j++) {
15295            if (bus_dmamap_create(fp->rx_mbuf_tag,
15296                                  BUS_DMA_NOWAIT,
15297                                  &fp->rx_mbuf_chain[j].m_map)) {
15298                /* XXX unwind and free previous fastpath allocations */
15299                BLOGE(sc, "Failed to create dma map for "
15300                          "'fp %d rx mbuf %d' (%d)\n",
15301                      i, j, rc);
15302                return (1);
15303            }
15304        }
15305
15306        /* create dma map for the spare rx mbuf cluster */
15307        if (bus_dmamap_create(fp->rx_mbuf_tag,
15308                              BUS_DMA_NOWAIT,
15309                              &fp->rx_mbuf_spare_map)) {
15310            /* XXX unwind and free previous fastpath allocations */
15311            BLOGE(sc, "Failed to create dma map for "
15312                      "'fp %d spare rx mbuf' (%d)\n",
15313                  i, rc);
15314            return (1);
15315        }
15316
15317        /***************************/
15318        /* FP RX SGE MBUF DMA MAPS */
15319        /***************************/
15320
15321        /* create a dma tag for the rx sge mbufs */
15322        rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15323                                1,                  /* alignment */
15324                                0,                  /* boundary limit */
15325                                BUS_SPACE_MAXADDR,  /* restricted low */
15326                                BUS_SPACE_MAXADDR,  /* restricted hi */
15327                                NULL,               /* addr filter() */
15328                                NULL,               /* addr filter() arg */
15329                                BCM_PAGE_SIZE,      /* max map size */
15330                                1,                  /* num discontinuous */
15331                                BCM_PAGE_SIZE,      /* max seg size */
15332                                0,                  /* flags */
15333                                NULL,               /* lock() */
15334                                NULL,               /* lock() arg */
15335                                &fp->rx_sge_mbuf_tag); /* returned dma tag */
15336        if (rc != 0) {
15337            /* XXX unwind and free previous fastpath allocations */
15338            BLOGE(sc, "Failed to create dma tag for "
15339                      "'fp %d rx sge mbufs' (%d)\n",
15340                  i, rc);
15341            return (1);
15342        }
15343
15344        /* create dma maps for the rx sge mbuf clusters */
15345        for (j = 0; j < RX_SGE_TOTAL; j++) {
15346            if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
15347                                  BUS_DMA_NOWAIT,
15348                                  &fp->rx_sge_mbuf_chain[j].m_map)) {
15349                /* XXX unwind and free previous fastpath allocations */
15350                BLOGE(sc, "Failed to create dma map for "
15351                          "'fp %d rx sge mbuf %d' (%d)\n",
15352                      i, j, rc);
15353                return (1);
15354            }
15355        }
15356
15357        /* create dma map for the spare rx sge mbuf cluster */
15358        if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
15359                              BUS_DMA_NOWAIT,
15360                              &fp->rx_sge_mbuf_spare_map)) {
15361            /* XXX unwind and free previous fastpath allocations */
15362            BLOGE(sc, "Failed to create dma map for "
15363                      "'fp %d spare rx sge mbuf' (%d)\n",
15364                  i, rc);
15365            return (1);
15366        }
15367
15368        /***************************/
15369        /* FP RX TPA MBUF DMA MAPS */
15370        /***************************/
15371
15372        /* create dma maps for the rx tpa mbuf clusters */
15373        max_agg_queues = MAX_AGG_QS(sc);
15374
15375        for (j = 0; j < max_agg_queues; j++) {
15376            if (bus_dmamap_create(fp->rx_mbuf_tag,
15377                                  BUS_DMA_NOWAIT,
15378                                  &fp->rx_tpa_info[j].bd.m_map)) {
15379                /* XXX unwind and free previous fastpath allocations */
15380                BLOGE(sc, "Failed to create dma map for "
15381                          "'fp %d rx tpa mbuf %d' (%d)\n",
15382                      i, j, rc);
15383                return (1);
15384            }
15385        }
15386
15387        /* create dma map for the spare rx tpa mbuf cluster */
15388        if (bus_dmamap_create(fp->rx_mbuf_tag,
15389                              BUS_DMA_NOWAIT,
15390                              &fp->rx_tpa_info_mbuf_spare_map)) {
15391            /* XXX unwind and free previous fastpath allocations */
15392            BLOGE(sc, "Failed to create dma map for "
15393                      "'fp %d spare rx tpa mbuf' (%d)\n",
15394                  i, rc);
15395            return (1);
15396        }
15397
15398        bxe_init_sge_ring_bit_mask(fp);
15399    }
15400
15401    return (0);
15402}
15403
15404static void
15405bxe_free_hsi_mem(struct bxe_softc *sc)
15406{
15407    struct bxe_fastpath *fp;
15408    int max_agg_queues;
15409    int i, j;
15410
15411    if (sc->parent_dma_tag == NULL) {
15412        return; /* assume nothing was allocated */
15413    }
15414
15415    for (i = 0; i < sc->num_queues; i++) {
15416        fp = &sc->fp[i];
15417
15418        /*******************/
15419        /* FP STATUS BLOCK */
15420        /*******************/
15421
15422        bxe_dma_free(sc, &fp->sb_dma);
15423        memset(&fp->status_block, 0, sizeof(fp->status_block));
15424
15425        /******************/
15426        /* FP TX BD CHAIN */
15427        /******************/
15428
15429        bxe_dma_free(sc, &fp->tx_dma);
15430        fp->tx_chain = NULL;
15431
15432        /******************/
15433        /* FP RX BD CHAIN */
15434        /******************/
15435
15436        bxe_dma_free(sc, &fp->rx_dma);
15437        fp->rx_chain = NULL;
15438
15439        /*******************/
15440        /* FP RX RCQ CHAIN */
15441        /*******************/
15442
15443        bxe_dma_free(sc, &fp->rcq_dma);
15444        fp->rcq_chain = NULL;
15445
15446        /*******************/
15447        /* FP RX SGE CHAIN */
15448        /*******************/
15449
15450        bxe_dma_free(sc, &fp->rx_sge_dma);
15451        fp->rx_sge_chain = NULL;
15452
15453        /***********************/
15454        /* FP TX MBUF DMA MAPS */
15455        /***********************/
15456
15457        if (fp->tx_mbuf_tag != NULL) {
15458            for (j = 0; j < TX_BD_TOTAL; j++) {
15459                if (fp->tx_mbuf_chain[j].m_map != NULL) {
15460                    bus_dmamap_unload(fp->tx_mbuf_tag,
15461                                      fp->tx_mbuf_chain[j].m_map);
15462                    bus_dmamap_destroy(fp->tx_mbuf_tag,
15463                                       fp->tx_mbuf_chain[j].m_map);
15464                }
15465            }
15466
15467            bus_dma_tag_destroy(fp->tx_mbuf_tag);
15468            fp->tx_mbuf_tag = NULL;
15469        }
15470
15471        /***********************/
15472        /* FP RX MBUF DMA MAPS */
15473        /***********************/
15474
15475        if (fp->rx_mbuf_tag != NULL) {
15476            for (j = 0; j < RX_BD_TOTAL; j++) {
15477                if (fp->rx_mbuf_chain[j].m_map != NULL) {
15478                    bus_dmamap_unload(fp->rx_mbuf_tag,
15479                                      fp->rx_mbuf_chain[j].m_map);
15480                    bus_dmamap_destroy(fp->rx_mbuf_tag,
15481                                       fp->rx_mbuf_chain[j].m_map);
15482                }
15483            }
15484
15485            if (fp->rx_mbuf_spare_map != NULL) {
15486                bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
15487                bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
15488            }
15489
15490            /***************************/
15491            /* FP RX TPA MBUF DMA MAPS */
15492            /***************************/
15493
15494            max_agg_queues = MAX_AGG_QS(sc);
15495
15496            for (j = 0; j < max_agg_queues; j++) {
15497                if (fp->rx_tpa_info[j].bd.m_map != NULL) {
15498                    bus_dmamap_unload(fp->rx_mbuf_tag,
15499                                      fp->rx_tpa_info[j].bd.m_map);
15500                    bus_dmamap_destroy(fp->rx_mbuf_tag,
15501                                       fp->rx_tpa_info[j].bd.m_map);
15502                }
15503            }
15504
15505            if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
15506                bus_dmamap_unload(fp->rx_mbuf_tag,
15507                                  fp->rx_tpa_info_mbuf_spare_map);
15508                bus_dmamap_destroy(fp->rx_mbuf_tag,
15509                                   fp->rx_tpa_info_mbuf_spare_map);
15510            }
15511
15512            bus_dma_tag_destroy(fp->rx_mbuf_tag);
15513            fp->rx_mbuf_tag = NULL;
15514        }
15515
15516        /***************************/
15517        /* FP RX SGE MBUF DMA MAPS */
15518        /***************************/
15519
15520        if (fp->rx_sge_mbuf_tag != NULL) {
15521            for (j = 0; j < RX_SGE_TOTAL; j++) {
15522                if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
15523                    bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15524                                      fp->rx_sge_mbuf_chain[j].m_map);
15525                    bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15526                                       fp->rx_sge_mbuf_chain[j].m_map);
15527                }
15528            }
15529
15530            if (fp->rx_sge_mbuf_spare_map != NULL) {
15531                bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15532                                  fp->rx_sge_mbuf_spare_map);
15533                bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15534                                   fp->rx_sge_mbuf_spare_map);
15535            }
15536
15537            bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
15538            fp->rx_sge_mbuf_tag = NULL;
15539        }
15540    }
15541
15542    /***************************/
15543    /* FW DECOMPRESSION BUFFER */
15544    /***************************/
15545
15546    bxe_dma_free(sc, &sc->gz_buf_dma);
15547    sc->gz_buf = NULL;
15548    free(sc->gz_strm, M_DEVBUF);
15549    sc->gz_strm = NULL;
15550
15551    /*******************/
15552    /* SLOW PATH QUEUE */
15553    /*******************/
15554
15555    bxe_dma_free(sc, &sc->spq_dma);
15556    sc->spq = NULL;
15557
15558    /*************/
15559    /* SLOW PATH */
15560    /*************/
15561
15562    bxe_dma_free(sc, &sc->sp_dma);
15563    sc->sp = NULL;
15564
15565    /***************/
15566    /* EVENT QUEUE */
15567    /***************/
15568
15569    bxe_dma_free(sc, &sc->eq_dma);
15570    sc->eq = NULL;
15571
15572    /************************/
15573    /* DEFAULT STATUS BLOCK */
15574    /************************/
15575
15576    bxe_dma_free(sc, &sc->def_sb_dma);
15577    sc->def_sb = NULL;
15578
15579    bus_dma_tag_destroy(sc->parent_dma_tag);
15580    sc->parent_dma_tag = NULL;
15581}
15582
15583/*
15584 * Previous driver DMAE transaction may have occurred when pre-boot stage
15585 * ended and boot began. This would invalidate the addresses of the
15586 * transaction, resulting in was-error bit set in the PCI causing all
15587 * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15588 * the interrupt which detected this from the pglueb and the was-done bit
15589 */
15590static void
15591bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15592{
15593    uint32_t val;
15594
15595    if (!CHIP_IS_E1x(sc)) {
15596        val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15597        if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15598            BLOGD(sc, DBG_LOAD,
15599                  "Clearing 'was-error' bit that was set in pglueb");
15600            REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15601        }
15602    }
15603}
15604
15605static int
15606bxe_prev_mcp_done(struct bxe_softc *sc)
15607{
15608    uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15609                                 DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15610    if (!rc) {
15611        BLOGE(sc, "MCP response failure, aborting\n");
15612        return (-1);
15613    }
15614
15615    return (0);
15616}
15617
15618static struct bxe_prev_list_node *
15619bxe_prev_path_get_entry(struct bxe_softc *sc)
15620{
15621    struct bxe_prev_list_node *tmp;
15622
15623    LIST_FOREACH(tmp, &bxe_prev_list, node) {
15624        if ((sc->pcie_bus == tmp->bus) &&
15625            (sc->pcie_device == tmp->slot) &&
15626            (SC_PATH(sc) == tmp->path)) {
15627            return (tmp);
15628        }
15629    }
15630
15631    return (NULL);
15632}
15633
15634static uint8_t
15635bxe_prev_is_path_marked(struct bxe_softc *sc)
15636{
15637    struct bxe_prev_list_node *tmp;
15638    int rc = FALSE;
15639
15640    mtx_lock(&bxe_prev_mtx);
15641
15642    tmp = bxe_prev_path_get_entry(sc);
15643    if (tmp) {
15644        if (tmp->aer) {
15645            BLOGD(sc, DBG_LOAD,
15646                  "Path %d/%d/%d was marked by AER\n",
15647                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15648        } else {
15649            rc = TRUE;
15650            BLOGD(sc, DBG_LOAD,
15651                  "Path %d/%d/%d was already cleaned from previous drivers\n",
15652                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15653        }
15654    }
15655
15656    mtx_unlock(&bxe_prev_mtx);
15657
15658    return (rc);
15659}
15660
15661static int
15662bxe_prev_mark_path(struct bxe_softc *sc,
15663                   uint8_t          after_undi)
15664{
15665    struct bxe_prev_list_node *tmp;
15666
15667    mtx_lock(&bxe_prev_mtx);
15668
15669    /* Check whether the entry for this path already exists */
15670    tmp = bxe_prev_path_get_entry(sc);
15671    if (tmp) {
15672        if (!tmp->aer) {
15673            BLOGD(sc, DBG_LOAD,
15674                  "Re-marking AER in path %d/%d/%d\n",
15675                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15676        } else {
15677            BLOGD(sc, DBG_LOAD,
15678                  "Removing AER indication from path %d/%d/%d\n",
15679                  sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15680            tmp->aer = 0;
15681        }
15682
15683        mtx_unlock(&bxe_prev_mtx);
15684        return (0);
15685    }
15686
15687    mtx_unlock(&bxe_prev_mtx);
15688
15689    /* Create an entry for this path and add it */
15690    tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15691                 (M_NOWAIT | M_ZERO));
15692    if (!tmp) {
15693        BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15694        return (-1);
15695    }
15696
15697    tmp->bus  = sc->pcie_bus;
15698    tmp->slot = sc->pcie_device;
15699    tmp->path = SC_PATH(sc);
15700    tmp->aer  = 0;
15701    tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15702
15703    mtx_lock(&bxe_prev_mtx);
15704
15705    BLOGD(sc, DBG_LOAD,
15706          "Marked path %d/%d/%d - finished previous unload\n",
15707          sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15708    LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15709
15710    mtx_unlock(&bxe_prev_mtx);
15711
15712    return (0);
15713}
15714
15715static int
15716bxe_do_flr(struct bxe_softc *sc)
15717{
15718    int i;
15719
15720    /* only E2 and onwards support FLR */
15721    if (CHIP_IS_E1x(sc)) {
15722        BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15723        return (-1);
15724    }
15725
15726    /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15727    if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15728        BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15729              sc->devinfo.bc_ver);
15730        return (-1);
15731    }
15732
15733    /* Wait for Transaction Pending bit clean */
15734    for (i = 0; i < 4; i++) {
15735        if (i) {
15736            DELAY(((1 << (i - 1)) * 100) * 1000);
15737        }
15738
15739        if (!bxe_is_pcie_pending(sc)) {
15740            goto clear;
15741        }
15742    }
15743
15744    BLOGE(sc, "PCIE transaction is not cleared, "
15745              "proceeding with reset anyway\n");
15746
15747clear:
15748
15749    BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15750    bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15751
15752    return (0);
15753}
15754
15755struct bxe_mac_vals {
15756    uint32_t xmac_addr;
15757    uint32_t xmac_val;
15758    uint32_t emac_addr;
15759    uint32_t emac_val;
15760    uint32_t umac_addr;
15761    uint32_t umac_val;
15762    uint32_t bmac_addr;
15763    uint32_t bmac_val[2];
15764};
15765
15766static void
15767bxe_prev_unload_close_mac(struct bxe_softc *sc,
15768                          struct bxe_mac_vals *vals)
15769{
15770    uint32_t val, base_addr, offset, mask, reset_reg;
15771    uint8_t mac_stopped = FALSE;
15772    uint8_t port = SC_PORT(sc);
15773    uint32_t wb_data[2];
15774
15775    /* reset addresses as they also mark which values were changed */
15776    vals->bmac_addr = 0;
15777    vals->umac_addr = 0;
15778    vals->xmac_addr = 0;
15779    vals->emac_addr = 0;
15780
15781    reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15782
15783    if (!CHIP_IS_E3(sc)) {
15784        val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15785        mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15786        if ((mask & reset_reg) && val) {
15787            BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15788            base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15789                                    : NIG_REG_INGRESS_BMAC0_MEM;
15790            offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15791                                    : BIGMAC_REGISTER_BMAC_CONTROL;
15792
15793            /*
15794             * use rd/wr since we cannot use dmae. This is safe
15795             * since MCP won't access the bus due to the request
15796             * to unload, and no function on the path can be
15797             * loaded at this time.
15798             */
15799            wb_data[0] = REG_RD(sc, base_addr + offset);
15800            wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15801            vals->bmac_addr = base_addr + offset;
15802            vals->bmac_val[0] = wb_data[0];
15803            vals->bmac_val[1] = wb_data[1];
15804            wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15805            REG_WR(sc, vals->bmac_addr, wb_data[0]);
15806            REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15807        }
15808
15809        BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15810        vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15811        vals->emac_val = REG_RD(sc, vals->emac_addr);
15812        REG_WR(sc, vals->emac_addr, 0);
15813        mac_stopped = TRUE;
15814    } else {
15815        if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15816            BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15817            base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15818            val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15819            REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15820            REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15821            vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15822            vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15823            REG_WR(sc, vals->xmac_addr, 0);
15824            mac_stopped = TRUE;
15825        }
15826
15827        mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15828        if (mask & reset_reg) {
15829            BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15830            base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15831            vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15832            vals->umac_val = REG_RD(sc, vals->umac_addr);
15833            REG_WR(sc, vals->umac_addr, 0);
15834            mac_stopped = TRUE;
15835        }
15836    }
15837
15838    if (mac_stopped) {
15839        DELAY(20000);
15840    }
15841}
15842
15843#define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15844#define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15845#define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15846#define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15847
15848static void
15849bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15850                         uint8_t          port,
15851                         uint8_t          inc)
15852{
15853    uint16_t rcq, bd;
15854    uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15855
15856    rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15857    bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15858
15859    tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15860    REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15861
15862    BLOGD(sc, DBG_LOAD,
15863          "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15864          port, bd, rcq);
15865}
15866
15867static int
15868bxe_prev_unload_common(struct bxe_softc *sc)
15869{
15870    uint32_t reset_reg, tmp_reg = 0, rc;
15871    uint8_t prev_undi = FALSE;
15872    struct bxe_mac_vals mac_vals;
15873    uint32_t timer_count = 1000;
15874    uint32_t prev_brb;
15875
15876    /*
15877     * It is possible a previous function received 'common' answer,
15878     * but hasn't loaded yet, therefore creating a scenario of
15879     * multiple functions receiving 'common' on the same path.
15880     */
15881    BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15882
15883    memset(&mac_vals, 0, sizeof(mac_vals));
15884
15885    if (bxe_prev_is_path_marked(sc)) {
15886        return (bxe_prev_mcp_done(sc));
15887    }
15888
15889    reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15890
15891    /* Reset should be performed after BRB is emptied */
15892    if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15893        /* Close the MAC Rx to prevent BRB from filling up */
15894        bxe_prev_unload_close_mac(sc, &mac_vals);
15895
15896        /* close LLH filters towards the BRB */
15897        elink_set_rx_filter(&sc->link_params, 0);
15898
15899        /*
15900         * Check if the UNDI driver was previously loaded.
15901         * UNDI driver initializes CID offset for normal bell to 0x7
15902         */
15903        if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15904            tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15905            if (tmp_reg == 0x7) {
15906                BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15907                prev_undi = TRUE;
15908                /* clear the UNDI indication */
15909                REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15910                /* clear possible idle check errors */
15911                REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15912            }
15913        }
15914
15915        /* wait until BRB is empty */
15916        tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15917        while (timer_count) {
15918            prev_brb = tmp_reg;
15919
15920            tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15921            if (!tmp_reg) {
15922                break;
15923            }
15924
15925            BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15926
15927            /* reset timer as long as BRB actually gets emptied */
15928            if (prev_brb > tmp_reg) {
15929                timer_count = 1000;
15930            } else {
15931                timer_count--;
15932            }
15933
15934            /* If UNDI resides in memory, manually increment it */
15935            if (prev_undi) {
15936                bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15937            }
15938
15939            DELAY(10);
15940        }
15941
15942        if (!timer_count) {
15943            BLOGE(sc, "Failed to empty BRB\n");
15944        }
15945    }
15946
15947    /* No packets are in the pipeline, path is ready for reset */
15948    bxe_reset_common(sc);
15949
15950    if (mac_vals.xmac_addr) {
15951        REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15952    }
15953    if (mac_vals.umac_addr) {
15954        REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15955    }
15956    if (mac_vals.emac_addr) {
15957        REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15958    }
15959    if (mac_vals.bmac_addr) {
15960        REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15961        REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15962    }
15963
15964    rc = bxe_prev_mark_path(sc, prev_undi);
15965    if (rc) {
15966        bxe_prev_mcp_done(sc);
15967        return (rc);
15968    }
15969
15970    return (bxe_prev_mcp_done(sc));
15971}
15972
15973static int
15974bxe_prev_unload_uncommon(struct bxe_softc *sc)
15975{
15976    int rc;
15977
15978    BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15979
15980    /* Test if previous unload process was already finished for this path */
15981    if (bxe_prev_is_path_marked(sc)) {
15982        return (bxe_prev_mcp_done(sc));
15983    }
15984
15985    BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15986
15987    /*
15988     * If function has FLR capabilities, and existing FW version matches
15989     * the one required, then FLR will be sufficient to clean any residue
15990     * left by previous driver
15991     */
15992    rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15993    if (!rc) {
15994        /* fw version is good */
15995        BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15996        rc = bxe_do_flr(sc);
15997    }
15998
15999    if (!rc) {
16000        /* FLR was performed */
16001        BLOGD(sc, DBG_LOAD, "FLR successful\n");
16002        return (0);
16003    }
16004
16005    BLOGD(sc, DBG_LOAD, "Could not FLR\n");
16006
16007    /* Close the MCP request, return failure*/
16008    rc = bxe_prev_mcp_done(sc);
16009    if (!rc) {
16010        rc = BXE_PREV_WAIT_NEEDED;
16011    }
16012
16013    return (rc);
16014}
16015
16016static int
16017bxe_prev_unload(struct bxe_softc *sc)
16018{
16019    int time_counter = 10;
16020    uint32_t fw, hw_lock_reg, hw_lock_val;
16021    uint32_t rc = 0;
16022
16023    /*
16024     * Clear HW from errors which may have resulted from an interrupted
16025     * DMAE transaction.
16026     */
16027    bxe_prev_interrupted_dmae(sc);
16028
16029    /* Release previously held locks */
16030    hw_lock_reg =
16031        (SC_FUNC(sc) <= 5) ?
16032            (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
16033            (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
16034
16035    hw_lock_val = (REG_RD(sc, hw_lock_reg));
16036    if (hw_lock_val) {
16037        if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
16038            BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
16039            REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
16040                   (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
16041        }
16042        BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
16043        REG_WR(sc, hw_lock_reg, 0xffffffff);
16044    } else {
16045        BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
16046    }
16047
16048    if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
16049        BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
16050        REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
16051    }
16052
16053    do {
16054        /* Lock MCP using an unload request */
16055        fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
16056        if (!fw) {
16057            BLOGE(sc, "MCP response failure, aborting\n");
16058            rc = -1;
16059            break;
16060        }
16061
16062        if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
16063            rc = bxe_prev_unload_common(sc);
16064            break;
16065        }
16066
16067        /* non-common reply from MCP night require looping */
16068        rc = bxe_prev_unload_uncommon(sc);
16069        if (rc != BXE_PREV_WAIT_NEEDED) {
16070            break;
16071        }
16072
16073        DELAY(20000);
16074    } while (--time_counter);
16075
16076    if (!time_counter || rc) {
16077        BLOGE(sc, "Failed to unload previous driver!\n");
16078        rc = -1;
16079    }
16080
16081    return (rc);
16082}
16083
16084void
16085bxe_dcbx_set_state(struct bxe_softc *sc,
16086                   uint8_t          dcb_on,
16087                   uint32_t         dcbx_enabled)
16088{
16089    if (!CHIP_IS_E1x(sc)) {
16090        sc->dcb_state = dcb_on;
16091        sc->dcbx_enabled = dcbx_enabled;
16092    } else {
16093        sc->dcb_state = FALSE;
16094        sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
16095    }
16096    BLOGD(sc, DBG_LOAD,
16097          "DCB state [%s:%s]\n",
16098          dcb_on ? "ON" : "OFF",
16099          (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
16100          (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
16101          (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
16102          "on-chip with negotiation" : "invalid");
16103}
16104
16105/* must be called after sriov-enable */
16106static int
16107bxe_set_qm_cid_count(struct bxe_softc *sc)
16108{
16109    int cid_count = BXE_L2_MAX_CID(sc);
16110
16111    if (IS_SRIOV(sc)) {
16112        cid_count += BXE_VF_CIDS;
16113    }
16114
16115    if (CNIC_SUPPORT(sc)) {
16116        cid_count += CNIC_CID_MAX;
16117    }
16118
16119    return (roundup(cid_count, QM_CID_ROUND));
16120}
16121
16122static void
16123bxe_init_multi_cos(struct bxe_softc *sc)
16124{
16125    int pri, cos;
16126
16127    uint32_t pri_map = 0; /* XXX change to user config */
16128
16129    for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
16130        cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
16131        if (cos < sc->max_cos) {
16132            sc->prio_to_cos[pri] = cos;
16133        } else {
16134            BLOGW(sc, "Invalid COS %d for priority %d "
16135                      "(max COS is %d), setting to 0\n",
16136                  cos, pri, (sc->max_cos - 1));
16137            sc->prio_to_cos[pri] = 0;
16138        }
16139    }
16140}
16141
16142static int
16143bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
16144{
16145    struct bxe_softc *sc;
16146    int error, result;
16147
16148    result = 0;
16149    error = sysctl_handle_int(oidp, &result, 0, req);
16150
16151    if (error || !req->newptr) {
16152        return (error);
16153    }
16154
16155    if (result == 1) {
16156        sc = (struct bxe_softc *)arg1;
16157        BLOGI(sc, "... dumping driver state ...\n");
16158        /* XXX */
16159    }
16160
16161    return (error);
16162}
16163
16164static int
16165bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
16166{
16167    struct bxe_softc *sc = (struct bxe_softc *)arg1;
16168    uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
16169    uint32_t *offset;
16170    uint64_t value = 0;
16171    int index = (int)arg2;
16172
16173    if (index >= BXE_NUM_ETH_STATS) {
16174        BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
16175        return (-1);
16176    }
16177
16178    offset = (eth_stats + bxe_eth_stats_arr[index].offset);
16179
16180    switch (bxe_eth_stats_arr[index].size) {
16181    case 4:
16182        value = (uint64_t)*offset;
16183        break;
16184    case 8:
16185        value = HILO_U64(*offset, *(offset + 1));
16186        break;
16187    default:
16188        BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
16189              index, bxe_eth_stats_arr[index].size);
16190        return (-1);
16191    }
16192
16193    return (sysctl_handle_64(oidp, &value, 0, req));
16194}
16195
16196static int
16197bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
16198{
16199    struct bxe_softc *sc = (struct bxe_softc *)arg1;
16200    uint32_t *eth_stats;
16201    uint32_t *offset;
16202    uint64_t value = 0;
16203    uint32_t q_stat = (uint32_t)arg2;
16204    uint32_t fp_index = ((q_stat >> 16) & 0xffff);
16205    uint32_t index = (q_stat & 0xffff);
16206
16207    eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
16208
16209    if (index >= BXE_NUM_ETH_Q_STATS) {
16210        BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
16211        return (-1);
16212    }
16213
16214    offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
16215
16216    switch (bxe_eth_q_stats_arr[index].size) {
16217    case 4:
16218        value = (uint64_t)*offset;
16219        break;
16220    case 8:
16221        value = HILO_U64(*offset, *(offset + 1));
16222        break;
16223    default:
16224        BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
16225              index, bxe_eth_q_stats_arr[index].size);
16226        return (-1);
16227    }
16228
16229    return (sysctl_handle_64(oidp, &value, 0, req));
16230}
16231
16232static void
16233bxe_add_sysctls(struct bxe_softc *sc)
16234{
16235    struct sysctl_ctx_list *ctx;
16236    struct sysctl_oid_list *children;
16237    struct sysctl_oid *queue_top, *queue;
16238    struct sysctl_oid_list *queue_top_children, *queue_children;
16239    char queue_num_buf[32];
16240    uint32_t q_stat;
16241    int i, j;
16242
16243    ctx = device_get_sysctl_ctx(sc->dev);
16244    children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
16245
16246    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
16247                      CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
16248                      "version");
16249
16250    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
16251                      CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
16252                      "bootcode version");
16253
16254    snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
16255             BCM_5710_FW_MAJOR_VERSION,
16256             BCM_5710_FW_MINOR_VERSION,
16257             BCM_5710_FW_REVISION_VERSION,
16258             BCM_5710_FW_ENGINEERING_VERSION);
16259    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
16260                      CTLFLAG_RD, &sc->fw_ver_str, 0,
16261                      "firmware version");
16262
16263    snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
16264        ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
16265         (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
16266         (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
16267         (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
16268                                                                "Unknown"));
16269    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
16270                      CTLFLAG_RD, &sc->mf_mode_str, 0,
16271                      "multifunction mode");
16272
16273    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
16274                    CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
16275                    "multifunction vnics per port");
16276
16277    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
16278                      CTLFLAG_RD, &sc->mac_addr_str, 0,
16279                      "mac address");
16280
16281    snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
16282        ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
16283         (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
16284         (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
16285                                              "???GT/s"),
16286        sc->devinfo.pcie_link_width);
16287    SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
16288                      CTLFLAG_RD, &sc->pci_link_str, 0,
16289                      "pci link status");
16290
16291    sc->debug = bxe_debug;
16292    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
16293                    CTLFLAG_RW, &sc->debug, 0,
16294                    "debug logging mode");
16295
16296    sc->rx_budget = bxe_rx_budget;
16297    SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
16298                    CTLFLAG_RW, &sc->rx_budget, 0,
16299                    "rx processing budget");
16300
16301    SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
16302                    CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
16303                    bxe_sysctl_state, "IU", "dump driver state");
16304
16305    for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
16306        SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
16307                        bxe_eth_stats_arr[i].string,
16308                        CTLTYPE_U64 | CTLFLAG_RD, sc, i,
16309                        bxe_sysctl_eth_stat, "LU",
16310                        bxe_eth_stats_arr[i].string);
16311    }
16312
16313    /* add a new parent node for all queues "dev.bxe.#.queue" */
16314    queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
16315                                CTLFLAG_RD, NULL, "queue");
16316    queue_top_children = SYSCTL_CHILDREN(queue_top);
16317
16318    for (i = 0; i < sc->num_queues; i++) {
16319        /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
16320        snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
16321        queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
16322                                queue_num_buf, CTLFLAG_RD, NULL,
16323                                "single queue");
16324        queue_children = SYSCTL_CHILDREN(queue);
16325
16326        for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
16327            q_stat = ((i << 16) | j);
16328            SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
16329                            bxe_eth_q_stats_arr[j].string,
16330                            CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
16331                            bxe_sysctl_eth_q_stat, "LU",
16332                            bxe_eth_q_stats_arr[j].string);
16333        }
16334    }
16335}
16336
16337/*
16338 * Device attach function.
16339 *
16340 * Allocates device resources, performs secondary chip identification, and
16341 * initializes driver instance variables. This function is called from driver
16342 * load after a successful probe.
16343 *
16344 * Returns:
16345 *   0 = Success, >0 = Failure
16346 */
16347static int
16348bxe_attach(device_t dev)
16349{
16350    struct bxe_softc *sc;
16351
16352    sc = device_get_softc(dev);
16353
16354    BLOGD(sc, DBG_LOAD, "Starting attach...\n");
16355
16356    sc->state = BXE_STATE_CLOSED;
16357
16358    sc->dev  = dev;
16359    sc->unit = device_get_unit(dev);
16360
16361    BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
16362
16363    sc->pcie_bus    = pci_get_bus(dev);
16364    sc->pcie_device = pci_get_slot(dev);
16365    sc->pcie_func   = pci_get_function(dev);
16366
16367    /* enable bus master capability */
16368    pci_enable_busmaster(dev);
16369
16370    /* get the BARs */
16371    if (bxe_allocate_bars(sc) != 0) {
16372        return (ENXIO);
16373    }
16374
16375    /* initialize the mutexes */
16376    bxe_init_mutexes(sc);
16377
16378    /* prepare the periodic callout */
16379    callout_init(&sc->periodic_callout, 0);
16380
16381    /* prepare the chip taskqueue */
16382    sc->chip_tq_flags = CHIP_TQ_NONE;
16383    snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
16384             "bxe%d_chip_tq", sc->unit);
16385    TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
16386    sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
16387                                   taskqueue_thread_enqueue,
16388                                   &sc->chip_tq);
16389    taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
16390                            "%s", sc->chip_tq_name);
16391
16392    /* get device info and set params */
16393    if (bxe_get_device_info(sc) != 0) {
16394        BLOGE(sc, "getting device info\n");
16395        bxe_deallocate_bars(sc);
16396        pci_disable_busmaster(dev);
16397        return (ENXIO);
16398    }
16399
16400    /* get final misc params */
16401    bxe_get_params(sc);
16402
16403    /* set the default MTU (changed via ifconfig) */
16404    sc->mtu = ETHERMTU;
16405
16406    bxe_set_modes_bitmap(sc);
16407
16408    /* XXX
16409     * If in AFEX mode and the function is configured for FCoE
16410     * then bail... no L2 allowed.
16411     */
16412
16413    /* get phy settings from shmem and 'and' against admin settings */
16414    bxe_get_phy_info(sc);
16415
16416    /* initialize the FreeBSD ifnet interface */
16417    if (bxe_init_ifnet(sc) != 0) {
16418        bxe_release_mutexes(sc);
16419        bxe_deallocate_bars(sc);
16420        pci_disable_busmaster(dev);
16421        return (ENXIO);
16422    }
16423
16424    /* allocate device interrupts */
16425    if (bxe_interrupt_alloc(sc) != 0) {
16426        if (sc->ifnet != NULL) {
16427            ether_ifdetach(sc->ifnet);
16428        }
16429        ifmedia_removeall(&sc->ifmedia);
16430        bxe_release_mutexes(sc);
16431        bxe_deallocate_bars(sc);
16432        pci_disable_busmaster(dev);
16433        return (ENXIO);
16434    }
16435
16436    /* allocate ilt */
16437    if (bxe_alloc_ilt_mem(sc) != 0) {
16438        bxe_interrupt_free(sc);
16439        if (sc->ifnet != NULL) {
16440            ether_ifdetach(sc->ifnet);
16441        }
16442        ifmedia_removeall(&sc->ifmedia);
16443        bxe_release_mutexes(sc);
16444        bxe_deallocate_bars(sc);
16445        pci_disable_busmaster(dev);
16446        return (ENXIO);
16447    }
16448
16449    /* allocate the host hardware/software hsi structures */
16450    if (bxe_alloc_hsi_mem(sc) != 0) {
16451        bxe_free_ilt_mem(sc);
16452        bxe_interrupt_free(sc);
16453        if (sc->ifnet != NULL) {
16454            ether_ifdetach(sc->ifnet);
16455        }
16456        ifmedia_removeall(&sc->ifmedia);
16457        bxe_release_mutexes(sc);
16458        bxe_deallocate_bars(sc);
16459        pci_disable_busmaster(dev);
16460        return (ENXIO);
16461    }
16462
16463    /* need to reset chip if UNDI was active */
16464    if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16465        /* init fw_seq */
16466        sc->fw_seq =
16467            (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16468             DRV_MSG_SEQ_NUMBER_MASK);
16469        BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16470        bxe_prev_unload(sc);
16471    }
16472
16473#if 1
16474    /* XXX */
16475    bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16476#else
16477    if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16478        SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16479        SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16480        SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16481        bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16482        bxe_dcbx_init_params(sc);
16483    } else {
16484        bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16485    }
16486#endif
16487
16488    /* calculate qm_cid_count */
16489    sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16490    BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16491
16492    sc->max_cos = 1;
16493    bxe_init_multi_cos(sc);
16494
16495    bxe_add_sysctls(sc);
16496
16497    return (0);
16498}
16499
16500/*
16501 * Device detach function.
16502 *
16503 * Stops the controller, resets the controller, and releases resources.
16504 *
16505 * Returns:
16506 *   0 = Success, >0 = Failure
16507 */
16508static int
16509bxe_detach(device_t dev)
16510{
16511    struct bxe_softc *sc;
16512    struct ifnet *ifp;
16513
16514    sc = device_get_softc(dev);
16515
16516    BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16517
16518    ifp = sc->ifnet;
16519    if (ifp != NULL && ifp->if_vlantrunk != NULL) {
16520        BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16521        return(EBUSY);
16522    }
16523
16524    /* stop the periodic callout */
16525    bxe_periodic_stop(sc);
16526
16527    /* stop the chip taskqueue */
16528    atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16529    if (sc->chip_tq) {
16530        taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16531        taskqueue_free(sc->chip_tq);
16532        sc->chip_tq = NULL;
16533    }
16534
16535    /* stop and reset the controller if it was open */
16536    if (sc->state != BXE_STATE_CLOSED) {
16537        BXE_CORE_LOCK(sc);
16538        bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16539        BXE_CORE_UNLOCK(sc);
16540    }
16541
16542    /* release the network interface */
16543    if (ifp != NULL) {
16544        ether_ifdetach(ifp);
16545    }
16546    ifmedia_removeall(&sc->ifmedia);
16547
16548    /* XXX do the following based on driver state... */
16549
16550    /* free the host hardware/software hsi structures */
16551    bxe_free_hsi_mem(sc);
16552
16553    /* free ilt */
16554    bxe_free_ilt_mem(sc);
16555
16556    /* release the interrupts */
16557    bxe_interrupt_free(sc);
16558
16559    /* Release the mutexes*/
16560    bxe_release_mutexes(sc);
16561
16562    /* Release the PCIe BAR mapped memory */
16563    bxe_deallocate_bars(sc);
16564
16565    /* Release the FreeBSD interface. */
16566    if (sc->ifnet != NULL) {
16567        if_free(sc->ifnet);
16568    }
16569
16570    pci_disable_busmaster(dev);
16571
16572    return (0);
16573}
16574
16575/*
16576 * Device shutdown function.
16577 *
16578 * Stops and resets the controller.
16579 *
16580 * Returns:
16581 *   Nothing
16582 */
16583static int
16584bxe_shutdown(device_t dev)
16585{
16586    struct bxe_softc *sc;
16587
16588    sc = device_get_softc(dev);
16589
16590    BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16591
16592    /* stop the periodic callout */
16593    bxe_periodic_stop(sc);
16594
16595    BXE_CORE_LOCK(sc);
16596    bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16597    BXE_CORE_UNLOCK(sc);
16598
16599    return (0);
16600}
16601
16602void
16603bxe_igu_ack_sb(struct bxe_softc *sc,
16604               uint8_t          igu_sb_id,
16605               uint8_t          segment,
16606               uint16_t         index,
16607               uint8_t          op,
16608               uint8_t          update)
16609{
16610    uint32_t igu_addr = sc->igu_base_addr;
16611    igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16612    bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16613}
16614
16615static void
16616bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16617                     uint8_t          func,
16618                     uint8_t          idu_sb_id,
16619                     uint8_t          is_pf)
16620{
16621    uint32_t data, ctl, cnt = 100;
16622    uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16623    uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16624    uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16625    uint32_t sb_bit =  1 << (idu_sb_id%32);
16626    uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16627    uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16628
16629    /* Not supported in BC mode */
16630    if (CHIP_INT_MODE_IS_BC(sc)) {
16631        return;
16632    }
16633
16634    data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16635             IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16636            IGU_REGULAR_CLEANUP_SET |
16637            IGU_REGULAR_BCLEANUP);
16638
16639    ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16640           (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16641           (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16642
16643    BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16644            data, igu_addr_data);
16645    REG_WR(sc, igu_addr_data, data);
16646
16647    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16648                      BUS_SPACE_BARRIER_WRITE);
16649    mb();
16650
16651    BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16652            ctl, igu_addr_ctl);
16653    REG_WR(sc, igu_addr_ctl, ctl);
16654
16655    bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16656                      BUS_SPACE_BARRIER_WRITE);
16657    mb();
16658
16659    /* wait for clean up to finish */
16660    while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16661        DELAY(20000);
16662    }
16663
16664    if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16665        BLOGD(sc, DBG_LOAD,
16666              "Unable to finish IGU cleanup: "
16667              "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16668              idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16669    }
16670}
16671
16672static void
16673bxe_igu_clear_sb(struct bxe_softc *sc,
16674                 uint8_t          idu_sb_id)
16675{
16676    bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16677}
16678
16679
16680
16681
16682
16683
16684
16685/*******************/
16686/* ECORE CALLBACKS */
16687/*******************/
16688
16689static void
16690bxe_reset_common(struct bxe_softc *sc)
16691{
16692    uint32_t val = 0x1400;
16693
16694    /* reset_common */
16695    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16696
16697    if (CHIP_IS_E3(sc)) {
16698        val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16699        val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16700    }
16701
16702    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16703}
16704
16705static void
16706bxe_common_init_phy(struct bxe_softc *sc)
16707{
16708    uint32_t shmem_base[2];
16709    uint32_t shmem2_base[2];
16710
16711    /* Avoid common init in case MFW supports LFA */
16712    if (SHMEM2_RD(sc, size) >
16713        (uint32_t)offsetof(struct shmem2_region,
16714                           lfa_host_addr[SC_PORT(sc)])) {
16715        return;
16716    }
16717
16718    shmem_base[0]  = sc->devinfo.shmem_base;
16719    shmem2_base[0] = sc->devinfo.shmem2_base;
16720
16721    if (!CHIP_IS_E1x(sc)) {
16722        shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16723        shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16724    }
16725
16726    BXE_PHY_LOCK(sc);
16727    elink_common_init_phy(sc, shmem_base, shmem2_base,
16728                          sc->devinfo.chip_id, 0);
16729    BXE_PHY_UNLOCK(sc);
16730}
16731
16732static void
16733bxe_pf_disable(struct bxe_softc *sc)
16734{
16735    uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16736
16737    val &= ~IGU_PF_CONF_FUNC_EN;
16738
16739    REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16740    REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16741    REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16742}
16743
16744static void
16745bxe_init_pxp(struct bxe_softc *sc)
16746{
16747    uint16_t devctl;
16748    int r_order, w_order;
16749
16750    devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16751
16752    BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16753
16754    w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16755
16756    if (sc->mrrs == -1) {
16757        r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16758    } else {
16759        BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16760        r_order = sc->mrrs;
16761    }
16762
16763    ecore_init_pxp_arb(sc, r_order, w_order);
16764}
16765
16766static uint32_t
16767bxe_get_pretend_reg(struct bxe_softc *sc)
16768{
16769    uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16770    uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16771    return (base + (SC_ABS_FUNC(sc)) * stride);
16772}
16773
16774/*
16775 * Called only on E1H or E2.
16776 * When pretending to be PF, the pretend value is the function number 0..7.
16777 * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16778 * combination.
16779 */
16780static int
16781bxe_pretend_func(struct bxe_softc *sc,
16782                 uint16_t         pretend_func_val)
16783{
16784    uint32_t pretend_reg;
16785
16786    if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16787        return (-1);
16788    }
16789
16790    /* get my own pretend register */
16791    pretend_reg = bxe_get_pretend_reg(sc);
16792    REG_WR(sc, pretend_reg, pretend_func_val);
16793    REG_RD(sc, pretend_reg);
16794    return (0);
16795}
16796
16797static void
16798bxe_iov_init_dmae(struct bxe_softc *sc)
16799{
16800    return;
16801#if 0
16802    BLOGD(sc, DBG_LOAD, "SRIOV is %s\n", IS_SRIOV(sc) ? "ON" : "OFF");
16803
16804    if (!IS_SRIOV(sc)) {
16805        return;
16806    }
16807
16808    REG_WR(sc, DMAE_REG_BACKWARD_COMP_EN, 0);
16809#endif
16810}
16811
16812#if 0
16813static int
16814bxe_iov_init_ilt(struct bxe_softc *sc,
16815                 uint16_t         line)
16816{
16817    return (line);
16818#if 0
16819    int i;
16820    struct ecore_ilt* ilt = sc->ilt;
16821
16822    if (!IS_SRIOV(sc)) {
16823        return (line);
16824    }
16825
16826    /* set vfs ilt lines */
16827    for (i = 0; i < BXE_VF_CIDS/ILT_PAGE_CIDS ; i++) {
16828        struct hw_dma *hw_cxt = SC_VF_CXT_PAGE(sc,i);
16829        ilt->lines[line+i].page = hw_cxt->addr;
16830        ilt->lines[line+i].page_mapping = hw_cxt->mapping;
16831        ilt->lines[line+i].size = hw_cxt->size; /* doesn't matter */
16832    }
16833    return (line+i);
16834#endif
16835}
16836#endif
16837
16838static void
16839bxe_iov_init_dq(struct bxe_softc *sc)
16840{
16841    return;
16842#if 0
16843    if (!IS_SRIOV(sc)) {
16844        return;
16845    }
16846
16847    /* Set the DQ such that the CID reflect the abs_vfid */
16848    REG_WR(sc, DORQ_REG_VF_NORM_VF_BASE, 0);
16849    REG_WR(sc, DORQ_REG_MAX_RVFID_SIZE, ilog2(BNX2X_MAX_NUM_OF_VFS));
16850
16851    /*
16852     * Set VFs starting CID. If its > 0 the preceding CIDs are belong to
16853     * the PF L2 queues
16854     */
16855    REG_WR(sc, DORQ_REG_VF_NORM_CID_BASE, BNX2X_FIRST_VF_CID);
16856
16857    /* The VF window size is the log2 of the max number of CIDs per VF */
16858    REG_WR(sc, DORQ_REG_VF_NORM_CID_WND_SIZE, BNX2X_VF_CID_WND);
16859
16860    /*
16861     * The VF doorbell size  0 - *B, 4 - 128B. We set it here to match
16862     * the Pf doorbell size although the 2 are independent.
16863     */
16864    REG_WR(sc, DORQ_REG_VF_NORM_CID_OFST,
16865           BNX2X_DB_SHIFT - BNX2X_DB_MIN_SHIFT);
16866
16867    /*
16868     * No security checks for now -
16869     * configure single rule (out of 16) mask = 0x1, value = 0x0,
16870     * CID range 0 - 0x1ffff
16871     */
16872    REG_WR(sc, DORQ_REG_VF_TYPE_MASK_0, 1);
16873    REG_WR(sc, DORQ_REG_VF_TYPE_VALUE_0, 0);
16874    REG_WR(sc, DORQ_REG_VF_TYPE_MIN_MCID_0, 0);
16875    REG_WR(sc, DORQ_REG_VF_TYPE_MAX_MCID_0, 0x1ffff);
16876
16877    /* set the number of VF alllowed doorbells to the full DQ range */
16878    REG_WR(sc, DORQ_REG_VF_NORM_MAX_CID_COUNT, 0x20000);
16879
16880    /* set the VF doorbell threshold */
16881    REG_WR(sc, DORQ_REG_VF_USAGE_CT_LIMIT, 4);
16882#endif
16883}
16884
16885/* send a NIG loopback debug packet */
16886static void
16887bxe_lb_pckt(struct bxe_softc *sc)
16888{
16889    uint32_t wb_write[3];
16890
16891    /* Ethernet source and destination addresses */
16892    wb_write[0] = 0x55555555;
16893    wb_write[1] = 0x55555555;
16894    wb_write[2] = 0x20;     /* SOP */
16895    REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16896
16897    /* NON-IP protocol */
16898    wb_write[0] = 0x09000000;
16899    wb_write[1] = 0x55555555;
16900    wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16901    REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16902}
16903
16904/*
16905 * Some of the internal memories are not directly readable from the driver.
16906 * To test them we send debug packets.
16907 */
16908static int
16909bxe_int_mem_test(struct bxe_softc *sc)
16910{
16911    int factor;
16912    int count, i;
16913    uint32_t val = 0;
16914
16915    if (CHIP_REV_IS_FPGA(sc)) {
16916        factor = 120;
16917    } else if (CHIP_REV_IS_EMUL(sc)) {
16918        factor = 200;
16919    } else {
16920        factor = 1;
16921    }
16922
16923    /* disable inputs of parser neighbor blocks */
16924    REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16925    REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16926    REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16927    REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16928
16929    /*  write 0 to parser credits for CFC search request */
16930    REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16931
16932    /* send Ethernet packet */
16933    bxe_lb_pckt(sc);
16934
16935    /* TODO do i reset NIG statistic? */
16936    /* Wait until NIG register shows 1 packet of size 0x10 */
16937    count = 1000 * factor;
16938    while (count) {
16939        bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16940        val = *BXE_SP(sc, wb_data[0]);
16941        if (val == 0x10) {
16942            break;
16943        }
16944
16945        DELAY(10000);
16946        count--;
16947    }
16948
16949    if (val != 0x10) {
16950        BLOGE(sc, "NIG timeout val=0x%x\n", val);
16951        return (-1);
16952    }
16953
16954    /* wait until PRS register shows 1 packet */
16955    count = (1000 * factor);
16956    while (count) {
16957        val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16958        if (val == 1) {
16959            break;
16960        }
16961
16962        DELAY(10000);
16963        count--;
16964    }
16965
16966    if (val != 0x1) {
16967        BLOGE(sc, "PRS timeout val=0x%x\n", val);
16968        return (-2);
16969    }
16970
16971    /* Reset and init BRB, PRS */
16972    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16973    DELAY(50000);
16974    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16975    DELAY(50000);
16976    ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16977    ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16978
16979    /* Disable inputs of parser neighbor blocks */
16980    REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16981    REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16982    REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16983    REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16984
16985    /* Write 0 to parser credits for CFC search request */
16986    REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16987
16988    /* send 10 Ethernet packets */
16989    for (i = 0; i < 10; i++) {
16990        bxe_lb_pckt(sc);
16991    }
16992
16993    /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16994    count = (1000 * factor);
16995    while (count) {
16996        bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16997        val = *BXE_SP(sc, wb_data[0]);
16998        if (val == 0xb0) {
16999            break;
17000        }
17001
17002        DELAY(10000);
17003        count--;
17004    }
17005
17006    if (val != 0xb0) {
17007        BLOGE(sc, "NIG timeout val=0x%x\n", val);
17008        return (-3);
17009    }
17010
17011    /* Wait until PRS register shows 2 packets */
17012    val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
17013    if (val != 2) {
17014        BLOGE(sc, "PRS timeout val=0x%x\n", val);
17015    }
17016
17017    /* Write 1 to parser credits for CFC search request */
17018    REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
17019
17020    /* Wait until PRS register shows 3 packets */
17021    DELAY(10000 * factor);
17022
17023    /* Wait until NIG register shows 1 packet of size 0x10 */
17024    val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
17025    if (val != 3) {
17026        BLOGE(sc, "PRS timeout val=0x%x\n", val);
17027    }
17028
17029    /* clear NIG EOP FIFO */
17030    for (i = 0; i < 11; i++) {
17031        REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
17032    }
17033
17034    val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
17035    if (val != 1) {
17036        BLOGE(sc, "clear of NIG failed\n");
17037        return (-4);
17038    }
17039
17040    /* Reset and init BRB, PRS, NIG */
17041    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
17042    DELAY(50000);
17043    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
17044    DELAY(50000);
17045    ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17046    ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17047    if (!CNIC_SUPPORT(sc)) {
17048        /* set NIC mode */
17049        REG_WR(sc, PRS_REG_NIC_MODE, 1);
17050    }
17051
17052    /* Enable inputs of parser neighbor blocks */
17053    REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
17054    REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
17055    REG_WR(sc, CFC_REG_DEBUG0, 0x0);
17056    REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
17057
17058    return (0);
17059}
17060
17061static void
17062bxe_setup_fan_failure_detection(struct bxe_softc *sc)
17063{
17064    int is_required;
17065    uint32_t val;
17066    int port;
17067
17068    is_required = 0;
17069    val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
17070           SHARED_HW_CFG_FAN_FAILURE_MASK);
17071
17072    if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
17073        is_required = 1;
17074    }
17075    /*
17076     * The fan failure mechanism is usually related to the PHY type since
17077     * the power consumption of the board is affected by the PHY. Currently,
17078     * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
17079     */
17080    else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
17081        for (port = PORT_0; port < PORT_MAX; port++) {
17082            is_required |= elink_fan_failure_det_req(sc,
17083                                                     sc->devinfo.shmem_base,
17084                                                     sc->devinfo.shmem2_base,
17085                                                     port);
17086        }
17087    }
17088
17089    BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
17090
17091    if (is_required == 0) {
17092        return;
17093    }
17094
17095    /* Fan failure is indicated by SPIO 5 */
17096    bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
17097
17098    /* set to active low mode */
17099    val = REG_RD(sc, MISC_REG_SPIO_INT);
17100    val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
17101    REG_WR(sc, MISC_REG_SPIO_INT, val);
17102
17103    /* enable interrupt to signal the IGU */
17104    val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17105    val |= MISC_SPIO_SPIO5;
17106    REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
17107}
17108
17109static void
17110bxe_enable_blocks_attention(struct bxe_softc *sc)
17111{
17112    uint32_t val;
17113
17114    REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
17115    if (!CHIP_IS_E1x(sc)) {
17116        REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
17117    } else {
17118        REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
17119    }
17120    REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17121    REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17122    /*
17123     * mask read length error interrupts in brb for parser
17124     * (parsing unit and 'checksum and crc' unit)
17125     * these errors are legal (PU reads fixed length and CAC can cause
17126     * read length error on truncated packets)
17127     */
17128    REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
17129    REG_WR(sc, QM_REG_QM_INT_MASK, 0);
17130    REG_WR(sc, TM_REG_TM_INT_MASK, 0);
17131    REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
17132    REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
17133    REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
17134/*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
17135/*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
17136    REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
17137    REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
17138    REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
17139/*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
17140/*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
17141    REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
17142    REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
17143    REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
17144    REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
17145/*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
17146/*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
17147
17148    val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
17149           PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
17150           PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
17151    if (!CHIP_IS_E1x(sc)) {
17152        val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
17153                PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
17154    }
17155    REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
17156
17157    REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
17158    REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
17159    REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
17160/*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
17161
17162    if (!CHIP_IS_E1x(sc)) {
17163        /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
17164        REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
17165    }
17166
17167    REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
17168    REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
17169/*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
17170    REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
17171}
17172
17173/**
17174 * bxe_init_hw_common - initialize the HW at the COMMON phase.
17175 *
17176 * @sc:     driver handle
17177 */
17178static int
17179bxe_init_hw_common(struct bxe_softc *sc)
17180{
17181    uint8_t abs_func_id;
17182    uint32_t val;
17183
17184    BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
17185          SC_ABS_FUNC(sc));
17186
17187    /*
17188     * take the RESET lock to protect undi_unload flow from accessing
17189     * registers while we are resetting the chip
17190     */
17191    bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
17192
17193    bxe_reset_common(sc);
17194
17195    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
17196
17197    val = 0xfffc;
17198    if (CHIP_IS_E3(sc)) {
17199        val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
17200        val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
17201    }
17202
17203    REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
17204
17205    bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
17206
17207    ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
17208    BLOGD(sc, DBG_LOAD, "after misc block init\n");
17209
17210    if (!CHIP_IS_E1x(sc)) {
17211        /*
17212         * 4-port mode or 2-port mode we need to turn off master-enable for
17213         * everyone. After that we turn it back on for self. So, we disregard
17214         * multi-function, and always disable all functions on the given path,
17215         * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
17216         */
17217        for (abs_func_id = SC_PATH(sc);
17218             abs_func_id < (E2_FUNC_MAX * 2);
17219             abs_func_id += 2) {
17220            if (abs_func_id == SC_ABS_FUNC(sc)) {
17221                REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17222                continue;
17223            }
17224
17225            bxe_pretend_func(sc, abs_func_id);
17226
17227            /* clear pf enable */
17228            bxe_pf_disable(sc);
17229
17230            bxe_pretend_func(sc, SC_ABS_FUNC(sc));
17231        }
17232    }
17233
17234    BLOGD(sc, DBG_LOAD, "after pf disable\n");
17235
17236    ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
17237
17238    if (CHIP_IS_E1(sc)) {
17239        /*
17240         * enable HW interrupt from PXP on USDM overflow
17241         * bit 16 on INT_MASK_0
17242         */
17243        REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
17244    }
17245
17246    ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
17247    bxe_init_pxp(sc);
17248
17249#ifdef __BIG_ENDIAN
17250    REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
17251    REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
17252    REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
17253    REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
17254    REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
17255    /* make sure this value is 0 */
17256    REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
17257
17258    //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
17259    REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
17260    REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
17261    REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
17262    REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
17263#endif
17264
17265    ecore_ilt_init_page_size(sc, INITOP_SET);
17266
17267    if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
17268        REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
17269    }
17270
17271    /* let the HW do it's magic... */
17272    DELAY(100000);
17273
17274    /* finish PXP init */
17275    val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
17276    if (val != 1) {
17277        BLOGE(sc, "PXP2 CFG failed\n");
17278        return (-1);
17279    }
17280    val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
17281    if (val != 1) {
17282        BLOGE(sc, "PXP2 RD_INIT failed\n");
17283        return (-1);
17284    }
17285
17286    BLOGD(sc, DBG_LOAD, "after pxp init\n");
17287
17288    /*
17289     * Timer bug workaround for E2 only. We need to set the entire ILT to have
17290     * entries with value "0" and valid bit on. This needs to be done by the
17291     * first PF that is loaded in a path (i.e. common phase)
17292     */
17293    if (!CHIP_IS_E1x(sc)) {
17294/*
17295 * In E2 there is a bug in the timers block that can cause function 6 / 7
17296 * (i.e. vnic3) to start even if it is marked as "scan-off".
17297 * This occurs when a different function (func2,3) is being marked
17298 * as "scan-off". Real-life scenario for example: if a driver is being
17299 * load-unloaded while func6,7 are down. This will cause the timer to access
17300 * the ilt, translate to a logical address and send a request to read/write.
17301 * Since the ilt for the function that is down is not valid, this will cause
17302 * a translation error which is unrecoverable.
17303 * The Workaround is intended to make sure that when this happens nothing
17304 * fatal will occur. The workaround:
17305 *  1.  First PF driver which loads on a path will:
17306 *      a.  After taking the chip out of reset, by using pretend,
17307 *          it will write "0" to the following registers of
17308 *          the other vnics.
17309 *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
17310 *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
17311 *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
17312 *          And for itself it will write '1' to
17313 *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
17314 *          dmae-operations (writing to pram for example.)
17315 *          note: can be done for only function 6,7 but cleaner this
17316 *            way.
17317 *      b.  Write zero+valid to the entire ILT.
17318 *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
17319 *          VNIC3 (of that port). The range allocated will be the
17320 *          entire ILT. This is needed to prevent  ILT range error.
17321 *  2.  Any PF driver load flow:
17322 *      a.  ILT update with the physical addresses of the allocated
17323 *          logical pages.
17324 *      b.  Wait 20msec. - note that this timeout is needed to make
17325 *          sure there are no requests in one of the PXP internal
17326 *          queues with "old" ILT addresses.
17327 *      c.  PF enable in the PGLC.
17328 *      d.  Clear the was_error of the PF in the PGLC. (could have
17329 *          occurred while driver was down)
17330 *      e.  PF enable in the CFC (WEAK + STRONG)
17331 *      f.  Timers scan enable
17332 *  3.  PF driver unload flow:
17333 *      a.  Clear the Timers scan_en.
17334 *      b.  Polling for scan_on=0 for that PF.
17335 *      c.  Clear the PF enable bit in the PXP.
17336 *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
17337 *      e.  Write zero+valid to all ILT entries (The valid bit must
17338 *          stay set)
17339 *      f.  If this is VNIC 3 of a port then also init
17340 *          first_timers_ilt_entry to zero and last_timers_ilt_entry
17341 *          to the last enrty in the ILT.
17342 *
17343 *      Notes:
17344 *      Currently the PF error in the PGLC is non recoverable.
17345 *      In the future the there will be a recovery routine for this error.
17346 *      Currently attention is masked.
17347 *      Having an MCP lock on the load/unload process does not guarantee that
17348 *      there is no Timer disable during Func6/7 enable. This is because the
17349 *      Timers scan is currently being cleared by the MCP on FLR.
17350 *      Step 2.d can be done only for PF6/7 and the driver can also check if
17351 *      there is error before clearing it. But the flow above is simpler and
17352 *      more general.
17353 *      All ILT entries are written by zero+valid and not just PF6/7
17354 *      ILT entries since in the future the ILT entries allocation for
17355 *      PF-s might be dynamic.
17356 */
17357        struct ilt_client_info ilt_cli;
17358        struct ecore_ilt ilt;
17359
17360        memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
17361        memset(&ilt, 0, sizeof(struct ecore_ilt));
17362
17363        /* initialize dummy TM client */
17364        ilt_cli.start      = 0;
17365        ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
17366        ilt_cli.client_num = ILT_CLIENT_TM;
17367
17368        /*
17369         * Step 1: set zeroes to all ilt page entries with valid bit on
17370         * Step 2: set the timers first/last ilt entry to point
17371         * to the entire range to prevent ILT range error for 3rd/4th
17372         * vnic (this code assumes existence of the vnic)
17373         *
17374         * both steps performed by call to ecore_ilt_client_init_op()
17375         * with dummy TM client
17376         *
17377         * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
17378         * and his brother are split registers
17379         */
17380
17381        bxe_pretend_func(sc, (SC_PATH(sc) + 6));
17382        ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
17383        bxe_pretend_func(sc, SC_ABS_FUNC(sc));
17384
17385        REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
17386        REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
17387        REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
17388    }
17389
17390    REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
17391    REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
17392
17393    if (!CHIP_IS_E1x(sc)) {
17394        int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
17395                     (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
17396
17397        ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
17398        ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
17399
17400        /* let the HW do it's magic... */
17401        do {
17402            DELAY(200000);
17403            val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
17404        } while (factor-- && (val != 1));
17405
17406        if (val != 1) {
17407            BLOGE(sc, "ATC_INIT failed\n");
17408            return (-1);
17409        }
17410    }
17411
17412    BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
17413
17414    ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
17415
17416    bxe_iov_init_dmae(sc);
17417
17418    /* clean the DMAE memory */
17419    sc->dmae_ready = 1;
17420    ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
17421
17422    ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
17423
17424    ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
17425
17426    ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
17427
17428    ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
17429
17430    bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
17431    bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17432    bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17433    bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17434
17435    ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17436
17437    /* QM queues pointers table */
17438    ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17439
17440    /* soft reset pulse */
17441    REG_WR(sc, QM_REG_SOFT_RESET, 1);
17442    REG_WR(sc, QM_REG_SOFT_RESET, 0);
17443
17444    if (CNIC_SUPPORT(sc))
17445        ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17446
17447    ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17448    REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17449    if (!CHIP_REV_IS_SLOW(sc)) {
17450        /* enable hw interrupt from doorbell Q */
17451        REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17452    }
17453
17454    ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17455
17456    ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17457    REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17458
17459    if (!CHIP_IS_E1(sc)) {
17460        REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17461    }
17462
17463    if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17464        if (IS_MF_AFEX(sc)) {
17465            /*
17466             * configure that AFEX and VLAN headers must be
17467             * received in AFEX mode
17468             */
17469            REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17470            REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17471            REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17472            REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17473            REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17474        } else {
17475            /*
17476             * Bit-map indicating which L2 hdrs may appear
17477             * after the basic Ethernet header
17478             */
17479            REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17480                   sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17481        }
17482    }
17483
17484    ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17485    ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17486    ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17487    ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17488
17489    if (!CHIP_IS_E1x(sc)) {
17490        /* reset VFC memories */
17491        REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17492               VFC_MEMORIES_RST_REG_CAM_RST |
17493               VFC_MEMORIES_RST_REG_RAM_RST);
17494        REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17495               VFC_MEMORIES_RST_REG_CAM_RST |
17496               VFC_MEMORIES_RST_REG_RAM_RST);
17497
17498        DELAY(20000);
17499    }
17500
17501    ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17502    ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17503    ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17504    ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17505
17506    /* sync semi rtc */
17507    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17508           0x80000000);
17509    REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17510           0x80000000);
17511
17512    ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17513    ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17514    ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17515
17516    if (!CHIP_IS_E1x(sc)) {
17517        if (IS_MF_AFEX(sc)) {
17518            /*
17519             * configure that AFEX and VLAN headers must be
17520             * sent in AFEX mode
17521             */
17522            REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17523            REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17524            REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17525            REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17526            REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17527        } else {
17528            REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17529                   sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17530        }
17531    }
17532
17533    REG_WR(sc, SRC_REG_SOFT_RST, 1);
17534
17535    ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17536
17537    if (CNIC_SUPPORT(sc)) {
17538        REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17539        REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17540        REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17541        REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17542        REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17543        REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17544        REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17545        REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17546        REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17547        REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17548    }
17549    REG_WR(sc, SRC_REG_SOFT_RST, 0);
17550
17551    if (sizeof(union cdu_context) != 1024) {
17552        /* we currently assume that a context is 1024 bytes */
17553        BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17554              (long)sizeof(union cdu_context));
17555    }
17556
17557    ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17558    val = (4 << 24) + (0 << 12) + 1024;
17559    REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17560
17561    ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17562
17563    REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17564    /* enable context validation interrupt from CFC */
17565    REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17566
17567    /* set the thresholds to prevent CFC/CDU race */
17568    REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17569    ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17570
17571    if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17572        REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17573    }
17574
17575    ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17576    ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17577
17578    /* Reset PCIE errors for debug */
17579    REG_WR(sc, 0x2814, 0xffffffff);
17580    REG_WR(sc, 0x3820, 0xffffffff);
17581
17582    if (!CHIP_IS_E1x(sc)) {
17583        REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17584               (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17585                PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17586        REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17587               (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17588                PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17589                PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17590        REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17591               (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17592                PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17593                PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17594    }
17595
17596    ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17597
17598    if (!CHIP_IS_E1(sc)) {
17599        /* in E3 this done in per-port section */
17600        if (!CHIP_IS_E3(sc))
17601            REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17602    }
17603
17604    if (CHIP_IS_E1H(sc)) {
17605        /* not applicable for E2 (and above ...) */
17606        REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17607    }
17608
17609    if (CHIP_REV_IS_SLOW(sc)) {
17610        DELAY(200000);
17611    }
17612
17613    /* finish CFC init */
17614    val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17615    if (val != 1) {
17616        BLOGE(sc, "CFC LL_INIT failed\n");
17617        return (-1);
17618    }
17619    val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17620    if (val != 1) {
17621        BLOGE(sc, "CFC AC_INIT failed\n");
17622        return (-1);
17623    }
17624    val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17625    if (val != 1) {
17626        BLOGE(sc, "CFC CAM_INIT failed\n");
17627        return (-1);
17628    }
17629    REG_WR(sc, CFC_REG_DEBUG0, 0);
17630
17631    if (CHIP_IS_E1(sc)) {
17632        /* read NIG statistic to see if this is our first up since powerup */
17633        bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17634        val = *BXE_SP(sc, wb_data[0]);
17635
17636        /* do internal memory self test */
17637        if ((val == 0) && bxe_int_mem_test(sc)) {
17638            BLOGE(sc, "internal mem self test failed\n");
17639            return (-1);
17640        }
17641    }
17642
17643    bxe_setup_fan_failure_detection(sc);
17644
17645    /* clear PXP2 attentions */
17646    REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17647
17648    bxe_enable_blocks_attention(sc);
17649
17650    if (!CHIP_REV_IS_SLOW(sc)) {
17651        ecore_enable_blocks_parity(sc);
17652    }
17653
17654    if (!BXE_NOMCP(sc)) {
17655        if (CHIP_IS_E1x(sc)) {
17656            bxe_common_init_phy(sc);
17657        }
17658    }
17659
17660    return (0);
17661}
17662
17663/**
17664 * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17665 *
17666 * @sc:     driver handle
17667 */
17668static int
17669bxe_init_hw_common_chip(struct bxe_softc *sc)
17670{
17671    int rc = bxe_init_hw_common(sc);
17672
17673    if (rc) {
17674        return (rc);
17675    }
17676
17677    /* In E2 2-PORT mode, same ext phy is used for the two paths */
17678    if (!BXE_NOMCP(sc)) {
17679        bxe_common_init_phy(sc);
17680    }
17681
17682    return (0);
17683}
17684
17685static int
17686bxe_init_hw_port(struct bxe_softc *sc)
17687{
17688    int port = SC_PORT(sc);
17689    int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17690    uint32_t low, high;
17691    uint32_t val;
17692
17693    BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17694
17695    REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17696
17697    ecore_init_block(sc, BLOCK_MISC, init_phase);
17698    ecore_init_block(sc, BLOCK_PXP, init_phase);
17699    ecore_init_block(sc, BLOCK_PXP2, init_phase);
17700
17701    /*
17702     * Timers bug workaround: disables the pf_master bit in pglue at
17703     * common phase, we need to enable it here before any dmae access are
17704     * attempted. Therefore we manually added the enable-master to the
17705     * port phase (it also happens in the function phase)
17706     */
17707    if (!CHIP_IS_E1x(sc)) {
17708        REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17709    }
17710
17711    ecore_init_block(sc, BLOCK_ATC, init_phase);
17712    ecore_init_block(sc, BLOCK_DMAE, init_phase);
17713    ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17714    ecore_init_block(sc, BLOCK_QM, init_phase);
17715
17716    ecore_init_block(sc, BLOCK_TCM, init_phase);
17717    ecore_init_block(sc, BLOCK_UCM, init_phase);
17718    ecore_init_block(sc, BLOCK_CCM, init_phase);
17719    ecore_init_block(sc, BLOCK_XCM, init_phase);
17720
17721    /* QM cid (connection) count */
17722    ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17723
17724    if (CNIC_SUPPORT(sc)) {
17725        ecore_init_block(sc, BLOCK_TM, init_phase);
17726        REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17727        REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17728    }
17729
17730    ecore_init_block(sc, BLOCK_DORQ, init_phase);
17731
17732    ecore_init_block(sc, BLOCK_BRB1, init_phase);
17733
17734    if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17735        if (IS_MF(sc)) {
17736            low = (BXE_ONE_PORT(sc) ? 160 : 246);
17737        } else if (sc->mtu > 4096) {
17738            if (BXE_ONE_PORT(sc)) {
17739                low = 160;
17740            } else {
17741                val = sc->mtu;
17742                /* (24*1024 + val*4)/256 */
17743                low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17744            }
17745        } else {
17746            low = (BXE_ONE_PORT(sc) ? 80 : 160);
17747        }
17748        high = (low + 56); /* 14*1024/256 */
17749        REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17750        REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17751    }
17752
17753    if (CHIP_IS_MODE_4_PORT(sc)) {
17754        REG_WR(sc, SC_PORT(sc) ?
17755               BRB1_REG_MAC_GUARANTIED_1 :
17756               BRB1_REG_MAC_GUARANTIED_0, 40);
17757    }
17758
17759    ecore_init_block(sc, BLOCK_PRS, init_phase);
17760    if (CHIP_IS_E3B0(sc)) {
17761        if (IS_MF_AFEX(sc)) {
17762            /* configure headers for AFEX mode */
17763            REG_WR(sc, SC_PORT(sc) ?
17764                   PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17765                   PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17766            REG_WR(sc, SC_PORT(sc) ?
17767                   PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17768                   PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17769            REG_WR(sc, SC_PORT(sc) ?
17770                   PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17771                   PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17772        } else {
17773            /* Ovlan exists only if we are in multi-function +
17774             * switch-dependent mode, in switch-independent there
17775             * is no ovlan headers
17776             */
17777            REG_WR(sc, SC_PORT(sc) ?
17778                   PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17779                   PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17780                   (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17781        }
17782    }
17783
17784    ecore_init_block(sc, BLOCK_TSDM, init_phase);
17785    ecore_init_block(sc, BLOCK_CSDM, init_phase);
17786    ecore_init_block(sc, BLOCK_USDM, init_phase);
17787    ecore_init_block(sc, BLOCK_XSDM, init_phase);
17788
17789    ecore_init_block(sc, BLOCK_TSEM, init_phase);
17790    ecore_init_block(sc, BLOCK_USEM, init_phase);
17791    ecore_init_block(sc, BLOCK_CSEM, init_phase);
17792    ecore_init_block(sc, BLOCK_XSEM, init_phase);
17793
17794    ecore_init_block(sc, BLOCK_UPB, init_phase);
17795    ecore_init_block(sc, BLOCK_XPB, init_phase);
17796
17797    ecore_init_block(sc, BLOCK_PBF, init_phase);
17798
17799    if (CHIP_IS_E1x(sc)) {
17800        /* configure PBF to work without PAUSE mtu 9000 */
17801        REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17802
17803        /* update threshold */
17804        REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17805        /* update init credit */
17806        REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17807
17808        /* probe changes */
17809        REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17810        DELAY(50);
17811        REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17812    }
17813
17814    if (CNIC_SUPPORT(sc)) {
17815        ecore_init_block(sc, BLOCK_SRC, init_phase);
17816    }
17817
17818    ecore_init_block(sc, BLOCK_CDU, init_phase);
17819    ecore_init_block(sc, BLOCK_CFC, init_phase);
17820
17821    if (CHIP_IS_E1(sc)) {
17822        REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17823        REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17824    }
17825    ecore_init_block(sc, BLOCK_HC, init_phase);
17826
17827    ecore_init_block(sc, BLOCK_IGU, init_phase);
17828
17829    ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17830    /* init aeu_mask_attn_func_0/1:
17831     *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17832     *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17833     *             bits 4-7 are used for "per vn group attention" */
17834    val = IS_MF(sc) ? 0xF7 : 0x7;
17835    /* Enable DCBX attention for all but E1 */
17836    val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17837    REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17838
17839    ecore_init_block(sc, BLOCK_NIG, init_phase);
17840
17841    if (!CHIP_IS_E1x(sc)) {
17842        /* Bit-map indicating which L2 hdrs may appear after the
17843         * basic Ethernet header
17844         */
17845        if (IS_MF_AFEX(sc)) {
17846            REG_WR(sc, SC_PORT(sc) ?
17847                   NIG_REG_P1_HDRS_AFTER_BASIC :
17848                   NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17849        } else {
17850            REG_WR(sc, SC_PORT(sc) ?
17851                   NIG_REG_P1_HDRS_AFTER_BASIC :
17852                   NIG_REG_P0_HDRS_AFTER_BASIC,
17853                   IS_MF_SD(sc) ? 7 : 6);
17854        }
17855
17856        if (CHIP_IS_E3(sc)) {
17857            REG_WR(sc, SC_PORT(sc) ?
17858                   NIG_REG_LLH1_MF_MODE :
17859                   NIG_REG_LLH_MF_MODE, IS_MF(sc));
17860        }
17861    }
17862    if (!CHIP_IS_E3(sc)) {
17863        REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17864    }
17865
17866    if (!CHIP_IS_E1(sc)) {
17867        /* 0x2 disable mf_ov, 0x1 enable */
17868        REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17869               (IS_MF_SD(sc) ? 0x1 : 0x2));
17870
17871        if (!CHIP_IS_E1x(sc)) {
17872            val = 0;
17873            switch (sc->devinfo.mf_info.mf_mode) {
17874            case MULTI_FUNCTION_SD:
17875                val = 1;
17876                break;
17877            case MULTI_FUNCTION_SI:
17878            case MULTI_FUNCTION_AFEX:
17879                val = 2;
17880                break;
17881            }
17882
17883            REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17884                        NIG_REG_LLH0_CLS_TYPE), val);
17885        }
17886        REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17887        REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17888        REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17889    }
17890
17891    /* If SPIO5 is set to generate interrupts, enable it for this port */
17892    val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17893    if (val & MISC_SPIO_SPIO5) {
17894        uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17895                                    MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17896        val = REG_RD(sc, reg_addr);
17897        val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17898        REG_WR(sc, reg_addr, val);
17899    }
17900
17901    return (0);
17902}
17903
17904static uint32_t
17905bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17906                       uint32_t         reg,
17907                       uint32_t         expected,
17908                       uint32_t         poll_count)
17909{
17910    uint32_t cur_cnt = poll_count;
17911    uint32_t val;
17912
17913    while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17914        DELAY(FLR_WAIT_INTERVAL);
17915    }
17916
17917    return (val);
17918}
17919
17920static int
17921bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17922                              uint32_t         reg,
17923                              char             *msg,
17924                              uint32_t         poll_cnt)
17925{
17926    uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17927
17928    if (val != 0) {
17929        BLOGE(sc, "%s usage count=%d\n", msg, val);
17930        return (1);
17931    }
17932
17933    return (0);
17934}
17935
17936/* Common routines with VF FLR cleanup */
17937static uint32_t
17938bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17939{
17940    /* adjust polling timeout */
17941    if (CHIP_REV_IS_EMUL(sc)) {
17942        return (FLR_POLL_CNT * 2000);
17943    }
17944
17945    if (CHIP_REV_IS_FPGA(sc)) {
17946        return (FLR_POLL_CNT * 120);
17947    }
17948
17949    return (FLR_POLL_CNT);
17950}
17951
17952static int
17953bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17954                           uint32_t         poll_cnt)
17955{
17956    /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17957    if (bxe_flr_clnup_poll_hw_counter(sc,
17958                                      CFC_REG_NUM_LCIDS_INSIDE_PF,
17959                                      "CFC PF usage counter timed out",
17960                                      poll_cnt)) {
17961        return (1);
17962    }
17963
17964    /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17965    if (bxe_flr_clnup_poll_hw_counter(sc,
17966                                      DORQ_REG_PF_USAGE_CNT,
17967                                      "DQ PF usage counter timed out",
17968                                      poll_cnt)) {
17969        return (1);
17970    }
17971
17972    /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17973    if (bxe_flr_clnup_poll_hw_counter(sc,
17974                                      QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17975                                      "QM PF usage counter timed out",
17976                                      poll_cnt)) {
17977        return (1);
17978    }
17979
17980    /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17981    if (bxe_flr_clnup_poll_hw_counter(sc,
17982                                      TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17983                                      "Timers VNIC usage counter timed out",
17984                                      poll_cnt)) {
17985        return (1);
17986    }
17987
17988    if (bxe_flr_clnup_poll_hw_counter(sc,
17989                                      TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17990                                      "Timers NUM_SCANS usage counter timed out",
17991                                      poll_cnt)) {
17992        return (1);
17993    }
17994
17995    /* Wait DMAE PF usage counter to zero */
17996    if (bxe_flr_clnup_poll_hw_counter(sc,
17997                                      dmae_reg_go_c[INIT_DMAE_C(sc)],
17998                                      "DMAE dommand register timed out",
17999                                      poll_cnt)) {
18000        return (1);
18001    }
18002
18003    return (0);
18004}
18005
18006#define OP_GEN_PARAM(param)                                            \
18007    (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
18008#define OP_GEN_TYPE(type)                                           \
18009    (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
18010#define OP_GEN_AGG_VECT(index)                                             \
18011    (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
18012
18013static int
18014bxe_send_final_clnup(struct bxe_softc *sc,
18015                     uint8_t          clnup_func,
18016                     uint32_t         poll_cnt)
18017{
18018    uint32_t op_gen_command = 0;
18019    uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
18020                          CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
18021    int ret = 0;
18022
18023    if (REG_RD(sc, comp_addr)) {
18024        BLOGE(sc, "Cleanup complete was not 0 before sending\n");
18025        return (1);
18026    }
18027
18028    op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
18029    op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
18030    op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
18031    op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
18032
18033    BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
18034    REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
18035
18036    if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
18037        BLOGE(sc, "FW final cleanup did not succeed\n");
18038        BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
18039              (REG_RD(sc, comp_addr)));
18040        bxe_panic(sc, ("FLR cleanup failed\n"));
18041        return (1);
18042    }
18043
18044    /* Zero completion for nxt FLR */
18045    REG_WR(sc, comp_addr, 0);
18046
18047    return (ret);
18048}
18049
18050static void
18051bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
18052                       struct pbf_pN_buf_regs *regs,
18053                       uint32_t               poll_count)
18054{
18055    uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
18056    uint32_t cur_cnt = poll_count;
18057
18058    crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
18059    crd = crd_start = REG_RD(sc, regs->crd);
18060    init_crd = REG_RD(sc, regs->init_crd);
18061
18062    BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
18063    BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
18064    BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
18065
18066    while ((crd != init_crd) &&
18067           ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
18068            (init_crd - crd_start))) {
18069        if (cur_cnt--) {
18070            DELAY(FLR_WAIT_INTERVAL);
18071            crd = REG_RD(sc, regs->crd);
18072            crd_freed = REG_RD(sc, regs->crd_freed);
18073        } else {
18074            BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
18075            BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
18076            BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
18077            break;
18078        }
18079    }
18080
18081    BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
18082          poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
18083}
18084
18085static void
18086bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
18087                       struct pbf_pN_cmd_regs *regs,
18088                       uint32_t               poll_count)
18089{
18090    uint32_t occup, to_free, freed, freed_start;
18091    uint32_t cur_cnt = poll_count;
18092
18093    occup = to_free = REG_RD(sc, regs->lines_occup);
18094    freed = freed_start = REG_RD(sc, regs->lines_freed);
18095
18096    BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
18097    BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
18098
18099    while (occup &&
18100           ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
18101        if (cur_cnt--) {
18102            DELAY(FLR_WAIT_INTERVAL);
18103            occup = REG_RD(sc, regs->lines_occup);
18104            freed = REG_RD(sc, regs->lines_freed);
18105        } else {
18106            BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
18107            BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
18108            BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
18109            break;
18110        }
18111    }
18112
18113    BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
18114          poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
18115}
18116
18117static void
18118bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
18119{
18120    struct pbf_pN_cmd_regs cmd_regs[] = {
18121        {0, (CHIP_IS_E3B0(sc)) ?
18122            PBF_REG_TQ_OCCUPANCY_Q0 :
18123            PBF_REG_P0_TQ_OCCUPANCY,
18124            (CHIP_IS_E3B0(sc)) ?
18125            PBF_REG_TQ_LINES_FREED_CNT_Q0 :
18126            PBF_REG_P0_TQ_LINES_FREED_CNT},
18127        {1, (CHIP_IS_E3B0(sc)) ?
18128            PBF_REG_TQ_OCCUPANCY_Q1 :
18129            PBF_REG_P1_TQ_OCCUPANCY,
18130            (CHIP_IS_E3B0(sc)) ?
18131            PBF_REG_TQ_LINES_FREED_CNT_Q1 :
18132            PBF_REG_P1_TQ_LINES_FREED_CNT},
18133        {4, (CHIP_IS_E3B0(sc)) ?
18134            PBF_REG_TQ_OCCUPANCY_LB_Q :
18135            PBF_REG_P4_TQ_OCCUPANCY,
18136            (CHIP_IS_E3B0(sc)) ?
18137            PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
18138            PBF_REG_P4_TQ_LINES_FREED_CNT}
18139    };
18140
18141    struct pbf_pN_buf_regs buf_regs[] = {
18142        {0, (CHIP_IS_E3B0(sc)) ?
18143            PBF_REG_INIT_CRD_Q0 :
18144            PBF_REG_P0_INIT_CRD ,
18145            (CHIP_IS_E3B0(sc)) ?
18146            PBF_REG_CREDIT_Q0 :
18147            PBF_REG_P0_CREDIT,
18148            (CHIP_IS_E3B0(sc)) ?
18149            PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
18150            PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
18151        {1, (CHIP_IS_E3B0(sc)) ?
18152            PBF_REG_INIT_CRD_Q1 :
18153            PBF_REG_P1_INIT_CRD,
18154            (CHIP_IS_E3B0(sc)) ?
18155            PBF_REG_CREDIT_Q1 :
18156            PBF_REG_P1_CREDIT,
18157            (CHIP_IS_E3B0(sc)) ?
18158            PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
18159            PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
18160        {4, (CHIP_IS_E3B0(sc)) ?
18161            PBF_REG_INIT_CRD_LB_Q :
18162            PBF_REG_P4_INIT_CRD,
18163            (CHIP_IS_E3B0(sc)) ?
18164            PBF_REG_CREDIT_LB_Q :
18165            PBF_REG_P4_CREDIT,
18166            (CHIP_IS_E3B0(sc)) ?
18167            PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
18168            PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
18169    };
18170
18171    int i;
18172
18173    /* Verify the command queues are flushed P0, P1, P4 */
18174    for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
18175        bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
18176    }
18177
18178    /* Verify the transmission buffers are flushed P0, P1, P4 */
18179    for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
18180        bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
18181    }
18182}
18183
18184static void
18185bxe_hw_enable_status(struct bxe_softc *sc)
18186{
18187    uint32_t val;
18188
18189    val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
18190    BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
18191
18192    val = REG_RD(sc, PBF_REG_DISABLE_PF);
18193    BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
18194
18195    val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
18196    BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
18197
18198    val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
18199    BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
18200
18201    val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
18202    BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
18203
18204    val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
18205    BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
18206
18207    val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
18208    BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
18209
18210    val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
18211    BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
18212}
18213
18214static int
18215bxe_pf_flr_clnup(struct bxe_softc *sc)
18216{
18217    uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
18218
18219    BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
18220
18221    /* Re-enable PF target read access */
18222    REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
18223
18224    /* Poll HW usage counters */
18225    BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
18226    if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
18227        return (-1);
18228    }
18229
18230    /* Zero the igu 'trailing edge' and 'leading edge' */
18231
18232    /* Send the FW cleanup command */
18233    if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
18234        return (-1);
18235    }
18236
18237    /* ATC cleanup */
18238
18239    /* Verify TX hw is flushed */
18240    bxe_tx_hw_flushed(sc, poll_cnt);
18241
18242    /* Wait 100ms (not adjusted according to platform) */
18243    DELAY(100000);
18244
18245    /* Verify no pending pci transactions */
18246    if (bxe_is_pcie_pending(sc)) {
18247        BLOGE(sc, "PCIE Transactions still pending\n");
18248    }
18249
18250    /* Debug */
18251    bxe_hw_enable_status(sc);
18252
18253    /*
18254     * Master enable - Due to WB DMAE writes performed before this
18255     * register is re-initialized as part of the regular function init
18256     */
18257    REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
18258
18259    return (0);
18260}
18261
18262#if 0
18263static void
18264bxe_init_searcher(struct bxe_softc *sc)
18265{
18266    int port = SC_PORT(sc);
18267    ecore_src_init_t2(sc, sc->t2, sc->t2_mapping, SRC_CONN_NUM);
18268    /* T1 hash bits value determines the T1 number of entries */
18269    REG_WR(sc, SRC_REG_NUMBER_HASH_BITS0 + port*4, SRC_HASH_BITS);
18270}
18271#endif
18272
18273static int
18274bxe_init_hw_func(struct bxe_softc *sc)
18275{
18276    int port = SC_PORT(sc);
18277    int func = SC_FUNC(sc);
18278    int init_phase = PHASE_PF0 + func;
18279    struct ecore_ilt *ilt = sc->ilt;
18280    uint16_t cdu_ilt_start;
18281    uint32_t addr, val;
18282    uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
18283    int i, main_mem_width, rc;
18284
18285    BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
18286
18287    /* FLR cleanup */
18288    if (!CHIP_IS_E1x(sc)) {
18289        rc = bxe_pf_flr_clnup(sc);
18290        if (rc) {
18291            BLOGE(sc, "FLR cleanup failed!\n");
18292            // XXX bxe_fw_dump(sc);
18293            // XXX bxe_idle_chk(sc);
18294            return (rc);
18295        }
18296    }
18297
18298    /* set MSI reconfigure capability */
18299    if (sc->devinfo.int_block == INT_BLOCK_HC) {
18300        addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
18301        val = REG_RD(sc, addr);
18302        val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
18303        REG_WR(sc, addr, val);
18304    }
18305
18306    ecore_init_block(sc, BLOCK_PXP, init_phase);
18307    ecore_init_block(sc, BLOCK_PXP2, init_phase);
18308
18309    ilt = sc->ilt;
18310    cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
18311
18312#if 0
18313    if (IS_SRIOV(sc)) {
18314        cdu_ilt_start += BXE_FIRST_VF_CID/ILT_PAGE_CIDS;
18315    }
18316    cdu_ilt_start = bxe_iov_init_ilt(sc, cdu_ilt_start);
18317
18318#if (BXE_FIRST_VF_CID > 0)
18319    /*
18320     * If BXE_FIRST_VF_CID > 0 then the PF L2 cids precedes
18321     * those of the VFs, so start line should be reset
18322     */
18323    cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
18324#endif
18325#endif
18326
18327    for (i = 0; i < L2_ILT_LINES(sc); i++) {
18328        ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
18329        ilt->lines[cdu_ilt_start + i].page_mapping =
18330            sc->context[i].vcxt_dma.paddr;
18331        ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
18332    }
18333    ecore_ilt_init_op(sc, INITOP_SET);
18334
18335#if 0
18336    if (!CONFIGURE_NIC_MODE(sc)) {
18337        bxe_init_searcher(sc);
18338        REG_WR(sc, PRS_REG_NIC_MODE, 0);
18339        BLOGD(sc, DBG_LOAD, "NIC MODE disabled\n");
18340    } else
18341#endif
18342    {
18343        /* Set NIC mode */
18344        REG_WR(sc, PRS_REG_NIC_MODE, 1);
18345        BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
18346    }
18347
18348    if (!CHIP_IS_E1x(sc)) {
18349        uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
18350
18351        /* Turn on a single ISR mode in IGU if driver is going to use
18352         * INT#x or MSI
18353         */
18354        if (sc->interrupt_mode != INTR_MODE_MSIX) {
18355            pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
18356        }
18357
18358        /*
18359         * Timers workaround bug: function init part.
18360         * Need to wait 20msec after initializing ILT,
18361         * needed to make sure there are no requests in
18362         * one of the PXP internal queues with "old" ILT addresses
18363         */
18364        DELAY(20000);
18365
18366        /*
18367         * Master enable - Due to WB DMAE writes performed before this
18368         * register is re-initialized as part of the regular function
18369         * init
18370         */
18371        REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
18372        /* Enable the function in IGU */
18373        REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
18374    }
18375
18376    sc->dmae_ready = 1;
18377
18378    ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
18379
18380    if (!CHIP_IS_E1x(sc))
18381        REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
18382
18383    ecore_init_block(sc, BLOCK_ATC, init_phase);
18384    ecore_init_block(sc, BLOCK_DMAE, init_phase);
18385    ecore_init_block(sc, BLOCK_NIG, init_phase);
18386    ecore_init_block(sc, BLOCK_SRC, init_phase);
18387    ecore_init_block(sc, BLOCK_MISC, init_phase);
18388    ecore_init_block(sc, BLOCK_TCM, init_phase);
18389    ecore_init_block(sc, BLOCK_UCM, init_phase);
18390    ecore_init_block(sc, BLOCK_CCM, init_phase);
18391    ecore_init_block(sc, BLOCK_XCM, init_phase);
18392    ecore_init_block(sc, BLOCK_TSEM, init_phase);
18393    ecore_init_block(sc, BLOCK_USEM, init_phase);
18394    ecore_init_block(sc, BLOCK_CSEM, init_phase);
18395    ecore_init_block(sc, BLOCK_XSEM, init_phase);
18396
18397    if (!CHIP_IS_E1x(sc))
18398        REG_WR(sc, QM_REG_PF_EN, 1);
18399
18400    if (!CHIP_IS_E1x(sc)) {
18401        REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18402        REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18403        REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18404        REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18405    }
18406    ecore_init_block(sc, BLOCK_QM, init_phase);
18407
18408    ecore_init_block(sc, BLOCK_TM, init_phase);
18409    ecore_init_block(sc, BLOCK_DORQ, init_phase);
18410
18411    bxe_iov_init_dq(sc);
18412
18413    ecore_init_block(sc, BLOCK_BRB1, init_phase);
18414    ecore_init_block(sc, BLOCK_PRS, init_phase);
18415    ecore_init_block(sc, BLOCK_TSDM, init_phase);
18416    ecore_init_block(sc, BLOCK_CSDM, init_phase);
18417    ecore_init_block(sc, BLOCK_USDM, init_phase);
18418    ecore_init_block(sc, BLOCK_XSDM, init_phase);
18419    ecore_init_block(sc, BLOCK_UPB, init_phase);
18420    ecore_init_block(sc, BLOCK_XPB, init_phase);
18421    ecore_init_block(sc, BLOCK_PBF, init_phase);
18422    if (!CHIP_IS_E1x(sc))
18423        REG_WR(sc, PBF_REG_DISABLE_PF, 0);
18424
18425    ecore_init_block(sc, BLOCK_CDU, init_phase);
18426
18427    ecore_init_block(sc, BLOCK_CFC, init_phase);
18428
18429    if (!CHIP_IS_E1x(sc))
18430        REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
18431
18432    if (IS_MF(sc)) {
18433        REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
18434        REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
18435    }
18436
18437    ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
18438
18439    /* HC init per function */
18440    if (sc->devinfo.int_block == INT_BLOCK_HC) {
18441        if (CHIP_IS_E1H(sc)) {
18442            REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18443
18444            REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18445            REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18446        }
18447        ecore_init_block(sc, BLOCK_HC, init_phase);
18448
18449    } else {
18450        int num_segs, sb_idx, prod_offset;
18451
18452        REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18453
18454        if (!CHIP_IS_E1x(sc)) {
18455            REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18456            REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18457        }
18458
18459        ecore_init_block(sc, BLOCK_IGU, init_phase);
18460
18461        if (!CHIP_IS_E1x(sc)) {
18462            int dsb_idx = 0;
18463            /**
18464             * Producer memory:
18465             * E2 mode: address 0-135 match to the mapping memory;
18466             * 136 - PF0 default prod; 137 - PF1 default prod;
18467             * 138 - PF2 default prod; 139 - PF3 default prod;
18468             * 140 - PF0 attn prod;    141 - PF1 attn prod;
18469             * 142 - PF2 attn prod;    143 - PF3 attn prod;
18470             * 144-147 reserved.
18471             *
18472             * E1.5 mode - In backward compatible mode;
18473             * for non default SB; each even line in the memory
18474             * holds the U producer and each odd line hold
18475             * the C producer. The first 128 producers are for
18476             * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18477             * producers are for the DSB for each PF.
18478             * Each PF has five segments: (the order inside each
18479             * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18480             * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18481             * 144-147 attn prods;
18482             */
18483            /* non-default-status-blocks */
18484            num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18485                IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18486            for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18487                prod_offset = (sc->igu_base_sb + sb_idx) *
18488                    num_segs;
18489
18490                for (i = 0; i < num_segs; i++) {
18491                    addr = IGU_REG_PROD_CONS_MEMORY +
18492                            (prod_offset + i) * 4;
18493                    REG_WR(sc, addr, 0);
18494                }
18495                /* send consumer update with value 0 */
18496                bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18497                           USTORM_ID, 0, IGU_INT_NOP, 1);
18498                bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18499            }
18500
18501            /* default-status-blocks */
18502            num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18503                IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18504
18505            if (CHIP_IS_MODE_4_PORT(sc))
18506                dsb_idx = SC_FUNC(sc);
18507            else
18508                dsb_idx = SC_VN(sc);
18509
18510            prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18511                       IGU_BC_BASE_DSB_PROD + dsb_idx :
18512                       IGU_NORM_BASE_DSB_PROD + dsb_idx);
18513
18514            /*
18515             * igu prods come in chunks of E1HVN_MAX (4) -
18516             * does not matters what is the current chip mode
18517             */
18518            for (i = 0; i < (num_segs * E1HVN_MAX);
18519                 i += E1HVN_MAX) {
18520                addr = IGU_REG_PROD_CONS_MEMORY +
18521                            (prod_offset + i)*4;
18522                REG_WR(sc, addr, 0);
18523            }
18524            /* send consumer update with 0 */
18525            if (CHIP_INT_MODE_IS_BC(sc)) {
18526                bxe_ack_sb(sc, sc->igu_dsb_id,
18527                           USTORM_ID, 0, IGU_INT_NOP, 1);
18528                bxe_ack_sb(sc, sc->igu_dsb_id,
18529                           CSTORM_ID, 0, IGU_INT_NOP, 1);
18530                bxe_ack_sb(sc, sc->igu_dsb_id,
18531                           XSTORM_ID, 0, IGU_INT_NOP, 1);
18532                bxe_ack_sb(sc, sc->igu_dsb_id,
18533                           TSTORM_ID, 0, IGU_INT_NOP, 1);
18534                bxe_ack_sb(sc, sc->igu_dsb_id,
18535                           ATTENTION_ID, 0, IGU_INT_NOP, 1);
18536            } else {
18537                bxe_ack_sb(sc, sc->igu_dsb_id,
18538                           USTORM_ID, 0, IGU_INT_NOP, 1);
18539                bxe_ack_sb(sc, sc->igu_dsb_id,
18540                           ATTENTION_ID, 0, IGU_INT_NOP, 1);
18541            }
18542            bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18543
18544            /* !!! these should become driver const once
18545               rf-tool supports split-68 const */
18546            REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18547            REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18548            REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18549            REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18550            REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18551            REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18552        }
18553    }
18554
18555    /* Reset PCIE errors for debug */
18556    REG_WR(sc, 0x2114, 0xffffffff);
18557    REG_WR(sc, 0x2120, 0xffffffff);
18558
18559    if (CHIP_IS_E1x(sc)) {
18560        main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18561        main_mem_base = HC_REG_MAIN_MEMORY +
18562                SC_PORT(sc) * (main_mem_size * 4);
18563        main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18564        main_mem_width = 8;
18565
18566        val = REG_RD(sc, main_mem_prty_clr);
18567        if (val) {
18568            BLOGD(sc, DBG_LOAD,
18569                  "Parity errors in HC block during function init (0x%x)!\n",
18570                  val);
18571        }
18572
18573        /* Clear "false" parity errors in MSI-X table */
18574        for (i = main_mem_base;
18575             i < main_mem_base + main_mem_size * 4;
18576             i += main_mem_width) {
18577            bxe_read_dmae(sc, i, main_mem_width / 4);
18578            bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18579                           i, main_mem_width / 4);
18580        }
18581        /* Clear HC parity attention */
18582        REG_RD(sc, main_mem_prty_clr);
18583    }
18584
18585#if 1
18586    /* Enable STORMs SP logging */
18587    REG_WR8(sc, BAR_USTRORM_INTMEM +
18588           USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18589    REG_WR8(sc, BAR_TSTRORM_INTMEM +
18590           TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18591    REG_WR8(sc, BAR_CSTRORM_INTMEM +
18592           CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18593    REG_WR8(sc, BAR_XSTRORM_INTMEM +
18594           XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18595#endif
18596
18597    elink_phy_probe(&sc->link_params);
18598
18599    return (0);
18600}
18601
18602static void
18603bxe_link_reset(struct bxe_softc *sc)
18604{
18605    if (!BXE_NOMCP(sc)) {
18606        BXE_PHY_LOCK(sc);
18607        elink_lfa_reset(&sc->link_params, &sc->link_vars);
18608        BXE_PHY_UNLOCK(sc);
18609    } else {
18610        if (!CHIP_REV_IS_SLOW(sc)) {
18611            BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18612        }
18613    }
18614}
18615
18616static void
18617bxe_reset_port(struct bxe_softc *sc)
18618{
18619    int port = SC_PORT(sc);
18620    uint32_t val;
18621
18622    /* reset physical Link */
18623    bxe_link_reset(sc);
18624
18625    REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18626
18627    /* Do not rcv packets to BRB */
18628    REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18629    /* Do not direct rcv packets that are not for MCP to the BRB */
18630    REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18631               NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18632
18633    /* Configure AEU */
18634    REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18635
18636    DELAY(100000);
18637
18638    /* Check for BRB port occupancy */
18639    val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18640    if (val) {
18641        BLOGD(sc, DBG_LOAD,
18642              "BRB1 is not empty, %d blocks are occupied\n", val);
18643    }
18644
18645    /* TODO: Close Doorbell port? */
18646}
18647
18648static void
18649bxe_ilt_wr(struct bxe_softc *sc,
18650           uint32_t         index,
18651           bus_addr_t       addr)
18652{
18653    int reg;
18654    uint32_t wb_write[2];
18655
18656    if (CHIP_IS_E1(sc)) {
18657        reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18658    } else {
18659        reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18660    }
18661
18662    wb_write[0] = ONCHIP_ADDR1(addr);
18663    wb_write[1] = ONCHIP_ADDR2(addr);
18664    REG_WR_DMAE(sc, reg, wb_write, 2);
18665}
18666
18667static void
18668bxe_clear_func_ilt(struct bxe_softc *sc,
18669                   uint32_t         func)
18670{
18671    uint32_t i, base = FUNC_ILT_BASE(func);
18672    for (i = base; i < base + ILT_PER_FUNC; i++) {
18673        bxe_ilt_wr(sc, i, 0);
18674    }
18675}
18676
18677static void
18678bxe_reset_func(struct bxe_softc *sc)
18679{
18680    struct bxe_fastpath *fp;
18681    int port = SC_PORT(sc);
18682    int func = SC_FUNC(sc);
18683    int i;
18684
18685    /* Disable the function in the FW */
18686    REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18687    REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18688    REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18689    REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18690
18691    /* FP SBs */
18692    FOR_EACH_ETH_QUEUE(sc, i) {
18693        fp = &sc->fp[i];
18694        REG_WR8(sc, BAR_CSTRORM_INTMEM +
18695                CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18696                SB_DISABLED);
18697    }
18698
18699#if 0
18700    if (CNIC_LOADED(sc)) {
18701        /* CNIC SB */
18702        REG_WR8(sc, BAR_CSTRORM_INTMEM +
18703                CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET
18704                (bxe_cnic_fw_sb_id(sc)), SB_DISABLED);
18705    }
18706#endif
18707
18708    /* SP SB */
18709    REG_WR8(sc, BAR_CSTRORM_INTMEM +
18710            CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18711            SB_DISABLED);
18712
18713    for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18714        REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18715    }
18716
18717    /* Configure IGU */
18718    if (sc->devinfo.int_block == INT_BLOCK_HC) {
18719        REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18720        REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18721    } else {
18722        REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18723        REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18724    }
18725
18726    if (CNIC_LOADED(sc)) {
18727        /* Disable Timer scan */
18728        REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18729        /*
18730         * Wait for at least 10ms and up to 2 second for the timers
18731         * scan to complete
18732         */
18733        for (i = 0; i < 200; i++) {
18734            DELAY(10000);
18735            if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18736                break;
18737        }
18738    }
18739
18740    /* Clear ILT */
18741    bxe_clear_func_ilt(sc, func);
18742
18743    /*
18744     * Timers workaround bug for E2: if this is vnic-3,
18745     * we need to set the entire ilt range for this timers.
18746     */
18747    if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18748        struct ilt_client_info ilt_cli;
18749        /* use dummy TM client */
18750        memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18751        ilt_cli.start = 0;
18752        ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18753        ilt_cli.client_num = ILT_CLIENT_TM;
18754
18755        ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18756    }
18757
18758    /* this assumes that reset_port() called before reset_func()*/
18759    if (!CHIP_IS_E1x(sc)) {
18760        bxe_pf_disable(sc);
18761    }
18762
18763    sc->dmae_ready = 0;
18764}
18765
18766static int
18767bxe_gunzip_init(struct bxe_softc *sc)
18768{
18769    return (0);
18770}
18771
18772static void
18773bxe_gunzip_end(struct bxe_softc *sc)
18774{
18775    return;
18776}
18777
18778static int
18779bxe_init_firmware(struct bxe_softc *sc)
18780{
18781    if (CHIP_IS_E1(sc)) {
18782        ecore_init_e1_firmware(sc);
18783        sc->iro_array = e1_iro_arr;
18784    } else if (CHIP_IS_E1H(sc)) {
18785        ecore_init_e1h_firmware(sc);
18786        sc->iro_array = e1h_iro_arr;
18787    } else if (!CHIP_IS_E1x(sc)) {
18788        ecore_init_e2_firmware(sc);
18789        sc->iro_array = e2_iro_arr;
18790    } else {
18791        BLOGE(sc, "Unsupported chip revision\n");
18792        return (-1);
18793    }
18794
18795    return (0);
18796}
18797
18798static void
18799bxe_release_firmware(struct bxe_softc *sc)
18800{
18801    /* Do nothing */
18802    return;
18803}
18804
18805static int
18806ecore_gunzip(struct bxe_softc *sc,
18807             const uint8_t    *zbuf,
18808             int              len)
18809{
18810    /* XXX : Implement... */
18811    BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18812    return (FALSE);
18813}
18814
18815static void
18816ecore_reg_wr_ind(struct bxe_softc *sc,
18817                 uint32_t         addr,
18818                 uint32_t         val)
18819{
18820    bxe_reg_wr_ind(sc, addr, val);
18821}
18822
18823static void
18824ecore_write_dmae_phys_len(struct bxe_softc *sc,
18825                          bus_addr_t       phys_addr,
18826                          uint32_t         addr,
18827                          uint32_t         len)
18828{
18829    bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18830}
18831
18832void
18833ecore_storm_memset_struct(struct bxe_softc *sc,
18834                          uint32_t         addr,
18835                          size_t           size,
18836                          uint32_t         *data)
18837{
18838    uint8_t i;
18839    for (i = 0; i < size/4; i++) {
18840        REG_WR(sc, addr + (i * 4), data[i]);
18841    }
18842}
18843
18844