]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/cxgbe/t4_main.c
Upgrade to OpenSSH 7.5p1.
[FreeBSD/FreeBSD.git] / sys / dev / cxgbe / t4_main.c
1 /*-
2  * Copyright (c) 2011 Chelsio Communications, Inc.
3  * All rights reserved.
4  * Written by: Navdeep Parhar <np@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include "opt_ddb.h"
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_rss.h"
35
36 #include <sys/param.h>
37 #include <sys/conf.h>
38 #include <sys/priv.h>
39 #include <sys/kernel.h>
40 #include <sys/bus.h>
41 #include <sys/module.h>
42 #include <sys/malloc.h>
43 #include <sys/queue.h>
44 #include <sys/taskqueue.h>
45 #include <sys/pciio.h>
46 #include <dev/pci/pcireg.h>
47 #include <dev/pci/pcivar.h>
48 #include <dev/pci/pci_private.h>
49 #include <sys/firmware.h>
50 #include <sys/sbuf.h>
51 #include <sys/smp.h>
52 #include <sys/socket.h>
53 #include <sys/sockio.h>
54 #include <sys/sysctl.h>
55 #include <net/ethernet.h>
56 #include <net/if.h>
57 #include <net/if_types.h>
58 #include <net/if_dl.h>
59 #include <net/if_vlan_var.h>
60 #ifdef RSS
61 #include <net/rss_config.h>
62 #endif
63 #if defined(__i386__) || defined(__amd64__)
64 #include <vm/vm.h>
65 #include <vm/pmap.h>
66 #endif
67 #ifdef DDB
68 #include <ddb/ddb.h>
69 #include <ddb/db_lex.h>
70 #endif
71
72 #include "common/common.h"
73 #include "common/t4_msg.h"
74 #include "common/t4_regs.h"
75 #include "common/t4_regs_values.h"
76 #include "cudbg/cudbg.h"
77 #include "t4_ioctl.h"
78 #include "t4_l2t.h"
79 #include "t4_mp_ring.h"
80 #include "t4_if.h"
81
82 /* T4 bus driver interface */
83 static int t4_probe(device_t);
84 static int t4_attach(device_t);
85 static int t4_detach(device_t);
86 static int t4_ready(device_t);
87 static int t4_read_port_device(device_t, int, device_t *);
88 static device_method_t t4_methods[] = {
89         DEVMETHOD(device_probe,         t4_probe),
90         DEVMETHOD(device_attach,        t4_attach),
91         DEVMETHOD(device_detach,        t4_detach),
92
93         DEVMETHOD(t4_is_main_ready,     t4_ready),
94         DEVMETHOD(t4_read_port_device,  t4_read_port_device),
95
96         DEVMETHOD_END
97 };
98 static driver_t t4_driver = {
99         "t4nex",
100         t4_methods,
101         sizeof(struct adapter)
102 };
103
104
105 /* T4 port (cxgbe) interface */
106 static int cxgbe_probe(device_t);
107 static int cxgbe_attach(device_t);
108 static int cxgbe_detach(device_t);
109 device_method_t cxgbe_methods[] = {
110         DEVMETHOD(device_probe,         cxgbe_probe),
111         DEVMETHOD(device_attach,        cxgbe_attach),
112         DEVMETHOD(device_detach,        cxgbe_detach),
113         { 0, 0 }
114 };
115 static driver_t cxgbe_driver = {
116         "cxgbe",
117         cxgbe_methods,
118         sizeof(struct port_info)
119 };
120
121 /* T4 VI (vcxgbe) interface */
122 static int vcxgbe_probe(device_t);
123 static int vcxgbe_attach(device_t);
124 static int vcxgbe_detach(device_t);
125 static device_method_t vcxgbe_methods[] = {
126         DEVMETHOD(device_probe,         vcxgbe_probe),
127         DEVMETHOD(device_attach,        vcxgbe_attach),
128         DEVMETHOD(device_detach,        vcxgbe_detach),
129         { 0, 0 }
130 };
131 static driver_t vcxgbe_driver = {
132         "vcxgbe",
133         vcxgbe_methods,
134         sizeof(struct vi_info)
135 };
136
137 static d_ioctl_t t4_ioctl;
138
139 static struct cdevsw t4_cdevsw = {
140        .d_version = D_VERSION,
141        .d_ioctl = t4_ioctl,
142        .d_name = "t4nex",
143 };
144
145 /* T5 bus driver interface */
146 static int t5_probe(device_t);
147 static device_method_t t5_methods[] = {
148         DEVMETHOD(device_probe,         t5_probe),
149         DEVMETHOD(device_attach,        t4_attach),
150         DEVMETHOD(device_detach,        t4_detach),
151
152         DEVMETHOD(t4_is_main_ready,     t4_ready),
153         DEVMETHOD(t4_read_port_device,  t4_read_port_device),
154
155         DEVMETHOD_END
156 };
157 static driver_t t5_driver = {
158         "t5nex",
159         t5_methods,
160         sizeof(struct adapter)
161 };
162
163
164 /* T5 port (cxl) interface */
165 static driver_t cxl_driver = {
166         "cxl",
167         cxgbe_methods,
168         sizeof(struct port_info)
169 };
170
171 /* T5 VI (vcxl) interface */
172 static driver_t vcxl_driver = {
173         "vcxl",
174         vcxgbe_methods,
175         sizeof(struct vi_info)
176 };
177
178 /* T6 bus driver interface */
179 static int t6_probe(device_t);
180 static device_method_t t6_methods[] = {
181         DEVMETHOD(device_probe,         t6_probe),
182         DEVMETHOD(device_attach,        t4_attach),
183         DEVMETHOD(device_detach,        t4_detach),
184
185         DEVMETHOD(t4_is_main_ready,     t4_ready),
186         DEVMETHOD(t4_read_port_device,  t4_read_port_device),
187
188         DEVMETHOD_END
189 };
190 static driver_t t6_driver = {
191         "t6nex",
192         t6_methods,
193         sizeof(struct adapter)
194 };
195
196
197 /* T6 port (cc) interface */
198 static driver_t cc_driver = {
199         "cc",
200         cxgbe_methods,
201         sizeof(struct port_info)
202 };
203
204 /* T6 VI (vcc) interface */
205 static driver_t vcc_driver = {
206         "vcc",
207         vcxgbe_methods,
208         sizeof(struct vi_info)
209 };
210
211 /* ifnet + media interface */
212 static void cxgbe_init(void *);
213 static int cxgbe_ioctl(struct ifnet *, unsigned long, caddr_t);
214 static int cxgbe_transmit(struct ifnet *, struct mbuf *);
215 static void cxgbe_qflush(struct ifnet *);
216 static int cxgbe_media_change(struct ifnet *);
217 static void cxgbe_media_status(struct ifnet *, struct ifmediareq *);
218
219 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
220
221 /*
222  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
223  * then ADAPTER_LOCK, then t4_uld_list_lock.
224  */
225 static struct sx t4_list_lock;
226 SLIST_HEAD(, adapter) t4_list;
227 #ifdef TCP_OFFLOAD
228 static struct sx t4_uld_list_lock;
229 SLIST_HEAD(, uld_info) t4_uld_list;
230 #endif
231
232 /*
233  * Tunables.  See tweak_tunables() too.
234  *
235  * Each tunable is set to a default value here if it's known at compile-time.
236  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
237  * provide a reasonable default (upto n) when the driver is loaded.
238  *
239  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
240  * T5 are under hw.cxl.
241  */
242
243 /*
244  * Number of queues for tx and rx, 10G and 1G, NIC and offload.
245  */
246 #define NTXQ_10G 16
247 int t4_ntxq10g = -NTXQ_10G;
248 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq10g);
249
250 #define NRXQ_10G 8
251 int t4_nrxq10g = -NRXQ_10G;
252 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq10g);
253
254 #define NTXQ_1G 4
255 int t4_ntxq1g = -NTXQ_1G;
256 TUNABLE_INT("hw.cxgbe.ntxq1g", &t4_ntxq1g);
257
258 #define NRXQ_1G 2
259 int t4_nrxq1g = -NRXQ_1G;
260 TUNABLE_INT("hw.cxgbe.nrxq1g", &t4_nrxq1g);
261
262 #define NTXQ_VI 1
263 static int t4_ntxq_vi = -NTXQ_VI;
264 TUNABLE_INT("hw.cxgbe.ntxq_vi", &t4_ntxq_vi);
265
266 #define NRXQ_VI 1
267 static int t4_nrxq_vi = -NRXQ_VI;
268 TUNABLE_INT("hw.cxgbe.nrxq_vi", &t4_nrxq_vi);
269
270 static int t4_rsrv_noflowq = 0;
271 TUNABLE_INT("hw.cxgbe.rsrv_noflowq", &t4_rsrv_noflowq);
272
273 #ifdef TCP_OFFLOAD
274 #define NOFLDTXQ_10G 8
275 static int t4_nofldtxq10g = -NOFLDTXQ_10G;
276 TUNABLE_INT("hw.cxgbe.nofldtxq10g", &t4_nofldtxq10g);
277
278 #define NOFLDRXQ_10G 2
279 static int t4_nofldrxq10g = -NOFLDRXQ_10G;
280 TUNABLE_INT("hw.cxgbe.nofldrxq10g", &t4_nofldrxq10g);
281
282 #define NOFLDTXQ_1G 2
283 static int t4_nofldtxq1g = -NOFLDTXQ_1G;
284 TUNABLE_INT("hw.cxgbe.nofldtxq1g", &t4_nofldtxq1g);
285
286 #define NOFLDRXQ_1G 1
287 static int t4_nofldrxq1g = -NOFLDRXQ_1G;
288 TUNABLE_INT("hw.cxgbe.nofldrxq1g", &t4_nofldrxq1g);
289
290 #define NOFLDTXQ_VI 1
291 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
292 TUNABLE_INT("hw.cxgbe.nofldtxq_vi", &t4_nofldtxq_vi);
293
294 #define NOFLDRXQ_VI 1
295 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
296 TUNABLE_INT("hw.cxgbe.nofldrxq_vi", &t4_nofldrxq_vi);
297 #endif
298
299 #ifdef DEV_NETMAP
300 #define NNMTXQ_VI 2
301 static int t4_nnmtxq_vi = -NNMTXQ_VI;
302 TUNABLE_INT("hw.cxgbe.nnmtxq_vi", &t4_nnmtxq_vi);
303
304 #define NNMRXQ_VI 2
305 static int t4_nnmrxq_vi = -NNMRXQ_VI;
306 TUNABLE_INT("hw.cxgbe.nnmrxq_vi", &t4_nnmrxq_vi);
307 #endif
308
309 /*
310  * Holdoff parameters for 10G and 1G ports.
311  */
312 #define TMR_IDX_10G 1
313 int t4_tmr_idx_10g = TMR_IDX_10G;
314 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx_10g);
315
316 #define PKTC_IDX_10G (-1)
317 int t4_pktc_idx_10g = PKTC_IDX_10G;
318 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx_10g);
319
320 #define TMR_IDX_1G 1
321 int t4_tmr_idx_1g = TMR_IDX_1G;
322 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_1G", &t4_tmr_idx_1g);
323
324 #define PKTC_IDX_1G (-1)
325 int t4_pktc_idx_1g = PKTC_IDX_1G;
326 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_1G", &t4_pktc_idx_1g);
327
328 /*
329  * Size (# of entries) of each tx and rx queue.
330  */
331 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
332 TUNABLE_INT("hw.cxgbe.qsize_txq", &t4_qsize_txq);
333
334 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
335 TUNABLE_INT("hw.cxgbe.qsize_rxq", &t4_qsize_rxq);
336
337 /*
338  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
339  */
340 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
341 TUNABLE_INT("hw.cxgbe.interrupt_types", &t4_intr_types);
342
343 /*
344  * Configuration file.
345  */
346 #define DEFAULT_CF      "default"
347 #define FLASH_CF        "flash"
348 #define UWIRE_CF        "uwire"
349 #define FPGA_CF         "fpga"
350 static char t4_cfg_file[32] = DEFAULT_CF;
351 TUNABLE_STR("hw.cxgbe.config_file", t4_cfg_file, sizeof(t4_cfg_file));
352
353 /*
354  * PAUSE settings (bit 0, 1 = rx_pause, tx_pause respectively).
355  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
356  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
357  *            mark or when signalled to do so, 0 to never emit PAUSE.
358  */
359 static int t4_pause_settings = PAUSE_TX | PAUSE_RX;
360 TUNABLE_INT("hw.cxgbe.pause_settings", &t4_pause_settings);
361
362 /*
363  * Forward Error Correction settings (bit 0, 1, 2 = FEC_RS, FEC_BASER_RS,
364  * FEC_RESERVED respectively).
365  * -1 to run with the firmware default.
366  *  0 to disable FEC.
367  */
368 static int t4_fec = -1;
369 TUNABLE_INT("hw.cxgbe.fec", &t4_fec);
370
371 /*
372  * Link autonegotiation.
373  * -1 to run with the firmware default.
374  *  0 to disable.
375  *  1 to enable.
376  */
377 static int t4_autoneg = -1;
378 TUNABLE_INT("hw.cxgbe.autoneg", &t4_autoneg);
379
380 /*
381  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
382  * encouraged respectively).
383  */
384 static unsigned int t4_fw_install = 1;
385 TUNABLE_INT("hw.cxgbe.fw_install", &t4_fw_install);
386
387 /*
388  * ASIC features that will be used.  Disable the ones you don't want so that the
389  * chip resources aren't wasted on features that will not be used.
390  */
391 static int t4_nbmcaps_allowed = 0;
392 TUNABLE_INT("hw.cxgbe.nbmcaps_allowed", &t4_nbmcaps_allowed);
393
394 static int t4_linkcaps_allowed = 0;     /* No DCBX, PPP, etc. by default */
395 TUNABLE_INT("hw.cxgbe.linkcaps_allowed", &t4_linkcaps_allowed);
396
397 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
398     FW_CAPS_CONFIG_SWITCH_EGRESS;
399 TUNABLE_INT("hw.cxgbe.switchcaps_allowed", &t4_switchcaps_allowed);
400
401 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC;
402 TUNABLE_INT("hw.cxgbe.niccaps_allowed", &t4_niccaps_allowed);
403
404 static int t4_toecaps_allowed = -1;
405 TUNABLE_INT("hw.cxgbe.toecaps_allowed", &t4_toecaps_allowed);
406
407 static int t4_rdmacaps_allowed = -1;
408 TUNABLE_INT("hw.cxgbe.rdmacaps_allowed", &t4_rdmacaps_allowed);
409
410 static int t4_cryptocaps_allowed = 0;
411 TUNABLE_INT("hw.cxgbe.cryptocaps_allowed", &t4_cryptocaps_allowed);
412
413 static int t4_iscsicaps_allowed = -1;
414 TUNABLE_INT("hw.cxgbe.iscsicaps_allowed", &t4_iscsicaps_allowed);
415
416 static int t4_fcoecaps_allowed = 0;
417 TUNABLE_INT("hw.cxgbe.fcoecaps_allowed", &t4_fcoecaps_allowed);
418
419 static int t5_write_combine = 0;
420 TUNABLE_INT("hw.cxl.write_combine", &t5_write_combine);
421
422 static int t4_num_vis = 1;
423 TUNABLE_INT("hw.cxgbe.num_vis", &t4_num_vis);
424
425 /* Functions used by extra VIs to obtain unique MAC addresses for each VI. */
426 static int vi_mac_funcs[] = {
427         FW_VI_FUNC_OFLD,
428         FW_VI_FUNC_IWARP,
429         FW_VI_FUNC_OPENISCSI,
430         FW_VI_FUNC_OPENFCOE,
431         FW_VI_FUNC_FOISCSI,
432         FW_VI_FUNC_FOFCOE,
433 };
434
435 struct intrs_and_queues {
436         uint16_t intr_type;     /* INTx, MSI, or MSI-X */
437         uint16_t nirq;          /* Total # of vectors */
438         uint16_t intr_flags_10g;/* Interrupt flags for each 10G port */
439         uint16_t intr_flags_1g; /* Interrupt flags for each 1G port */
440         uint16_t ntxq10g;       /* # of NIC txq's for each 10G port */
441         uint16_t nrxq10g;       /* # of NIC rxq's for each 10G port */
442         uint16_t ntxq1g;        /* # of NIC txq's for each 1G port */
443         uint16_t nrxq1g;        /* # of NIC rxq's for each 1G port */
444         uint16_t rsrv_noflowq;  /* Flag whether to reserve queue 0 */
445         uint16_t nofldtxq10g;   /* # of TOE txq's for each 10G port */
446         uint16_t nofldrxq10g;   /* # of TOE rxq's for each 10G port */
447         uint16_t nofldtxq1g;    /* # of TOE txq's for each 1G port */
448         uint16_t nofldrxq1g;    /* # of TOE rxq's for each 1G port */
449
450         /* The vcxgbe/vcxl interfaces use these and not the ones above. */
451         uint16_t ntxq_vi;       /* # of NIC txq's */
452         uint16_t nrxq_vi;       /* # of NIC rxq's */
453         uint16_t nofldtxq_vi;   /* # of TOE txq's */
454         uint16_t nofldrxq_vi;   /* # of TOE rxq's */
455         uint16_t nnmtxq_vi;     /* # of netmap txq's */
456         uint16_t nnmrxq_vi;     /* # of netmap rxq's */
457 };
458
459 struct filter_entry {
460         uint32_t valid:1;       /* filter allocated and valid */
461         uint32_t locked:1;      /* filter is administratively locked */
462         uint32_t pending:1;     /* filter action is pending firmware reply */
463         uint32_t smtidx:8;      /* Source MAC Table index for smac */
464         struct l2t_entry *l2t;  /* Layer Two Table entry for dmac */
465
466         struct t4_filter_specification fs;
467 };
468
469 static void setup_memwin(struct adapter *);
470 static void position_memwin(struct adapter *, int, uint32_t);
471 static int rw_via_memwin(struct adapter *, int, uint32_t, uint32_t *, int, int);
472 static inline int read_via_memwin(struct adapter *, int, uint32_t, uint32_t *,
473     int);
474 static inline int write_via_memwin(struct adapter *, int, uint32_t,
475     const uint32_t *, int);
476 static int validate_mem_range(struct adapter *, uint32_t, int);
477 static int fwmtype_to_hwmtype(int);
478 static int validate_mt_off_len(struct adapter *, int, uint32_t, int,
479     uint32_t *);
480 static int fixup_devlog_params(struct adapter *);
481 static int cfg_itype_and_nqueues(struct adapter *, int, int, int,
482     struct intrs_and_queues *);
483 static int prep_firmware(struct adapter *);
484 static int partition_resources(struct adapter *, const struct firmware *,
485     const char *);
486 static int get_params__pre_init(struct adapter *);
487 static int get_params__post_init(struct adapter *);
488 static int set_params__post_init(struct adapter *);
489 static void t4_set_desc(struct adapter *);
490 static void build_medialist(struct port_info *, struct ifmedia *);
491 static void init_l1cfg(struct port_info *);
492 static int cxgbe_init_synchronized(struct vi_info *);
493 static int cxgbe_uninit_synchronized(struct vi_info *);
494 static void quiesce_txq(struct adapter *, struct sge_txq *);
495 static void quiesce_wrq(struct adapter *, struct sge_wrq *);
496 static void quiesce_iq(struct adapter *, struct sge_iq *);
497 static void quiesce_fl(struct adapter *, struct sge_fl *);
498 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
499     driver_intr_t *, void *, char *);
500 static int t4_free_irq(struct adapter *, struct irq *);
501 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
502 static void vi_refresh_stats(struct adapter *, struct vi_info *);
503 static void cxgbe_refresh_stats(struct adapter *, struct port_info *);
504 static void cxgbe_tick(void *);
505 static void cxgbe_vlan_config(void *, struct ifnet *, uint16_t);
506 static void cxgbe_sysctls(struct port_info *);
507 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
508 static int sysctl_bitfield(SYSCTL_HANDLER_ARGS);
509 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
510 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
511 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
512 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
513 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
514 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
515 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
516 static int sysctl_fec(SYSCTL_HANDLER_ARGS);
517 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
518 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
519 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
520 #ifdef SBUF_DRAIN
521 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
522 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
523 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
524 static int sysctl_cim_la_t6(SYSCTL_HANDLER_ARGS);
525 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
526 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
527 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
528 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
529 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
530 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
531 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
532 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
533 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
534 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
535 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
536 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
537 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
538 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
539 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
540 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
541 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
542 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
543 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
544 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
545 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
546 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
547 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
548 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
549 static int sysctl_tc_params(SYSCTL_HANDLER_ARGS);
550 #endif
551 #ifdef TCP_OFFLOAD
552 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
553 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
554 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
555 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
556 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
557 #endif
558 static uint32_t fconf_iconf_to_mode(uint32_t, uint32_t);
559 static uint32_t mode_to_fconf(uint32_t);
560 static uint32_t mode_to_iconf(uint32_t);
561 static int check_fspec_against_fconf_iconf(struct adapter *,
562     struct t4_filter_specification *);
563 static int get_filter_mode(struct adapter *, uint32_t *);
564 static int set_filter_mode(struct adapter *, uint32_t);
565 static inline uint64_t get_filter_hits(struct adapter *, uint32_t);
566 static int get_filter(struct adapter *, struct t4_filter *);
567 static int set_filter(struct adapter *, struct t4_filter *);
568 static int del_filter(struct adapter *, struct t4_filter *);
569 static void clear_filter(struct filter_entry *);
570 static int set_filter_wr(struct adapter *, int);
571 static int del_filter_wr(struct adapter *, int);
572 static int set_tcb_rpl(struct sge_iq *, const struct rss_header *,
573     struct mbuf *);
574 static int get_sge_context(struct adapter *, struct t4_sge_context *);
575 static int load_fw(struct adapter *, struct t4_data *);
576 static int load_cfg(struct adapter *, struct t4_data *);
577 static int load_boot(struct adapter *, struct t4_bootrom *);
578 static int load_bootcfg(struct adapter *, struct t4_data *);
579 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
580 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
581 static int read_i2c(struct adapter *, struct t4_i2c_data *);
582 #ifdef TCP_OFFLOAD
583 static int toe_capability(struct vi_info *, int);
584 #endif
585 static int mod_event(module_t, int, void *);
586 static int notify_siblings(device_t, int);
587
588 struct {
589         uint16_t device;
590         char *desc;
591 } t4_pciids[] = {
592         {0xa000, "Chelsio Terminator 4 FPGA"},
593         {0x4400, "Chelsio T440-dbg"},
594         {0x4401, "Chelsio T420-CR"},
595         {0x4402, "Chelsio T422-CR"},
596         {0x4403, "Chelsio T440-CR"},
597         {0x4404, "Chelsio T420-BCH"},
598         {0x4405, "Chelsio T440-BCH"},
599         {0x4406, "Chelsio T440-CH"},
600         {0x4407, "Chelsio T420-SO"},
601         {0x4408, "Chelsio T420-CX"},
602         {0x4409, "Chelsio T420-BT"},
603         {0x440a, "Chelsio T404-BT"},
604         {0x440e, "Chelsio T440-LP-CR"},
605 }, t5_pciids[] = {
606         {0xb000, "Chelsio Terminator 5 FPGA"},
607         {0x5400, "Chelsio T580-dbg"},
608         {0x5401,  "Chelsio T520-CR"},           /* 2 x 10G */
609         {0x5402,  "Chelsio T522-CR"},           /* 2 x 10G, 2 X 1G */
610         {0x5403,  "Chelsio T540-CR"},           /* 4 x 10G */
611         {0x5407,  "Chelsio T520-SO"},           /* 2 x 10G, nomem */
612         {0x5409,  "Chelsio T520-BT"},           /* 2 x 10GBaseT */
613         {0x540a,  "Chelsio T504-BT"},           /* 4 x 1G */
614         {0x540d,  "Chelsio T580-CR"},           /* 2 x 40G */
615         {0x540e,  "Chelsio T540-LP-CR"},        /* 4 x 10G */
616         {0x5410,  "Chelsio T580-LP-CR"},        /* 2 x 40G */
617         {0x5411,  "Chelsio T520-LL-CR"},        /* 2 x 10G */
618         {0x5412,  "Chelsio T560-CR"},           /* 1 x 40G, 2 x 10G */
619         {0x5414,  "Chelsio T580-LP-SO-CR"},     /* 2 x 40G, nomem */
620         {0x5415,  "Chelsio T502-BT"},           /* 2 x 1G */
621 #ifdef notyet
622         {0x5404,  "Chelsio T520-BCH"},
623         {0x5405,  "Chelsio T540-BCH"},
624         {0x5406,  "Chelsio T540-CH"},
625         {0x5408,  "Chelsio T520-CX"},
626         {0x540b,  "Chelsio B520-SR"},
627         {0x540c,  "Chelsio B504-BT"},
628         {0x540f,  "Chelsio Amsterdam"},
629         {0x5413,  "Chelsio T580-CHR"},
630 #endif
631 }, t6_pciids[] = {
632         {0xc006, "Chelsio Terminator 6 FPGA"},  /* T6 PE10K6 FPGA (PF0) */
633         {0x6400, "Chelsio T6-DBG-25"},          /* 2 x 10/25G, debug */
634         {0x6401, "Chelsio T6225-CR"},           /* 2 x 10/25G */
635         {0x6402, "Chelsio T6225-SO-CR"},        /* 2 x 10/25G, nomem */
636         {0x6403, "Chelsio T6425-CR"},           /* 4 x 10/25G */
637         {0x6404, "Chelsio T6425-SO-CR"},        /* 4 x 10/25G, nomem */
638         {0x6405, "Chelsio T6225-OCP-SO"},       /* 2 x 10/25G, nomem */
639         {0x6406, "Chelsio T62100-OCP-SO"},      /* 2 x 40/50/100G, nomem */
640         {0x6407, "Chelsio T62100-LP-CR"},       /* 2 x 40/50/100G */
641         {0x6408, "Chelsio T62100-SO-CR"},       /* 2 x 40/50/100G, nomem */
642         {0x6409, "Chelsio T6210-BT"},           /* 2 x 10GBASE-T */
643         {0x640d, "Chelsio T62100-CR"},          /* 2 x 40/50/100G */
644         {0x6410, "Chelsio T6-DBG-100"},         /* 2 x 40/50/100G, debug */
645         {0x6411, "Chelsio T6225-LL-CR"},        /* 2 x 10/25G */
646         {0x6414, "Chelsio T61100-OCP-SO"},      /* 1 x 40/50/100G, nomem */
647         {0x6415, "Chelsio T6201-BT"},           /* 2 x 1000BASE-T */
648
649         /* Custom */
650         {0x6480, "Chelsio T6225 80"},
651         {0x6481, "Chelsio T62100 81"},
652 };
653
654 #ifdef TCP_OFFLOAD
655 /*
656  * service_iq() has an iq and needs the fl.  Offset of fl from the iq should be
657  * exactly the same for both rxq and ofld_rxq.
658  */
659 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
660 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
661 #endif
662 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
663
664 static int
665 t4_probe(device_t dev)
666 {
667         int i;
668         uint16_t v = pci_get_vendor(dev);
669         uint16_t d = pci_get_device(dev);
670         uint8_t f = pci_get_function(dev);
671
672         if (v != PCI_VENDOR_ID_CHELSIO)
673                 return (ENXIO);
674
675         /* Attach only to PF0 of the FPGA */
676         if (d == 0xa000 && f != 0)
677                 return (ENXIO);
678
679         for (i = 0; i < nitems(t4_pciids); i++) {
680                 if (d == t4_pciids[i].device) {
681                         device_set_desc(dev, t4_pciids[i].desc);
682                         return (BUS_PROBE_DEFAULT);
683                 }
684         }
685
686         return (ENXIO);
687 }
688
689 static int
690 t5_probe(device_t dev)
691 {
692         int i;
693         uint16_t v = pci_get_vendor(dev);
694         uint16_t d = pci_get_device(dev);
695         uint8_t f = pci_get_function(dev);
696
697         if (v != PCI_VENDOR_ID_CHELSIO)
698                 return (ENXIO);
699
700         /* Attach only to PF0 of the FPGA */
701         if (d == 0xb000 && f != 0)
702                 return (ENXIO);
703
704         for (i = 0; i < nitems(t5_pciids); i++) {
705                 if (d == t5_pciids[i].device) {
706                         device_set_desc(dev, t5_pciids[i].desc);
707                         return (BUS_PROBE_DEFAULT);
708                 }
709         }
710
711         return (ENXIO);
712 }
713
714 static int
715 t6_probe(device_t dev)
716 {
717         int i;
718         uint16_t v = pci_get_vendor(dev);
719         uint16_t d = pci_get_device(dev);
720
721         if (v != PCI_VENDOR_ID_CHELSIO)
722                 return (ENXIO);
723
724         for (i = 0; i < nitems(t6_pciids); i++) {
725                 if (d == t6_pciids[i].device) {
726                         device_set_desc(dev, t6_pciids[i].desc);
727                         return (BUS_PROBE_DEFAULT);
728                 }
729         }
730
731         return (ENXIO);
732 }
733
734 static void
735 t5_attribute_workaround(device_t dev)
736 {
737         device_t root_port;
738         uint32_t v;
739
740         /*
741          * The T5 chips do not properly echo the No Snoop and Relaxed
742          * Ordering attributes when replying to a TLP from a Root
743          * Port.  As a workaround, find the parent Root Port and
744          * disable No Snoop and Relaxed Ordering.  Note that this
745          * affects all devices under this root port.
746          */
747         root_port = pci_find_pcie_root_port(dev);
748         if (root_port == NULL) {
749                 device_printf(dev, "Unable to find parent root port\n");
750                 return;
751         }
752
753         v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
754             PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
755         if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
756             0)
757                 device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
758                     device_get_nameunit(root_port));
759 }
760
761 static const struct devnames devnames[] = {
762         {
763                 .nexus_name = "t4nex",
764                 .ifnet_name = "cxgbe",
765                 .vi_ifnet_name = "vcxgbe",
766                 .pf03_drv_name = "t4iov",
767                 .vf_nexus_name = "t4vf",
768                 .vf_ifnet_name = "cxgbev"
769         }, {
770                 .nexus_name = "t5nex",
771                 .ifnet_name = "cxl",
772                 .vi_ifnet_name = "vcxl",
773                 .pf03_drv_name = "t5iov",
774                 .vf_nexus_name = "t5vf",
775                 .vf_ifnet_name = "cxlv"
776         }, {
777                 .nexus_name = "t6nex",
778                 .ifnet_name = "cc",
779                 .vi_ifnet_name = "vcc",
780                 .pf03_drv_name = "t6iov",
781                 .vf_nexus_name = "t6vf",
782                 .vf_ifnet_name = "ccv"
783         }
784 };
785
786 void
787 t4_init_devnames(struct adapter *sc)
788 {
789         int id;
790
791         id = chip_id(sc);
792         if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
793                 sc->names = &devnames[id - CHELSIO_T4];
794         else {
795                 device_printf(sc->dev, "chip id %d is not supported.\n", id);
796                 sc->names = NULL;
797         }
798 }
799
800 static int
801 t4_attach(device_t dev)
802 {
803         struct adapter *sc;
804         int rc = 0, i, j, n10g, n1g, rqidx, tqidx;
805         struct make_dev_args mda;
806         struct intrs_and_queues iaq;
807         struct sge *s;
808         uint8_t *buf;
809 #ifdef TCP_OFFLOAD
810         int ofld_rqidx, ofld_tqidx;
811 #endif
812 #ifdef DEV_NETMAP
813         int nm_rqidx, nm_tqidx;
814 #endif
815         int num_vis;
816
817         sc = device_get_softc(dev);
818         sc->dev = dev;
819         TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
820
821         if ((pci_get_device(dev) & 0xff00) == 0x5400)
822                 t5_attribute_workaround(dev);
823         pci_enable_busmaster(dev);
824         if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
825                 uint32_t v;
826
827                 pci_set_max_read_req(dev, 4096);
828                 v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
829                 v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
830                 pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
831
832                 sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
833         }
834
835         sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
836         sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
837         sc->traceq = -1;
838         mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
839         snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
840             device_get_nameunit(dev));
841
842         snprintf(sc->lockname, sizeof(sc->lockname), "%s",
843             device_get_nameunit(dev));
844         mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
845         t4_add_adapter(sc);
846
847         mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
848         TAILQ_INIT(&sc->sfl);
849         callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
850
851         mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
852
853         rc = t4_map_bars_0_and_4(sc);
854         if (rc != 0)
855                 goto done; /* error message displayed already */
856
857         memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
858
859         /* Prepare the adapter for operation. */
860         buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
861         rc = -t4_prep_adapter(sc, buf);
862         free(buf, M_CXGBE);
863         if (rc != 0) {
864                 device_printf(dev, "failed to prepare adapter: %d.\n", rc);
865                 goto done;
866         }
867
868         /*
869          * This is the real PF# to which we're attaching.  Works from within PCI
870          * passthrough environments too, where pci_get_function() could return a
871          * different PF# depending on the passthrough configuration.  We need to
872          * use the real PF# in all our communication with the firmware.
873          */
874         j = t4_read_reg(sc, A_PL_WHOAMI);
875         sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
876         sc->mbox = sc->pf;
877
878         t4_init_devnames(sc);
879         if (sc->names == NULL) {
880                 rc = ENOTSUP;
881                 goto done; /* error message displayed already */
882         }
883
884         /*
885          * Do this really early, with the memory windows set up even before the
886          * character device.  The userland tool's register i/o and mem read
887          * will work even in "recovery mode".
888          */
889         setup_memwin(sc);
890         if (t4_init_devlog_params(sc, 0) == 0)
891                 fixup_devlog_params(sc);
892         make_dev_args_init(&mda);
893         mda.mda_devsw = &t4_cdevsw;
894         mda.mda_uid = UID_ROOT;
895         mda.mda_gid = GID_WHEEL;
896         mda.mda_mode = 0600;
897         mda.mda_si_drv1 = sc;
898         rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
899         if (rc != 0)
900                 device_printf(dev, "failed to create nexus char device: %d.\n",
901                     rc);
902
903         /* Go no further if recovery mode has been requested. */
904         if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
905                 device_printf(dev, "recovery mode.\n");
906                 goto done;
907         }
908
909 #if defined(__i386__)
910         if ((cpu_feature & CPUID_CX8) == 0) {
911                 device_printf(dev, "64 bit atomics not available.\n");
912                 rc = ENOTSUP;
913                 goto done;
914         }
915 #endif
916
917         /* Prepare the firmware for operation */
918         rc = prep_firmware(sc);
919         if (rc != 0)
920                 goto done; /* error message displayed already */
921
922         rc = get_params__post_init(sc);
923         if (rc != 0)
924                 goto done; /* error message displayed already */
925
926         rc = set_params__post_init(sc);
927         if (rc != 0)
928                 goto done; /* error message displayed already */
929
930         rc = t4_map_bar_2(sc);
931         if (rc != 0)
932                 goto done; /* error message displayed already */
933
934         rc = t4_create_dma_tag(sc);
935         if (rc != 0)
936                 goto done; /* error message displayed already */
937
938         /*
939          * Number of VIs to create per-port.  The first VI is the "main" regular
940          * VI for the port.  The rest are additional virtual interfaces on the
941          * same physical port.  Note that the main VI does not have native
942          * netmap support but the extra VIs do.
943          *
944          * Limit the number of VIs per port to the number of available
945          * MAC addresses per port.
946          */
947         if (t4_num_vis >= 1)
948                 num_vis = t4_num_vis;
949         else
950                 num_vis = 1;
951         if (num_vis > nitems(vi_mac_funcs)) {
952                 num_vis = nitems(vi_mac_funcs);
953                 device_printf(dev, "Number of VIs limited to %d\n", num_vis);
954         }
955
956         /*
957          * First pass over all the ports - allocate VIs and initialize some
958          * basic parameters like mac address, port type, etc.  We also figure
959          * out whether a port is 10G or 1G and use that information when
960          * calculating how many interrupts to attempt to allocate.
961          */
962         n10g = n1g = 0;
963         for_each_port(sc, i) {
964                 struct port_info *pi;
965
966                 pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
967                 sc->port[i] = pi;
968
969                 /* These must be set before t4_port_init */
970                 pi->adapter = sc;
971                 pi->port_id = i;
972                 /*
973                  * XXX: vi[0] is special so we can't delay this allocation until
974                  * pi->nvi's final value is known.
975                  */
976                 pi->vi = malloc(sizeof(struct vi_info) * num_vis, M_CXGBE,
977                     M_ZERO | M_WAITOK);
978
979                 /*
980                  * Allocate the "main" VI and initialize parameters
981                  * like mac addr.
982                  */
983                 rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
984                 if (rc != 0) {
985                         device_printf(dev, "unable to initialize port %d: %d\n",
986                             i, rc);
987                         free(pi->vi, M_CXGBE);
988                         free(pi, M_CXGBE);
989                         sc->port[i] = NULL;
990                         goto done;
991                 }
992
993                 snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
994                     device_get_nameunit(dev), i);
995                 mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
996                 sc->chan_map[pi->tx_chan] = i;
997
998                 if (port_top_speed(pi) >= 10) {
999                         n10g++;
1000                 } else {
1001                         n1g++;
1002                 }
1003
1004                 pi->dev = device_add_child(dev, sc->names->ifnet_name, -1);
1005                 if (pi->dev == NULL) {
1006                         device_printf(dev,
1007                             "failed to add device for port %d.\n", i);
1008                         rc = ENXIO;
1009                         goto done;
1010                 }
1011                 pi->vi[0].dev = pi->dev;
1012                 device_set_softc(pi->dev, pi);
1013         }
1014
1015         /*
1016          * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1017          */
1018         rc = cfg_itype_and_nqueues(sc, n10g, n1g, num_vis, &iaq);
1019         if (rc != 0)
1020                 goto done; /* error message displayed already */
1021         if (iaq.nrxq_vi + iaq.nofldrxq_vi + iaq.nnmrxq_vi == 0)
1022                 num_vis = 1;
1023
1024         sc->intr_type = iaq.intr_type;
1025         sc->intr_count = iaq.nirq;
1026
1027         s = &sc->sge;
1028         s->nrxq = n10g * iaq.nrxq10g + n1g * iaq.nrxq1g;
1029         s->ntxq = n10g * iaq.ntxq10g + n1g * iaq.ntxq1g;
1030         if (num_vis > 1) {
1031                 s->nrxq += (n10g + n1g) * (num_vis - 1) * iaq.nrxq_vi;
1032                 s->ntxq += (n10g + n1g) * (num_vis - 1) * iaq.ntxq_vi;
1033         }
1034         s->neq = s->ntxq + s->nrxq;     /* the free list in an rxq is an eq */
1035         s->neq += sc->params.nports + 1;/* ctrl queues: 1 per port + 1 mgmt */
1036         s->niq = s->nrxq + 1;           /* 1 extra for firmware event queue */
1037 #ifdef TCP_OFFLOAD
1038         if (is_offload(sc)) {
1039                 s->nofldrxq = n10g * iaq.nofldrxq10g + n1g * iaq.nofldrxq1g;
1040                 s->nofldtxq = n10g * iaq.nofldtxq10g + n1g * iaq.nofldtxq1g;
1041                 if (num_vis > 1) {
1042                         s->nofldrxq += (n10g + n1g) * (num_vis - 1) *
1043                             iaq.nofldrxq_vi;
1044                         s->nofldtxq += (n10g + n1g) * (num_vis - 1) *
1045                             iaq.nofldtxq_vi;
1046                 }
1047                 s->neq += s->nofldtxq + s->nofldrxq;
1048                 s->niq += s->nofldrxq;
1049
1050                 s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1051                     M_CXGBE, M_ZERO | M_WAITOK);
1052                 s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_wrq),
1053                     M_CXGBE, M_ZERO | M_WAITOK);
1054         }
1055 #endif
1056 #ifdef DEV_NETMAP
1057         if (num_vis > 1) {
1058                 s->nnmrxq = (n10g + n1g) * (num_vis - 1) * iaq.nnmrxq_vi;
1059                 s->nnmtxq = (n10g + n1g) * (num_vis - 1) * iaq.nnmtxq_vi;
1060         }
1061         s->neq += s->nnmtxq + s->nnmrxq;
1062         s->niq += s->nnmrxq;
1063
1064         s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1065             M_CXGBE, M_ZERO | M_WAITOK);
1066         s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1067             M_CXGBE, M_ZERO | M_WAITOK);
1068 #endif
1069
1070         s->ctrlq = malloc(sc->params.nports * sizeof(struct sge_wrq), M_CXGBE,
1071             M_ZERO | M_WAITOK);
1072         s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1073             M_ZERO | M_WAITOK);
1074         s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1075             M_ZERO | M_WAITOK);
1076         s->iqmap = malloc(s->niq * sizeof(struct sge_iq *), M_CXGBE,
1077             M_ZERO | M_WAITOK);
1078         s->eqmap = malloc(s->neq * sizeof(struct sge_eq *), M_CXGBE,
1079             M_ZERO | M_WAITOK);
1080
1081         sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1082             M_ZERO | M_WAITOK);
1083
1084         t4_init_l2t(sc, M_WAITOK);
1085         t4_init_tx_sched(sc);
1086
1087         /*
1088          * Second pass over the ports.  This time we know the number of rx and
1089          * tx queues that each port should get.
1090          */
1091         rqidx = tqidx = 0;
1092 #ifdef TCP_OFFLOAD
1093         ofld_rqidx = ofld_tqidx = 0;
1094 #endif
1095 #ifdef DEV_NETMAP
1096         nm_rqidx = nm_tqidx = 0;
1097 #endif
1098         for_each_port(sc, i) {
1099                 struct port_info *pi = sc->port[i];
1100                 struct vi_info *vi;
1101
1102                 if (pi == NULL)
1103                         continue;
1104
1105                 pi->nvi = num_vis;
1106                 for_each_vi(pi, j, vi) {
1107                         vi->pi = pi;
1108                         vi->qsize_rxq = t4_qsize_rxq;
1109                         vi->qsize_txq = t4_qsize_txq;
1110
1111                         vi->first_rxq = rqidx;
1112                         vi->first_txq = tqidx;
1113                         if (port_top_speed(pi) >= 10) {
1114                                 vi->tmr_idx = t4_tmr_idx_10g;
1115                                 vi->pktc_idx = t4_pktc_idx_10g;
1116                                 vi->flags |= iaq.intr_flags_10g & INTR_RXQ;
1117                                 vi->nrxq = j == 0 ? iaq.nrxq10g : iaq.nrxq_vi;
1118                                 vi->ntxq = j == 0 ? iaq.ntxq10g : iaq.ntxq_vi;
1119                         } else {
1120                                 vi->tmr_idx = t4_tmr_idx_1g;
1121                                 vi->pktc_idx = t4_pktc_idx_1g;
1122                                 vi->flags |= iaq.intr_flags_1g & INTR_RXQ;
1123                                 vi->nrxq = j == 0 ? iaq.nrxq1g : iaq.nrxq_vi;
1124                                 vi->ntxq = j == 0 ? iaq.ntxq1g : iaq.ntxq_vi;
1125                         }
1126                         rqidx += vi->nrxq;
1127                         tqidx += vi->ntxq;
1128
1129                         if (j == 0 && vi->ntxq > 1)
1130                                 vi->rsrv_noflowq = iaq.rsrv_noflowq ? 1 : 0;
1131                         else
1132                                 vi->rsrv_noflowq = 0;
1133
1134 #ifdef TCP_OFFLOAD
1135                         vi->first_ofld_rxq = ofld_rqidx;
1136                         vi->first_ofld_txq = ofld_tqidx;
1137                         if (port_top_speed(pi) >= 10) {
1138                                 vi->flags |= iaq.intr_flags_10g & INTR_OFLD_RXQ;
1139                                 vi->nofldrxq = j == 0 ? iaq.nofldrxq10g :
1140                                     iaq.nofldrxq_vi;
1141                                 vi->nofldtxq = j == 0 ? iaq.nofldtxq10g :
1142                                     iaq.nofldtxq_vi;
1143                         } else {
1144                                 vi->flags |= iaq.intr_flags_1g & INTR_OFLD_RXQ;
1145                                 vi->nofldrxq = j == 0 ? iaq.nofldrxq1g :
1146                                     iaq.nofldrxq_vi;
1147                                 vi->nofldtxq = j == 0 ? iaq.nofldtxq1g :
1148                                     iaq.nofldtxq_vi;
1149                         }
1150                         ofld_rqidx += vi->nofldrxq;
1151                         ofld_tqidx += vi->nofldtxq;
1152 #endif
1153 #ifdef DEV_NETMAP
1154                         if (j > 0) {
1155                                 vi->first_nm_rxq = nm_rqidx;
1156                                 vi->first_nm_txq = nm_tqidx;
1157                                 vi->nnmrxq = iaq.nnmrxq_vi;
1158                                 vi->nnmtxq = iaq.nnmtxq_vi;
1159                                 nm_rqidx += vi->nnmrxq;
1160                                 nm_tqidx += vi->nnmtxq;
1161                         }
1162 #endif
1163                 }
1164         }
1165
1166         rc = t4_setup_intr_handlers(sc);
1167         if (rc != 0) {
1168                 device_printf(dev,
1169                     "failed to setup interrupt handlers: %d\n", rc);
1170                 goto done;
1171         }
1172
1173         rc = bus_generic_probe(dev);
1174         if (rc != 0) {
1175                 device_printf(dev, "failed to probe child drivers: %d\n", rc);
1176                 goto done;
1177         }
1178
1179         rc = bus_generic_attach(dev);
1180         if (rc != 0) {
1181                 device_printf(dev,
1182                     "failed to attach all child ports: %d\n", rc);
1183                 goto done;
1184         }
1185
1186         device_printf(dev,
1187             "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1188             sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1189             sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1190             (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1191             sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1192
1193         t4_set_desc(sc);
1194
1195         notify_siblings(dev, 0);
1196
1197 done:
1198         if (rc != 0 && sc->cdev) {
1199                 /* cdev was created and so cxgbetool works; recover that way. */
1200                 device_printf(dev,
1201                     "error during attach, adapter is now in recovery mode.\n");
1202                 rc = 0;
1203         }
1204
1205         if (rc != 0)
1206                 t4_detach_common(dev);
1207         else
1208                 t4_sysctls(sc);
1209
1210         return (rc);
1211 }
1212
1213 static int
1214 t4_ready(device_t dev)
1215 {
1216         struct adapter *sc;
1217
1218         sc = device_get_softc(dev);
1219         if (sc->flags & FW_OK)
1220                 return (0);
1221         return (ENXIO);
1222 }
1223
1224 static int
1225 t4_read_port_device(device_t dev, int port, device_t *child)
1226 {
1227         struct adapter *sc;
1228         struct port_info *pi;
1229
1230         sc = device_get_softc(dev);
1231         if (port < 0 || port >= MAX_NPORTS)
1232                 return (EINVAL);
1233         pi = sc->port[port];
1234         if (pi == NULL || pi->dev == NULL)
1235                 return (ENXIO);
1236         *child = pi->dev;
1237         return (0);
1238 }
1239
1240 static int
1241 notify_siblings(device_t dev, int detaching)
1242 {
1243         device_t sibling;
1244         int error, i;
1245
1246         error = 0;
1247         for (i = 0; i < PCI_FUNCMAX; i++) {
1248                 if (i == pci_get_function(dev))
1249                         continue;
1250                 sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1251                     pci_get_slot(dev), i);
1252                 if (sibling == NULL || !device_is_attached(sibling))
1253                         continue;
1254                 if (detaching)
1255                         error = T4_DETACH_CHILD(sibling);
1256                 else
1257                         (void)T4_ATTACH_CHILD(sibling);
1258                 if (error)
1259                         break;
1260         }
1261         return (error);
1262 }
1263
1264 /*
1265  * Idempotent
1266  */
1267 static int
1268 t4_detach(device_t dev)
1269 {
1270         struct adapter *sc;
1271         int rc;
1272
1273         sc = device_get_softc(dev);
1274
1275         rc = notify_siblings(dev, 1);
1276         if (rc) {
1277                 device_printf(dev,
1278                     "failed to detach sibling devices: %d\n", rc);
1279                 return (rc);
1280         }
1281
1282         return (t4_detach_common(dev));
1283 }
1284
1285 int
1286 t4_detach_common(device_t dev)
1287 {
1288         struct adapter *sc;
1289         struct port_info *pi;
1290         int i, rc;
1291
1292         sc = device_get_softc(dev);
1293
1294         if (sc->flags & FULL_INIT_DONE) {
1295                 if (!(sc->flags & IS_VF))
1296                         t4_intr_disable(sc);
1297         }
1298
1299         if (sc->cdev) {
1300                 destroy_dev(sc->cdev);
1301                 sc->cdev = NULL;
1302         }
1303
1304         if (device_is_attached(dev)) {
1305                 rc = bus_generic_detach(dev);
1306                 if (rc) {
1307                         device_printf(dev,
1308                             "failed to detach child devices: %d\n", rc);
1309                         return (rc);
1310                 }
1311         }
1312
1313         for (i = 0; i < sc->intr_count; i++)
1314                 t4_free_irq(sc, &sc->irq[i]);
1315
1316         if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1317                 t4_free_tx_sched(sc);
1318
1319         for (i = 0; i < MAX_NPORTS; i++) {
1320                 pi = sc->port[i];
1321                 if (pi) {
1322                         t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1323                         if (pi->dev)
1324                                 device_delete_child(dev, pi->dev);
1325
1326                         mtx_destroy(&pi->pi_lock);
1327                         free(pi->vi, M_CXGBE);
1328                         free(pi, M_CXGBE);
1329                 }
1330         }
1331
1332         device_delete_children(dev);
1333
1334         if (sc->flags & FULL_INIT_DONE)
1335                 adapter_full_uninit(sc);
1336
1337         if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1338                 t4_fw_bye(sc, sc->mbox);
1339
1340         if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1341                 pci_release_msi(dev);
1342
1343         if (sc->regs_res)
1344                 bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1345                     sc->regs_res);
1346
1347         if (sc->udbs_res)
1348                 bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1349                     sc->udbs_res);
1350
1351         if (sc->msix_res)
1352                 bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1353                     sc->msix_res);
1354
1355         if (sc->l2t)
1356                 t4_free_l2t(sc->l2t);
1357
1358 #ifdef TCP_OFFLOAD
1359         free(sc->sge.ofld_rxq, M_CXGBE);
1360         free(sc->sge.ofld_txq, M_CXGBE);
1361 #endif
1362 #ifdef DEV_NETMAP
1363         free(sc->sge.nm_rxq, M_CXGBE);
1364         free(sc->sge.nm_txq, M_CXGBE);
1365 #endif
1366         free(sc->irq, M_CXGBE);
1367         free(sc->sge.rxq, M_CXGBE);
1368         free(sc->sge.txq, M_CXGBE);
1369         free(sc->sge.ctrlq, M_CXGBE);
1370         free(sc->sge.iqmap, M_CXGBE);
1371         free(sc->sge.eqmap, M_CXGBE);
1372         free(sc->tids.ftid_tab, M_CXGBE);
1373         t4_destroy_dma_tag(sc);
1374         if (mtx_initialized(&sc->sc_lock)) {
1375                 sx_xlock(&t4_list_lock);
1376                 SLIST_REMOVE(&t4_list, sc, adapter, link);
1377                 sx_xunlock(&t4_list_lock);
1378                 mtx_destroy(&sc->sc_lock);
1379         }
1380
1381         callout_drain(&sc->sfl_callout);
1382         if (mtx_initialized(&sc->tids.ftid_lock))
1383                 mtx_destroy(&sc->tids.ftid_lock);
1384         if (mtx_initialized(&sc->sfl_lock))
1385                 mtx_destroy(&sc->sfl_lock);
1386         if (mtx_initialized(&sc->ifp_lock))
1387                 mtx_destroy(&sc->ifp_lock);
1388         if (mtx_initialized(&sc->reg_lock))
1389                 mtx_destroy(&sc->reg_lock);
1390
1391         for (i = 0; i < NUM_MEMWIN; i++) {
1392                 struct memwin *mw = &sc->memwin[i];
1393
1394                 if (rw_initialized(&mw->mw_lock))
1395                         rw_destroy(&mw->mw_lock);
1396         }
1397
1398         bzero(sc, sizeof(*sc));
1399
1400         return (0);
1401 }
1402
1403 static int
1404 cxgbe_probe(device_t dev)
1405 {
1406         char buf[128];
1407         struct port_info *pi = device_get_softc(dev);
1408
1409         snprintf(buf, sizeof(buf), "port %d", pi->port_id);
1410         device_set_desc_copy(dev, buf);
1411
1412         return (BUS_PROBE_DEFAULT);
1413 }
1414
1415 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
1416     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
1417     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS)
1418 #define T4_CAP_ENABLE (T4_CAP)
1419
1420 static int
1421 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
1422 {
1423         struct ifnet *ifp;
1424         struct sbuf *sb;
1425
1426         vi->xact_addr_filt = -1;
1427         callout_init(&vi->tick, 1);
1428
1429         /* Allocate an ifnet and set it up */
1430         ifp = if_alloc(IFT_ETHER);
1431         if (ifp == NULL) {
1432                 device_printf(dev, "Cannot allocate ifnet\n");
1433                 return (ENOMEM);
1434         }
1435         vi->ifp = ifp;
1436         ifp->if_softc = vi;
1437
1438         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1439         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1440
1441         ifp->if_init = cxgbe_init;
1442         ifp->if_ioctl = cxgbe_ioctl;
1443         ifp->if_transmit = cxgbe_transmit;
1444         ifp->if_qflush = cxgbe_qflush;
1445         ifp->if_get_counter = cxgbe_get_counter;
1446
1447         ifp->if_capabilities = T4_CAP;
1448 #ifdef TCP_OFFLOAD
1449         if (vi->nofldrxq != 0)
1450                 ifp->if_capabilities |= IFCAP_TOE;
1451 #endif
1452 #ifdef DEV_NETMAP
1453         if (vi->nnmrxq != 0)
1454                 ifp->if_capabilities |= IFCAP_NETMAP;
1455 #endif
1456         ifp->if_capenable = T4_CAP_ENABLE;
1457         ifp->if_hwassist = CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
1458             CSUM_UDP_IPV6 | CSUM_TCP_IPV6;
1459
1460         ifp->if_hw_tsomax = 65536 - (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
1461         ifp->if_hw_tsomaxsegcount = TX_SGL_SEGS;
1462         ifp->if_hw_tsomaxsegsize = 65536;
1463
1464         /* Initialize ifmedia for this VI */
1465         ifmedia_init(&vi->media, IFM_IMASK, cxgbe_media_change,
1466             cxgbe_media_status);
1467
1468         vi->vlan_c = EVENTHANDLER_REGISTER(vlan_config, cxgbe_vlan_config, ifp,
1469             EVENTHANDLER_PRI_ANY);
1470
1471         ether_ifattach(ifp, vi->hw_addr);
1472 #ifdef DEV_NETMAP
1473         if (ifp->if_capabilities & IFCAP_NETMAP)
1474                 cxgbe_nm_attach(vi);
1475 #endif
1476         sb = sbuf_new_auto();
1477         sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
1478 #ifdef TCP_OFFLOAD
1479         if (ifp->if_capabilities & IFCAP_TOE)
1480                 sbuf_printf(sb, "; %d txq, %d rxq (TOE)",
1481                     vi->nofldtxq, vi->nofldrxq);
1482 #endif
1483 #ifdef DEV_NETMAP
1484         if (ifp->if_capabilities & IFCAP_NETMAP)
1485                 sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
1486                     vi->nnmtxq, vi->nnmrxq);
1487 #endif
1488         sbuf_finish(sb);
1489         device_printf(dev, "%s\n", sbuf_data(sb));
1490         sbuf_delete(sb);
1491
1492         vi_sysctls(vi);
1493
1494         return (0);
1495 }
1496
1497 static int
1498 cxgbe_attach(device_t dev)
1499 {
1500         struct port_info *pi = device_get_softc(dev);
1501         struct adapter *sc = pi->adapter;
1502         struct vi_info *vi;
1503         int i, rc;
1504
1505         callout_init_mtx(&pi->tick, &pi->pi_lock, 0);
1506
1507         rc = cxgbe_vi_attach(dev, &pi->vi[0]);
1508         if (rc)
1509                 return (rc);
1510
1511         for_each_vi(pi, i, vi) {
1512                 if (i == 0)
1513                         continue;
1514                 vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
1515                 if (vi->dev == NULL) {
1516                         device_printf(dev, "failed to add VI %d\n", i);
1517                         continue;
1518                 }
1519                 device_set_softc(vi->dev, vi);
1520         }
1521
1522         cxgbe_sysctls(pi);
1523
1524         bus_generic_attach(dev);
1525
1526         return (0);
1527 }
1528
1529 static void
1530 cxgbe_vi_detach(struct vi_info *vi)
1531 {
1532         struct ifnet *ifp = vi->ifp;
1533
1534         ether_ifdetach(ifp);
1535
1536         if (vi->vlan_c)
1537                 EVENTHANDLER_DEREGISTER(vlan_config, vi->vlan_c);
1538
1539         /* Let detach proceed even if these fail. */
1540 #ifdef DEV_NETMAP
1541         if (ifp->if_capabilities & IFCAP_NETMAP)
1542                 cxgbe_nm_detach(vi);
1543 #endif
1544         cxgbe_uninit_synchronized(vi);
1545         callout_drain(&vi->tick);
1546         vi_full_uninit(vi);
1547
1548         ifmedia_removeall(&vi->media);
1549         if_free(vi->ifp);
1550         vi->ifp = NULL;
1551 }
1552
1553 static int
1554 cxgbe_detach(device_t dev)
1555 {
1556         struct port_info *pi = device_get_softc(dev);
1557         struct adapter *sc = pi->adapter;
1558         int rc;
1559
1560         /* Detach the extra VIs first. */
1561         rc = bus_generic_detach(dev);
1562         if (rc)
1563                 return (rc);
1564         device_delete_children(dev);
1565
1566         doom_vi(sc, &pi->vi[0]);
1567
1568         if (pi->flags & HAS_TRACEQ) {
1569                 sc->traceq = -1;        /* cloner should not create ifnet */
1570                 t4_tracer_port_detach(sc);
1571         }
1572
1573         cxgbe_vi_detach(&pi->vi[0]);
1574         callout_drain(&pi->tick);
1575
1576         end_synchronized_op(sc, 0);
1577
1578         return (0);
1579 }
1580
1581 static void
1582 cxgbe_init(void *arg)
1583 {
1584         struct vi_info *vi = arg;
1585         struct adapter *sc = vi->pi->adapter;
1586
1587         if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
1588                 return;
1589         cxgbe_init_synchronized(vi);
1590         end_synchronized_op(sc, 0);
1591 }
1592
1593 static int
1594 cxgbe_ioctl(struct ifnet *ifp, unsigned long cmd, caddr_t data)
1595 {
1596         int rc = 0, mtu, flags, can_sleep;
1597         struct vi_info *vi = ifp->if_softc;
1598         struct adapter *sc = vi->pi->adapter;
1599         struct ifreq *ifr = (struct ifreq *)data;
1600         uint32_t mask;
1601
1602         switch (cmd) {
1603         case SIOCSIFMTU:
1604                 mtu = ifr->ifr_mtu;
1605                 if (mtu < ETHERMIN || mtu > MAX_MTU)
1606                         return (EINVAL);
1607
1608                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
1609                 if (rc)
1610                         return (rc);
1611                 ifp->if_mtu = mtu;
1612                 if (vi->flags & VI_INIT_DONE) {
1613                         t4_update_fl_bufsize(ifp);
1614                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1615                                 rc = update_mac_settings(ifp, XGMAC_MTU);
1616                 }
1617                 end_synchronized_op(sc, 0);
1618                 break;
1619
1620         case SIOCSIFFLAGS:
1621                 can_sleep = 0;
1622 redo_sifflags:
1623                 rc = begin_synchronized_op(sc, vi,
1624                     can_sleep ? (SLEEP_OK | INTR_OK) : HOLD_LOCK, "t4flg");
1625                 if (rc)
1626                         return (rc);
1627
1628                 if (ifp->if_flags & IFF_UP) {
1629                         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1630                                 flags = vi->if_flags;
1631                                 if ((ifp->if_flags ^ flags) &
1632                                     (IFF_PROMISC | IFF_ALLMULTI)) {
1633                                         if (can_sleep == 1) {
1634                                                 end_synchronized_op(sc, 0);
1635                                                 can_sleep = 0;
1636                                                 goto redo_sifflags;
1637                                         }
1638                                         rc = update_mac_settings(ifp,
1639                                             XGMAC_PROMISC | XGMAC_ALLMULTI);
1640                                 }
1641                         } else {
1642                                 if (can_sleep == 0) {
1643                                         end_synchronized_op(sc, LOCK_HELD);
1644                                         can_sleep = 1;
1645                                         goto redo_sifflags;
1646                                 }
1647                                 rc = cxgbe_init_synchronized(vi);
1648                         }
1649                         vi->if_flags = ifp->if_flags;
1650                 } else if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1651                         if (can_sleep == 0) {
1652                                 end_synchronized_op(sc, LOCK_HELD);
1653                                 can_sleep = 1;
1654                                 goto redo_sifflags;
1655                         }
1656                         rc = cxgbe_uninit_synchronized(vi);
1657                 }
1658                 end_synchronized_op(sc, can_sleep ? 0 : LOCK_HELD);
1659                 break;
1660
1661         case SIOCADDMULTI:
1662         case SIOCDELMULTI: /* these two are called with a mutex held :-( */
1663                 rc = begin_synchronized_op(sc, vi, HOLD_LOCK, "t4multi");
1664                 if (rc)
1665                         return (rc);
1666                 if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1667                         rc = update_mac_settings(ifp, XGMAC_MCADDRS);
1668                 end_synchronized_op(sc, LOCK_HELD);
1669                 break;
1670
1671         case SIOCSIFCAP:
1672                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
1673                 if (rc)
1674                         return (rc);
1675
1676                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1677                 if (mask & IFCAP_TXCSUM) {
1678                         ifp->if_capenable ^= IFCAP_TXCSUM;
1679                         ifp->if_hwassist ^= (CSUM_TCP | CSUM_UDP | CSUM_IP);
1680
1681                         if (IFCAP_TSO4 & ifp->if_capenable &&
1682                             !(IFCAP_TXCSUM & ifp->if_capenable)) {
1683                                 ifp->if_capenable &= ~IFCAP_TSO4;
1684                                 if_printf(ifp,
1685                                     "tso4 disabled due to -txcsum.\n");
1686                         }
1687                 }
1688                 if (mask & IFCAP_TXCSUM_IPV6) {
1689                         ifp->if_capenable ^= IFCAP_TXCSUM_IPV6;
1690                         ifp->if_hwassist ^= (CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
1691
1692                         if (IFCAP_TSO6 & ifp->if_capenable &&
1693                             !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
1694                                 ifp->if_capenable &= ~IFCAP_TSO6;
1695                                 if_printf(ifp,
1696                                     "tso6 disabled due to -txcsum6.\n");
1697                         }
1698                 }
1699                 if (mask & IFCAP_RXCSUM)
1700                         ifp->if_capenable ^= IFCAP_RXCSUM;
1701                 if (mask & IFCAP_RXCSUM_IPV6)
1702                         ifp->if_capenable ^= IFCAP_RXCSUM_IPV6;
1703
1704                 /*
1705                  * Note that we leave CSUM_TSO alone (it is always set).  The
1706                  * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
1707                  * sending a TSO request our way, so it's sufficient to toggle
1708                  * IFCAP_TSOx only.
1709                  */
1710                 if (mask & IFCAP_TSO4) {
1711                         if (!(IFCAP_TSO4 & ifp->if_capenable) &&
1712                             !(IFCAP_TXCSUM & ifp->if_capenable)) {
1713                                 if_printf(ifp, "enable txcsum first.\n");
1714                                 rc = EAGAIN;
1715                                 goto fail;
1716                         }
1717                         ifp->if_capenable ^= IFCAP_TSO4;
1718                 }
1719                 if (mask & IFCAP_TSO6) {
1720                         if (!(IFCAP_TSO6 & ifp->if_capenable) &&
1721                             !(IFCAP_TXCSUM_IPV6 & ifp->if_capenable)) {
1722                                 if_printf(ifp, "enable txcsum6 first.\n");
1723                                 rc = EAGAIN;
1724                                 goto fail;
1725                         }
1726                         ifp->if_capenable ^= IFCAP_TSO6;
1727                 }
1728                 if (mask & IFCAP_LRO) {
1729 #if defined(INET) || defined(INET6)
1730                         int i;
1731                         struct sge_rxq *rxq;
1732
1733                         ifp->if_capenable ^= IFCAP_LRO;
1734                         for_each_rxq(vi, i, rxq) {
1735                                 if (ifp->if_capenable & IFCAP_LRO)
1736                                         rxq->iq.flags |= IQ_LRO_ENABLED;
1737                                 else
1738                                         rxq->iq.flags &= ~IQ_LRO_ENABLED;
1739                         }
1740 #endif
1741                 }
1742 #ifdef TCP_OFFLOAD
1743                 if (mask & IFCAP_TOE) {
1744                         int enable = (ifp->if_capenable ^ mask) & IFCAP_TOE;
1745
1746                         rc = toe_capability(vi, enable);
1747                         if (rc != 0)
1748                                 goto fail;
1749
1750                         ifp->if_capenable ^= mask;
1751                 }
1752 #endif
1753                 if (mask & IFCAP_VLAN_HWTAGGING) {
1754                         ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
1755                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1756                                 rc = update_mac_settings(ifp, XGMAC_VLANEX);
1757                 }
1758                 if (mask & IFCAP_VLAN_MTU) {
1759                         ifp->if_capenable ^= IFCAP_VLAN_MTU;
1760
1761                         /* Need to find out how to disable auto-mtu-inflation */
1762                 }
1763                 if (mask & IFCAP_VLAN_HWTSO)
1764                         ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
1765                 if (mask & IFCAP_VLAN_HWCSUM)
1766                         ifp->if_capenable ^= IFCAP_VLAN_HWCSUM;
1767
1768 #ifdef VLAN_CAPABILITIES
1769                 VLAN_CAPABILITIES(ifp);
1770 #endif
1771 fail:
1772                 end_synchronized_op(sc, 0);
1773                 break;
1774
1775         case SIOCSIFMEDIA:
1776         case SIOCGIFMEDIA:
1777         case SIOCGIFXMEDIA:
1778                 ifmedia_ioctl(ifp, ifr, &vi->media, cmd);
1779                 break;
1780
1781         case SIOCGI2C: {
1782                 struct ifi2creq i2c;
1783
1784                 rc = copyin(ifr->ifr_data, &i2c, sizeof(i2c));
1785                 if (rc != 0)
1786                         break;
1787                 if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
1788                         rc = EPERM;
1789                         break;
1790                 }
1791                 if (i2c.len > sizeof(i2c.data)) {
1792                         rc = EINVAL;
1793                         break;
1794                 }
1795                 rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
1796                 if (rc)
1797                         return (rc);
1798                 rc = -t4_i2c_rd(sc, sc->mbox, vi->pi->port_id, i2c.dev_addr,
1799                     i2c.offset, i2c.len, &i2c.data[0]);
1800                 end_synchronized_op(sc, 0);
1801                 if (rc == 0)
1802                         rc = copyout(&i2c, ifr->ifr_data, sizeof(i2c));
1803                 break;
1804         }
1805
1806         default:
1807                 rc = ether_ioctl(ifp, cmd, data);
1808         }
1809
1810         return (rc);
1811 }
1812
1813 static int
1814 cxgbe_transmit(struct ifnet *ifp, struct mbuf *m)
1815 {
1816         struct vi_info *vi = ifp->if_softc;
1817         struct port_info *pi = vi->pi;
1818         struct adapter *sc = pi->adapter;
1819         struct sge_txq *txq;
1820         void *items[1];
1821         int rc;
1822
1823         M_ASSERTPKTHDR(m);
1824         MPASS(m->m_nextpkt == NULL);    /* not quite ready for this yet */
1825
1826         if (__predict_false(pi->link_cfg.link_ok == 0)) {
1827                 m_freem(m);
1828                 return (ENETDOWN);
1829         }
1830
1831         rc = parse_pkt(sc, &m);
1832         if (__predict_false(rc != 0)) {
1833                 MPASS(m == NULL);                       /* was freed already */
1834                 atomic_add_int(&pi->tx_parse_error, 1); /* rare, atomic is ok */
1835                 return (rc);
1836         }
1837
1838         /* Select a txq. */
1839         txq = &sc->sge.txq[vi->first_txq];
1840         if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
1841                 txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
1842                     vi->rsrv_noflowq);
1843
1844         items[0] = m;
1845         rc = mp_ring_enqueue(txq->r, items, 1, 4096);
1846         if (__predict_false(rc != 0))
1847                 m_freem(m);
1848
1849         return (rc);
1850 }
1851
1852 static void
1853 cxgbe_qflush(struct ifnet *ifp)
1854 {
1855         struct vi_info *vi = ifp->if_softc;
1856         struct sge_txq *txq;
1857         int i;
1858
1859         /* queues do not exist if !VI_INIT_DONE. */
1860         if (vi->flags & VI_INIT_DONE) {
1861                 for_each_txq(vi, i, txq) {
1862                         TXQ_LOCK(txq);
1863                         txq->eq.flags |= EQ_QFLUSH;
1864                         TXQ_UNLOCK(txq);
1865                         while (!mp_ring_is_idle(txq->r)) {
1866                                 mp_ring_check_drainage(txq->r, 0);
1867                                 pause("qflush", 1);
1868                         }
1869                         TXQ_LOCK(txq);
1870                         txq->eq.flags &= ~EQ_QFLUSH;
1871                         TXQ_UNLOCK(txq);
1872                 }
1873         }
1874         if_qflush(ifp);
1875 }
1876
1877 static uint64_t
1878 vi_get_counter(struct ifnet *ifp, ift_counter c)
1879 {
1880         struct vi_info *vi = ifp->if_softc;
1881         struct fw_vi_stats_vf *s = &vi->stats;
1882
1883         vi_refresh_stats(vi->pi->adapter, vi);
1884
1885         switch (c) {
1886         case IFCOUNTER_IPACKETS:
1887                 return (s->rx_bcast_frames + s->rx_mcast_frames +
1888                     s->rx_ucast_frames);
1889         case IFCOUNTER_IERRORS:
1890                 return (s->rx_err_frames);
1891         case IFCOUNTER_OPACKETS:
1892                 return (s->tx_bcast_frames + s->tx_mcast_frames +
1893                     s->tx_ucast_frames + s->tx_offload_frames);
1894         case IFCOUNTER_OERRORS:
1895                 return (s->tx_drop_frames);
1896         case IFCOUNTER_IBYTES:
1897                 return (s->rx_bcast_bytes + s->rx_mcast_bytes +
1898                     s->rx_ucast_bytes);
1899         case IFCOUNTER_OBYTES:
1900                 return (s->tx_bcast_bytes + s->tx_mcast_bytes +
1901                     s->tx_ucast_bytes + s->tx_offload_bytes);
1902         case IFCOUNTER_IMCASTS:
1903                 return (s->rx_mcast_frames);
1904         case IFCOUNTER_OMCASTS:
1905                 return (s->tx_mcast_frames);
1906         case IFCOUNTER_OQDROPS: {
1907                 uint64_t drops;
1908
1909                 drops = 0;
1910                 if (vi->flags & VI_INIT_DONE) {
1911                         int i;
1912                         struct sge_txq *txq;
1913
1914                         for_each_txq(vi, i, txq)
1915                                 drops += counter_u64_fetch(txq->r->drops);
1916                 }
1917
1918                 return (drops);
1919
1920         }
1921
1922         default:
1923                 return (if_get_counter_default(ifp, c));
1924         }
1925 }
1926
1927 uint64_t
1928 cxgbe_get_counter(struct ifnet *ifp, ift_counter c)
1929 {
1930         struct vi_info *vi = ifp->if_softc;
1931         struct port_info *pi = vi->pi;
1932         struct adapter *sc = pi->adapter;
1933         struct port_stats *s = &pi->stats;
1934
1935         if (pi->nvi > 1 || sc->flags & IS_VF)
1936                 return (vi_get_counter(ifp, c));
1937
1938         cxgbe_refresh_stats(sc, pi);
1939
1940         switch (c) {
1941         case IFCOUNTER_IPACKETS:
1942                 return (s->rx_frames);
1943
1944         case IFCOUNTER_IERRORS:
1945                 return (s->rx_jabber + s->rx_runt + s->rx_too_long +
1946                     s->rx_fcs_err + s->rx_len_err);
1947
1948         case IFCOUNTER_OPACKETS:
1949                 return (s->tx_frames);
1950
1951         case IFCOUNTER_OERRORS:
1952                 return (s->tx_error_frames);
1953
1954         case IFCOUNTER_IBYTES:
1955                 return (s->rx_octets);
1956
1957         case IFCOUNTER_OBYTES:
1958                 return (s->tx_octets);
1959
1960         case IFCOUNTER_IMCASTS:
1961                 return (s->rx_mcast_frames);
1962
1963         case IFCOUNTER_OMCASTS:
1964                 return (s->tx_mcast_frames);
1965
1966         case IFCOUNTER_IQDROPS:
1967                 return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
1968                     s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
1969                     s->rx_trunc3 + pi->tnl_cong_drops);
1970
1971         case IFCOUNTER_OQDROPS: {
1972                 uint64_t drops;
1973
1974                 drops = s->tx_drop;
1975                 if (vi->flags & VI_INIT_DONE) {
1976                         int i;
1977                         struct sge_txq *txq;
1978
1979                         for_each_txq(vi, i, txq)
1980                                 drops += counter_u64_fetch(txq->r->drops);
1981                 }
1982
1983                 return (drops);
1984
1985         }
1986
1987         default:
1988                 return (if_get_counter_default(ifp, c));
1989         }
1990 }
1991
1992 static int
1993 cxgbe_media_change(struct ifnet *ifp)
1994 {
1995         struct vi_info *vi = ifp->if_softc;
1996
1997         device_printf(vi->dev, "%s unimplemented.\n", __func__);
1998
1999         return (EOPNOTSUPP);
2000 }
2001
2002 static void
2003 cxgbe_media_status(struct ifnet *ifp, struct ifmediareq *ifmr)
2004 {
2005         struct vi_info *vi = ifp->if_softc;
2006         struct port_info *pi = vi->pi;
2007         struct ifmedia_entry *cur;
2008         struct link_config *lc = &pi->link_cfg;
2009
2010         /*
2011          * If all the interfaces are administratively down the firmware does not
2012          * report transceiver changes.  Refresh port info here so that ifconfig
2013          * displays accurate information at all times.
2014          */
2015         if (begin_synchronized_op(pi->adapter, NULL, SLEEP_OK | INTR_OK,
2016             "t4med") == 0) {
2017                 PORT_LOCK(pi);
2018                 if (pi->up_vis == 0) {
2019                         t4_update_port_info(pi);
2020                         build_medialist(pi, &vi->media);
2021                 }
2022                 PORT_UNLOCK(pi);
2023                 end_synchronized_op(pi->adapter, 0);
2024         }
2025
2026         cur = vi->media.ifm_cur;
2027
2028         ifmr->ifm_status = IFM_AVALID;
2029         if (lc->link_ok == 0)
2030                 return;
2031
2032         ifmr->ifm_status |= IFM_ACTIVE;
2033         ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
2034         if (lc->fc & PAUSE_RX)
2035                 ifmr->ifm_active |= IFM_ETH_RXPAUSE;
2036         if (lc->fc & PAUSE_TX)
2037                 ifmr->ifm_active |= IFM_ETH_TXPAUSE;
2038
2039         /* active and current will differ iff current media is autoselect. */
2040         if (IFM_SUBTYPE(cur->ifm_media) != IFM_AUTO)
2041                 return;
2042
2043         ifmr->ifm_active = IFM_ETHER | IFM_FDX;
2044         if (lc->fc & PAUSE_RX)
2045                 ifmr->ifm_active |= IFM_ETH_RXPAUSE;
2046         if (lc->fc & PAUSE_TX)
2047                 ifmr->ifm_active |= IFM_ETH_TXPAUSE;
2048         switch (lc->speed) {
2049         case 10000:
2050                 ifmr->ifm_active |= IFM_10G_T;
2051                 break;
2052         case 1000:
2053                 ifmr->ifm_active |= IFM_1000_T;
2054                 break;
2055         case 100:
2056                 ifmr->ifm_active |= IFM_100_TX;
2057                 break;
2058         case 10:
2059                 ifmr->ifm_active |= IFM_10_T;
2060                 break;
2061         default:
2062                 device_printf(vi->dev, "link up but speed unknown (%u)\n",
2063                     lc->speed);
2064         }
2065 }
2066
2067 static int
2068 vcxgbe_probe(device_t dev)
2069 {
2070         char buf[128];
2071         struct vi_info *vi = device_get_softc(dev);
2072
2073         snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
2074             vi - vi->pi->vi);
2075         device_set_desc_copy(dev, buf);
2076
2077         return (BUS_PROBE_DEFAULT);
2078 }
2079
2080 static int
2081 vcxgbe_attach(device_t dev)
2082 {
2083         struct vi_info *vi;
2084         struct port_info *pi;
2085         struct adapter *sc;
2086         int func, index, rc;
2087         u32 param, val;
2088
2089         vi = device_get_softc(dev);
2090         pi = vi->pi;
2091         sc = pi->adapter;
2092
2093         index = vi - pi->vi;
2094         KASSERT(index < nitems(vi_mac_funcs),
2095             ("%s: VI %s doesn't have a MAC func", __func__,
2096             device_get_nameunit(dev)));
2097         func = vi_mac_funcs[index];
2098         rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
2099             vi->hw_addr, &vi->rss_size, func, 0);
2100         if (rc < 0) {
2101                 device_printf(dev, "Failed to allocate virtual interface "
2102                     "for port %d: %d\n", pi->port_id, -rc);
2103                 return (-rc);
2104         }
2105         vi->viid = rc;
2106         if (chip_id(sc) <= CHELSIO_T5)
2107                 vi->smt_idx = (rc & 0x7f) << 1;
2108         else
2109                 vi->smt_idx = (rc & 0x7f);
2110
2111         param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
2112             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
2113             V_FW_PARAMS_PARAM_YZ(vi->viid);
2114         rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
2115         if (rc)
2116                 vi->rss_base = 0xffff;
2117         else {
2118                 /* MPASS((val >> 16) == rss_size); */
2119                 vi->rss_base = val & 0xffff;
2120         }
2121
2122         rc = cxgbe_vi_attach(dev, vi);
2123         if (rc) {
2124                 t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
2125                 return (rc);
2126         }
2127         return (0);
2128 }
2129
2130 static int
2131 vcxgbe_detach(device_t dev)
2132 {
2133         struct vi_info *vi;
2134         struct adapter *sc;
2135
2136         vi = device_get_softc(dev);
2137         sc = vi->pi->adapter;
2138
2139         doom_vi(sc, vi);
2140
2141         cxgbe_vi_detach(vi);
2142         t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
2143
2144         end_synchronized_op(sc, 0);
2145
2146         return (0);
2147 }
2148
2149 void
2150 t4_fatal_err(struct adapter *sc)
2151 {
2152         t4_set_reg_field(sc, A_SGE_CONTROL, F_GLOBALENABLE, 0);
2153         t4_intr_disable(sc);
2154         log(LOG_EMERG, "%s: encountered fatal error, adapter stopped.\n",
2155             device_get_nameunit(sc->dev));
2156 }
2157
2158 void
2159 t4_add_adapter(struct adapter *sc)
2160 {
2161         sx_xlock(&t4_list_lock);
2162         SLIST_INSERT_HEAD(&t4_list, sc, link);
2163         sx_xunlock(&t4_list_lock);
2164 }
2165
2166 int
2167 t4_map_bars_0_and_4(struct adapter *sc)
2168 {
2169         sc->regs_rid = PCIR_BAR(0);
2170         sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
2171             &sc->regs_rid, RF_ACTIVE);
2172         if (sc->regs_res == NULL) {
2173                 device_printf(sc->dev, "cannot map registers.\n");
2174                 return (ENXIO);
2175         }
2176         sc->bt = rman_get_bustag(sc->regs_res);
2177         sc->bh = rman_get_bushandle(sc->regs_res);
2178         sc->mmio_len = rman_get_size(sc->regs_res);
2179         setbit(&sc->doorbells, DOORBELL_KDB);
2180
2181         sc->msix_rid = PCIR_BAR(4);
2182         sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
2183             &sc->msix_rid, RF_ACTIVE);
2184         if (sc->msix_res == NULL) {
2185                 device_printf(sc->dev, "cannot map MSI-X BAR.\n");
2186                 return (ENXIO);
2187         }
2188
2189         return (0);
2190 }
2191
2192 int
2193 t4_map_bar_2(struct adapter *sc)
2194 {
2195
2196         /*
2197          * T4: only iWARP driver uses the userspace doorbells.  There is no need
2198          * to map it if RDMA is disabled.
2199          */
2200         if (is_t4(sc) && sc->rdmacaps == 0)
2201                 return (0);
2202
2203         sc->udbs_rid = PCIR_BAR(2);
2204         sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
2205             &sc->udbs_rid, RF_ACTIVE);
2206         if (sc->udbs_res == NULL) {
2207                 device_printf(sc->dev, "cannot map doorbell BAR.\n");
2208                 return (ENXIO);
2209         }
2210         sc->udbs_base = rman_get_virtual(sc->udbs_res);
2211
2212         if (chip_id(sc) >= CHELSIO_T5) {
2213                 setbit(&sc->doorbells, DOORBELL_UDB);
2214 #if defined(__i386__) || defined(__amd64__)
2215                 if (t5_write_combine) {
2216                         int rc, mode;
2217
2218                         /*
2219                          * Enable write combining on BAR2.  This is the
2220                          * userspace doorbell BAR and is split into 128B
2221                          * (UDBS_SEG_SIZE) doorbell regions, each associated
2222                          * with an egress queue.  The first 64B has the doorbell
2223                          * and the second 64B can be used to submit a tx work
2224                          * request with an implicit doorbell.
2225                          */
2226
2227                         rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
2228                             rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
2229                         if (rc == 0) {
2230                                 clrbit(&sc->doorbells, DOORBELL_UDB);
2231                                 setbit(&sc->doorbells, DOORBELL_WCWR);
2232                                 setbit(&sc->doorbells, DOORBELL_UDBWC);
2233                         } else {
2234                                 device_printf(sc->dev,
2235                                     "couldn't enable write combining: %d\n",
2236                                     rc);
2237                         }
2238
2239                         mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
2240                         t4_write_reg(sc, A_SGE_STAT_CFG,
2241                             V_STATSOURCE_T5(7) | mode);
2242                 }
2243 #endif
2244         }
2245
2246         return (0);
2247 }
2248
2249 struct memwin_init {
2250         uint32_t base;
2251         uint32_t aperture;
2252 };
2253
2254 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
2255         { MEMWIN0_BASE, MEMWIN0_APERTURE },
2256         { MEMWIN1_BASE, MEMWIN1_APERTURE },
2257         { MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
2258 };
2259
2260 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
2261         { MEMWIN0_BASE, MEMWIN0_APERTURE },
2262         { MEMWIN1_BASE, MEMWIN1_APERTURE },
2263         { MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
2264 };
2265
2266 static void
2267 setup_memwin(struct adapter *sc)
2268 {
2269         const struct memwin_init *mw_init;
2270         struct memwin *mw;
2271         int i;
2272         uint32_t bar0;
2273
2274         if (is_t4(sc)) {
2275                 /*
2276                  * Read low 32b of bar0 indirectly via the hardware backdoor
2277                  * mechanism.  Works from within PCI passthrough environments
2278                  * too, where rman_get_start() can return a different value.  We
2279                  * need to program the T4 memory window decoders with the actual
2280                  * addresses that will be coming across the PCIe link.
2281                  */
2282                 bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
2283                 bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
2284
2285                 mw_init = &t4_memwin[0];
2286         } else {
2287                 /* T5+ use the relative offset inside the PCIe BAR */
2288                 bar0 = 0;
2289
2290                 mw_init = &t5_memwin[0];
2291         }
2292
2293         for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
2294                 rw_init(&mw->mw_lock, "memory window access");
2295                 mw->mw_base = mw_init->base;
2296                 mw->mw_aperture = mw_init->aperture;
2297                 mw->mw_curpos = 0;
2298                 t4_write_reg(sc,
2299                     PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
2300                     (mw->mw_base + bar0) | V_BIR(0) |
2301                     V_WINDOW(ilog2(mw->mw_aperture) - 10));
2302                 rw_wlock(&mw->mw_lock);
2303                 position_memwin(sc, i, 0);
2304                 rw_wunlock(&mw->mw_lock);
2305         }
2306
2307         /* flush */
2308         t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
2309 }
2310
2311 /*
2312  * Positions the memory window at the given address in the card's address space.
2313  * There are some alignment requirements and the actual position may be at an
2314  * address prior to the requested address.  mw->mw_curpos always has the actual
2315  * position of the window.
2316  */
2317 static void
2318 position_memwin(struct adapter *sc, int idx, uint32_t addr)
2319 {
2320         struct memwin *mw;
2321         uint32_t pf;
2322         uint32_t reg;
2323
2324         MPASS(idx >= 0 && idx < NUM_MEMWIN);
2325         mw = &sc->memwin[idx];
2326         rw_assert(&mw->mw_lock, RA_WLOCKED);
2327
2328         if (is_t4(sc)) {
2329                 pf = 0;
2330                 mw->mw_curpos = addr & ~0xf;    /* start must be 16B aligned */
2331         } else {
2332                 pf = V_PFNUM(sc->pf);
2333                 mw->mw_curpos = addr & ~0x7f;   /* start must be 128B aligned */
2334         }
2335         reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
2336         t4_write_reg(sc, reg, mw->mw_curpos | pf);
2337         t4_read_reg(sc, reg);   /* flush */
2338 }
2339
2340 static int
2341 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
2342     int len, int rw)
2343 {
2344         struct memwin *mw;
2345         uint32_t mw_end, v;
2346
2347         MPASS(idx >= 0 && idx < NUM_MEMWIN);
2348
2349         /* Memory can only be accessed in naturally aligned 4 byte units */
2350         if (addr & 3 || len & 3 || len <= 0)
2351                 return (EINVAL);
2352
2353         mw = &sc->memwin[idx];
2354         while (len > 0) {
2355                 rw_rlock(&mw->mw_lock);
2356                 mw_end = mw->mw_curpos + mw->mw_aperture;
2357                 if (addr >= mw_end || addr < mw->mw_curpos) {
2358                         /* Will need to reposition the window */
2359                         if (!rw_try_upgrade(&mw->mw_lock)) {
2360                                 rw_runlock(&mw->mw_lock);
2361                                 rw_wlock(&mw->mw_lock);
2362                         }
2363                         rw_assert(&mw->mw_lock, RA_WLOCKED);
2364                         position_memwin(sc, idx, addr);
2365                         rw_downgrade(&mw->mw_lock);
2366                         mw_end = mw->mw_curpos + mw->mw_aperture;
2367                 }
2368                 rw_assert(&mw->mw_lock, RA_RLOCKED);
2369                 while (addr < mw_end && len > 0) {
2370                         if (rw == 0) {
2371                                 v = t4_read_reg(sc, mw->mw_base + addr -
2372                                     mw->mw_curpos);
2373                                 *val++ = le32toh(v);
2374                         } else {
2375                                 v = *val++;
2376                                 t4_write_reg(sc, mw->mw_base + addr -
2377                                     mw->mw_curpos, htole32(v));
2378                         }
2379                         addr += 4;
2380                         len -= 4;
2381                 }
2382                 rw_runlock(&mw->mw_lock);
2383         }
2384
2385         return (0);
2386 }
2387
2388 static inline int
2389 read_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
2390     int len)
2391 {
2392
2393         return (rw_via_memwin(sc, idx, addr, val, len, 0));
2394 }
2395
2396 static inline int
2397 write_via_memwin(struct adapter *sc, int idx, uint32_t addr,
2398     const uint32_t *val, int len)
2399 {
2400
2401         return (rw_via_memwin(sc, idx, addr, (void *)(uintptr_t)val, len, 1));
2402 }
2403
2404 static int
2405 t4_range_cmp(const void *a, const void *b)
2406 {
2407         return ((const struct t4_range *)a)->start -
2408                ((const struct t4_range *)b)->start;
2409 }
2410
2411 /*
2412  * Verify that the memory range specified by the addr/len pair is valid within
2413  * the card's address space.
2414  */
2415 static int
2416 validate_mem_range(struct adapter *sc, uint32_t addr, int len)
2417 {
2418         struct t4_range mem_ranges[4], *r, *next;
2419         uint32_t em, addr_len;
2420         int i, n, remaining;
2421
2422         /* Memory can only be accessed in naturally aligned 4 byte units */
2423         if (addr & 3 || len & 3 || len <= 0)
2424                 return (EINVAL);
2425
2426         /* Enabled memories */
2427         em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
2428
2429         r = &mem_ranges[0];
2430         n = 0;
2431         bzero(r, sizeof(mem_ranges));
2432         if (em & F_EDRAM0_ENABLE) {
2433                 addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
2434                 r->size = G_EDRAM0_SIZE(addr_len) << 20;
2435                 if (r->size > 0) {
2436                         r->start = G_EDRAM0_BASE(addr_len) << 20;
2437                         if (addr >= r->start &&
2438                             addr + len <= r->start + r->size)
2439                                 return (0);
2440                         r++;
2441                         n++;
2442                 }
2443         }
2444         if (em & F_EDRAM1_ENABLE) {
2445                 addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
2446                 r->size = G_EDRAM1_SIZE(addr_len) << 20;
2447                 if (r->size > 0) {
2448                         r->start = G_EDRAM1_BASE(addr_len) << 20;
2449                         if (addr >= r->start &&
2450                             addr + len <= r->start + r->size)
2451                                 return (0);
2452                         r++;
2453                         n++;
2454                 }
2455         }
2456         if (em & F_EXT_MEM_ENABLE) {
2457                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
2458                 r->size = G_EXT_MEM_SIZE(addr_len) << 20;
2459                 if (r->size > 0) {
2460                         r->start = G_EXT_MEM_BASE(addr_len) << 20;
2461                         if (addr >= r->start &&
2462                             addr + len <= r->start + r->size)
2463                                 return (0);
2464                         r++;
2465                         n++;
2466                 }
2467         }
2468         if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
2469                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
2470                 r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
2471                 if (r->size > 0) {
2472                         r->start = G_EXT_MEM1_BASE(addr_len) << 20;
2473                         if (addr >= r->start &&
2474                             addr + len <= r->start + r->size)
2475                                 return (0);
2476                         r++;
2477                         n++;
2478                 }
2479         }
2480         MPASS(n <= nitems(mem_ranges));
2481
2482         if (n > 1) {
2483                 /* Sort and merge the ranges. */
2484                 qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
2485
2486                 /* Start from index 0 and examine the next n - 1 entries. */
2487                 r = &mem_ranges[0];
2488                 for (remaining = n - 1; remaining > 0; remaining--, r++) {
2489
2490                         MPASS(r->size > 0);     /* r is a valid entry. */
2491                         next = r + 1;
2492                         MPASS(next->size > 0);  /* and so is the next one. */
2493
2494                         while (r->start + r->size >= next->start) {
2495                                 /* Merge the next one into the current entry. */
2496                                 r->size = max(r->start + r->size,
2497                                     next->start + next->size) - r->start;
2498                                 n--;    /* One fewer entry in total. */
2499                                 if (--remaining == 0)
2500                                         goto done;      /* short circuit */
2501                                 next++;
2502                         }
2503                         if (next != r + 1) {
2504                                 /*
2505                                  * Some entries were merged into r and next
2506                                  * points to the first valid entry that couldn't
2507                                  * be merged.
2508                                  */
2509                                 MPASS(next->size > 0);  /* must be valid */
2510                                 memcpy(r + 1, next, remaining * sizeof(*r));
2511 #ifdef INVARIANTS
2512                                 /*
2513                                  * This so that the foo->size assertion in the
2514                                  * next iteration of the loop do the right
2515                                  * thing for entries that were pulled up and are
2516                                  * no longer valid.
2517                                  */
2518                                 MPASS(n < nitems(mem_ranges));
2519                                 bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
2520                                     sizeof(struct t4_range));
2521 #endif
2522                         }
2523                 }
2524 done:
2525                 /* Done merging the ranges. */
2526                 MPASS(n > 0);
2527                 r = &mem_ranges[0];
2528                 for (i = 0; i < n; i++, r++) {
2529                         if (addr >= r->start &&
2530                             addr + len <= r->start + r->size)
2531                                 return (0);
2532                 }
2533         }
2534
2535         return (EFAULT);
2536 }
2537
2538 static int
2539 fwmtype_to_hwmtype(int mtype)
2540 {
2541
2542         switch (mtype) {
2543         case FW_MEMTYPE_EDC0:
2544                 return (MEM_EDC0);
2545         case FW_MEMTYPE_EDC1:
2546                 return (MEM_EDC1);
2547         case FW_MEMTYPE_EXTMEM:
2548                 return (MEM_MC0);
2549         case FW_MEMTYPE_EXTMEM1:
2550                 return (MEM_MC1);
2551         default:
2552                 panic("%s: cannot translate fw mtype %d.", __func__, mtype);
2553         }
2554 }
2555
2556 /*
2557  * Verify that the memory range specified by the memtype/offset/len pair is
2558  * valid and lies entirely within the memtype specified.  The global address of
2559  * the start of the range is returned in addr.
2560  */
2561 static int
2562 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, int len,
2563     uint32_t *addr)
2564 {
2565         uint32_t em, addr_len, maddr;
2566
2567         /* Memory can only be accessed in naturally aligned 4 byte units */
2568         if (off & 3 || len & 3 || len == 0)
2569                 return (EINVAL);
2570
2571         em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
2572         switch (fwmtype_to_hwmtype(mtype)) {
2573         case MEM_EDC0:
2574                 if (!(em & F_EDRAM0_ENABLE))
2575                         return (EINVAL);
2576                 addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
2577                 maddr = G_EDRAM0_BASE(addr_len) << 20;
2578                 break;
2579         case MEM_EDC1:
2580                 if (!(em & F_EDRAM1_ENABLE))
2581                         return (EINVAL);
2582                 addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
2583                 maddr = G_EDRAM1_BASE(addr_len) << 20;
2584                 break;
2585         case MEM_MC:
2586                 if (!(em & F_EXT_MEM_ENABLE))
2587                         return (EINVAL);
2588                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
2589                 maddr = G_EXT_MEM_BASE(addr_len) << 20;
2590                 break;
2591         case MEM_MC1:
2592                 if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
2593                         return (EINVAL);
2594                 addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
2595                 maddr = G_EXT_MEM1_BASE(addr_len) << 20;
2596                 break;
2597         default:
2598                 return (EINVAL);
2599         }
2600
2601         *addr = maddr + off;    /* global address */
2602         return (validate_mem_range(sc, *addr, len));
2603 }
2604
2605 static int
2606 fixup_devlog_params(struct adapter *sc)
2607 {
2608         struct devlog_params *dparams = &sc->params.devlog;
2609         int rc;
2610
2611         rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
2612             dparams->size, &dparams->addr);
2613
2614         return (rc);
2615 }
2616
2617 static int
2618 cfg_itype_and_nqueues(struct adapter *sc, int n10g, int n1g, int num_vis,
2619     struct intrs_and_queues *iaq)
2620 {
2621         int rc, itype, navail, nrxq10g, nrxq1g, n;
2622         int nofldrxq10g = 0, nofldrxq1g = 0;
2623
2624         bzero(iaq, sizeof(*iaq));
2625
2626         iaq->ntxq10g = t4_ntxq10g;
2627         iaq->ntxq1g = t4_ntxq1g;
2628         iaq->ntxq_vi = t4_ntxq_vi;
2629         iaq->nrxq10g = nrxq10g = t4_nrxq10g;
2630         iaq->nrxq1g = nrxq1g = t4_nrxq1g;
2631         iaq->nrxq_vi = t4_nrxq_vi;
2632         iaq->rsrv_noflowq = t4_rsrv_noflowq;
2633 #ifdef TCP_OFFLOAD
2634         if (is_offload(sc)) {
2635                 iaq->nofldtxq10g = t4_nofldtxq10g;
2636                 iaq->nofldtxq1g = t4_nofldtxq1g;
2637                 iaq->nofldtxq_vi = t4_nofldtxq_vi;
2638                 iaq->nofldrxq10g = nofldrxq10g = t4_nofldrxq10g;
2639                 iaq->nofldrxq1g = nofldrxq1g = t4_nofldrxq1g;
2640                 iaq->nofldrxq_vi = t4_nofldrxq_vi;
2641         }
2642 #endif
2643 #ifdef DEV_NETMAP
2644         iaq->nnmtxq_vi = t4_nnmtxq_vi;
2645         iaq->nnmrxq_vi = t4_nnmrxq_vi;
2646 #endif
2647
2648         for (itype = INTR_MSIX; itype; itype >>= 1) {
2649
2650                 if ((itype & t4_intr_types) == 0)
2651                         continue;       /* not allowed */
2652
2653                 if (itype == INTR_MSIX)
2654                         navail = pci_msix_count(sc->dev);
2655                 else if (itype == INTR_MSI)
2656                         navail = pci_msi_count(sc->dev);
2657                 else
2658                         navail = 1;
2659 restart:
2660                 if (navail == 0)
2661                         continue;
2662
2663                 iaq->intr_type = itype;
2664                 iaq->intr_flags_10g = 0;
2665                 iaq->intr_flags_1g = 0;
2666
2667                 /*
2668                  * Best option: an interrupt vector for errors, one for the
2669                  * firmware event queue, and one for every rxq (NIC and TOE) of
2670                  * every VI.  The VIs that support netmap use the same
2671                  * interrupts for the NIC rx queues and the netmap rx queues
2672                  * because only one set of queues is active at a time.
2673                  */
2674                 iaq->nirq = T4_EXTRA_INTR;
2675                 iaq->nirq += n10g * (nrxq10g + nofldrxq10g);
2676                 iaq->nirq += n1g * (nrxq1g + nofldrxq1g);
2677                 iaq->nirq += (n10g + n1g) * (num_vis - 1) *
2678                     max(iaq->nrxq_vi, iaq->nnmrxq_vi);  /* See comment above. */
2679                 iaq->nirq += (n10g + n1g) * (num_vis - 1) * iaq->nofldrxq_vi;
2680                 if (iaq->nirq <= navail &&
2681                     (itype != INTR_MSI || powerof2(iaq->nirq))) {
2682                         iaq->intr_flags_10g = INTR_ALL;
2683                         iaq->intr_flags_1g = INTR_ALL;
2684                         goto allocate;
2685                 }
2686
2687                 /* Disable the VIs (and netmap) if there aren't enough intrs */
2688                 if (num_vis > 1) {
2689                         device_printf(sc->dev, "virtual interfaces disabled "
2690                             "because num_vis=%u with current settings "
2691                             "(nrxq10g=%u, nrxq1g=%u, nofldrxq10g=%u, "
2692                             "nofldrxq1g=%u, nrxq_vi=%u nofldrxq_vi=%u, "
2693                             "nnmrxq_vi=%u) would need %u interrupts but "
2694                             "only %u are available.\n", num_vis, nrxq10g,
2695                             nrxq1g, nofldrxq10g, nofldrxq1g, iaq->nrxq_vi,
2696                             iaq->nofldrxq_vi, iaq->nnmrxq_vi, iaq->nirq,
2697                             navail);
2698                         num_vis = 1;
2699                         iaq->ntxq_vi = iaq->nrxq_vi = 0;
2700                         iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
2701                         iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
2702                         goto restart;
2703                 }
2704
2705                 /*
2706                  * Second best option: a vector for errors, one for the firmware
2707                  * event queue, and vectors for either all the NIC rx queues or
2708                  * all the TOE rx queues.  The queues that don't get vectors
2709                  * will forward their interrupts to those that do.
2710                  */
2711                 iaq->nirq = T4_EXTRA_INTR;
2712                 if (nrxq10g >= nofldrxq10g) {
2713                         iaq->intr_flags_10g = INTR_RXQ;
2714                         iaq->nirq += n10g * nrxq10g;
2715                 } else {
2716                         iaq->intr_flags_10g = INTR_OFLD_RXQ;
2717                         iaq->nirq += n10g * nofldrxq10g;
2718                 }
2719                 if (nrxq1g >= nofldrxq1g) {
2720                         iaq->intr_flags_1g = INTR_RXQ;
2721                         iaq->nirq += n1g * nrxq1g;
2722                 } else {
2723                         iaq->intr_flags_1g = INTR_OFLD_RXQ;
2724                         iaq->nirq += n1g * nofldrxq1g;
2725                 }
2726                 if (iaq->nirq <= navail &&
2727                     (itype != INTR_MSI || powerof2(iaq->nirq)))
2728                         goto allocate;
2729
2730                 /*
2731                  * Next best option: an interrupt vector for errors, one for the
2732                  * firmware event queue, and at least one per main-VI.  At this
2733                  * point we know we'll have to downsize nrxq and/or nofldrxq to
2734                  * fit what's available to us.
2735                  */
2736                 iaq->nirq = T4_EXTRA_INTR;
2737                 iaq->nirq += n10g + n1g;
2738                 if (iaq->nirq <= navail) {
2739                         int leftover = navail - iaq->nirq;
2740
2741                         if (n10g > 0) {
2742                                 int target = max(nrxq10g, nofldrxq10g);
2743
2744                                 iaq->intr_flags_10g = nrxq10g >= nofldrxq10g ?
2745                                     INTR_RXQ : INTR_OFLD_RXQ;
2746
2747                                 n = 1;
2748                                 while (n < target && leftover >= n10g) {
2749                                         leftover -= n10g;
2750                                         iaq->nirq += n10g;
2751                                         n++;
2752                                 }
2753                                 iaq->nrxq10g = min(n, nrxq10g);
2754 #ifdef TCP_OFFLOAD
2755                                 iaq->nofldrxq10g = min(n, nofldrxq10g);
2756 #endif
2757                         }
2758
2759                         if (n1g > 0) {
2760                                 int target = max(nrxq1g, nofldrxq1g);
2761
2762                                 iaq->intr_flags_1g = nrxq1g >= nofldrxq1g ?
2763                                     INTR_RXQ : INTR_OFLD_RXQ;
2764
2765                                 n = 1;
2766                                 while (n < target && leftover >= n1g) {
2767                                         leftover -= n1g;
2768                                         iaq->nirq += n1g;
2769                                         n++;
2770                                 }
2771                                 iaq->nrxq1g = min(n, nrxq1g);
2772 #ifdef TCP_OFFLOAD
2773                                 iaq->nofldrxq1g = min(n, nofldrxq1g);
2774 #endif
2775                         }
2776
2777                         if (itype != INTR_MSI || powerof2(iaq->nirq))
2778                                 goto allocate;
2779                 }
2780
2781                 /*
2782                  * Least desirable option: one interrupt vector for everything.
2783                  */
2784                 iaq->nirq = iaq->nrxq10g = iaq->nrxq1g = 1;
2785                 iaq->intr_flags_10g = iaq->intr_flags_1g = 0;
2786 #ifdef TCP_OFFLOAD
2787                 if (is_offload(sc))
2788                         iaq->nofldrxq10g = iaq->nofldrxq1g = 1;
2789 #endif
2790 allocate:
2791                 navail = iaq->nirq;
2792                 rc = 0;
2793                 if (itype == INTR_MSIX)
2794                         rc = pci_alloc_msix(sc->dev, &navail);
2795                 else if (itype == INTR_MSI)
2796                         rc = pci_alloc_msi(sc->dev, &navail);
2797
2798                 if (rc == 0) {
2799                         if (navail == iaq->nirq)
2800                                 return (0);
2801
2802                         /*
2803                          * Didn't get the number requested.  Use whatever number
2804                          * the kernel is willing to allocate (it's in navail).
2805                          */
2806                         device_printf(sc->dev, "fewer vectors than requested, "
2807                             "type=%d, req=%d, rcvd=%d; will downshift req.\n",
2808                             itype, iaq->nirq, navail);
2809                         pci_release_msi(sc->dev);
2810                         goto restart;
2811                 }
2812
2813                 device_printf(sc->dev,
2814                     "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
2815                     itype, rc, iaq->nirq, navail);
2816         }
2817
2818         device_printf(sc->dev,
2819             "failed to find a usable interrupt type.  "
2820             "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
2821             pci_msix_count(sc->dev), pci_msi_count(sc->dev));
2822
2823         return (ENXIO);
2824 }
2825
2826 #define FW_VERSION(chip) ( \
2827     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
2828     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
2829     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
2830     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
2831 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
2832
2833 struct fw_info {
2834         uint8_t chip;
2835         char *kld_name;
2836         char *fw_mod_name;
2837         struct fw_hdr fw_hdr;   /* XXX: waste of space, need a sparse struct */
2838 } fw_info[] = {
2839         {
2840                 .chip = CHELSIO_T4,
2841                 .kld_name = "t4fw_cfg",
2842                 .fw_mod_name = "t4fw",
2843                 .fw_hdr = {
2844                         .chip = FW_HDR_CHIP_T4,
2845                         .fw_ver = htobe32_const(FW_VERSION(T4)),
2846                         .intfver_nic = FW_INTFVER(T4, NIC),
2847                         .intfver_vnic = FW_INTFVER(T4, VNIC),
2848                         .intfver_ofld = FW_INTFVER(T4, OFLD),
2849                         .intfver_ri = FW_INTFVER(T4, RI),
2850                         .intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
2851                         .intfver_iscsi = FW_INTFVER(T4, ISCSI),
2852                         .intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
2853                         .intfver_fcoe = FW_INTFVER(T4, FCOE),
2854                 },
2855         }, {
2856                 .chip = CHELSIO_T5,
2857                 .kld_name = "t5fw_cfg",
2858                 .fw_mod_name = "t5fw",
2859                 .fw_hdr = {
2860                         .chip = FW_HDR_CHIP_T5,
2861                         .fw_ver = htobe32_const(FW_VERSION(T5)),
2862                         .intfver_nic = FW_INTFVER(T5, NIC),
2863                         .intfver_vnic = FW_INTFVER(T5, VNIC),
2864                         .intfver_ofld = FW_INTFVER(T5, OFLD),
2865                         .intfver_ri = FW_INTFVER(T5, RI),
2866                         .intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
2867                         .intfver_iscsi = FW_INTFVER(T5, ISCSI),
2868                         .intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
2869                         .intfver_fcoe = FW_INTFVER(T5, FCOE),
2870                 },
2871         }, {
2872                 .chip = CHELSIO_T6,
2873                 .kld_name = "t6fw_cfg",
2874                 .fw_mod_name = "t6fw",
2875                 .fw_hdr = {
2876                         .chip = FW_HDR_CHIP_T6,
2877                         .fw_ver = htobe32_const(FW_VERSION(T6)),
2878                         .intfver_nic = FW_INTFVER(T6, NIC),
2879                         .intfver_vnic = FW_INTFVER(T6, VNIC),
2880                         .intfver_ofld = FW_INTFVER(T6, OFLD),
2881                         .intfver_ri = FW_INTFVER(T6, RI),
2882                         .intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
2883                         .intfver_iscsi = FW_INTFVER(T6, ISCSI),
2884                         .intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
2885                         .intfver_fcoe = FW_INTFVER(T6, FCOE),
2886                 },
2887         }
2888 };
2889
2890 static struct fw_info *
2891 find_fw_info(int chip)
2892 {
2893         int i;
2894
2895         for (i = 0; i < nitems(fw_info); i++) {
2896                 if (fw_info[i].chip == chip)
2897                         return (&fw_info[i]);
2898         }
2899         return (NULL);
2900 }
2901
2902 /*
2903  * Is the given firmware API compatible with the one the driver was compiled
2904  * with?
2905  */
2906 static int
2907 fw_compatible(const struct fw_hdr *hdr1, const struct fw_hdr *hdr2)
2908 {
2909
2910         /* short circuit if it's the exact same firmware version */
2911         if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
2912                 return (1);
2913
2914         /*
2915          * XXX: Is this too conservative?  Perhaps I should limit this to the
2916          * features that are supported in the driver.
2917          */
2918 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
2919         if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
2920             SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
2921             SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
2922                 return (1);
2923 #undef SAME_INTF
2924
2925         return (0);
2926 }
2927
2928 /*
2929  * The firmware in the KLD is usable, but should it be installed?  This routine
2930  * explains itself in detail if it indicates the KLD firmware should be
2931  * installed.
2932  */
2933 static int
2934 should_install_kld_fw(struct adapter *sc, int card_fw_usable, int k, int c)
2935 {
2936         const char *reason;
2937
2938         if (!card_fw_usable) {
2939                 reason = "incompatible or unusable";
2940                 goto install;
2941         }
2942
2943         if (k > c) {
2944                 reason = "older than the version bundled with this driver";
2945                 goto install;
2946         }
2947
2948         if (t4_fw_install == 2 && k != c) {
2949                 reason = "different than the version bundled with this driver";
2950                 goto install;
2951         }
2952
2953         return (0);
2954
2955 install:
2956         if (t4_fw_install == 0) {
2957                 device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
2958                     "but the driver is prohibited from installing a different "
2959                     "firmware on the card.\n",
2960                     G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
2961                     G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
2962
2963                 return (0);
2964         }
2965
2966         device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
2967             "installing firmware %u.%u.%u.%u on card.\n",
2968             G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
2969             G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
2970             G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
2971             G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k));
2972
2973         return (1);
2974 }
2975
2976 /*
2977  * Establish contact with the firmware and determine if we are the master driver
2978  * or not, and whether we are responsible for chip initialization.
2979  */
2980 static int
2981 prep_firmware(struct adapter *sc)
2982 {
2983         const struct firmware *fw = NULL, *default_cfg;
2984         int rc, pf, card_fw_usable, kld_fw_usable, need_fw_reset = 1;
2985         enum dev_state state;
2986         struct fw_info *fw_info;
2987         struct fw_hdr *card_fw;         /* fw on the card */
2988         const struct fw_hdr *kld_fw;    /* fw in the KLD */
2989         const struct fw_hdr *drv_fw;    /* fw header the driver was compiled
2990                                            against */
2991
2992         /* This is the firmware whose headers the driver was compiled against */
2993         fw_info = find_fw_info(chip_id(sc));
2994         if (fw_info == NULL) {
2995                 device_printf(sc->dev,
2996                     "unable to look up firmware information for chip %d.\n",
2997                     chip_id(sc));
2998                 return (EINVAL);
2999         }
3000         drv_fw = &fw_info->fw_hdr;
3001
3002         /*
3003          * The firmware KLD contains many modules.  The KLD name is also the
3004          * name of the module that contains the default config file.
3005          */
3006         default_cfg = firmware_get(fw_info->kld_name);
3007
3008         /* This is the firmware in the KLD */
3009         fw = firmware_get(fw_info->fw_mod_name);
3010         if (fw != NULL) {
3011                 kld_fw = (const void *)fw->data;
3012                 kld_fw_usable = fw_compatible(drv_fw, kld_fw);
3013         } else {
3014                 kld_fw = NULL;
3015                 kld_fw_usable = 0;
3016         }
3017
3018         /* Read the header of the firmware on the card */
3019         card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
3020         rc = -t4_read_flash(sc, FLASH_FW_START,
3021             sizeof (*card_fw) / sizeof (uint32_t), (uint32_t *)card_fw, 1);
3022         if (rc == 0) {
3023                 card_fw_usable = fw_compatible(drv_fw, (const void*)card_fw);
3024                 if (card_fw->fw_ver == be32toh(0xffffffff)) {
3025                         uint32_t d = be32toh(kld_fw->fw_ver);
3026
3027                         if (!kld_fw_usable) {
3028                                 device_printf(sc->dev,
3029                                     "no firmware on the card and no usable "
3030                                     "firmware bundled with the driver.\n");
3031                                 rc = EIO;
3032                                 goto done;
3033                         } else if (t4_fw_install == 0) {
3034                                 device_printf(sc->dev,
3035                                     "no firmware on the card and the driver "
3036                                     "is prohibited from installing new "
3037                                     "firmware.\n");
3038                                 rc = EIO;
3039                                 goto done;
3040                         }
3041
3042                         device_printf(sc->dev, "no firmware on the card, "
3043                             "installing firmware %d.%d.%d.%d\n",
3044                             G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
3045                             G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
3046                         rc = t4_fw_forceinstall(sc, fw->data, fw->datasize);
3047                         if (rc < 0) {
3048                                 rc = -rc;
3049                                 device_printf(sc->dev,
3050                                     "firmware install failed: %d.\n", rc);
3051                                 goto done;
3052                         }
3053                         memcpy(card_fw, kld_fw, sizeof(*card_fw));
3054                         card_fw_usable = 1;
3055                         need_fw_reset = 0;
3056                 }
3057         } else {
3058                 device_printf(sc->dev,
3059                     "Unable to read card's firmware header: %d\n", rc);
3060                 card_fw_usable = 0;
3061         }
3062
3063         /* Contact firmware. */
3064         rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
3065         if (rc < 0 || state == DEV_STATE_ERR) {
3066                 rc = -rc;
3067                 device_printf(sc->dev,
3068                     "failed to connect to the firmware: %d, %d.\n", rc, state);
3069                 goto done;
3070         }
3071         pf = rc;
3072         if (pf == sc->mbox)
3073                 sc->flags |= MASTER_PF;
3074         else if (state == DEV_STATE_UNINIT) {
3075                 /*
3076                  * We didn't get to be the master so we definitely won't be
3077                  * configuring the chip.  It's a bug if someone else hasn't
3078                  * configured it already.
3079                  */
3080                 device_printf(sc->dev, "couldn't be master(%d), "
3081                     "device not already initialized either(%d).\n", rc, state);
3082                 rc = EPROTO;
3083                 goto done;
3084         }
3085
3086         if (card_fw_usable && card_fw->fw_ver == drv_fw->fw_ver &&
3087             (!kld_fw_usable || kld_fw->fw_ver == drv_fw->fw_ver)) {
3088                 /*
3089                  * Common case: the firmware on the card is an exact match and
3090                  * the KLD is an exact match too, or the KLD is
3091                  * absent/incompatible.  Note that t4_fw_install = 2 is ignored
3092                  * here -- use cxgbetool loadfw if you want to reinstall the
3093                  * same firmware as the one on the card.
3094                  */
3095         } else if (kld_fw_usable && state == DEV_STATE_UNINIT &&
3096             should_install_kld_fw(sc, card_fw_usable, be32toh(kld_fw->fw_ver),
3097             be32toh(card_fw->fw_ver))) {
3098
3099                 rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
3100                 if (rc != 0) {
3101                         device_printf(sc->dev,
3102                             "failed to install firmware: %d\n", rc);
3103                         goto done;
3104                 }
3105
3106                 /* Installed successfully, update the cached header too. */
3107                 memcpy(card_fw, kld_fw, sizeof(*card_fw));
3108                 card_fw_usable = 1;
3109                 need_fw_reset = 0;      /* already reset as part of load_fw */
3110         }
3111
3112         if (!card_fw_usable) {
3113                 uint32_t d, c, k;
3114
3115                 d = ntohl(drv_fw->fw_ver);
3116                 c = ntohl(card_fw->fw_ver);
3117                 k = kld_fw ? ntohl(kld_fw->fw_ver) : 0;
3118
3119                 device_printf(sc->dev, "Cannot find a usable firmware: "
3120                     "fw_install %d, chip state %d, "
3121                     "driver compiled with %d.%d.%d.%d, "
3122                     "card has %d.%d.%d.%d, KLD has %d.%d.%d.%d\n",
3123                     t4_fw_install, state,
3124                     G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
3125                     G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d),
3126                     G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
3127                     G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c),
3128                     G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
3129                     G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k));
3130                 rc = EINVAL;
3131                 goto done;
3132         }
3133
3134         /* Reset device */
3135         if (need_fw_reset &&
3136             (rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST)) != 0) {
3137                 device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
3138                 if (rc != ETIMEDOUT && rc != EIO)
3139                         t4_fw_bye(sc, sc->mbox);
3140                 goto done;
3141         }
3142         sc->flags |= FW_OK;
3143
3144         rc = get_params__pre_init(sc);
3145         if (rc != 0)
3146                 goto done; /* error message displayed already */
3147
3148         /* Partition adapter resources as specified in the config file. */
3149         if (state == DEV_STATE_UNINIT) {
3150
3151                 KASSERT(sc->flags & MASTER_PF,
3152                     ("%s: trying to change chip settings when not master.",
3153                     __func__));
3154
3155                 rc = partition_resources(sc, default_cfg, fw_info->kld_name);
3156                 if (rc != 0)
3157                         goto done;      /* error message displayed already */
3158
3159                 t4_tweak_chip_settings(sc);
3160
3161                 /* get basic stuff going */
3162                 rc = -t4_fw_initialize(sc, sc->mbox);
3163                 if (rc != 0) {
3164                         device_printf(sc->dev, "fw init failed: %d.\n", rc);
3165                         goto done;
3166                 }
3167         } else {
3168                 snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", pf);
3169                 sc->cfcsum = 0;
3170         }
3171
3172 done:
3173         free(card_fw, M_CXGBE);
3174         if (fw != NULL)
3175                 firmware_put(fw, FIRMWARE_UNLOAD);
3176         if (default_cfg != NULL)
3177                 firmware_put(default_cfg, FIRMWARE_UNLOAD);
3178
3179         return (rc);
3180 }
3181
3182 #define FW_PARAM_DEV(param) \
3183         (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
3184          V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
3185 #define FW_PARAM_PFVF(param) \
3186         (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
3187          V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
3188
3189 /*
3190  * Partition chip resources for use between various PFs, VFs, etc.
3191  */
3192 static int
3193 partition_resources(struct adapter *sc, const struct firmware *default_cfg,
3194     const char *name_prefix)
3195 {
3196         const struct firmware *cfg = NULL;
3197         int rc = 0;
3198         struct fw_caps_config_cmd caps;
3199         uint32_t mtype, moff, finicsum, cfcsum;
3200
3201         /*
3202          * Figure out what configuration file to use.  Pick the default config
3203          * file for the card if the user hasn't specified one explicitly.
3204          */
3205         snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", t4_cfg_file);
3206         if (strncmp(t4_cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
3207                 /* Card specific overrides go here. */
3208                 if (pci_get_device(sc->dev) == 0x440a)
3209                         snprintf(sc->cfg_file, sizeof(sc->cfg_file), UWIRE_CF);
3210                 if (is_fpga(sc))
3211                         snprintf(sc->cfg_file, sizeof(sc->cfg_file), FPGA_CF);
3212         }
3213
3214         /*
3215          * We need to load another module if the profile is anything except
3216          * "default" or "flash".
3217          */
3218         if (strncmp(sc->cfg_file, DEFAULT_CF, sizeof(sc->cfg_file)) != 0 &&
3219             strncmp(sc->cfg_file, FLASH_CF, sizeof(sc->cfg_file)) != 0) {
3220                 char s[32];
3221
3222                 snprintf(s, sizeof(s), "%s_%s", name_prefix, sc->cfg_file);
3223                 cfg = firmware_get(s);
3224                 if (cfg == NULL) {
3225                         if (default_cfg != NULL) {
3226                                 device_printf(sc->dev,
3227                                     "unable to load module \"%s\" for "
3228                                     "configuration profile \"%s\", will use "
3229                                     "the default config file instead.\n",
3230                                     s, sc->cfg_file);
3231                                 snprintf(sc->cfg_file, sizeof(sc->cfg_file),
3232                                     "%s", DEFAULT_CF);
3233                         } else {
3234                                 device_printf(sc->dev,
3235                                     "unable to load module \"%s\" for "
3236                                     "configuration profile \"%s\", will use "
3237                                     "the config file on the card's flash "
3238                                     "instead.\n", s, sc->cfg_file);
3239                                 snprintf(sc->cfg_file, sizeof(sc->cfg_file),
3240                                     "%s", FLASH_CF);
3241                         }
3242                 }
3243         }
3244
3245         if (strncmp(sc->cfg_file, DEFAULT_CF, sizeof(sc->cfg_file)) == 0 &&
3246             default_cfg == NULL) {
3247                 device_printf(sc->dev,
3248                     "default config file not available, will use the config "
3249                     "file on the card's flash instead.\n");
3250                 snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", FLASH_CF);
3251         }
3252
3253         if (strncmp(sc->cfg_file, FLASH_CF, sizeof(sc->cfg_file)) != 0) {
3254                 u_int cflen;
3255                 const uint32_t *cfdata;
3256                 uint32_t param, val, addr;
3257
3258                 KASSERT(cfg != NULL || default_cfg != NULL,
3259                     ("%s: no config to upload", __func__));
3260
3261                 /*
3262                  * Ask the firmware where it wants us to upload the config file.
3263                  */
3264                 param = FW_PARAM_DEV(CF);
3265                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3266                 if (rc != 0) {
3267                         /* No support for config file?  Shouldn't happen. */
3268                         device_printf(sc->dev,
3269                             "failed to query config file location: %d.\n", rc);
3270                         goto done;
3271                 }
3272                 mtype = G_FW_PARAMS_PARAM_Y(val);
3273                 moff = G_FW_PARAMS_PARAM_Z(val) << 16;
3274
3275                 /*
3276                  * XXX: sheer laziness.  We deliberately added 4 bytes of
3277                  * useless stuffing/comments at the end of the config file so
3278                  * it's ok to simply throw away the last remaining bytes when
3279                  * the config file is not an exact multiple of 4.  This also
3280                  * helps with the validate_mt_off_len check.
3281                  */
3282                 if (cfg != NULL) {
3283                         cflen = cfg->datasize & ~3;
3284                         cfdata = cfg->data;
3285                 } else {
3286                         cflen = default_cfg->datasize & ~3;
3287                         cfdata = default_cfg->data;
3288                 }
3289
3290                 if (cflen > FLASH_CFG_MAX_SIZE) {
3291                         device_printf(sc->dev,
3292                             "config file too long (%d, max allowed is %d).  "
3293                             "Will try to use the config on the card, if any.\n",
3294                             cflen, FLASH_CFG_MAX_SIZE);
3295                         goto use_config_on_flash;
3296                 }
3297
3298                 rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
3299                 if (rc != 0) {
3300                         device_printf(sc->dev,
3301                             "%s: addr (%d/0x%x) or len %d is not valid: %d.  "
3302                             "Will try to use the config on the card, if any.\n",
3303                             __func__, mtype, moff, cflen, rc);
3304                         goto use_config_on_flash;
3305                 }
3306                 write_via_memwin(sc, 2, addr, cfdata, cflen);
3307         } else {
3308 use_config_on_flash:
3309                 mtype = FW_MEMTYPE_FLASH;
3310                 moff = t4_flash_cfg_addr(sc);
3311         }
3312
3313         bzero(&caps, sizeof(caps));
3314         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3315             F_FW_CMD_REQUEST | F_FW_CMD_READ);
3316         caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
3317             V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
3318             V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) | FW_LEN16(caps));
3319         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
3320         if (rc != 0) {
3321                 device_printf(sc->dev,
3322                     "failed to pre-process config file: %d "
3323                     "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
3324                 goto done;
3325         }
3326
3327         finicsum = be32toh(caps.finicsum);
3328         cfcsum = be32toh(caps.cfcsum);
3329         if (finicsum != cfcsum) {
3330                 device_printf(sc->dev,
3331                     "WARNING: config file checksum mismatch: %08x %08x\n",
3332                     finicsum, cfcsum);
3333         }
3334         sc->cfcsum = cfcsum;
3335
3336 #define LIMIT_CAPS(x) do { \
3337         caps.x &= htobe16(t4_##x##_allowed); \
3338 } while (0)
3339
3340         /*
3341          * Let the firmware know what features will (not) be used so it can tune
3342          * things accordingly.
3343          */
3344         LIMIT_CAPS(nbmcaps);
3345         LIMIT_CAPS(linkcaps);
3346         LIMIT_CAPS(switchcaps);
3347         LIMIT_CAPS(niccaps);
3348         LIMIT_CAPS(toecaps);
3349         LIMIT_CAPS(rdmacaps);
3350         LIMIT_CAPS(cryptocaps);
3351         LIMIT_CAPS(iscsicaps);
3352         LIMIT_CAPS(fcoecaps);
3353 #undef LIMIT_CAPS
3354
3355         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3356             F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
3357         caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
3358         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
3359         if (rc != 0) {
3360                 device_printf(sc->dev,
3361                     "failed to process config file: %d.\n", rc);
3362         }
3363 done:
3364         if (cfg != NULL)
3365                 firmware_put(cfg, FIRMWARE_UNLOAD);
3366         return (rc);
3367 }
3368
3369 /*
3370  * Retrieve parameters that are needed (or nice to have) very early.
3371  */
3372 static int
3373 get_params__pre_init(struct adapter *sc)
3374 {
3375         int rc;
3376         uint32_t param[2], val[2];
3377
3378         t4_get_version_info(sc);
3379
3380         snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
3381             G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
3382             G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
3383             G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
3384             G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
3385
3386         snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
3387             G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
3388             G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
3389             G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
3390             G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
3391
3392         snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
3393             G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
3394             G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
3395             G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
3396             G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
3397
3398         snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
3399             G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
3400             G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
3401             G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
3402             G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
3403
3404         param[0] = FW_PARAM_DEV(PORTVEC);
3405         param[1] = FW_PARAM_DEV(CCLK);
3406         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
3407         if (rc != 0) {
3408                 device_printf(sc->dev,
3409                     "failed to query parameters (pre_init): %d.\n", rc);
3410                 return (rc);
3411         }
3412
3413         sc->params.portvec = val[0];
3414         sc->params.nports = bitcount32(val[0]);
3415         sc->params.vpd.cclk = val[1];
3416
3417         /* Read device log parameters. */
3418         rc = -t4_init_devlog_params(sc, 1);
3419         if (rc == 0)
3420                 fixup_devlog_params(sc);
3421         else {
3422                 device_printf(sc->dev,
3423                     "failed to get devlog parameters: %d.\n", rc);
3424                 rc = 0; /* devlog isn't critical for device operation */
3425         }
3426
3427         return (rc);
3428 }
3429
3430 /*
3431  * Retrieve various parameters that are of interest to the driver.  The device
3432  * has been initialized by the firmware at this point.
3433  */
3434 static int
3435 get_params__post_init(struct adapter *sc)
3436 {
3437         int rc;
3438         uint32_t param[7], val[7];
3439         struct fw_caps_config_cmd caps;
3440
3441         param[0] = FW_PARAM_PFVF(IQFLINT_START);
3442         param[1] = FW_PARAM_PFVF(EQ_START);
3443         param[2] = FW_PARAM_PFVF(FILTER_START);
3444         param[3] = FW_PARAM_PFVF(FILTER_END);
3445         param[4] = FW_PARAM_PFVF(L2T_START);
3446         param[5] = FW_PARAM_PFVF(L2T_END);
3447         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3448         if (rc != 0) {
3449                 device_printf(sc->dev,
3450                     "failed to query parameters (post_init): %d.\n", rc);
3451                 return (rc);
3452         }
3453
3454         sc->sge.iq_start = val[0];
3455         sc->sge.eq_start = val[1];
3456         sc->tids.ftid_base = val[2];
3457         sc->tids.nftids = val[3] - val[2] + 1;
3458         sc->params.ftid_min = val[2];
3459         sc->params.ftid_max = val[3];
3460         sc->vres.l2t.start = val[4];
3461         sc->vres.l2t.size = val[5] - val[4] + 1;
3462         KASSERT(sc->vres.l2t.size <= L2T_SIZE,
3463             ("%s: L2 table size (%u) larger than expected (%u)",
3464             __func__, sc->vres.l2t.size, L2T_SIZE));
3465
3466         /* get capabilites */
3467         bzero(&caps, sizeof(caps));
3468         caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3469             F_FW_CMD_REQUEST | F_FW_CMD_READ);
3470         caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
3471         rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
3472         if (rc != 0) {
3473                 device_printf(sc->dev,
3474                     "failed to get card capabilities: %d.\n", rc);
3475                 return (rc);
3476         }
3477
3478 #define READ_CAPS(x) do { \
3479         sc->x = htobe16(caps.x); \
3480 } while (0)
3481         READ_CAPS(nbmcaps);
3482         READ_CAPS(linkcaps);
3483         READ_CAPS(switchcaps);
3484         READ_CAPS(niccaps);
3485         READ_CAPS(toecaps);
3486         READ_CAPS(rdmacaps);
3487         READ_CAPS(cryptocaps);
3488         READ_CAPS(iscsicaps);
3489         READ_CAPS(fcoecaps);
3490
3491         if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
3492                 param[0] = FW_PARAM_PFVF(ETHOFLD_START);
3493                 param[1] = FW_PARAM_PFVF(ETHOFLD_END);
3494                 param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
3495                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
3496                 if (rc != 0) {
3497                         device_printf(sc->dev,
3498                             "failed to query NIC parameters: %d.\n", rc);
3499                         return (rc);
3500                 }
3501                 sc->tids.etid_base = val[0];
3502                 sc->params.etid_min = val[0];
3503                 sc->tids.netids = val[1] - val[0] + 1;
3504                 sc->params.netids = sc->tids.netids;
3505                 sc->params.eo_wr_cred = val[2];
3506                 sc->params.ethoffload = 1;
3507         }
3508
3509         if (sc->toecaps) {
3510                 /* query offload-related parameters */
3511                 param[0] = FW_PARAM_DEV(NTID);
3512                 param[1] = FW_PARAM_PFVF(SERVER_START);
3513                 param[2] = FW_PARAM_PFVF(SERVER_END);
3514                 param[3] = FW_PARAM_PFVF(TDDP_START);
3515                 param[4] = FW_PARAM_PFVF(TDDP_END);
3516                 param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
3517                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3518                 if (rc != 0) {
3519                         device_printf(sc->dev,
3520                             "failed to query TOE parameters: %d.\n", rc);
3521                         return (rc);
3522                 }
3523                 sc->tids.ntids = val[0];
3524                 sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
3525                 sc->tids.stid_base = val[1];
3526                 sc->tids.nstids = val[2] - val[1] + 1;
3527                 sc->vres.ddp.start = val[3];
3528                 sc->vres.ddp.size = val[4] - val[3] + 1;
3529                 sc->params.ofldq_wr_cred = val[5];
3530                 sc->params.offload = 1;
3531         }
3532         if (sc->rdmacaps) {
3533                 param[0] = FW_PARAM_PFVF(STAG_START);
3534                 param[1] = FW_PARAM_PFVF(STAG_END);
3535                 param[2] = FW_PARAM_PFVF(RQ_START);
3536                 param[3] = FW_PARAM_PFVF(RQ_END);
3537                 param[4] = FW_PARAM_PFVF(PBL_START);
3538                 param[5] = FW_PARAM_PFVF(PBL_END);
3539                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3540                 if (rc != 0) {
3541                         device_printf(sc->dev,
3542                             "failed to query RDMA parameters(1): %d.\n", rc);
3543                         return (rc);
3544                 }
3545                 sc->vres.stag.start = val[0];
3546                 sc->vres.stag.size = val[1] - val[0] + 1;
3547                 sc->vres.rq.start = val[2];
3548                 sc->vres.rq.size = val[3] - val[2] + 1;
3549                 sc->vres.pbl.start = val[4];
3550                 sc->vres.pbl.size = val[5] - val[4] + 1;
3551
3552                 param[0] = FW_PARAM_PFVF(SQRQ_START);
3553                 param[1] = FW_PARAM_PFVF(SQRQ_END);
3554                 param[2] = FW_PARAM_PFVF(CQ_START);
3555                 param[3] = FW_PARAM_PFVF(CQ_END);
3556                 param[4] = FW_PARAM_PFVF(OCQ_START);
3557                 param[5] = FW_PARAM_PFVF(OCQ_END);
3558                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3559                 if (rc != 0) {
3560                         device_printf(sc->dev,
3561                             "failed to query RDMA parameters(2): %d.\n", rc);
3562                         return (rc);
3563                 }
3564                 sc->vres.qp.start = val[0];
3565                 sc->vres.qp.size = val[1] - val[0] + 1;
3566                 sc->vres.cq.start = val[2];
3567                 sc->vres.cq.size = val[3] - val[2] + 1;
3568                 sc->vres.ocq.start = val[4];
3569                 sc->vres.ocq.size = val[5] - val[4] + 1;
3570
3571                 param[0] = FW_PARAM_PFVF(SRQ_START);
3572                 param[1] = FW_PARAM_PFVF(SRQ_END);
3573                 param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
3574                 param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
3575                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
3576                 if (rc != 0) {
3577                         device_printf(sc->dev,
3578                             "failed to query RDMA parameters(3): %d.\n", rc);
3579                         return (rc);
3580                 }
3581                 sc->vres.srq.start = val[0];
3582                 sc->vres.srq.size = val[1] - val[0] + 1;
3583                 sc->params.max_ordird_qp = val[2];
3584                 sc->params.max_ird_adapter = val[3];
3585         }
3586         if (sc->iscsicaps) {
3587                 param[0] = FW_PARAM_PFVF(ISCSI_START);
3588                 param[1] = FW_PARAM_PFVF(ISCSI_END);
3589                 rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
3590                 if (rc != 0) {
3591                         device_printf(sc->dev,
3592                             "failed to query iSCSI parameters: %d.\n", rc);
3593                         return (rc);
3594                 }
3595                 sc->vres.iscsi.start = val[0];
3596                 sc->vres.iscsi.size = val[1] - val[0] + 1;
3597         }
3598
3599         t4_init_sge_params(sc);
3600
3601         /*
3602          * We've got the params we wanted to query via the firmware.  Now grab
3603          * some others directly from the chip.
3604          */
3605         rc = t4_read_chip_settings(sc);
3606
3607         return (rc);
3608 }
3609
3610 static int
3611 set_params__post_init(struct adapter *sc)
3612 {
3613         uint32_t param, val;
3614         int i, v, shift;
3615         char s[32];
3616
3617         /* ask for encapsulated CPLs */
3618         param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
3619         val = 1;
3620         (void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3621
3622         /*
3623          * Override the TOE timers with user provided tunables.  This is not the
3624          * recommended way to change the timers (the firmware config file is) so
3625          * these tunables are not documented.
3626          *
3627          * All the timer tunables are in milliseconds.
3628          */
3629         if (TUNABLE_INT_FETCH("hw.cxgbe.toe.keepalive_idle", &v)) {
3630                 t4_set_reg_field(sc, A_TP_KEEP_IDLE,
3631                     V_KEEPALIVEIDLE(M_KEEPALIVEIDLE),
3632                     V_KEEPALIVEIDLE(ms_to_tcp_ticks(sc, v)));
3633         }
3634         if (TUNABLE_INT_FETCH("hw.cxgbe.toe.keepalive_interval", &v)) {
3635                 t4_set_reg_field(sc, A_TP_KEEP_INTVL,
3636                     V_KEEPALIVEINTVL(M_KEEPALIVEINTVL),
3637                     V_KEEPALIVEINTVL(ms_to_tcp_ticks(sc, v)));
3638         }
3639         if (TUNABLE_INT_FETCH("hw.cxgbe.toe.keepalive_count", &v)) {
3640                 v &= M_KEEPALIVEMAXR1;
3641                 t4_set_reg_field(sc, A_TP_SHIFT_CNT,
3642                     V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
3643                     V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
3644                     V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
3645         }
3646         if (TUNABLE_INT_FETCH("hw.cxgbe.toe.rexmt_min", &v)) {
3647                 t4_set_reg_field(sc, A_TP_RXT_MIN,
3648                     V_RXTMIN(M_RXTMIN), V_RXTMIN(ms_to_tcp_ticks(sc, v)));
3649         }
3650         if (TUNABLE_INT_FETCH("hw.cxgbe.toe.rexmt_max", &v)) {
3651                 t4_set_reg_field(sc, A_TP_RXT_MAX,
3652                     V_RXTMAX(M_RXTMAX), V_RXTMAX(ms_to_tcp_ticks(sc, v)));
3653         }
3654         if (TUNABLE_INT_FETCH("hw.cxgbe.toe.rexmt_count", &v)) {
3655                 v &= M_RXTSHIFTMAXR1;
3656                 t4_set_reg_field(sc, A_TP_SHIFT_CNT,
3657                     V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
3658                     V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
3659                     V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
3660         }
3661         for (i = 0; i < 16; i++) {
3662                 snprintf(s, sizeof(s), "hw.cxgbe.toe.rexmt_backoff.%d", i);
3663                 if (TUNABLE_INT_FETCH(s, &v)) {
3664                         v &= M_TIMERBACKOFFINDEX0;
3665                         shift = (i & 3) << 3;
3666                         t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
3667                             M_TIMERBACKOFFINDEX0 << shift, v << shift);
3668                 }
3669         }
3670         return (0);
3671 }
3672
3673 #undef FW_PARAM_PFVF
3674 #undef FW_PARAM_DEV
3675
3676 static void
3677 t4_set_desc(struct adapter *sc)
3678 {
3679         char buf[128];
3680         struct adapter_params *p = &sc->params;
3681
3682         snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
3683
3684         device_set_desc_copy(sc->dev, buf);
3685 }
3686
3687 static void
3688 build_medialist(struct port_info *pi, struct ifmedia *media)
3689 {
3690         int m;
3691
3692         PORT_LOCK_ASSERT_OWNED(pi);
3693
3694         ifmedia_removeall(media);
3695
3696         /*
3697          * XXX: Would it be better to ifmedia_add all 4 combinations of pause
3698          * settings for every speed instead of just txpause|rxpause?  ifconfig
3699          * media display looks much better if autoselect is the only case where
3700          * ifm_current is different from ifm_active.  If the user picks anything
3701          * except txpause|rxpause the display is ugly.
3702          */
3703         m = IFM_ETHER | IFM_FDX | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE;
3704
3705         switch(pi->port_type) {
3706         case FW_PORT_TYPE_BT_XFI:
3707         case FW_PORT_TYPE_BT_XAUI:
3708                 ifmedia_add(media, m | IFM_10G_T, 0, NULL);
3709                 /* fall through */
3710
3711         case FW_PORT_TYPE_BT_SGMII:
3712                 ifmedia_add(media, m | IFM_1000_T, 0, NULL);
3713                 ifmedia_add(media, m | IFM_100_TX, 0, NULL);
3714                 ifmedia_add(media, IFM_ETHER | IFM_AUTO, 0, NULL);
3715                 ifmedia_set(media, IFM_ETHER | IFM_AUTO);
3716                 break;
3717
3718         case FW_PORT_TYPE_CX4:
3719                 ifmedia_add(media, m | IFM_10G_CX4, 0, NULL);
3720                 ifmedia_set(media, m | IFM_10G_CX4);
3721                 break;
3722
3723         case FW_PORT_TYPE_QSFP_10G:
3724         case FW_PORT_TYPE_SFP:
3725         case FW_PORT_TYPE_FIBER_XFI:
3726         case FW_PORT_TYPE_FIBER_XAUI:
3727                 switch (pi->mod_type) {
3728
3729                 case FW_PORT_MOD_TYPE_LR:
3730                         ifmedia_add(media, m | IFM_10G_LR, 0, NULL);
3731                         ifmedia_set(media, m | IFM_10G_LR);
3732                         break;
3733
3734                 case FW_PORT_MOD_TYPE_SR:
3735                         ifmedia_add(media, m | IFM_10G_SR, 0, NULL);
3736                         ifmedia_set(media, m | IFM_10G_SR);
3737                         break;
3738
3739                 case FW_PORT_MOD_TYPE_LRM:
3740                         ifmedia_add(media, m | IFM_10G_LRM, 0, NULL);
3741                         ifmedia_set(media, m | IFM_10G_LRM);
3742                         break;
3743
3744                 case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3745                 case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3746                         ifmedia_add(media, m | IFM_10G_TWINAX, 0, NULL);
3747                         ifmedia_set(media, m | IFM_10G_TWINAX);
3748                         break;
3749
3750                 case FW_PORT_MOD_TYPE_NONE:
3751                         m &= ~IFM_FDX;
3752                         ifmedia_add(media, m | IFM_NONE, 0, NULL);
3753                         ifmedia_set(media, m | IFM_NONE);
3754                         break;
3755
3756                 case FW_PORT_MOD_TYPE_NA:
3757                 case FW_PORT_MOD_TYPE_ER:
3758                 default:
3759                         device_printf(pi->dev,
3760                             "unknown port_type (%d), mod_type (%d)\n",
3761                             pi->port_type, pi->mod_type);
3762                         ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3763                         ifmedia_set(media, m | IFM_UNKNOWN);
3764                         break;
3765                 }
3766                 break;
3767
3768         case FW_PORT_TYPE_CR_QSFP:
3769         case FW_PORT_TYPE_SFP28:
3770         case FW_PORT_TYPE_KR_SFP28:
3771                 switch (pi->mod_type) {
3772
3773                 case FW_PORT_MOD_TYPE_SR:
3774                         ifmedia_add(media, m | IFM_25G_SR, 0, NULL);
3775                         ifmedia_set(media, m | IFM_25G_SR);
3776                         break;
3777
3778                 case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3779                 case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3780                         ifmedia_add(media, m | IFM_25G_CR, 0, NULL);
3781                         ifmedia_set(media, m | IFM_25G_CR);
3782                         break;
3783
3784                 case FW_PORT_MOD_TYPE_NONE:
3785                         m &= ~IFM_FDX;
3786                         ifmedia_add(media, m | IFM_NONE, 0, NULL);
3787                         ifmedia_set(media, m | IFM_NONE);
3788                         break;
3789
3790                 default:
3791                         device_printf(pi->dev,
3792                             "unknown port_type (%d), mod_type (%d)\n",
3793                             pi->port_type, pi->mod_type);
3794                         ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3795                         ifmedia_set(media, m | IFM_UNKNOWN);
3796                         break;
3797                 }
3798                 break;
3799
3800         case FW_PORT_TYPE_QSFP:
3801                 switch (pi->mod_type) {
3802
3803                 case FW_PORT_MOD_TYPE_LR:
3804                         ifmedia_add(media, m | IFM_40G_LR4, 0, NULL);
3805                         ifmedia_set(media, m | IFM_40G_LR4);
3806                         break;
3807
3808                 case FW_PORT_MOD_TYPE_SR:
3809                         ifmedia_add(media, m | IFM_40G_SR4, 0, NULL);
3810                         ifmedia_set(media, m | IFM_40G_SR4);
3811                         break;
3812
3813                 case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3814                 case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3815                         ifmedia_add(media, m | IFM_40G_CR4, 0, NULL);
3816                         ifmedia_set(media, m | IFM_40G_CR4);
3817                         break;
3818
3819                 case FW_PORT_MOD_TYPE_NONE:
3820                         m &= ~IFM_FDX;
3821                         ifmedia_add(media, m | IFM_NONE, 0, NULL);
3822                         ifmedia_set(media, m | IFM_NONE);
3823                         break;
3824
3825                 default:
3826                         device_printf(pi->dev,
3827                             "unknown port_type (%d), mod_type (%d)\n",
3828                             pi->port_type, pi->mod_type);
3829                         ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3830                         ifmedia_set(media, m | IFM_UNKNOWN);
3831                         break;
3832                 }
3833                 break;
3834
3835         case FW_PORT_TYPE_KR4_100G:
3836         case FW_PORT_TYPE_CR4_QSFP:
3837                 switch (pi->mod_type) {
3838
3839                 case FW_PORT_MOD_TYPE_LR:
3840                         ifmedia_add(media, m | IFM_100G_LR4, 0, NULL);
3841                         ifmedia_set(media, m | IFM_100G_LR4);
3842                         break;
3843
3844                 case FW_PORT_MOD_TYPE_SR:
3845                         ifmedia_add(media, m | IFM_100G_SR4, 0, NULL);
3846                         ifmedia_set(media, m | IFM_100G_SR4);
3847                         break;
3848
3849                 case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3850                 case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3851                         ifmedia_add(media, m | IFM_100G_CR4, 0, NULL);
3852                         ifmedia_set(media, m | IFM_100G_CR4);
3853                         break;
3854
3855                 case FW_PORT_MOD_TYPE_NONE:
3856                         m &= ~IFM_FDX;
3857                         ifmedia_add(media, m | IFM_NONE, 0, NULL);
3858                         ifmedia_set(media, m | IFM_NONE);
3859                         break;
3860
3861                 default:
3862                         device_printf(pi->dev,
3863                             "unknown port_type (%d), mod_type (%d)\n",
3864                             pi->port_type, pi->mod_type);
3865                         ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3866                         ifmedia_set(media, m | IFM_UNKNOWN);
3867                         break;
3868                 }
3869                 break;
3870
3871         default:
3872                 device_printf(pi->dev,
3873                     "unknown port_type (%d), mod_type (%d)\n", pi->port_type,
3874                     pi->mod_type);
3875                 ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3876                 ifmedia_set(media, m | IFM_UNKNOWN);
3877                 break;
3878         }
3879 }
3880
3881 /*
3882  * Update all the requested_* fields in the link config and then send a mailbox
3883  * command to apply the settings.
3884  */
3885 static void
3886 init_l1cfg(struct port_info *pi)
3887 {
3888         struct adapter *sc = pi->adapter;
3889         struct link_config *lc = &pi->link_cfg;
3890         int rc;
3891
3892         ASSERT_SYNCHRONIZED_OP(sc);
3893
3894         if (t4_autoneg != 0 && lc->supported & FW_PORT_CAP_ANEG) {
3895                 lc->requested_aneg = AUTONEG_ENABLE;
3896                 lc->requested_speed = 0;
3897         } else {
3898                 lc->requested_aneg = AUTONEG_DISABLE;
3899                 lc->requested_speed = port_top_speed(pi);       /* in Gbps */
3900         }
3901
3902         lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX);
3903
3904         if (t4_fec != -1) {
3905                 lc->requested_fec = t4_fec & (FEC_RS | FEC_BASER_RS |
3906                     FEC_RESERVED);
3907         } else {
3908                 /* Use the suggested value provided by the firmware in acaps */
3909                 if (lc->advertising & FW_PORT_CAP_FEC_RS)
3910                         lc->requested_fec = FEC_RS;
3911                 else if (lc->advertising & FW_PORT_CAP_FEC_BASER_RS)
3912                         lc->requested_fec = FEC_BASER_RS;
3913                 else if (lc->advertising & FW_PORT_CAP_FEC_RESERVED)
3914                         lc->requested_fec = FEC_RESERVED;
3915                 else
3916                         lc->requested_fec = 0;
3917         }
3918
3919         rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
3920         if (rc != 0) {
3921                 device_printf(pi->dev, "l1cfg failed: %d\n", rc);
3922         } else {
3923                 lc->fc = lc->requested_fc;
3924                 lc->fec = lc->requested_fec;
3925         }
3926 }
3927
3928 #define FW_MAC_EXACT_CHUNK      7
3929
3930 /*
3931  * Program the port's XGMAC based on parameters in ifnet.  The caller also
3932  * indicates which parameters should be programmed (the rest are left alone).
3933  */
3934 int
3935 update_mac_settings(struct ifnet *ifp, int flags)
3936 {
3937         int rc = 0;
3938         struct vi_info *vi = ifp->if_softc;
3939         struct port_info *pi = vi->pi;
3940         struct adapter *sc = pi->adapter;
3941         int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
3942
3943         ASSERT_SYNCHRONIZED_OP(sc);
3944         KASSERT(flags, ("%s: not told what to update.", __func__));
3945
3946         if (flags & XGMAC_MTU)
3947                 mtu = ifp->if_mtu;
3948
3949         if (flags & XGMAC_PROMISC)
3950                 promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
3951
3952         if (flags & XGMAC_ALLMULTI)
3953                 allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
3954
3955         if (flags & XGMAC_VLANEX)
3956                 vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
3957
3958         if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
3959                 rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
3960                     allmulti, 1, vlanex, false);
3961                 if (rc) {
3962                         if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
3963                             rc);
3964                         return (rc);
3965                 }
3966         }
3967
3968         if (flags & XGMAC_UCADDR) {
3969                 uint8_t ucaddr[ETHER_ADDR_LEN];
3970
3971                 bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
3972                 rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
3973                     ucaddr, true, true);
3974                 if (rc < 0) {
3975                         rc = -rc;
3976                         if_printf(ifp, "change_mac failed: %d\n", rc);
3977                         return (rc);
3978                 } else {
3979                         vi->xact_addr_filt = rc;
3980                         rc = 0;
3981                 }
3982         }
3983
3984         if (flags & XGMAC_MCADDRS) {
3985                 const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
3986                 int del = 1;
3987                 uint64_t hash = 0;
3988                 struct ifmultiaddr *ifma;
3989                 int i = 0, j;
3990
3991                 if_maddr_rlock(ifp);
3992                 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3993                         if (ifma->ifma_addr->sa_family != AF_LINK)
3994                                 continue;
3995                         mcaddr[i] =
3996                             LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
3997                         MPASS(ETHER_IS_MULTICAST(mcaddr[i]));
3998                         i++;
3999
4000                         if (i == FW_MAC_EXACT_CHUNK) {
4001                                 rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
4002                                     del, i, mcaddr, NULL, &hash, 0);
4003                                 if (rc < 0) {
4004                                         rc = -rc;
4005                                         for (j = 0; j < i; j++) {
4006                                                 if_printf(ifp,
4007                                                     "failed to add mc address"
4008                                                     " %02x:%02x:%02x:"
4009                                                     "%02x:%02x:%02x rc=%d\n",
4010                                                     mcaddr[j][0], mcaddr[j][1],
4011                                                     mcaddr[j][2], mcaddr[j][3],
4012                                                     mcaddr[j][4], mcaddr[j][5],
4013                                                     rc);
4014                                         }
4015                                         goto mcfail;
4016                                 }
4017                                 del = 0;
4018                                 i = 0;
4019                         }
4020                 }
4021                 if (i > 0) {
4022                         rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, del, i,
4023                             mcaddr, NULL, &hash, 0);
4024                         if (rc < 0) {
4025                                 rc = -rc;
4026                                 for (j = 0; j < i; j++) {
4027                                         if_printf(ifp,
4028                                             "failed to add mc address"
4029                                             " %02x:%02x:%02x:"
4030                                             "%02x:%02x:%02x rc=%d\n",
4031                                             mcaddr[j][0], mcaddr[j][1],
4032                                             mcaddr[j][2], mcaddr[j][3],
4033                                             mcaddr[j][4], mcaddr[j][5],
4034                                             rc);
4035                                 }
4036                                 goto mcfail;
4037                         }
4038                 }
4039
4040                 rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, hash, 0);
4041                 if (rc != 0)
4042                         if_printf(ifp, "failed to set mc address hash: %d", rc);
4043 mcfail:
4044                 if_maddr_runlock(ifp);
4045         }
4046
4047         return (rc);
4048 }
4049
4050 /*
4051  * {begin|end}_synchronized_op must be called from the same thread.
4052  */
4053 int
4054 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
4055     char *wmesg)
4056 {
4057         int rc, pri;
4058
4059 #ifdef WITNESS
4060         /* the caller thinks it's ok to sleep, but is it really? */
4061         if (flags & SLEEP_OK)
4062                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
4063                     "begin_synchronized_op");
4064 #endif
4065
4066         if (INTR_OK)
4067                 pri = PCATCH;
4068         else
4069                 pri = 0;
4070
4071         ADAPTER_LOCK(sc);
4072         for (;;) {
4073
4074                 if (vi && IS_DOOMED(vi)) {
4075                         rc = ENXIO;
4076                         goto done;
4077                 }
4078
4079                 if (!IS_BUSY(sc)) {
4080                         rc = 0;
4081                         break;
4082                 }
4083
4084                 if (!(flags & SLEEP_OK)) {
4085                         rc = EBUSY;
4086                         goto done;
4087                 }
4088
4089                 if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
4090                         rc = EINTR;
4091                         goto done;
4092                 }
4093         }
4094
4095         KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
4096         SET_BUSY(sc);
4097 #ifdef INVARIANTS
4098         sc->last_op = wmesg;
4099         sc->last_op_thr = curthread;
4100         sc->last_op_flags = flags;
4101 #endif
4102
4103 done:
4104         if (!(flags & HOLD_LOCK) || rc)
4105                 ADAPTER_UNLOCK(sc);
4106
4107         return (rc);
4108 }
4109
4110 /*
4111  * Tell if_ioctl and if_init that the VI is going away.  This is
4112  * special variant of begin_synchronized_op and must be paired with a
4113  * call to end_synchronized_op.
4114  */
4115 void
4116 doom_vi(struct adapter *sc, struct vi_info *vi)
4117 {
4118
4119         ADAPTER_LOCK(sc);
4120         SET_DOOMED(vi);
4121         wakeup(&sc->flags);
4122         while (IS_BUSY(sc))
4123                 mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
4124         SET_BUSY(sc);
4125 #ifdef INVARIANTS
4126         sc->last_op = "t4detach";
4127         sc->last_op_thr = curthread;
4128         sc->last_op_flags = 0;
4129 #endif
4130         ADAPTER_UNLOCK(sc);
4131 }
4132
4133 /*
4134  * {begin|end}_synchronized_op must be called from the same thread.
4135  */
4136 void
4137 end_synchronized_op(struct adapter *sc, int flags)
4138 {
4139
4140         if (flags & LOCK_HELD)
4141                 ADAPTER_LOCK_ASSERT_OWNED(sc);
4142         else
4143                 ADAPTER_LOCK(sc);
4144
4145         KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
4146         CLR_BUSY(sc);
4147         wakeup(&sc->flags);
4148         ADAPTER_UNLOCK(sc);
4149 }
4150
4151 static int
4152 cxgbe_init_synchronized(struct vi_info *vi)
4153 {
4154         struct port_info *pi = vi->pi;
4155         struct adapter *sc = pi->adapter;
4156         struct ifnet *ifp = vi->ifp;
4157         int rc = 0, i;
4158         struct sge_txq *txq;
4159
4160         ASSERT_SYNCHRONIZED_OP(sc);
4161
4162         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4163                 return (0);     /* already running */
4164
4165         if (!(sc->flags & FULL_INIT_DONE) &&
4166             ((rc = adapter_full_init(sc)) != 0))
4167                 return (rc);    /* error message displayed already */
4168
4169         if (!(vi->flags & VI_INIT_DONE) &&
4170             ((rc = vi_full_init(vi)) != 0))
4171                 return (rc); /* error message displayed already */
4172
4173         rc = update_mac_settings(ifp, XGMAC_ALL);
4174         if (rc)
4175                 goto done;      /* error message displayed already */
4176
4177         rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
4178         if (rc != 0) {
4179                 if_printf(ifp, "enable_vi failed: %d\n", rc);
4180                 goto done;
4181         }
4182
4183         /*
4184          * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
4185          * if this changes.
4186          */
4187
4188         for_each_txq(vi, i, txq) {
4189                 TXQ_LOCK(txq);
4190                 txq->eq.flags |= EQ_ENABLED;
4191                 TXQ_UNLOCK(txq);
4192         }
4193
4194         /*
4195          * The first iq of the first port to come up is used for tracing.
4196          */
4197         if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
4198                 sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
4199                 t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
4200                     A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
4201                     V_QUEUENUMBER(sc->traceq));
4202                 pi->flags |= HAS_TRACEQ;
4203         }
4204
4205         /* all ok */
4206         PORT_LOCK(pi);
4207         if (pi->up_vis++ == 0) {
4208                 t4_update_port_info(pi);
4209                 build_medialist(vi->pi, &vi->media);
4210                 init_l1cfg(pi);
4211         }
4212         ifp->if_drv_flags |= IFF_DRV_RUNNING;
4213
4214         if (pi->nvi > 1 || sc->flags & IS_VF)
4215                 callout_reset(&vi->tick, hz, vi_tick, vi);
4216         else
4217                 callout_reset(&pi->tick, hz, cxgbe_tick, pi);
4218         PORT_UNLOCK(pi);
4219 done:
4220         if (rc != 0)
4221                 cxgbe_uninit_synchronized(vi);
4222
4223         return (rc);
4224 }
4225
4226 /*
4227  * Idempotent.
4228  */
4229 static int
4230 cxgbe_uninit_synchronized(struct vi_info *vi)
4231 {
4232         struct port_info *pi = vi->pi;
4233         struct adapter *sc = pi->adapter;
4234         struct ifnet *ifp = vi->ifp;
4235         int rc, i;
4236         struct sge_txq *txq;
4237
4238         ASSERT_SYNCHRONIZED_OP(sc);
4239
4240         if (!(vi->flags & VI_INIT_DONE)) {
4241                 KASSERT(!(ifp->if_drv_flags & IFF_DRV_RUNNING),
4242                     ("uninited VI is running"));
4243                 return (0);
4244         }
4245
4246         /*
4247          * Disable the VI so that all its data in either direction is discarded
4248          * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
4249          * tick) intact as the TP can deliver negative advice or data that it's
4250          * holding in its RAM (for an offloaded connection) even after the VI is
4251          * disabled.
4252          */
4253         rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
4254         if (rc) {
4255                 if_printf(ifp, "disable_vi failed: %d\n", rc);
4256                 return (rc);
4257         }
4258
4259         for_each_txq(vi, i, txq) {
4260                 TXQ_LOCK(txq);
4261                 txq->eq.flags &= ~EQ_ENABLED;
4262                 TXQ_UNLOCK(txq);
4263         }
4264
4265         PORT_LOCK(pi);
4266         if (pi->nvi > 1 || sc->flags & IS_VF)
4267                 callout_stop(&vi->tick);
4268         else
4269                 callout_stop(&pi->tick);
4270         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
4271                 PORT_UNLOCK(pi);
4272                 return (0);
4273         }
4274         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
4275         pi->up_vis--;
4276         if (pi->up_vis > 0) {
4277                 PORT_UNLOCK(pi);
4278                 return (0);
4279         }
4280         PORT_UNLOCK(pi);
4281
4282         pi->link_cfg.link_ok = 0;
4283         pi->link_cfg.speed = 0;
4284         pi->link_cfg.link_down_rc = 255;
4285         t4_os_link_changed(pi, NULL);
4286
4287         return (0);
4288 }
4289
4290 /*
4291  * It is ok for this function to fail midway and return right away.  t4_detach
4292  * will walk the entire sc->irq list and clean up whatever is valid.
4293  */
4294 int
4295 t4_setup_intr_handlers(struct adapter *sc)
4296 {
4297         int rc, rid, p, q, v;
4298         char s[8];
4299         struct irq *irq;
4300         struct port_info *pi;
4301         struct vi_info *vi;
4302         struct sge *sge = &sc->sge;
4303         struct sge_rxq *rxq;
4304 #ifdef TCP_OFFLOAD
4305         struct sge_ofld_rxq *ofld_rxq;
4306 #endif
4307 #ifdef DEV_NETMAP
4308         struct sge_nm_rxq *nm_rxq;
4309 #endif
4310 #ifdef RSS
4311         int nbuckets = rss_getnumbuckets();
4312 #endif
4313
4314         /*
4315          * Setup interrupts.
4316          */
4317         irq = &sc->irq[0];
4318         rid = sc->intr_type == INTR_INTX ? 0 : 1;
4319         if (sc->intr_count == 1)
4320                 return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
4321
4322         /* Multiple interrupts. */
4323         if (sc->flags & IS_VF)
4324                 KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
4325                     ("%s: too few intr.", __func__));
4326         else
4327                 KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
4328                     ("%s: too few intr.", __func__));
4329
4330         /* The first one is always error intr on PFs */
4331         if (!(sc->flags & IS_VF)) {
4332                 rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
4333                 if (rc != 0)
4334                         return (rc);
4335                 irq++;
4336                 rid++;
4337         }
4338
4339         /* The second one is always the firmware event queue (first on VFs) */
4340         rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
4341         if (rc != 0)
4342                 return (rc);
4343         irq++;
4344         rid++;
4345
4346         for_each_port(sc, p) {
4347                 pi = sc->port[p];
4348                 for_each_vi(pi, v, vi) {
4349                         vi->first_intr = rid - 1;
4350
4351                         if (vi->nnmrxq > 0) {
4352                                 int n = max(vi->nrxq, vi->nnmrxq);
4353
4354                                 MPASS(vi->flags & INTR_RXQ);
4355
4356                                 rxq = &sge->rxq[vi->first_rxq];
4357 #ifdef DEV_NETMAP
4358                                 nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
4359 #endif
4360                                 for (q = 0; q < n; q++) {
4361                                         snprintf(s, sizeof(s), "%x%c%x", p,
4362                                             'a' + v, q);
4363                                         if (q < vi->nrxq)
4364                                                 irq->rxq = rxq++;
4365 #ifdef DEV_NETMAP
4366                                         if (q < vi->nnmrxq)
4367                                                 irq->nm_rxq = nm_rxq++;
4368 #endif
4369                                         rc = t4_alloc_irq(sc, irq, rid,
4370                                             t4_vi_intr, irq, s);
4371                                         if (rc != 0)
4372                                                 return (rc);
4373                                         irq++;
4374                                         rid++;
4375                                         vi->nintr++;
4376                                 }
4377                         } else if (vi->flags & INTR_RXQ) {
4378                                 for_each_rxq(vi, q, rxq) {
4379                                         snprintf(s, sizeof(s), "%x%c%x", p,
4380                                             'a' + v, q);
4381                                         rc = t4_alloc_irq(sc, irq, rid,
4382                                             t4_intr, rxq, s);
4383                                         if (rc != 0)
4384                                                 return (rc);
4385 #ifdef RSS
4386                                         bus_bind_intr(sc->dev, irq->res,
4387                                             rss_getcpu(q % nbuckets));
4388 #endif
4389                                         irq++;
4390                                         rid++;
4391                                         vi->nintr++;
4392                                 }
4393                         }
4394 #ifdef TCP_OFFLOAD
4395                         if (vi->flags & INTR_OFLD_RXQ) {
4396                                 for_each_ofld_rxq(vi, q, ofld_rxq) {
4397                                         snprintf(s, sizeof(s), "%x%c%x", p,
4398                                             'A' + v, q);
4399                                         rc = t4_alloc_irq(sc, irq, rid,
4400                                             t4_intr, ofld_rxq, s);
4401                                         if (rc != 0)
4402                                                 return (rc);
4403                                         irq++;
4404                                         rid++;
4405                                         vi->nintr++;
4406                                 }
4407                         }
4408 #endif
4409                 }
4410         }
4411         MPASS(irq == &sc->irq[sc->intr_count]);
4412
4413         return (0);
4414 }
4415
4416 int
4417 adapter_full_init(struct adapter *sc)
4418 {
4419         int rc, i;
4420 #ifdef RSS
4421         uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
4422         uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
4423 #endif
4424
4425         ASSERT_SYNCHRONIZED_OP(sc);
4426         ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
4427         KASSERT((sc->flags & FULL_INIT_DONE) == 0,
4428             ("%s: FULL_INIT_DONE already", __func__));
4429
4430         /*
4431          * queues that belong to the adapter (not any particular port).
4432          */
4433         rc = t4_setup_adapter_queues(sc);
4434         if (rc != 0)
4435                 goto done;
4436
4437         for (i = 0; i < nitems(sc->tq); i++) {
4438                 sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
4439                     taskqueue_thread_enqueue, &sc->tq[i]);
4440                 if (sc->tq[i] == NULL) {
4441                         device_printf(sc->dev,
4442                             "failed to allocate task queue %d\n", i);
4443                         rc = ENOMEM;
4444                         goto done;
4445                 }
4446                 taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
4447                     device_get_nameunit(sc->dev), i);
4448         }
4449 #ifdef RSS
4450         MPASS(RSS_KEYSIZE == 40);
4451         rss_getkey((void *)&raw_rss_key[0]);
4452         for (i = 0; i < nitems(rss_key); i++) {
4453                 rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
4454         }
4455         t4_write_rss_key(sc, &rss_key[0], -1, 1);
4456 #endif
4457
4458         if (!(sc->flags & IS_VF))
4459                 t4_intr_enable(sc);
4460         sc->flags |= FULL_INIT_DONE;
4461 done:
4462         if (rc != 0)
4463                 adapter_full_uninit(sc);
4464
4465         return (rc);
4466 }
4467
4468 int
4469 adapter_full_uninit(struct adapter *sc)
4470 {
4471         int i;
4472
4473         ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
4474
4475         t4_teardown_adapter_queues(sc);
4476
4477         for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
4478                 taskqueue_free(sc->tq[i]);
4479                 sc->tq[i] = NULL;
4480         }
4481
4482         sc->flags &= ~FULL_INIT_DONE;
4483
4484         return (0);
4485 }
4486
4487 #ifdef RSS
4488 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
4489     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
4490     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
4491     RSS_HASHTYPE_RSS_UDP_IPV6)
4492
4493 /* Translates kernel hash types to hardware. */
4494 static int
4495 hashconfig_to_hashen(int hashconfig)
4496 {
4497         int hashen = 0;
4498
4499         if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
4500                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
4501         if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
4502                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
4503         if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
4504                 hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
4505                     F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
4506         }
4507         if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
4508                 hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
4509                     F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
4510         }
4511         if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
4512                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
4513         if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
4514                 hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
4515
4516         return (hashen);
4517 }
4518
4519 /* Translates hardware hash types to kernel. */
4520 static int
4521 hashen_to_hashconfig(int hashen)
4522 {
4523         int hashconfig = 0;
4524
4525         if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
4526                 /*
4527                  * If UDP hashing was enabled it must have been enabled for
4528                  * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
4529                  * enabling any 4-tuple hash is nonsense configuration.
4530                  */
4531                 MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
4532                     F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
4533
4534                 if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
4535                         hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
4536                 if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
4537                         hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
4538         }
4539         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
4540                 hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
4541         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
4542                 hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
4543         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
4544                 hashconfig |= RSS_HASHTYPE_RSS_IPV4;
4545         if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
4546                 hashconfig |= RSS_HASHTYPE_RSS_IPV6;
4547
4548         return (hashconfig);
4549 }
4550 #endif
4551
4552 int
4553 vi_full_init(struct vi_info *vi)
4554 {
4555         struct adapter *sc = vi->pi->adapter;
4556         struct ifnet *ifp = vi->ifp;
4557         uint16_t *rss;
4558         struct sge_rxq *rxq;
4559         int rc, i, j, hashen;
4560 #ifdef RSS
4561         int nbuckets = rss_getnumbuckets();
4562         int hashconfig = rss_gethashconfig();
4563         int extra;
4564 #endif
4565
4566         ASSERT_SYNCHRONIZED_OP(sc);
4567         KASSERT((vi->flags & VI_INIT_DONE) == 0,
4568             ("%s: VI_INIT_DONE already", __func__));
4569
4570         sysctl_ctx_init(&vi->ctx);
4571         vi->flags |= VI_SYSCTL_CTX;
4572
4573         /*
4574          * Allocate tx/rx/fl queues for this VI.
4575          */
4576         rc = t4_setup_vi_queues(vi);
4577         if (rc != 0)
4578                 goto done;      /* error message displayed already */
4579
4580         /*
4581          * Setup RSS for this VI.  Save a copy of the RSS table for later use.
4582          */
4583         if (vi->nrxq > vi->rss_size) {
4584                 if_printf(ifp, "nrxq (%d) > hw RSS table size (%d); "
4585                     "some queues will never receive traffic.\n", vi->nrxq,
4586                     vi->rss_size);
4587         } else if (vi->rss_size % vi->nrxq) {
4588                 if_printf(ifp, "nrxq (%d), hw RSS table size (%d); "
4589                     "expect uneven traffic distribution.\n", vi->nrxq,
4590                     vi->rss_size);
4591         }
4592 #ifdef RSS
4593         if (vi->nrxq != nbuckets) {
4594                 if_printf(ifp, "nrxq (%d) != kernel RSS buckets (%d);"
4595                     "performance will be impacted.\n", vi->nrxq, nbuckets);
4596         }
4597 #endif
4598         rss = malloc(vi->rss_size * sizeof (*rss), M_CXGBE, M_ZERO | M_WAITOK);
4599         for (i = 0; i < vi->rss_size;) {
4600 #ifdef RSS
4601                 j = rss_get_indirection_to_bucket(i);
4602                 j %= vi->nrxq;
4603                 rxq = &sc->sge.rxq[vi->first_rxq + j];
4604                 rss[i++] = rxq->iq.abs_id;
4605 #else
4606                 for_each_rxq(vi, j, rxq) {
4607                         rss[i++] = rxq->iq.abs_id;
4608                         if (i == vi->rss_size)
4609                                 break;
4610                 }
4611 #endif
4612         }
4613
4614         rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size, rss,
4615             vi->rss_size);
4616         if (rc != 0) {
4617                 if_printf(ifp, "rss_config failed: %d\n", rc);
4618                 goto done;
4619         }
4620
4621 #ifdef RSS
4622         hashen = hashconfig_to_hashen(hashconfig);
4623
4624         /*
4625          * We may have had to enable some hashes even though the global config
4626          * wants them disabled.  This is a potential problem that must be
4627          * reported to the user.
4628          */
4629         extra = hashen_to_hashconfig(hashen) ^ hashconfig;
4630
4631         /*
4632          * If we consider only the supported hash types, then the enabled hashes
4633          * are a superset of the requested hashes.  In other words, there cannot
4634          * be any supported hash that was requested but not enabled, but there
4635          * can be hashes that were not requested but had to be enabled.
4636          */
4637         extra &= SUPPORTED_RSS_HASHTYPES;
4638         MPASS((extra & hashconfig) == 0);
4639
4640         if (extra) {
4641                 if_printf(ifp,
4642                     "global RSS config (0x%x) cannot be accommodated.\n",
4643                     hashconfig);
4644         }
4645         if (extra & RSS_HASHTYPE_RSS_IPV4)
4646                 if_printf(ifp, "IPv4 2-tuple hashing forced on.\n");
4647         if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
4648                 if_printf(ifp, "TCP/IPv4 4-tuple hashing forced on.\n");
4649         if (extra & RSS_HASHTYPE_RSS_IPV6)
4650                 if_printf(ifp, "IPv6 2-tuple hashing forced on.\n");
4651         if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
4652                 if_printf(ifp, "TCP/IPv6 4-tuple hashing forced on.\n");
4653         if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
4654                 if_printf(ifp, "UDP/IPv4 4-tuple hashing forced on.\n");
4655         if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
4656                 if_printf(ifp, "UDP/IPv6 4-tuple hashing forced on.\n");
4657 #else
4658         hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
4659             F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
4660             F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
4661             F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
4662 #endif
4663         rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, hashen, rss[0], 0, 0);
4664         if (rc != 0) {
4665                 if_printf(ifp, "rss hash/defaultq config failed: %d\n", rc);
4666                 goto done;
4667         }
4668
4669         vi->rss = rss;
4670         vi->flags |= VI_INIT_DONE;
4671 done:
4672         if (rc != 0)
4673                 vi_full_uninit(vi);
4674
4675         return (rc);
4676 }
4677
4678 /*
4679  * Idempotent.
4680  */
4681 int
4682 vi_full_uninit(struct vi_info *vi)
4683 {
4684         struct port_info *pi = vi->pi;
4685         struct adapter *sc = pi->adapter;
4686         int i;
4687         struct sge_rxq *rxq;
4688         struct sge_txq *txq;
4689 #ifdef TCP_OFFLOAD
4690         struct sge_ofld_rxq *ofld_rxq;
4691         struct sge_wrq *ofld_txq;
4692 #endif
4693
4694         if (vi->flags & VI_INIT_DONE) {
4695
4696                 /* Need to quiesce queues.  */
4697
4698                 /* XXX: Only for the first VI? */
4699                 if (IS_MAIN_VI(vi) && !(sc->flags & IS_VF))
4700                         quiesce_wrq(sc, &sc->sge.ctrlq[pi->port_id]);
4701
4702                 for_each_txq(vi, i, txq) {
4703                         quiesce_txq(sc, txq);
4704                 }
4705
4706 #ifdef TCP_OFFLOAD
4707                 for_each_ofld_txq(vi, i, ofld_txq) {
4708                         quiesce_wrq(sc, ofld_txq);
4709                 }
4710 #endif
4711
4712                 for_each_rxq(vi, i, rxq) {
4713                         quiesce_iq(sc, &rxq->iq);
4714                         quiesce_fl(sc, &rxq->fl);
4715                 }
4716
4717 #ifdef TCP_OFFLOAD
4718                 for_each_ofld_rxq(vi, i, ofld_rxq) {
4719                         quiesce_iq(sc, &ofld_rxq->iq);
4720                         quiesce_fl(sc, &ofld_rxq->fl);
4721                 }
4722 #endif
4723                 free(vi->rss, M_CXGBE);
4724                 free(vi->nm_rss, M_CXGBE);
4725         }
4726
4727         t4_teardown_vi_queues(vi);
4728         vi->flags &= ~VI_INIT_DONE;
4729
4730         return (0);
4731 }
4732
4733 static void
4734 quiesce_txq(struct adapter *sc, struct sge_txq *txq)
4735 {
4736         struct sge_eq *eq = &txq->eq;
4737         struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
4738
4739         (void) sc;      /* unused */
4740
4741 #ifdef INVARIANTS
4742         TXQ_LOCK(txq);
4743         MPASS((eq->flags & EQ_ENABLED) == 0);
4744         TXQ_UNLOCK(txq);
4745 #endif
4746
4747         /* Wait for the mp_ring to empty. */
4748         while (!mp_ring_is_idle(txq->r)) {
4749                 mp_ring_check_drainage(txq->r, 0);
4750                 pause("rquiesce", 1);
4751         }
4752
4753         /* Then wait for the hardware to finish. */
4754         while (spg->cidx != htobe16(eq->pidx))
4755                 pause("equiesce", 1);
4756
4757         /* Finally, wait for the driver to reclaim all descriptors. */
4758         while (eq->cidx != eq->pidx)
4759                 pause("dquiesce", 1);
4760 }
4761
4762 static void
4763 quiesce_wrq(struct adapter *sc, struct sge_wrq *wrq)
4764 {
4765
4766         /* XXXTX */
4767 }
4768
4769 static void
4770 quiesce_iq(struct adapter *sc, struct sge_iq *iq)
4771 {
4772         (void) sc;      /* unused */
4773
4774         /* Synchronize with the interrupt handler */
4775         while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
4776                 pause("iqfree", 1);
4777 }
4778
4779 static void
4780 quiesce_fl(struct adapter *sc, struct sge_fl *fl)
4781 {
4782         mtx_lock(&sc->sfl_lock);
4783         FL_LOCK(fl);
4784         fl->flags |= FL_DOOMED;
4785         FL_UNLOCK(fl);
4786         callout_stop(&sc->sfl_callout);
4787         mtx_unlock(&sc->sfl_lock);
4788
4789         KASSERT((fl->flags & FL_STARVING) == 0,
4790             ("%s: still starving", __func__));
4791 }
4792
4793 static int
4794 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
4795     driver_intr_t *handler, void *arg, char *name)
4796 {
4797         int rc;
4798
4799         irq->rid = rid;
4800         irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
4801             RF_SHAREABLE | RF_ACTIVE);
4802         if (irq->res == NULL) {
4803                 device_printf(sc->dev,
4804                     "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
4805                 return (ENOMEM);
4806         }
4807
4808         rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
4809             NULL, handler, arg, &irq->tag);
4810         if (rc != 0) {
4811                 device_printf(sc->dev,
4812                     "failed to setup interrupt for rid %d, name %s: %d\n",
4813                     rid, name, rc);
4814         } else if (name)
4815                 bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
4816
4817         return (rc);
4818 }
4819
4820 static int
4821 t4_free_irq(struct adapter *sc, struct irq *irq)
4822 {
4823         if (irq->tag)
4824                 bus_teardown_intr(sc->dev, irq->res, irq->tag);
4825         if (irq->res)
4826                 bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
4827
4828         bzero(irq, sizeof(*irq));
4829
4830         return (0);
4831 }
4832
4833 static void
4834 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
4835 {
4836
4837         regs->version = chip_id(sc) | chip_rev(sc) << 10;
4838         t4_get_regs(sc, buf, regs->len);
4839 }
4840
4841 #define A_PL_INDIR_CMD  0x1f8
4842
4843 #define S_PL_AUTOINC    31
4844 #define M_PL_AUTOINC    0x1U
4845 #define V_PL_AUTOINC(x) ((x) << S_PL_AUTOINC)
4846 #define G_PL_AUTOINC(x) (((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
4847
4848 #define S_PL_VFID       20
4849 #define M_PL_VFID       0xffU
4850 #define V_PL_VFID(x)    ((x) << S_PL_VFID)
4851 #define G_PL_VFID(x)    (((x) >> S_PL_VFID) & M_PL_VFID)
4852
4853 #define S_PL_ADDR       0
4854 #define M_PL_ADDR       0xfffffU
4855 #define V_PL_ADDR(x)    ((x) << S_PL_ADDR)
4856 #define G_PL_ADDR(x)    (((x) >> S_PL_ADDR) & M_PL_ADDR)
4857
4858 #define A_PL_INDIR_DATA 0x1fc
4859
4860 static uint64_t
4861 read_vf_stat(struct adapter *sc, unsigned int viid, int reg)
4862 {
4863         u32 stats[2];
4864
4865         mtx_assert(&sc->reg_lock, MA_OWNED);
4866         if (sc->flags & IS_VF) {
4867                 stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
4868                 stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
4869         } else {
4870                 t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
4871                     V_PL_VFID(G_FW_VIID_VIN(viid)) |
4872                     V_PL_ADDR(VF_MPS_REG(reg)));
4873                 stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
4874                 stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
4875         }
4876         return (((uint64_t)stats[1]) << 32 | stats[0]);
4877 }
4878
4879 static void
4880 t4_get_vi_stats(struct adapter *sc, unsigned int viid,
4881     struct fw_vi_stats_vf *stats)
4882 {
4883
4884 #define GET_STAT(name) \
4885         read_vf_stat(sc, viid, A_MPS_VF_STAT_##name##_L)
4886
4887         stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
4888         stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
4889         stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
4890         stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
4891         stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
4892         stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
4893         stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
4894         stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
4895         stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
4896         stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
4897         stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
4898         stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
4899         stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
4900         stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
4901         stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
4902         stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
4903
4904 #undef GET_STAT
4905 }
4906
4907 static void
4908 t4_clr_vi_stats(struct adapter *sc, unsigned int viid)
4909 {
4910         int reg;
4911
4912         t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
4913             V_PL_VFID(G_FW_VIID_VIN(viid)) |
4914             V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
4915         for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
4916              reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
4917                 t4_write_reg(sc, A_PL_INDIR_DATA, 0);
4918 }
4919
4920 static void
4921 vi_refresh_stats(struct adapter *sc, struct vi_info *vi)
4922 {
4923         struct timeval tv;
4924         const struct timeval interval = {0, 250000};    /* 250ms */
4925
4926         if (!(vi->flags & VI_INIT_DONE))
4927                 return;
4928
4929         getmicrotime(&tv);
4930         timevalsub(&tv, &interval);
4931         if (timevalcmp(&tv, &vi->last_refreshed, <))
4932                 return;
4933
4934         mtx_lock(&sc->reg_lock);
4935         t4_get_vi_stats(sc, vi->viid, &vi->stats);
4936         getmicrotime(&vi->last_refreshed);
4937         mtx_unlock(&sc->reg_lock);
4938 }
4939
4940 static void
4941 cxgbe_refresh_stats(struct adapter *sc, struct port_info *pi)
4942 {
4943         int i;
4944         u_int v, tnl_cong_drops;
4945         struct timeval tv;
4946         const struct timeval interval = {0, 250000};    /* 250ms */
4947
4948         getmicrotime(&tv);
4949         timevalsub(&tv, &interval);
4950         if (timevalcmp(&tv, &pi->last_refreshed, <))
4951                 return;
4952
4953         tnl_cong_drops = 0;
4954         t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
4955         for (i = 0; i < sc->chip_params->nchan; i++) {
4956                 if (pi->rx_chan_map & (1 << i)) {
4957                         mtx_lock(&sc->reg_lock);
4958                         t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
4959                             1, A_TP_MIB_TNL_CNG_DROP_0 + i);
4960                         mtx_unlock(&sc->reg_lock);
4961                         tnl_cong_drops += v;
4962                 }
4963         }
4964         pi->tnl_cong_drops = tnl_cong_drops;
4965         getmicrotime(&pi->last_refreshed);
4966 }
4967
4968 static void
4969 cxgbe_tick(void *arg)
4970 {
4971         struct port_info *pi = arg;
4972         struct adapter *sc = pi->adapter;
4973
4974         PORT_LOCK_ASSERT_OWNED(pi);
4975         cxgbe_refresh_stats(sc, pi);
4976
4977         callout_schedule(&pi->tick, hz);
4978 }
4979
4980 void
4981 vi_tick(void *arg)
4982 {
4983         struct vi_info *vi = arg;
4984         struct adapter *sc = vi->pi->adapter;
4985
4986         vi_refresh_stats(sc, vi);
4987
4988         callout_schedule(&vi->tick, hz);
4989 }
4990
4991 static void
4992 cxgbe_vlan_config(void *arg, struct ifnet *ifp, uint16_t vid)
4993 {
4994         struct ifnet *vlan;
4995
4996         if (arg != ifp || ifp->if_type != IFT_ETHER)
4997                 return;
4998
4999         vlan = VLAN_DEVAT(ifp, vid);
5000         VLAN_SETCOOKIE(vlan, ifp);
5001 }
5002
5003 /*
5004  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
5005  */
5006 static char *caps_decoder[] = {
5007         "\20\001IPMI\002NCSI",                          /* 0: NBM */
5008         "\20\001PPP\002QFC\003DCBX",                    /* 1: link */
5009         "\20\001INGRESS\002EGRESS",                     /* 2: switch */
5010         "\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"      /* 3: NIC */
5011             "\006HASHFILTER\007ETHOFLD",
5012         "\20\001TOE",                                   /* 4: TOE */
5013         "\20\001RDDP\002RDMAC",                         /* 5: RDMA */
5014         "\20\001INITIATOR_PDU\002TARGET_PDU"            /* 6: iSCSI */
5015             "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
5016             "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
5017             "\007T10DIF"
5018             "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
5019         "\20\001LOOKASIDE\002TLSKEYS",                  /* 7: Crypto */
5020         "\20\001INITIATOR\002TARGET\003CTRL_OFLD"       /* 8: FCoE */
5021                     "\004PO_INITIATOR\005PO_TARGET",
5022 };
5023
5024 void
5025 t4_sysctls(struct adapter *sc)
5026 {
5027         struct sysctl_ctx_list *ctx;
5028         struct sysctl_oid *oid;
5029         struct sysctl_oid_list *children, *c0;
5030         static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
5031
5032         ctx = device_get_sysctl_ctx(sc->dev);
5033
5034         /*
5035          * dev.t4nex.X.
5036          */
5037         oid = device_get_sysctl_tree(sc->dev);
5038         c0 = children = SYSCTL_CHILDREN(oid);
5039
5040         sc->sc_do_rxcopy = 1;
5041         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
5042             &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
5043
5044         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
5045             sc->params.nports, "# of ports");
5046
5047         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
5048             CTLTYPE_STRING | CTLFLAG_RD, doorbells, sc->doorbells,
5049             sysctl_bitfield, "A", "available doorbells");
5050
5051         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
5052             sc->params.vpd.cclk, "core clock frequency (in KHz)");
5053
5054         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
5055             CTLTYPE_STRING | CTLFLAG_RD, sc->params.sge.timer_val,
5056             sizeof(sc->params.sge.timer_val), sysctl_int_array, "A",
5057             "interrupt holdoff timer values (us)");
5058
5059         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
5060             CTLTYPE_STRING | CTLFLAG_RD, sc->params.sge.counter_val,
5061             sizeof(sc->params.sge.counter_val), sysctl_int_array, "A",
5062             "interrupt holdoff packet counter values");
5063
5064         t4_sge_sysctls(sc, ctx, children);
5065
5066         sc->lro_timeout = 100;
5067         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
5068             &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
5069
5070         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
5071             &sc->debug_flags, 0, "flags to enable runtime debugging");
5072
5073         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
5074             CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
5075
5076         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
5077             CTLFLAG_RD, sc->fw_version, 0, "firmware version");
5078
5079         if (sc->flags & IS_VF)
5080                 return;
5081
5082         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
5083             NULL, chip_rev(sc), "chip hardware revision");
5084
5085         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
5086             CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
5087
5088         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
5089             CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
5090
5091         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
5092             CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
5093
5094         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
5095             CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
5096
5097         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
5098             sc->er_version, 0, "expansion ROM version");
5099
5100         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
5101             sc->bs_version, 0, "bootstrap firmware version");
5102
5103         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
5104             NULL, sc->params.scfg_vers, "serial config version");
5105
5106         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
5107             NULL, sc->params.vpd_vers, "VPD version");
5108
5109         SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
5110             CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
5111
5112         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
5113             sc->cfcsum, "config file checksum");
5114
5115 #define SYSCTL_CAP(name, n, text) \
5116         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
5117             CTLTYPE_STRING | CTLFLAG_RD, caps_decoder[n], sc->name, \
5118             sysctl_bitfield, "A", "available " text " capabilities")
5119
5120         SYSCTL_CAP(nbmcaps, 0, "NBM");
5121         SYSCTL_CAP(linkcaps, 1, "link");
5122         SYSCTL_CAP(switchcaps, 2, "switch");
5123         SYSCTL_CAP(niccaps, 3, "NIC");
5124         SYSCTL_CAP(toecaps, 4, "TCP offload");
5125         SYSCTL_CAP(rdmacaps, 5, "RDMA");
5126         SYSCTL_CAP(iscsicaps, 6, "iSCSI");
5127         SYSCTL_CAP(cryptocaps, 7, "crypto");
5128         SYSCTL_CAP(fcoecaps, 8, "FCoE");
5129 #undef SYSCTL_CAP
5130
5131         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
5132             NULL, sc->tids.nftids, "number of filters");
5133
5134         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature", CTLTYPE_INT |
5135             CTLFLAG_RD, sc, 0, sysctl_temperature, "I",
5136             "chip temperature (in Celsius)");
5137
5138 #ifdef SBUF_DRAIN
5139         /*
5140          * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
5141          */
5142         oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
5143             CTLFLAG_RD | CTLFLAG_SKIP, NULL,
5144             "logs and miscellaneous information");
5145         children = SYSCTL_CHILDREN(oid);
5146
5147         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
5148             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5149             sysctl_cctrl, "A", "congestion control");
5150
5151         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
5152             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5153             sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
5154
5155         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
5156             CTLTYPE_STRING | CTLFLAG_RD, sc, 1,
5157             sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
5158
5159         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
5160             CTLTYPE_STRING | CTLFLAG_RD, sc, 2,
5161             sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
5162
5163         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
5164             CTLTYPE_STRING | CTLFLAG_RD, sc, 3,
5165             sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
5166
5167         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
5168             CTLTYPE_STRING | CTLFLAG_RD, sc, 4,
5169             sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
5170
5171         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
5172             CTLTYPE_STRING | CTLFLAG_RD, sc, 5,
5173             sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
5174
5175         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
5176             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5177             chip_id(sc) <= CHELSIO_T5 ? sysctl_cim_la : sysctl_cim_la_t6,
5178             "A", "CIM logic analyzer");
5179
5180         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
5181             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5182             sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
5183
5184         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
5185             CTLTYPE_STRING | CTLFLAG_RD, sc, 0 + CIM_NUM_IBQ,
5186             sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
5187
5188         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
5189             CTLTYPE_STRING | CTLFLAG_RD, sc, 1 + CIM_NUM_IBQ,
5190             sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
5191
5192         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
5193             CTLTYPE_STRING | CTLFLAG_RD, sc, 2 + CIM_NUM_IBQ,
5194             sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
5195
5196         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
5197             CTLTYPE_STRING | CTLFLAG_RD, sc, 3 + CIM_NUM_IBQ,
5198             sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
5199
5200         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
5201             CTLTYPE_STRING | CTLFLAG_RD, sc, 4 + CIM_NUM_IBQ,
5202             sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
5203
5204         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
5205             CTLTYPE_STRING | CTLFLAG_RD, sc, 5 + CIM_NUM_IBQ,
5206             sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
5207
5208         if (chip_id(sc) > CHELSIO_T4) {
5209                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
5210                     CTLTYPE_STRING | CTLFLAG_RD, sc, 6 + CIM_NUM_IBQ,
5211                     sysctl_cim_ibq_obq, "A", "CIM OBQ 6 (SGE0-RX)");
5212
5213                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
5214                     CTLTYPE_STRING | CTLFLAG_RD, sc, 7 + CIM_NUM_IBQ,
5215                     sysctl_cim_ibq_obq, "A", "CIM OBQ 7 (SGE1-RX)");
5216         }
5217
5218         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
5219             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5220             sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
5221
5222         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
5223             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5224             sysctl_cim_qcfg, "A", "CIM queue configuration");
5225
5226         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
5227             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5228             sysctl_cpl_stats, "A", "CPL statistics");
5229
5230         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
5231             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5232             sysctl_ddp_stats, "A", "non-TCP DDP statistics");
5233
5234         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
5235             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5236             sysctl_devlog, "A", "firmware's device log");
5237
5238         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
5239             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5240             sysctl_fcoe_stats, "A", "FCoE statistics");
5241
5242         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
5243             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5244             sysctl_hw_sched, "A", "hardware scheduler ");
5245
5246         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
5247             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5248             sysctl_l2t, "A", "hardware L2 table");
5249
5250         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
5251             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5252             sysctl_lb_stats, "A", "loopback statistics");
5253
5254         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
5255             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5256             sysctl_meminfo, "A", "memory regions");
5257
5258         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
5259             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5260             chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
5261             "A", "MPS TCAM entries");
5262
5263         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
5264             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5265             sysctl_path_mtus, "A", "path MTUs");
5266
5267         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
5268             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5269             sysctl_pm_stats, "A", "PM statistics");
5270
5271         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
5272             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5273             sysctl_rdma_stats, "A", "RDMA statistics");
5274
5275         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
5276             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5277             sysctl_tcp_stats, "A", "TCP statistics");
5278
5279         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
5280             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5281             sysctl_tids, "A", "TID information");
5282
5283         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
5284             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5285             sysctl_tp_err_stats, "A", "TP error statistics");
5286
5287         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
5288             CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_tp_la_mask, "I",
5289             "TP logic analyzer event capture mask");
5290
5291         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
5292             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5293             sysctl_tp_la, "A", "TP logic analyzer");
5294
5295         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
5296             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5297             sysctl_tx_rate, "A", "Tx rate");
5298
5299         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
5300             CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5301             sysctl_ulprx_la, "A", "ULPRX logic analyzer");
5302
5303         if (chip_id(sc) >= CHELSIO_T5) {
5304                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
5305                     CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5306                     sysctl_wcwr_stats, "A", "write combined work requests");
5307         }
5308 #endif
5309
5310 #ifdef TCP_OFFLOAD
5311         if (is_offload(sc)) {
5312                 int i;
5313                 char s[4];
5314
5315                 /*
5316                  * dev.t4nex.X.toe.
5317                  */
5318                 oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe", CTLFLAG_RD,
5319                     NULL, "TOE parameters");
5320                 children = SYSCTL_CHILDREN(oid);
5321
5322                 sc->tt.sndbuf = 256 * 1024;
5323                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
5324                     &sc->tt.sndbuf, 0, "max hardware send buffer size");
5325
5326                 sc->tt.ddp = 0;
5327                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp", CTLFLAG_RW,
5328                     &sc->tt.ddp, 0, "DDP allowed");
5329
5330                 sc->tt.rx_coalesce = 1;
5331                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
5332                     CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
5333
5334                 sc->tt.tx_align = 1;
5335                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
5336                     CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
5337
5338                 sc->tt.tx_zcopy = 0;
5339                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
5340                     CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
5341                     "Enable zero-copy aio_write(2)");
5342
5343                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
5344                     CTLTYPE_STRING | CTLFLAG_RD, sc, 0, sysctl_tp_tick, "A",
5345                     "TP timer tick (us)");
5346
5347                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
5348                     CTLTYPE_STRING | CTLFLAG_RD, sc, 1, sysctl_tp_tick, "A",
5349                     "TCP timestamp tick (us)");
5350
5351                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
5352                     CTLTYPE_STRING | CTLFLAG_RD, sc, 2, sysctl_tp_tick, "A",
5353                     "DACK tick (us)");
5354
5355                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
5356                     CTLTYPE_UINT | CTLFLAG_RD, sc, 0, sysctl_tp_dack_timer,
5357                     "IU", "DACK timer (us)");
5358
5359                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
5360                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_RXT_MIN,
5361                     sysctl_tp_timer, "LU", "Minimum retransmit interval (us)");
5362
5363                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
5364                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_RXT_MAX,
5365                     sysctl_tp_timer, "LU", "Maximum retransmit interval (us)");
5366
5367                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
5368                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_PERS_MIN,
5369                     sysctl_tp_timer, "LU", "Persist timer min (us)");
5370
5371                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
5372                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_PERS_MAX,
5373                     sysctl_tp_timer, "LU", "Persist timer max (us)");
5374
5375                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
5376                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_KEEP_IDLE,
5377                     sysctl_tp_timer, "LU", "Keepalive idle timer (us)");
5378
5379                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
5380                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_KEEP_INTVL,
5381                     sysctl_tp_timer, "LU", "Keepalive interval timer (us)");
5382
5383                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
5384                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_INIT_SRTT,
5385                     sysctl_tp_timer, "LU", "Initial SRTT (us)");
5386
5387                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
5388                     CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_FINWAIT2_TIMER,
5389                     sysctl_tp_timer, "LU", "FINWAIT2 timer (us)");
5390
5391                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
5392                     CTLTYPE_UINT | CTLFLAG_RD, sc, S_SYNSHIFTMAX,
5393                     sysctl_tp_shift_cnt, "IU",
5394                     "Number of SYN retransmissions before abort");
5395
5396                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
5397                     CTLTYPE_UINT | CTLFLAG_RD, sc, S_RXTSHIFTMAXR2,
5398                     sysctl_tp_shift_cnt, "IU",
5399                     "Number of retransmissions before abort");
5400
5401                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
5402                     CTLTYPE_UINT | CTLFLAG_RD, sc, S_KEEPALIVEMAXR2,
5403                     sysctl_tp_shift_cnt, "IU",
5404                     "Number of keepalive probes before abort");
5405
5406                 oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
5407                     CTLFLAG_RD, NULL, "TOE retransmit backoffs");
5408                 children = SYSCTL_CHILDREN(oid);
5409                 for (i = 0; i < 16; i++) {
5410                         snprintf(s, sizeof(s), "%u", i);
5411                         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
5412                             CTLTYPE_UINT | CTLFLAG_RD, sc, i, sysctl_tp_backoff,
5413                             "IU", "TOE retransmit backoff");
5414                 }
5415         }
5416 #endif
5417 }
5418
5419 void
5420 vi_sysctls(struct vi_info *vi)
5421 {
5422         struct sysctl_ctx_list *ctx;
5423         struct sysctl_oid *oid;
5424         struct sysctl_oid_list *children;
5425
5426         ctx = device_get_sysctl_ctx(vi->dev);
5427
5428         /*
5429          * dev.v?(cxgbe|cxl).X.
5430          */
5431         oid = device_get_sysctl_tree(vi->dev);
5432         children = SYSCTL_CHILDREN(oid);
5433
5434         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
5435             vi->viid, "VI identifer");
5436         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
5437             &vi->nrxq, 0, "# of rx queues");
5438         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
5439             &vi->ntxq, 0, "# of tx queues");
5440         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
5441             &vi->first_rxq, 0, "index of first rx queue");
5442         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
5443             &vi->first_txq, 0, "index of first tx queue");
5444         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
5445             vi->rss_size, "size of RSS indirection table");
5446
5447         if (IS_MAIN_VI(vi)) {
5448                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
5449                     CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_noflowq, "IU",
5450                     "Reserve queue 0 for non-flowid packets");
5451         }
5452
5453 #ifdef TCP_OFFLOAD
5454         if (vi->nofldrxq != 0) {
5455                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
5456                     &vi->nofldrxq, 0,
5457                     "# of rx queues for offloaded TCP connections");
5458                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
5459                     &vi->nofldtxq, 0,
5460                     "# of tx queues for offloaded TCP connections");
5461                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
5462                     CTLFLAG_RD, &vi->first_ofld_rxq, 0,
5463                     "index of first TOE rx queue");
5464                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
5465                     CTLFLAG_RD, &vi->first_ofld_txq, 0,
5466                     "index of first TOE tx queue");
5467         }
5468 #endif
5469 #ifdef DEV_NETMAP
5470         if (vi->nnmrxq != 0) {
5471                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
5472                     &vi->nnmrxq, 0, "# of netmap rx queues");
5473                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
5474                     &vi->nnmtxq, 0, "# of netmap tx queues");
5475                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
5476                     CTLFLAG_RD, &vi->first_nm_rxq, 0,
5477                     "index of first netmap rx queue");
5478                 SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
5479                     CTLFLAG_RD, &vi->first_nm_txq, 0,
5480                     "index of first netmap tx queue");
5481         }
5482 #endif
5483
5484         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
5485             CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_holdoff_tmr_idx, "I",
5486             "holdoff timer index");
5487         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
5488             CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_holdoff_pktc_idx, "I",
5489             "holdoff packet counter index");
5490
5491         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
5492             CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_qsize_rxq, "I",
5493             "rx queue size");
5494         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
5495             CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_qsize_txq, "I",
5496             "tx queue size");
5497 }
5498
5499 static void
5500 cxgbe_sysctls(struct port_info *pi)
5501 {
5502         struct sysctl_ctx_list *ctx;
5503         struct sysctl_oid *oid;
5504         struct sysctl_oid_list *children, *children2;
5505         struct adapter *sc = pi->adapter;
5506         int i;
5507         char name[16];
5508
5509         ctx = device_get_sysctl_ctx(pi->dev);
5510
5511         /*
5512          * dev.cxgbe.X.
5513          */
5514         oid = device_get_sysctl_tree(pi->dev);
5515         children = SYSCTL_CHILDREN(oid);
5516
5517         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc", CTLTYPE_STRING |
5518            CTLFLAG_RD, pi, 0, sysctl_linkdnrc, "A", "reason why link is down");
5519         if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
5520                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
5521                     CTLTYPE_INT | CTLFLAG_RD, pi, 0, sysctl_btphy, "I",
5522                     "PHY temperature (in Celsius)");
5523                 SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
5524                     CTLTYPE_INT | CTLFLAG_RD, pi, 1, sysctl_btphy, "I",
5525                     "PHY firmware version");
5526         }
5527
5528         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
5529             CTLTYPE_STRING | CTLFLAG_RW, pi, 0, sysctl_pause_settings, "A",
5530             "PAUSE settings (bit 0 = rx_pause, bit 1 = tx_pause)");
5531         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fec",
5532             CTLTYPE_STRING | CTLFLAG_RW, pi, 0, sysctl_fec, "A",
5533             "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
5534         SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
5535             CTLTYPE_INT | CTLFLAG_RW, pi, 0, sysctl_autoneg, "I",
5536             "autonegotiation (-1 = not supported)");
5537
5538         SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
5539             port_top_speed(pi), "max speed (in Gbps)");
5540
5541         if (sc->flags & IS_VF)
5542                 return;
5543
5544         /*
5545          * dev.(cxgbe|cxl).X.tc.
5546          */
5547         oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc", CTLFLAG_RD, NULL,
5548             "Tx scheduler traffic classes (cl_rl)");
5549         for (i = 0; i < sc->chip_params->nsched_cls; i++) {
5550                 struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
5551
5552                 snprintf(name, sizeof(name), "%d", i);
5553                 children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
5554                     SYSCTL_CHILDREN(oid), OID_AUTO, name, CTLFLAG_RD, NULL,
5555                     "traffic class"));
5556                 SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "flags", CTLFLAG_RD,
5557                     &tc->flags, 0, "flags");
5558                 SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
5559                     CTLFLAG_RD, &tc->refcount, 0, "references to this class");
5560 #ifdef SBUF_DRAIN
5561                 SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
5562                     CTLTYPE_STRING | CTLFLAG_RD, sc, (pi->port_id << 16) | i,
5563                     sysctl_tc_params, "A", "traffic class parameters");
5564 #endif
5565         }
5566
5567         /*
5568          * dev.cxgbe.X.stats.
5569          */
5570         oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats", CTLFLAG_RD,
5571             NULL, "port statistics");
5572         children = SYSCTL_CHILDREN(oid);
5573         SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
5574             &pi->tx_parse_error, 0,
5575             "# of tx packets with invalid length or # of segments");
5576
5577 #define SYSCTL_ADD_T4_REG64(pi, name, desc, reg) \
5578         SYSCTL_ADD_OID(ctx, children, OID_AUTO, name, \
5579             CTLTYPE_U64 | CTLFLAG_RD, sc, reg, \
5580             sysctl_handle_t4_reg64, "QU", desc)
5581
5582         SYSCTL_ADD_T4_REG64(pi, "tx_octets", "# of octets in good frames",
5583             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_BYTES_L));
5584         SYSCTL_ADD_T4_REG64(pi, "tx_frames", "total # of good frames",
5585             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_FRAMES_L));
5586         SYSCTL_ADD_T4_REG64(pi, "tx_bcast_frames", "# of broadcast frames",
5587             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_BCAST_L));
5588         SYSCTL_ADD_T4_REG64(pi, "tx_mcast_frames", "# of multicast frames",
5589             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_MCAST_L));
5590         SYSCTL_ADD_T4_REG64(pi, "tx_ucast_frames", "# of unicast frames",
5591             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_UCAST_L));
5592         SYSCTL_ADD_T4_REG64(pi, "tx_error_frames", "# of error frames",
5593             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_ERROR_L));
5594         SYSCTL_ADD_T4_REG64(pi, "tx_frames_64",
5595             "# of tx frames in this range",
5596             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_64B_L));
5597         SYSCTL_ADD_T4_REG64(pi, "tx_frames_65_127",
5598             "# of tx frames in this range",
5599             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_65B_127B_L));
5600         SYSCTL_ADD_T4_REG64(pi, "tx_frames_128_255",
5601             "# of tx frames in this range",
5602             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_128B_255B_L));
5603         SYSCTL_ADD_T4_REG64(pi, "tx_frames_256_511",
5604             "# of tx frames in this range",
5605             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_256B_511B_L));
5606         SYSCTL_ADD_T4_REG64(pi, "tx_frames_512_1023",
5607             "# of tx frames in this range",
5608             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_512B_1023B_L));
5609         SYSCTL_ADD_T4_REG64(pi, "tx_frames_1024_1518",
5610             "# of tx frames in this range",
5611             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_1024B_1518B_L));
5612         SYSCTL_ADD_T4_REG64(pi, "tx_frames_1519_max",
5613             "# of tx frames in this range",
5614             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_1519B_MAX_L));
5615         SYSCTL_ADD_T4_REG64(pi, "tx_drop", "# of dropped tx frames",
5616             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_DROP_L));
5617         SYSCTL_ADD_T4_REG64(pi, "tx_pause", "# of pause frames transmitted",
5618             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PAUSE_L));
5619         SYSCTL_ADD_T4_REG64(pi, "tx_ppp0", "# of PPP prio 0 frames transmitted",
5620             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP0_L));
5621         SYSCTL_ADD_T4_REG64(pi, "tx_ppp1", "# of PPP prio 1 frames transmitted",
5622             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP1_L));
5623         SYSCTL_ADD_T4_REG64(pi, "tx_ppp2", "# of PPP prio 2 frames transmitted",
5624             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP2_L));
5625         SYSCTL_ADD_T4_REG64(pi, "tx_ppp3", "# of PPP prio 3 frames transmitted",
5626             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP3_L));
5627         SYSCTL_ADD_T4_REG64(pi, "tx_ppp4", "# of PPP prio 4 frames transmitted",
5628             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP4_L));
5629         SYSCTL_ADD_T4_REG64(pi, "tx_ppp5", "# of PPP prio 5 frames transmitted",
5630             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP5_L));
5631         SYSCTL_ADD_T4_REG64(pi, "tx_ppp6", "# of PPP prio 6 frames transmitted",
5632             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP6_L));
5633         SYSCTL_ADD_T4_REG64(pi, "tx_ppp7", "# of PPP prio 7 frames transmitted",
5634             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP7_L));
5635
5636         SYSCTL_ADD_T4_REG64(pi, "rx_octets", "# of octets in good frames",
5637             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_BYTES_L));
5638         SYSCTL_ADD_T4_REG64(pi, "rx_frames", "total # of good frames",
5639             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_FRAMES_L));
5640         SYSCTL_ADD_T4_REG64(pi, "rx_bcast_frames", "# of broadcast frames",
5641             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_BCAST_L));
5642         SYSCTL_ADD_T4_REG64(pi, "rx_mcast_frames", "# of multicast frames",
5643             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MCAST_L));
5644         SYSCTL_ADD_T4_REG64(pi, "rx_ucast_frames", "# of unicast frames",
5645             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_UCAST_L));
5646         SYSCTL_ADD_T4_REG64(pi, "rx_too_long", "# of frames exceeding MTU",
5647             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MTU_ERROR_L));
5648         SYSCTL_ADD_T4_REG64(pi, "rx_jabber", "# of jabber frames",
5649             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MTU_CRC_ERROR_L));
5650         SYSCTL_ADD_T4_REG64(pi, "rx_fcs_err",
5651             "# of frames received with bad FCS",
5652             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L));
5653         SYSCTL_ADD_T4_REG64(pi, "rx_len_err",
5654             "# of frames received with length error",
5655             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_LEN_ERROR_L));
5656         SYSCTL_ADD_T4_REG64(pi, "rx_symbol_err", "symbol errors",
5657             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_SYM_ERROR_L));
5658         SYSCTL_ADD_T4_REG64(pi, "rx_runt", "# of short frames received",
5659             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_LESS_64B_L));
5660         SYSCTL_ADD_T4_REG64(pi, "rx_frames_64",
5661             "# of rx frames in this range",
5662             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_64B_L));
5663         SYSCTL_ADD_T4_REG64(pi, "rx_frames_65_127",
5664             "# of rx frames in this range",
5665             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_65B_127B_L));
5666         SYSCTL_ADD_T4_REG64(pi, "rx_frames_128_255",
5667             "# of rx frames in this range",
5668             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_128B_255B_L));
5669         SYSCTL_ADD_T4_REG64(pi, "rx_frames_256_511",
5670             "# of rx frames in this range",
5671             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_256B_511B_L));
5672         SYSCTL_ADD_T4_REG64(pi, "rx_frames_512_1023",
5673             "# of rx frames in this range",
5674             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_512B_1023B_L));
5675         SYSCTL_ADD_T4_REG64(pi, "rx_frames_1024_1518",
5676             "# of rx frames in this range",
5677             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_1024B_1518B_L));
5678         SYSCTL_ADD_T4_REG64(pi, "rx_frames_1519_max",
5679             "# of rx frames in this range",
5680             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_1519B_MAX_L));
5681         SYSCTL_ADD_T4_REG64(pi, "rx_pause", "# of pause frames received",
5682             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PAUSE_L));
5683         SYSCTL_ADD_T4_REG64(pi, "rx_ppp0", "# of PPP prio 0 frames received",
5684             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP0_L));
5685         SYSCTL_ADD_T4_REG64(pi, "rx_ppp1", "# of PPP prio 1 frames received",
5686             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP1_L));
5687         SYSCTL_ADD_T4_REG64(pi, "rx_ppp2", "# of PPP prio 2 frames received",
5688             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP2_L));
5689         SYSCTL_ADD_T4_REG64(pi, "rx_ppp3", "# of PPP prio 3 frames received",
5690             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP3_L));
5691         SYSCTL_ADD_T4_REG64(pi, "rx_ppp4", "# of PPP prio 4 frames received",
5692             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP4_L));
5693         SYSCTL_ADD_T4_REG64(pi, "rx_ppp5", "# of PPP prio 5 frames received",
5694             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP5_L));
5695         SYSCTL_ADD_T4_REG64(pi, "rx_ppp6", "# of PPP prio 6 frames received",
5696             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP6_L));
5697         SYSCTL_ADD_T4_REG64(pi, "rx_ppp7", "# of PPP prio 7 frames received",
5698             PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP7_L));
5699
5700 #undef SYSCTL_ADD_T4_REG64
5701
5702 #define SYSCTL_ADD_T4_PORTSTAT(name, desc) \
5703         SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
5704             &pi->stats.name, desc)
5705
5706         /* We get these from port_stats and they may be stale by up to 1s */
5707         SYSCTL_ADD_T4_PORTSTAT(rx_ovflow0,
5708             "# drops due to buffer-group 0 overflows");
5709         SYSCTL_ADD_T4_PORTSTAT(rx_ovflow1,
5710             "# drops due to buffer-group 1 overflows");
5711         SYSCTL_ADD_T4_PORTSTAT(rx_ovflow2,
5712             "# drops due to buffer-group 2 overflows");
5713         SYSCTL_ADD_T4_PORTSTAT(rx_ovflow3,
5714             "# drops due to buffer-group 3 overflows");
5715         SYSCTL_ADD_T4_PORTSTAT(rx_trunc0,
5716             "# of buffer-group 0 truncated packets");
5717         SYSCTL_ADD_T4_PORTSTAT(rx_trunc1,
5718             "# of buffer-group 1 truncated packets");
5719         SYSCTL_ADD_T4_PORTSTAT(rx_trunc2,
5720             "# of buffer-group 2 truncated packets");
5721         SYSCTL_ADD_T4_PORTSTAT(rx_trunc3,
5722             "# of buffer-group 3 truncated packets");
5723
5724 #undef SYSCTL_ADD_T4_PORTSTAT
5725 }
5726
5727 static int
5728 sysctl_int_array(SYSCTL_HANDLER_ARGS)
5729 {
5730         int rc, *i, space = 0;
5731         struct sbuf sb;
5732
5733         sbuf_new_for_sysctl(&sb, NULL, 64, req);
5734         for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
5735                 if (space)
5736                         sbuf_printf(&sb, " ");
5737                 sbuf_printf(&sb, "%d", *i);
5738                 space = 1;
5739         }
5740         rc = sbuf_finish(&sb);
5741         sbuf_delete(&sb);
5742         return (rc);
5743 }
5744
5745 static int
5746 sysctl_bitfield(SYSCTL_HANDLER_ARGS)
5747 {
5748         int rc;
5749         struct sbuf *sb;
5750
5751         rc = sysctl_wire_old_buffer(req, 0);
5752         if (rc != 0)
5753                 return(rc);
5754
5755         sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
5756         if (sb == NULL)
5757                 return (ENOMEM);
5758
5759         sbuf_printf(sb, "%b", (int)arg2, (char *)arg1);
5760         rc = sbuf_finish(sb);
5761         sbuf_delete(sb);
5762
5763         return (rc);
5764 }
5765
5766 static int
5767 sysctl_btphy(SYSCTL_HANDLER_ARGS)
5768 {
5769         struct port_info *pi = arg1;
5770         int op = arg2;
5771         struct adapter *sc = pi->adapter;
5772         u_int v;
5773         int rc;
5774
5775         rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
5776         if (rc)
5777                 return (rc);
5778         /* XXX: magic numbers */
5779         rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e, op ? 0x20 : 0xc820,
5780             &v);
5781         end_synchronized_op(sc, 0);
5782         if (rc)
5783                 return (rc);
5784         if (op == 0)
5785                 v /= 256;
5786
5787         rc = sysctl_handle_int(oidp, &v, 0, req);
5788         return (rc);
5789 }
5790
5791 static int
5792 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
5793 {
5794         struct vi_info *vi = arg1;
5795         int rc, val;
5796
5797         val = vi->rsrv_noflowq;
5798         rc = sysctl_handle_int(oidp, &val, 0, req);
5799         if (rc != 0 || req->newptr == NULL)
5800                 return (rc);
5801
5802         if ((val >= 1) && (vi->ntxq > 1))
5803                 vi->rsrv_noflowq = 1;
5804         else
5805                 vi->rsrv_noflowq = 0;
5806
5807         return (rc);
5808 }
5809
5810 static int
5811 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
5812 {
5813         struct vi_info *vi = arg1;
5814         struct adapter *sc = vi->pi->adapter;
5815         int idx, rc, i;
5816         struct sge_rxq *rxq;
5817 #ifdef TCP_OFFLOAD
5818         struct sge_ofld_rxq *ofld_rxq;
5819 #endif
5820         uint8_t v;
5821
5822         idx = vi->tmr_idx;
5823
5824         rc = sysctl_handle_int(oidp, &idx, 0, req);
5825         if (rc != 0 || req->newptr == NULL)
5826                 return (rc);
5827
5828         if (idx < 0 || idx >= SGE_NTIMERS)
5829                 return (EINVAL);
5830
5831         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
5832             "t4tmr");
5833         if (rc)
5834                 return (rc);
5835
5836         v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
5837         for_each_rxq(vi, i, rxq) {
5838 #ifdef atomic_store_rel_8
5839                 atomic_store_rel_8(&rxq->iq.intr_params, v);
5840 #else
5841                 rxq->iq.intr_params = v;
5842 #endif
5843         }
5844 #ifdef TCP_OFFLOAD
5845         for_each_ofld_rxq(vi, i, ofld_rxq) {
5846 #ifdef atomic_store_rel_8
5847                 atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
5848 #else
5849                 ofld_rxq->iq.intr_params = v;
5850 #endif
5851         }
5852 #endif
5853         vi->tmr_idx = idx;
5854
5855         end_synchronized_op(sc, LOCK_HELD);
5856         return (0);
5857 }
5858
5859 static int
5860 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
5861 {
5862         struct vi_info *vi = arg1;
5863         struct adapter *sc = vi->pi->adapter;
5864         int idx, rc;
5865
5866         idx = vi->pktc_idx;
5867
5868         rc = sysctl_handle_int(oidp, &idx, 0, req);
5869         if (rc != 0 || req->newptr == NULL)
5870                 return (rc);
5871
5872         if (idx < -1 || idx >= SGE_NCOUNTERS)
5873                 return (EINVAL);
5874
5875         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
5876             "t4pktc");
5877         if (rc)
5878                 return (rc);
5879
5880         if (vi->flags & VI_INIT_DONE)
5881                 rc = EBUSY; /* cannot be changed once the queues are created */
5882         else
5883                 vi->pktc_idx = idx;
5884
5885         end_synchronized_op(sc, LOCK_HELD);
5886         return (rc);
5887 }
5888
5889 static int
5890 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
5891 {
5892         struct vi_info *vi = arg1;
5893         struct adapter *sc = vi->pi->adapter;
5894         int qsize, rc;
5895
5896         qsize = vi->qsize_rxq;
5897
5898         rc = sysctl_handle_int(oidp, &qsize, 0, req);
5899         if (rc != 0 || req->newptr == NULL)
5900                 return (rc);
5901
5902         if (qsize < 128 || (qsize & 7))
5903                 return (EINVAL);
5904
5905         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
5906             "t4rxqs");
5907         if (rc)
5908                 return (rc);
5909
5910         if (vi->flags & VI_INIT_DONE)
5911                 rc = EBUSY; /* cannot be changed once the queues are created */
5912         else
5913                 vi->qsize_rxq = qsize;
5914
5915         end_synchronized_op(sc, LOCK_HELD);
5916         return (rc);
5917 }
5918
5919 static int
5920 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
5921 {
5922         struct vi_info *vi = arg1;
5923         struct adapter *sc = vi->pi->adapter;
5924         int qsize, rc;
5925
5926         qsize = vi->qsize_txq;
5927
5928         rc = sysctl_handle_int(oidp, &qsize, 0, req);
5929         if (rc != 0 || req->newptr == NULL)
5930                 return (rc);
5931
5932         if (qsize < 128 || qsize > 65536)
5933                 return (EINVAL);
5934
5935         rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
5936             "t4txqs");
5937         if (rc)
5938                 return (rc);
5939
5940         if (vi->flags & VI_INIT_DONE)
5941                 rc = EBUSY; /* cannot be changed once the queues are created */
5942         else
5943                 vi->qsize_txq = qsize;
5944
5945         end_synchronized_op(sc, LOCK_HELD);
5946         return (rc);
5947 }
5948
5949 static int
5950 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
5951 {
5952         struct port_info *pi = arg1;
5953         struct adapter *sc = pi->adapter;
5954         struct link_config *lc = &pi->link_cfg;
5955         int rc;
5956
5957         if (req->newptr == NULL) {
5958                 struct sbuf *sb;
5959                 static char *bits = "\20\1PAUSE_RX\2PAUSE_TX";
5960
5961                 rc = sysctl_wire_old_buffer(req, 0);
5962                 if (rc != 0)
5963                         return(rc);
5964
5965                 sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
5966                 if (sb == NULL)
5967                         return (ENOMEM);
5968
5969                 sbuf_printf(sb, "%b", lc->fc & (PAUSE_TX | PAUSE_RX), bits);
5970                 rc = sbuf_finish(sb);
5971                 sbuf_delete(sb);
5972         } else {
5973                 char s[2];
5974                 int n;
5975
5976                 s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX));
5977                 s[1] = 0;
5978
5979                 rc = sysctl_handle_string(oidp, s, sizeof(s), req);
5980                 if (rc != 0)
5981                         return(rc);
5982
5983                 if (s[1] != 0)
5984                         return (EINVAL);
5985                 if (s[0] < '0' || s[0] > '9')
5986                         return (EINVAL);        /* not a number */
5987                 n = s[0] - '0';
5988                 if (n & ~(PAUSE_TX | PAUSE_RX))
5989                         return (EINVAL);        /* some other bit is set too */
5990
5991                 rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
5992                     "t4PAUSE");
5993                 if (rc)
5994                         return (rc);
5995                 if ((lc->requested_fc & (PAUSE_TX | PAUSE_RX)) != n) {
5996                         lc->requested_fc &= ~(PAUSE_TX | PAUSE_RX);
5997                         lc->requested_fc |= n;
5998                         rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
5999                         if (rc == 0) {
6000                                 lc->fc = lc->requested_fc;
6001                         }
6002                 }
6003                 end_synchronized_op(sc, 0);
6004         }
6005
6006         return (rc);
6007 }
6008
6009 static int
6010 sysctl_fec(SYSCTL_HANDLER_ARGS)
6011 {
6012         struct port_info *pi = arg1;
6013         struct adapter *sc = pi->adapter;
6014         struct link_config *lc = &pi->link_cfg;
6015         int rc;
6016
6017         if (req->newptr == NULL) {
6018                 struct sbuf *sb;
6019                 static char *bits = "\20\1RS\2BASER_RS\3RESERVED";
6020
6021                 rc = sysctl_wire_old_buffer(req, 0);
6022                 if (rc != 0)
6023                         return(rc);
6024
6025                 sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
6026                 if (sb == NULL)
6027                         return (ENOMEM);
6028
6029                 sbuf_printf(sb, "%b", lc->fec & M_FW_PORT_CAP_FEC, bits);
6030                 rc = sbuf_finish(sb);
6031                 sbuf_delete(sb);
6032         } else {
6033                 char s[2];
6034                 int n;
6035
6036                 s[0] = '0' + (lc->requested_fec & M_FW_PORT_CAP_FEC);
6037                 s[1] = 0;
6038
6039                 rc = sysctl_handle_string(oidp, s, sizeof(s), req);
6040                 if (rc != 0)
6041                         return(rc);
6042
6043                 if (s[1] != 0)
6044                         return (EINVAL);
6045                 if (s[0] < '0' || s[0] > '9')
6046                         return (EINVAL);        /* not a number */
6047                 n = s[0] - '0';
6048                 if (n & ~M_FW_PORT_CAP_FEC)
6049                         return (EINVAL);        /* some other bit is set too */
6050
6051                 rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
6052                     "t4fec");
6053                 if (rc)
6054                         return (rc);
6055                 if ((lc->requested_fec & M_FW_PORT_CAP_FEC) != n) {
6056                         lc->requested_fec = n &
6057                             G_FW_PORT_CAP_FEC(lc->supported);
6058                         rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6059                         if (rc == 0) {
6060                                 lc->fec = lc->requested_fec;
6061                         }
6062                 }
6063                 end_synchronized_op(sc, 0);
6064         }
6065
6066         return (rc);
6067 }
6068
6069 static int
6070 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
6071 {
6072         struct port_info *pi = arg1;
6073         struct adapter *sc = pi->adapter;
6074         struct link_config *lc = &pi->link_cfg;
6075         int rc, val, old;
6076
6077         if (lc->supported & FW_PORT_CAP_ANEG)
6078                 val = lc->requested_aneg == AUTONEG_ENABLE ? 1 : 0;
6079         else
6080                 val = -1;
6081         rc = sysctl_handle_int(oidp, &val, 0, req);
6082         if (rc != 0 || req->newptr == NULL)
6083                 return (rc);
6084         if ((lc->supported & FW_PORT_CAP_ANEG) == 0)
6085                 return (ENOTSUP);
6086
6087         if (val == 0)
6088                 val = AUTONEG_DISABLE;
6089         else if (val == 1)
6090                 val = AUTONEG_ENABLE;
6091         else
6092                 return (EINVAL);
6093         if (lc->requested_aneg == val)
6094                 return (0);     /* no change */
6095
6096         rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
6097             "t4aneg");
6098         if (rc)
6099                 return (rc);
6100         old = lc->requested_aneg;
6101         lc->requested_aneg = val;
6102         rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6103         if (rc != 0)
6104                 lc->requested_aneg = old;
6105         end_synchronized_op(sc, 0);
6106         return (rc);
6107 }
6108
6109 static int
6110 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
6111 {
6112         struct adapter *sc = arg1;
6113         int reg = arg2;
6114         uint64_t val;
6115
6116         val = t4_read_reg64(sc, reg);
6117
6118         return (sysctl_handle_64(oidp, &val, 0, req));
6119 }
6120
6121 static int
6122 sysctl_temperature(SYSCTL_HANDLER_ARGS)
6123 {
6124         struct adapter *sc = arg1;
6125         int rc, t;
6126         uint32_t param, val;
6127
6128         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
6129         if (rc)
6130                 return (rc);
6131         param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
6132             V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
6133             V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
6134         rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
6135         end_synchronized_op(sc, 0);
6136         if (rc)
6137                 return (rc);
6138
6139         /* unknown is returned as 0 but we display -1 in that case */
6140         t = val == 0 ? -1 : val;
6141
6142         rc = sysctl_handle_int(oidp, &t, 0, req);
6143         return (rc);
6144 }
6145
6146 #ifdef SBUF_DRAIN
6147 static int
6148 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
6149 {
6150         struct adapter *sc = arg1;
6151         struct sbuf *sb;
6152         int rc, i;
6153         uint16_t incr[NMTUS][NCCTRL_WIN];
6154         static const char *dec_fac[] = {
6155                 "0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
6156                 "0.9375"
6157         };
6158
6159         rc = sysctl_wire_old_buffer(req, 0);
6160         if (rc != 0)
6161                 return (rc);
6162
6163         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6164         if (sb == NULL)
6165                 return (ENOMEM);
6166
6167         t4_read_cong_tbl(sc, incr);
6168
6169         for (i = 0; i < NCCTRL_WIN; ++i) {
6170                 sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
6171                     incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
6172                     incr[5][i], incr[6][i], incr[7][i]);
6173                 sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
6174                     incr[8][i], incr[9][i], incr[10][i], incr[11][i],
6175                     incr[12][i], incr[13][i], incr[14][i], incr[15][i],
6176                     sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
6177         }
6178
6179         rc = sbuf_finish(sb);
6180         sbuf_delete(sb);
6181
6182         return (rc);
6183 }
6184
6185 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
6186         "TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",   /* ibq's */
6187         "ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI", /* obq's */
6188         "SGE0-RX", "SGE1-RX"    /* additional obq's (T5 onwards) */
6189 };
6190
6191 static int
6192 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
6193 {
6194         struct adapter *sc = arg1;
6195         struct sbuf *sb;
6196         int rc, i, n, qid = arg2;
6197         uint32_t *buf, *p;
6198         char *qtype;
6199         u_int cim_num_obq = sc->chip_params->cim_num_obq;
6200
6201         KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
6202             ("%s: bad qid %d\n", __func__, qid));
6203
6204         if (qid < CIM_NUM_IBQ) {
6205                 /* inbound queue */
6206                 qtype = "IBQ";
6207                 n = 4 * CIM_IBQ_SIZE;
6208                 buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
6209                 rc = t4_read_cim_ibq(sc, qid, buf, n);
6210         } else {
6211                 /* outbound queue */
6212                 qtype = "OBQ";
6213                 qid -= CIM_NUM_IBQ;
6214                 n = 4 * cim_num_obq * CIM_OBQ_SIZE;
6215                 buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
6216                 rc = t4_read_cim_obq(sc, qid, buf, n);
6217         }
6218
6219         if (rc < 0) {
6220                 rc = -rc;
6221                 goto done;
6222         }
6223         n = rc * sizeof(uint32_t);      /* rc has # of words actually read */
6224
6225         rc = sysctl_wire_old_buffer(req, 0);
6226         if (rc != 0)
6227                 goto done;
6228
6229         sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
6230         if (sb == NULL) {
6231                 rc = ENOMEM;
6232                 goto done;
6233         }
6234
6235         sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
6236         for (i = 0, p = buf; i < n; i += 16, p += 4)
6237                 sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
6238                     p[2], p[3]);
6239
6240         rc = sbuf_finish(sb);
6241         sbuf_delete(sb);
6242 done:
6243         free(buf, M_CXGBE);
6244         return (rc);
6245 }
6246
6247 static int
6248 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
6249 {
6250         struct adapter *sc = arg1;
6251         u_int cfg;
6252         struct sbuf *sb;
6253         uint32_t *buf, *p;
6254         int rc;
6255
6256         MPASS(chip_id(sc) <= CHELSIO_T5);
6257
6258         rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
6259         if (rc != 0)
6260                 return (rc);
6261
6262         rc = sysctl_wire_old_buffer(req, 0);
6263         if (rc != 0)
6264                 return (rc);
6265
6266         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6267         if (sb == NULL)
6268                 return (ENOMEM);
6269
6270         buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
6271             M_ZERO | M_WAITOK);
6272
6273         rc = -t4_cim_read_la(sc, buf, NULL);
6274         if (rc != 0)
6275                 goto done;
6276
6277         sbuf_printf(sb, "Status   Data      PC%s",
6278             cfg & F_UPDBGLACAPTPCONLY ? "" :
6279             "     LS0Stat  LS0Addr             LS0Data");
6280
6281         for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
6282                 if (cfg & F_UPDBGLACAPTPCONLY) {
6283                         sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
6284                             p[6], p[7]);
6285                         sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
6286                             (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
6287                             p[4] & 0xff, p[5] >> 8);
6288                         sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
6289                             (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
6290                             p[1] & 0xf, p[2] >> 4);
6291                 } else {
6292                         sbuf_printf(sb,
6293                             "\n  %02x   %x%07x %x%07x %08x %08x "
6294                             "%08x%08x%08x%08x",
6295                             (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
6296                             p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
6297                             p[6], p[7]);
6298                 }
6299         }
6300
6301         rc = sbuf_finish(sb);
6302         sbuf_delete(sb);
6303 done:
6304         free(buf, M_CXGBE);
6305         return (rc);
6306 }
6307
6308 static int
6309 sysctl_cim_la_t6(SYSCTL_HANDLER_ARGS)
6310 {
6311         struct adapter *sc = arg1;
6312         u_int cfg;
6313         struct sbuf *sb;
6314         uint32_t *buf, *p;
6315         int rc;
6316
6317         MPASS(chip_id(sc) > CHELSIO_T5);
6318
6319         rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
6320         if (rc != 0)
6321                 return (rc);
6322
6323         rc = sysctl_wire_old_buffer(req, 0);
6324         if (rc != 0)
6325                 return (rc);
6326
6327         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6328         if (sb == NULL)
6329                 return (ENOMEM);
6330
6331         buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
6332             M_ZERO | M_WAITOK);
6333
6334         rc = -t4_cim_read_la(sc, buf, NULL);
6335         if (rc != 0)
6336                 goto done;
6337
6338         sbuf_printf(sb, "Status   Inst    Data      PC%s",
6339             cfg & F_UPDBGLACAPTPCONLY ? "" :
6340             "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
6341
6342         for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
6343                 if (cfg & F_UPDBGLACAPTPCONLY) {
6344                         sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
6345                             p[3] & 0xff, p[2], p[1], p[0]);
6346                         sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
6347                             (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
6348                             p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
6349                         sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
6350                             (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
6351                             p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
6352                             p[6] >> 16);
6353                 } else {
6354                         sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
6355                             "%08x %08x %08x %08x %08x %08x",
6356                             (p[9] >> 16) & 0xff,
6357                             p[9] & 0xffff, p[8] >> 16,
6358                             p[8] & 0xffff, p[7] >> 16,
6359                             p[7] & 0xffff, p[6] >> 16,
6360                             p[2], p[1], p[0], p[5], p[4], p[3]);
6361                 }
6362         }
6363
6364         rc = sbuf_finish(sb);
6365         sbuf_delete(sb);
6366 done:
6367         free(buf, M_CXGBE);
6368         return (rc);
6369 }
6370
6371 static int
6372 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
6373 {
6374         struct adapter *sc = arg1;
6375         u_int i;
6376         struct sbuf *sb;
6377         uint32_t *buf, *p;
6378         int rc;
6379
6380         rc = sysctl_wire_old_buffer(req, 0);
6381         if (rc != 0)
6382                 return (rc);
6383
6384         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6385         if (sb == NULL)
6386                 return (ENOMEM);
6387
6388         buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
6389             M_ZERO | M_WAITOK);
6390
6391         t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
6392         p = buf;
6393
6394         for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
6395                 sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
6396                     p[1], p[0]);
6397         }
6398
6399         sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
6400         for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
6401                 sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
6402                     (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
6403                     (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
6404                     (p[1] >> 2) | ((p[2] & 3) << 30),
6405                     (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
6406                     p[0] & 1);
6407         }
6408
6409         rc = sbuf_finish(sb);
6410         sbuf_delete(sb);
6411         free(buf, M_CXGBE);
6412         return (rc);
6413 }
6414
6415 static int
6416 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
6417 {
6418         struct adapter *sc = arg1;
6419         u_int i;
6420         struct sbuf *sb;
6421         uint32_t *buf, *p;
6422         int rc;
6423
6424         rc = sysctl_wire_old_buffer(req, 0);
6425         if (rc != 0)
6426                 return (rc);
6427
6428         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6429         if (sb == NULL)
6430                 return (ENOMEM);
6431
6432         buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
6433             M_ZERO | M_WAITOK);
6434
6435         t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
6436         p = buf;
6437
6438         sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
6439         for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
6440                 sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
6441                     (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
6442                     p[4], p[3], p[2], p[1], p[0]);
6443         }
6444
6445         sbuf_printf(sb, "\n\nCntl ID               Data");
6446         for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
6447                 sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
6448                     (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
6449         }
6450
6451         rc = sbuf_finish(sb);
6452         sbuf_delete(sb);
6453         free(buf, M_CXGBE);
6454         return (rc);
6455 }
6456
6457 static int
6458 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
6459 {
6460         struct adapter *sc = arg1;
6461         struct sbuf *sb;
6462         int rc, i;
6463         uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
6464         uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
6465         uint16_t thres[CIM_NUM_IBQ];
6466         uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
6467         uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
6468         u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
6469
6470         cim_num_obq = sc->chip_params->cim_num_obq;
6471         if (is_t4(sc)) {
6472                 ibq_rdaddr = A_UP_IBQ_0_RDADDR;
6473                 obq_rdaddr = A_UP_OBQ_0_REALADDR;
6474         } else {
6475                 ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
6476                 obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
6477         }
6478         nq = CIM_NUM_IBQ + cim_num_obq;
6479
6480         rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
6481         if (rc == 0)
6482                 rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq, obq_wr);
6483         if (rc != 0)
6484                 return (rc);
6485
6486         t4_read_cimq_cfg(sc, base, size, thres);
6487
6488         rc = sysctl_wire_old_buffer(req, 0);
6489         if (rc != 0)
6490                 return (rc);
6491
6492         sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
6493         if (sb == NULL)
6494                 return (ENOMEM);
6495
6496         sbuf_printf(sb,
6497             "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
6498
6499         for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
6500                 sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
6501                     qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
6502                     G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
6503                     G_QUEREMFLITS(p[2]) * 16);
6504         for ( ; i < nq; i++, p += 4, wr += 2)
6505                 sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
6506                     base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
6507                     wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
6508                     G_QUEREMFLITS(p[2]) * 16);
6509
6510         rc = sbuf_finish(sb);
6511         sbuf_delete(sb);
6512
6513         return (rc);
6514 }
6515
6516 static int
6517 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
6518 {
6519         struct adapter *sc = arg1;
6520         struct sbuf *sb;
6521         int rc;
6522         struct tp_cpl_stats stats;
6523
6524         rc = sysctl_wire_old_buffer(req, 0);
6525         if (rc != 0)
6526                 return (rc);
6527
6528         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6529         if (sb == NULL)
6530                 return (ENOMEM);
6531
6532         mtx_lock(&sc->reg_lock);
6533         t4_tp_get_cpl_stats(sc, &stats, 0);
6534         mtx_unlock(&sc->reg_lock);
6535
6536         if (sc->chip_params->nchan > 2) {
6537                 sbuf_printf(sb, "                 channel 0  channel 1"
6538                     "  channel 2  channel 3");
6539                 sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
6540                     stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
6541                 sbuf_printf(sb, "\nCPL responses:   %10u %10u %10u %10u",
6542                     stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
6543         } else {
6544                 sbuf_printf(sb, "                 channel 0  channel 1");
6545                 sbuf_printf(sb, "\nCPL requests:   %10u %10u",
6546                     stats.req[0], stats.req[1]);
6547                 sbuf_printf(sb, "\nCPL responses:   %10u %10u",
6548                     stats.rsp[0], stats.rsp[1]);
6549         }
6550
6551         rc = sbuf_finish(sb);
6552         sbuf_delete(sb);
6553
6554         return (rc);
6555 }
6556
6557 static int
6558 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
6559 {
6560         struct adapter *sc = arg1;
6561         struct sbuf *sb;
6562         int rc;
6563         struct tp_usm_stats stats;
6564
6565         rc = sysctl_wire_old_buffer(req, 0);
6566         if (rc != 0)
6567                 return(rc);
6568
6569         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6570         if (sb == NULL)
6571                 return (ENOMEM);
6572
6573         t4_get_usm_stats(sc, &stats, 1);
6574
6575         sbuf_printf(sb, "Frames: %u\n", stats.frames);
6576         sbuf_printf(sb, "Octets: %ju\n", stats.octets);
6577         sbuf_printf(sb, "Drops:  %u", stats.drops);
6578
6579         rc = sbuf_finish(sb);
6580         sbuf_delete(sb);
6581
6582         return (rc);
6583 }
6584
6585 static const char * const devlog_level_strings[] = {
6586         [FW_DEVLOG_LEVEL_EMERG]         = "EMERG",
6587         [FW_DEVLOG_LEVEL_CRIT]          = "CRIT",
6588         [FW_DEVLOG_LEVEL_ERR]           = "ERR",
6589         [FW_DEVLOG_LEVEL_NOTICE]        = "NOTICE",
6590         [FW_DEVLOG_LEVEL_INFO]          = "INFO",
6591         [FW_DEVLOG_LEVEL_DEBUG]         = "DEBUG"
6592 };
6593
6594 static const char * const devlog_facility_strings[] = {
6595         [FW_DEVLOG_FACILITY_CORE]       = "CORE",
6596         [FW_DEVLOG_FACILITY_CF]         = "CF",
6597         [FW_DEVLOG_FACILITY_SCHED]      = "SCHED",
6598         [FW_DEVLOG_FACILITY_TIMER]      = "TIMER",
6599         [FW_DEVLOG_FACILITY_RES]        = "RES",
6600         [FW_DEVLOG_FACILITY_HW]         = "HW",
6601         [FW_DEVLOG_FACILITY_FLR]        = "FLR",
6602         [FW_DEVLOG_FACILITY_DMAQ]       = "DMAQ",
6603         [FW_DEVLOG_FACILITY_PHY]        = "PHY",
6604         [FW_DEVLOG_FACILITY_MAC]        = "MAC",
6605         [FW_DEVLOG_FACILITY_PORT]       = "PORT",
6606         [FW_DEVLOG_FACILITY_VI]         = "VI",
6607         [FW_DEVLOG_FACILITY_FILTER]     = "FILTER",
6608         [FW_DEVLOG_FACILITY_ACL]        = "ACL",
6609         [FW_DEVLOG_FACILITY_TM]         = "TM",
6610         [FW_DEVLOG_FACILITY_QFC]        = "QFC",
6611         [FW_DEVLOG_FACILITY_DCB]        = "DCB",
6612         [FW_DEVLOG_FACILITY_ETH]        = "ETH",
6613         [FW_DEVLOG_FACILITY_OFLD]       = "OFLD",
6614         [FW_DEVLOG_FACILITY_RI]         = "RI",
6615         [FW_DEVLOG_FACILITY_ISCSI]      = "ISCSI",
6616         [FW_DEVLOG_FACILITY_FCOE]       = "FCOE",
6617         [FW_DEVLOG_FACILITY_FOISCSI]    = "FOISCSI",
6618         [FW_DEVLOG_FACILITY_FOFCOE]     = "FOFCOE",
6619         [FW_DEVLOG_FACILITY_CHNET]      = "CHNET",
6620 };
6621
6622 static int
6623 sysctl_devlog(SYSCTL_HANDLER_ARGS)
6624 {
6625         struct adapter *sc = arg1;
6626         struct devlog_params *dparams = &sc->params.devlog;
6627         struct fw_devlog_e *buf, *e;
6628         int i, j, rc, nentries, first = 0;
6629         struct sbuf *sb;
6630         uint64_t ftstamp = UINT64_MAX;
6631
6632         if (dparams->addr == 0)
6633                 return (ENXIO);
6634
6635         buf = malloc(dparams->size, M_CXGBE, M_NOWAIT);
6636         if (buf == NULL)
6637                 return (ENOMEM);
6638
6639         rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf, dparams->size);
6640         if (rc != 0)
6641                 goto done;
6642
6643         nentries = dparams->size / sizeof(struct fw_devlog_e);
6644         for (i = 0; i < nentries; i++) {
6645                 e = &buf[i];
6646
6647                 if (e->timestamp == 0)
6648                         break;  /* end */
6649
6650                 e->timestamp = be64toh(e->timestamp);
6651                 e->seqno = be32toh(e->seqno);
6652                 for (j = 0; j < 8; j++)
6653                         e->params[j] = be32toh(e->params[j]);
6654
6655                 if (e->timestamp < ftstamp) {
6656                         ftstamp = e->timestamp;
6657                         first = i;
6658                 }
6659         }
6660
6661         if (buf[first].timestamp == 0)
6662                 goto done;      /* nothing in the log */
6663
6664         rc = sysctl_wire_old_buffer(req, 0);
6665         if (rc != 0)
6666                 goto done;
6667
6668         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6669         if (sb == NULL) {
6670                 rc = ENOMEM;
6671                 goto done;
6672         }
6673         sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
6674             "Seq#", "Tstamp", "Level", "Facility", "Message");
6675
6676         i = first;
6677         do {
6678                 e = &buf[i];
6679                 if (e->timestamp == 0)
6680                         break;  /* end */
6681
6682                 sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
6683                     e->seqno, e->timestamp,
6684                     (e->level < nitems(devlog_level_strings) ?
6685                         devlog_level_strings[e->level] : "UNKNOWN"),
6686                     (e->facility < nitems(devlog_facility_strings) ?
6687                         devlog_facility_strings[e->facility] : "UNKNOWN"));
6688                 sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
6689                     e->params[2], e->params[3], e->params[4],
6690                     e->params[5], e->params[6], e->params[7]);
6691
6692                 if (++i == nentries)
6693                         i = 0;
6694         } while (i != first);
6695
6696         rc = sbuf_finish(sb);
6697         sbuf_delete(sb);
6698 done:
6699         free(buf, M_CXGBE);
6700         return (rc);
6701 }
6702
6703 static int
6704 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
6705 {
6706         struct adapter *sc = arg1;
6707         struct sbuf *sb;
6708         int rc;
6709         struct tp_fcoe_stats stats[MAX_NCHAN];
6710         int i, nchan = sc->chip_params->nchan;
6711
6712         rc = sysctl_wire_old_buffer(req, 0);
6713         if (rc != 0)
6714                 return (rc);
6715
6716         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6717         if (sb == NULL)
6718                 return (ENOMEM);
6719
6720         for (i = 0; i < nchan; i++)
6721                 t4_get_fcoe_stats(sc, i, &stats[i], 1);
6722
6723         if (nchan > 2) {
6724                 sbuf_printf(sb, "                   channel 0        channel 1"
6725                     "        channel 2        channel 3");
6726                 sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
6727                     stats[0].octets_ddp, stats[1].octets_ddp,
6728                     stats[2].octets_ddp, stats[3].octets_ddp);
6729                 sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
6730                     stats[0].frames_ddp, stats[1].frames_ddp,
6731                     stats[2].frames_ddp, stats[3].frames_ddp);
6732                 sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
6733                     stats[0].frames_drop, stats[1].frames_drop,
6734                     stats[2].frames_drop, stats[3].frames_drop);
6735         } else {
6736                 sbuf_printf(sb, "                   channel 0        channel 1");
6737                 sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
6738                     stats[0].octets_ddp, stats[1].octets_ddp);
6739                 sbuf_printf(sb, "\nframesDDP:  %16u %16u",
6740                     stats[0].frames_ddp, stats[1].frames_ddp);
6741                 sbuf_printf(sb, "\nframesDrop: %16u %16u",
6742                     stats[0].frames_drop, stats[1].frames_drop);
6743         }
6744
6745         rc = sbuf_finish(sb);
6746         sbuf_delete(sb);
6747
6748         return (rc);
6749 }
6750
6751 static int
6752 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
6753 {
6754         struct adapter *sc = arg1;
6755         struct sbuf *sb;
6756         int rc, i;
6757         unsigned int map, kbps, ipg, mode;
6758         unsigned int pace_tab[NTX_SCHED];
6759
6760         rc = sysctl_wire_old_buffer(req, 0);
6761         if (rc != 0)
6762                 return (rc);
6763
6764         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6765         if (sb == NULL)
6766                 return (ENOMEM);
6767
6768         map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
6769         mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
6770         t4_read_pace_tbl(sc, pace_tab);
6771
6772         sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
6773             "Class IPG (0.1 ns)   Flow IPG (us)");
6774
6775         for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
6776                 t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
6777                 sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
6778                     (mode & (1 << i)) ? "flow" : "class", map & 3);
6779                 if (kbps)
6780                         sbuf_printf(sb, "%9u     ", kbps);
6781                 else
6782                         sbuf_printf(sb, " disabled     ");
6783
6784                 if (ipg)
6785                         sbuf_printf(sb, "%13u        ", ipg);
6786                 else
6787                         sbuf_printf(sb, "     disabled        ");
6788
6789                 if (pace_tab[i])
6790                         sbuf_printf(sb, "%10u", pace_tab[i]);
6791                 else
6792                         sbuf_printf(sb, "  disabled");
6793         }
6794
6795         rc = sbuf_finish(sb);
6796         sbuf_delete(sb);
6797
6798         return (rc);
6799 }
6800
6801 static int
6802 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
6803 {
6804         struct adapter *sc = arg1;
6805         struct sbuf *sb;
6806         int rc, i, j;
6807         uint64_t *p0, *p1;
6808         struct lb_port_stats s[2];
6809         static const char *stat_name[] = {
6810                 "OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
6811                 "UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
6812                 "Frames128To255:", "Frames256To511:", "Frames512To1023:",
6813                 "Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
6814                 "BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
6815                 "BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
6816                 "BG2FramesTrunc:", "BG3FramesTrunc:"
6817         };
6818
6819         rc = sysctl_wire_old_buffer(req, 0);
6820         if (rc != 0)
6821                 return (rc);
6822
6823         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6824         if (sb == NULL)
6825                 return (ENOMEM);
6826
6827         memset(s, 0, sizeof(s));
6828
6829         for (i = 0; i < sc->chip_params->nchan; i += 2) {
6830                 t4_get_lb_stats(sc, i, &s[0]);
6831                 t4_get_lb_stats(sc, i + 1, &s[1]);
6832
6833                 p0 = &s[0].octets;
6834                 p1 = &s[1].octets;
6835                 sbuf_printf(sb, "%s                       Loopback %u"
6836                     "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
6837
6838                 for (j = 0; j < nitems(stat_name); j++)
6839                         sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
6840                                    *p0++, *p1++);
6841         }
6842
6843         rc = sbuf_finish(sb);
6844         sbuf_delete(sb);
6845
6846         return (rc);
6847 }
6848
6849 static int
6850 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
6851 {
6852         int rc = 0;
6853         struct port_info *pi = arg1;
6854         struct link_config *lc = &pi->link_cfg;
6855         struct sbuf *sb;
6856
6857         rc = sysctl_wire_old_buffer(req, 0);
6858         if (rc != 0)
6859                 return(rc);
6860         sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
6861         if (sb == NULL)
6862                 return (ENOMEM);
6863
6864         if (lc->link_ok || lc->link_down_rc == 255)
6865                 sbuf_printf(sb, "n/a");
6866         else
6867                 sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
6868
6869         rc = sbuf_finish(sb);
6870         sbuf_delete(sb);
6871
6872         return (rc);
6873 }
6874
6875 struct mem_desc {
6876         unsigned int base;
6877         unsigned int limit;
6878         unsigned int idx;
6879 };
6880
6881 static int
6882 mem_desc_cmp(const void *a, const void *b)
6883 {
6884         return ((const struct mem_desc *)a)->base -
6885                ((const struct mem_desc *)b)->base;
6886 }
6887
6888 static void
6889 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
6890     unsigned int to)
6891 {
6892         unsigned int size;
6893
6894         if (from == to)
6895                 return;
6896
6897         size = to - from + 1;
6898         if (size == 0)
6899                 return;
6900
6901         /* XXX: need humanize_number(3) in libkern for a more readable 'size' */
6902         sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
6903 }
6904
6905 static int
6906 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
6907 {
6908         struct adapter *sc = arg1;
6909         struct sbuf *sb;
6910         int rc, i, n;
6911         uint32_t lo, hi, used, alloc;
6912         static const char *memory[] = {"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:"};
6913         static const char *region[] = {
6914                 "DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
6915                 "Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
6916                 "Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
6917                 "TDDP region:", "TPT region:", "STAG region:", "RQ region:",
6918                 "RQUDP region:", "PBL region:", "TXPBL region:",
6919                 "DBVFIFO region:", "ULPRX state:", "ULPTX state:",
6920                 "On-chip queues:"
6921         };
6922         struct mem_desc avail[4];
6923         struct mem_desc mem[nitems(region) + 3];        /* up to 3 holes */
6924         struct mem_desc *md = mem;
6925
6926         rc = sysctl_wire_old_buffer(req, 0);
6927         if (rc != 0)
6928                 return (rc);
6929
6930         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6931         if (sb == NULL)
6932                 return (ENOMEM);
6933
6934         for (i = 0; i < nitems(mem); i++) {
6935                 mem[i].limit = 0;
6936                 mem[i].idx = i;
6937         }
6938
6939         /* Find and sort the populated memory ranges */
6940         i = 0;
6941         lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
6942         if (lo & F_EDRAM0_ENABLE) {
6943                 hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
6944                 avail[i].base = G_EDRAM0_BASE(hi) << 20;
6945                 avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
6946                 avail[i].idx = 0;
6947                 i++;
6948         }
6949         if (lo & F_EDRAM1_ENABLE) {
6950                 hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
6951                 avail[i].base = G_EDRAM1_BASE(hi) << 20;
6952                 avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
6953                 avail[i].idx = 1;
6954                 i++;
6955         }
6956         if (lo & F_EXT_MEM_ENABLE) {
6957                 hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
6958                 avail[i].base = G_EXT_MEM_BASE(hi) << 20;
6959                 avail[i].limit = avail[i].base +
6960                     (G_EXT_MEM_SIZE(hi) << 20);
6961                 avail[i].idx = is_t5(sc) ? 3 : 2;       /* Call it MC0 for T5 */
6962                 i++;
6963         }
6964         if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
6965                 hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
6966                 avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
6967                 avail[i].limit = avail[i].base +
6968                     (G_EXT_MEM1_SIZE(hi) << 20);
6969                 avail[i].idx = 4;
6970                 i++;
6971         }
6972         if (!i)                                    /* no memory available */
6973                 return 0;
6974         qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
6975
6976         (md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
6977         (md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
6978         (md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
6979         (md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
6980         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
6981         (md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
6982         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
6983         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
6984         (md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
6985
6986         /* the next few have explicit upper bounds */
6987         md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
6988         md->limit = md->base - 1 +
6989                     t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
6990                     G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
6991         md++;
6992
6993         md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
6994         md->limit = md->base - 1 +
6995                     t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
6996                     G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
6997         md++;
6998
6999         if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
7000                 if (chip_id(sc) <= CHELSIO_T5)
7001                         md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
7002                 else
7003                         md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
7004                 md->limit = 0;
7005         } else {
7006                 md->base = 0;
7007                 md->idx = nitems(region);  /* hide it */
7008         }
7009         md++;
7010
7011 #define ulp_region(reg) \
7012         md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
7013         (md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
7014
7015         ulp_region(RX_ISCSI);
7016         ulp_region(RX_TDDP);
7017         ulp_region(TX_TPT);
7018         ulp_region(RX_STAG);
7019         ulp_region(RX_RQ);
7020         ulp_region(RX_RQUDP);
7021         ulp_region(RX_PBL);
7022         ulp_region(TX_PBL);
7023 #undef ulp_region
7024
7025         md->base = 0;
7026         md->idx = nitems(region);
7027         if (!is_t4(sc)) {
7028                 uint32_t size = 0;
7029                 uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
7030                 uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
7031
7032                 if (is_t5(sc)) {
7033                         if (sge_ctrl & F_VFIFO_ENABLE)
7034                                 size = G_DBVFIFO_SIZE(fifo_size);
7035                 } else
7036                         size = G_T6_DBVFIFO_SIZE(fifo_size);
7037
7038                 if (size) {
7039                         md->base = G_BASEADDR(t4_read_reg(sc,
7040                             A_SGE_DBVFIFO_BADDR));
7041                         md->limit = md->base + (size << 2) - 1;
7042                 }
7043         }
7044         md++;
7045
7046         md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
7047         md->limit = 0;
7048         md++;
7049         md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
7050         md->limit = 0;
7051         md++;
7052
7053         md->base = sc->vres.ocq.start;
7054         if (sc->vres.ocq.size)
7055                 md->limit = md->base + sc->vres.ocq.size - 1;
7056         else
7057                 md->idx = nitems(region);  /* hide it */
7058         md++;
7059
7060         /* add any address-space holes, there can be up to 3 */
7061         for (n = 0; n < i - 1; n++)
7062                 if (avail[n].limit < avail[n + 1].base)
7063                         (md++)->base = avail[n].limit;
7064         if (avail[n].limit)
7065                 (md++)->base = avail[n].limit;
7066
7067         n = md - mem;
7068         qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
7069
7070         for (lo = 0; lo < i; lo++)
7071                 mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
7072                                 avail[lo].limit - 1);
7073
7074         sbuf_printf(sb, "\n");
7075         for (i = 0; i < n; i++) {
7076                 if (mem[i].idx >= nitems(region))
7077                         continue;                        /* skip holes */
7078                 if (!mem[i].limit)
7079                         mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
7080                 mem_region_show(sb, region[mem[i].idx], mem[i].base,
7081                                 mem[i].limit);
7082         }
7083
7084         sbuf_printf(sb, "\n");
7085         lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
7086         hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
7087         mem_region_show(sb, "uP RAM:", lo, hi);
7088
7089         lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
7090         hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
7091         mem_region_show(sb, "uP Extmem2:", lo, hi);
7092
7093         lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
7094         sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
7095                    G_PMRXMAXPAGE(lo),
7096                    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
7097                    (lo & F_PMRXNUMCHN) ? 2 : 1);
7098
7099         lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
7100         hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
7101         sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
7102                    G_PMTXMAXPAGE(lo),
7103                    hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
7104                    hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
7105         sbuf_printf(sb, "%u p-structs\n",
7106                    t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
7107
7108         for (i = 0; i < 4; i++) {
7109                 if (chip_id(sc) > CHELSIO_T5)
7110                         lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
7111                 else
7112                         lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
7113                 if (is_t5(sc)) {
7114                         used = G_T5_USED(lo);
7115                         alloc = G_T5_ALLOC(lo);
7116                 } else {
7117                         used = G_USED(lo);
7118                         alloc = G_ALLOC(lo);
7119                 }
7120                 /* For T6 these are MAC buffer groups */
7121                 sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
7122                     i, used, alloc);
7123         }
7124         for (i = 0; i < sc->chip_params->nchan; i++) {
7125                 if (chip_id(sc) > CHELSIO_T5)
7126                         lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
7127                 else
7128                         lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
7129                 if (is_t5(sc)) {
7130                         used = G_T5_USED(lo);
7131                         alloc = G_T5_ALLOC(lo);
7132                 } else {
7133                         used = G_USED(lo);
7134                         alloc = G_ALLOC(lo);
7135                 }
7136                 /* For T6 these are MAC buffer groups */
7137                 sbuf_printf(sb,
7138                     "\nLoopback %d using %u pages out of %u allocated",
7139                     i, used, alloc);
7140         }
7141
7142         rc = sbuf_finish(sb);
7143         sbuf_delete(sb);
7144
7145         return (rc);
7146 }
7147
7148 static inline void
7149 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
7150 {
7151         *mask = x | y;
7152         y = htobe64(y);
7153         memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
7154 }
7155
7156 static int
7157 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
7158 {
7159         struct adapter *sc = arg1;
7160         struct sbuf *sb;
7161         int rc, i;
7162
7163         MPASS(chip_id(sc) <= CHELSIO_T5);
7164
7165         rc = sysctl_wire_old_buffer(req, 0);
7166         if (rc != 0)
7167                 return (rc);
7168
7169         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7170         if (sb == NULL)
7171                 return (ENOMEM);
7172
7173         sbuf_printf(sb,
7174             "Idx  Ethernet address     Mask     Vld Ports PF"
7175             "  VF              Replication             P0 P1 P2 P3  ML");
7176         for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
7177                 uint64_t tcamx, tcamy, mask;
7178                 uint32_t cls_lo, cls_hi;
7179                 uint8_t addr[ETHER_ADDR_LEN];
7180
7181                 tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
7182                 tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
7183                 if (tcamx & tcamy)
7184                         continue;
7185                 tcamxy2valmask(tcamx, tcamy, addr, &mask);
7186                 cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
7187                 cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
7188                 sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
7189                            "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
7190                            addr[3], addr[4], addr[5], (uintmax_t)mask,
7191                            (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
7192                            G_PORTMAP(cls_hi), G_PF(cls_lo),
7193                            (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
7194
7195                 if (cls_lo & F_REPLICATE) {
7196                         struct fw_ldst_cmd ldst_cmd;
7197
7198                         memset(&ldst_cmd, 0, sizeof(ldst_cmd));
7199                         ldst_cmd.op_to_addrspace =
7200                             htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
7201                                 F_FW_CMD_REQUEST | F_FW_CMD_READ |
7202                                 V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
7203                         ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
7204                         ldst_cmd.u.mps.rplc.fid_idx =
7205                             htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
7206                                 V_FW_LDST_CMD_IDX(i));
7207
7208                         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
7209                             "t4mps");
7210                         if (rc)
7211                                 break;
7212                         rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
7213                             sizeof(ldst_cmd), &ldst_cmd);
7214                         end_synchronized_op(sc, 0);
7215
7216                         if (rc != 0) {
7217                                 sbuf_printf(sb, "%36d", rc);
7218                                 rc = 0;
7219                         } else {
7220                                 sbuf_printf(sb, " %08x %08x %08x %08x",
7221                                     be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
7222                                     be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
7223                                     be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
7224                                     be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
7225                         }
7226                 } else
7227                         sbuf_printf(sb, "%36s", "");
7228
7229                 sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
7230                     G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
7231                     G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
7232         }
7233
7234         if (rc)
7235                 (void) sbuf_finish(sb);
7236         else
7237                 rc = sbuf_finish(sb);
7238         sbuf_delete(sb);
7239
7240         return (rc);
7241 }
7242
7243 static int
7244 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
7245 {
7246         struct adapter *sc = arg1;
7247         struct sbuf *sb;
7248         int rc, i;
7249
7250         MPASS(chip_id(sc) > CHELSIO_T5);
7251
7252         rc = sysctl_wire_old_buffer(req, 0);
7253         if (rc != 0)
7254                 return (rc);
7255
7256         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7257         if (sb == NULL)
7258                 return (ENOMEM);
7259
7260         sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
7261             "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
7262             "                           Replication"
7263             "                                    P0 P1 P2 P3  ML\n");
7264
7265         for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
7266                 uint8_t dip_hit, vlan_vld, lookup_type, port_num;
7267                 uint16_t ivlan;
7268                 uint64_t tcamx, tcamy, val, mask;
7269                 uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
7270                 uint8_t addr[ETHER_ADDR_LEN];
7271
7272                 ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
7273                 if (i < 256)
7274                         ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
7275                 else
7276                         ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
7277                 t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
7278                 val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
7279                 tcamy = G_DMACH(val) << 32;
7280                 tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
7281                 data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
7282                 lookup_type = G_DATALKPTYPE(data2);
7283                 port_num = G_DATAPORTNUM(data2);
7284                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
7285                         /* Inner header VNI */
7286                         vniy = ((data2 & F_DATAVIDH2) << 23) |
7287                                        (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
7288                         dip_hit = data2 & F_DATADIPHIT;
7289                         vlan_vld = 0;
7290                 } else {
7291                         vniy = 0;
7292                         dip_hit = 0;
7293                         vlan_vld = data2 & F_DATAVIDH2;
7294                         ivlan = G_VIDL(val);
7295                 }
7296
7297                 ctl |= V_CTLXYBITSEL(1);
7298                 t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
7299                 val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
7300                 tcamx = G_DMACH(val) << 32;
7301                 tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
7302                 data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
7303                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
7304                         /* Inner header VNI mask */
7305                         vnix = ((data2 & F_DATAVIDH2) << 23) |
7306                                (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
7307                 } else
7308                         vnix = 0;
7309
7310                 if (tcamx & tcamy)
7311                         continue;
7312                 tcamxy2valmask(tcamx, tcamy, addr, &mask);
7313
7314                 cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
7315                 cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
7316
7317                 if (lookup_type && lookup_type != M_DATALKPTYPE) {
7318                         sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
7319                             "%012jx %06x %06x    -    -   %3c"
7320                             "      'I'  %4x   %3c   %#x%4u%4d", i, addr[0],
7321                             addr[1], addr[2], addr[3], addr[4], addr[5],
7322                             (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
7323                             port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
7324                             G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
7325                             cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
7326                 } else {
7327                         sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
7328                             "%012jx    -       -   ", i, addr[0], addr[1],
7329                             addr[2], addr[3], addr[4], addr[5],
7330                             (uintmax_t)mask);
7331
7332                         if (vlan_vld)
7333                                 sbuf_printf(sb, "%4u   Y     ", ivlan);
7334                         else
7335                                 sbuf_printf(sb, "  -    N     ");
7336
7337                         sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
7338                             lookup_type ? 'I' : 'O', port_num,
7339                             cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
7340                             G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
7341                             cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
7342                 }
7343
7344
7345                 if (cls_lo & F_T6_REPLICATE) {
7346                         struct fw_ldst_cmd ldst_cmd;
7347
7348                         memset(&ldst_cmd, 0, sizeof(ldst_cmd));
7349                         ldst_cmd.op_to_addrspace =
7350                             htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
7351                                 F_FW_CMD_REQUEST | F_FW_CMD_READ |
7352                                 V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
7353                         ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
7354                         ldst_cmd.u.mps.rplc.fid_idx =
7355                             htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
7356                                 V_FW_LDST_CMD_IDX(i));
7357
7358                         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
7359                             "t6mps");
7360                         if (rc)
7361                                 break;
7362                         rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
7363                             sizeof(ldst_cmd), &ldst_cmd);
7364                         end_synchronized_op(sc, 0);
7365
7366                         if (rc != 0) {
7367                                 sbuf_printf(sb, "%72d", rc);
7368                                 rc = 0;
7369                         } else {
7370                                 sbuf_printf(sb, " %08x %08x %08x %08x"
7371                                     " %08x %08x %08x %08x",
7372                                     be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
7373                                     be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
7374                                     be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
7375                                     be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
7376                                     be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
7377                                     be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
7378                                     be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
7379                                     be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
7380                         }
7381                 } else
7382                         sbuf_printf(sb, "%72s", "");
7383
7384                 sbuf_printf(sb, "%4u%3u%3u%3u %#x",
7385                     G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
7386                     G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
7387                     (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
7388         }
7389
7390         if (rc)
7391                 (void) sbuf_finish(sb);
7392         else
7393                 rc = sbuf_finish(sb);
7394         sbuf_delete(sb);
7395
7396         return (rc);
7397 }
7398
7399 static int
7400 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
7401 {
7402         struct adapter *sc = arg1;
7403         struct sbuf *sb;
7404         int rc;
7405         uint16_t mtus[NMTUS];
7406
7407         rc = sysctl_wire_old_buffer(req, 0);
7408         if (rc != 0)
7409                 return (rc);
7410
7411         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7412         if (sb == NULL)
7413                 return (ENOMEM);
7414
7415         t4_read_mtu_tbl(sc, mtus, NULL);
7416
7417         sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
7418             mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
7419             mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
7420             mtus[14], mtus[15]);
7421
7422         rc = sbuf_finish(sb);
7423         sbuf_delete(sb);
7424
7425         return (rc);
7426 }
7427
7428 static int
7429 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
7430 {
7431         struct adapter *sc = arg1;
7432         struct sbuf *sb;
7433         int rc, i;
7434         uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
7435         uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
7436         static const char *tx_stats[MAX_PM_NSTATS] = {
7437                 "Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
7438                 "Tx FIFO wait", NULL, "Tx latency"
7439         };
7440         static const char *rx_stats[MAX_PM_NSTATS] = {
7441                 "Read:", "Write bypass:", "Write mem:", "Flush:",
7442                 "Rx FIFO wait", NULL, "Rx latency"
7443         };
7444
7445         rc = sysctl_wire_old_buffer(req, 0);
7446         if (rc != 0)
7447                 return (rc);
7448
7449         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7450         if (sb == NULL)
7451                 return (ENOMEM);
7452
7453         t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
7454         t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
7455
7456         sbuf_printf(sb, "                Tx pcmds             Tx bytes");
7457         for (i = 0; i < 4; i++) {
7458                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
7459                     tx_cyc[i]);
7460         }
7461
7462         sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
7463         for (i = 0; i < 4; i++) {
7464                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
7465                     rx_cyc[i]);
7466         }
7467
7468         if (chip_id(sc) > CHELSIO_T5) {
7469                 sbuf_printf(sb,
7470                     "\n              Total wait      Total occupancy");
7471                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
7472                     tx_cyc[i]);
7473                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
7474                     rx_cyc[i]);
7475
7476                 i += 2;
7477                 MPASS(i < nitems(tx_stats));
7478
7479                 sbuf_printf(sb,
7480                     "\n                   Reads           Total wait");
7481                 sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
7482                     tx_cyc[i]);
7483                 sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
7484                     rx_cyc[i]);
7485         }
7486
7487         rc = sbuf_finish(sb);
7488         sbuf_delete(sb);
7489
7490         return (rc);
7491 }
7492
7493 static int
7494 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
7495 {
7496         struct adapter *sc = arg1;
7497         struct sbuf *sb;
7498         int rc;
7499         struct tp_rdma_stats stats;
7500
7501         rc = sysctl_wire_old_buffer(req, 0);
7502         if (rc != 0)
7503                 return (rc);
7504
7505         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7506         if (sb == NULL)
7507                 return (ENOMEM);
7508
7509         mtx_lock(&sc->reg_lock);
7510         t4_tp_get_rdma_stats(sc, &stats, 0);
7511         mtx_unlock(&sc->reg_lock);
7512
7513         sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
7514         sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
7515
7516         rc = sbuf_finish(sb);
7517         sbuf_delete(sb);
7518
7519         return (rc);
7520 }
7521
7522 static int
7523 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
7524 {
7525         struct adapter *sc = arg1;
7526         struct sbuf *sb;
7527         int rc;
7528         struct tp_tcp_stats v4, v6;
7529
7530         rc = sysctl_wire_old_buffer(req, 0);
7531         if (rc != 0)
7532                 return (rc);
7533
7534         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7535         if (sb == NULL)
7536                 return (ENOMEM);
7537
7538         mtx_lock(&sc->reg_lock);
7539         t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
7540         mtx_unlock(&sc->reg_lock);
7541
7542         sbuf_printf(sb,
7543             "                                IP                 IPv6\n");
7544         sbuf_printf(sb, "OutRsts:      %20u %20u\n",
7545             v4.tcp_out_rsts, v6.tcp_out_rsts);
7546         sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
7547             v4.tcp_in_segs, v6.tcp_in_segs);
7548         sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
7549             v4.tcp_out_segs, v6.tcp_out_segs);
7550         sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
7551             v4.tcp_retrans_segs, v6.tcp_retrans_segs);
7552
7553         rc = sbuf_finish(sb);
7554         sbuf_delete(sb);
7555
7556         return (rc);
7557 }
7558
7559 static int
7560 sysctl_tids(SYSCTL_HANDLER_ARGS)
7561 {
7562         struct adapter *sc = arg1;
7563         struct sbuf *sb;
7564         int rc;
7565         struct tid_info *t = &sc->tids;
7566
7567         rc = sysctl_wire_old_buffer(req, 0);
7568         if (rc != 0)
7569                 return (rc);
7570
7571         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7572         if (sb == NULL)
7573                 return (ENOMEM);
7574
7575         if (t->natids) {
7576                 sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
7577                     t->atids_in_use);
7578         }
7579
7580         if (t->ntids) {
7581                 sbuf_printf(sb, "TID range: ");
7582                 if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
7583                         uint32_t b, hb;
7584
7585                         if (chip_id(sc) <= CHELSIO_T5) {
7586                                 b = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
7587                                 hb = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
7588                         } else {
7589                                 b = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
7590                                 hb = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
7591                         }
7592
7593                         if (b)
7594                                 sbuf_printf(sb, "0-%u, ", b - 1);
7595                         sbuf_printf(sb, "%u-%u", hb, t->ntids - 1);
7596                 } else
7597                         sbuf_printf(sb, "0-%u", t->ntids - 1);
7598                 sbuf_printf(sb, ", in use: %u\n",
7599                     atomic_load_acq_int(&t->tids_in_use));
7600         }
7601
7602         if (t->nstids) {
7603                 sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
7604                     t->stid_base + t->nstids - 1, t->stids_in_use);
7605         }
7606
7607         if (t->nftids) {
7608                 sbuf_printf(sb, "FTID range: %u-%u\n", t->ftid_base,
7609                     t->ftid_base + t->nftids - 1);
7610         }
7611
7612         if (t->netids) {
7613                 sbuf_printf(sb, "ETID range: %u-%u\n", t->etid_base,
7614                     t->etid_base + t->netids - 1);
7615         }
7616
7617         sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users",
7618             t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4),
7619             t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6));
7620
7621         rc = sbuf_finish(sb);
7622         sbuf_delete(sb);
7623
7624         return (rc);
7625 }
7626
7627 static int
7628 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
7629 {
7630         struct adapter *sc = arg1;
7631         struct sbuf *sb;
7632         int rc;
7633         struct tp_err_stats stats;
7634
7635         rc = sysctl_wire_old_buffer(req, 0);
7636         if (rc != 0)
7637                 return (rc);
7638
7639         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7640         if (sb == NULL)
7641                 return (ENOMEM);
7642
7643         mtx_lock(&sc->reg_lock);
7644         t4_tp_get_err_stats(sc, &stats, 0);
7645         mtx_unlock(&sc->reg_lock);
7646
7647         if (sc->chip_params->nchan > 2) {
7648                 sbuf_printf(sb, "                 channel 0  channel 1"
7649                     "  channel 2  channel 3\n");
7650                 sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
7651                     stats.mac_in_errs[0], stats.mac_in_errs[1],
7652                     stats.mac_in_errs[2], stats.mac_in_errs[3]);
7653                 sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
7654                     stats.hdr_in_errs[0], stats.hdr_in_errs[1],
7655                     stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
7656                 sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
7657                     stats.tcp_in_errs[0], stats.tcp_in_errs[1],
7658                     stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
7659                 sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
7660                     stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
7661                     stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
7662                 sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
7663                     stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
7664                     stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
7665                 sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
7666                     stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
7667                     stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
7668                 sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
7669                     stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
7670                     stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
7671                 sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
7672                     stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
7673                     stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
7674         } else {
7675                 sbuf_printf(sb, "                 channel 0  channel 1\n");
7676                 sbuf_printf(sb, "macInErrs:      %10u %10u\n",
7677                     stats.mac_in_errs[0], stats.mac_in_errs[1]);
7678                 sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
7679                     stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
7680                 sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
7681                     stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
7682                 sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
7683                     stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
7684                 sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
7685                     stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
7686                 sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
7687                     stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
7688                 sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
7689                     stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
7690                 sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
7691                     stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
7692         }
7693
7694         sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
7695             stats.ofld_no_neigh, stats.ofld_cong_defer);
7696
7697         rc = sbuf_finish(sb);
7698         sbuf_delete(sb);
7699
7700         return (rc);
7701 }
7702
7703 static int
7704 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
7705 {
7706         struct adapter *sc = arg1;
7707         struct tp_params *tpp = &sc->params.tp;
7708         u_int mask;
7709         int rc;
7710
7711         mask = tpp->la_mask >> 16;
7712         rc = sysctl_handle_int(oidp, &mask, 0, req);
7713         if (rc != 0 || req->newptr == NULL)
7714                 return (rc);
7715         if (mask > 0xffff)
7716                 return (EINVAL);
7717         tpp->la_mask = mask << 16;
7718         t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U, tpp->la_mask);
7719
7720         return (0);
7721 }
7722
7723 struct field_desc {
7724         const char *name;
7725         u_int start;
7726         u_int width;
7727 };
7728
7729 static void
7730 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
7731 {
7732         char buf[32];
7733         int line_size = 0;
7734
7735         while (f->name) {
7736                 uint64_t mask = (1ULL << f->width) - 1;
7737                 int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
7738                     ((uintmax_t)v >> f->start) & mask);
7739
7740                 if (line_size + len >= 79) {
7741                         line_size = 8;
7742                         sbuf_printf(sb, "\n        ");
7743                 }
7744                 sbuf_printf(sb, "%s ", buf);
7745                 line_size += len + 1;
7746                 f++;
7747         }
7748         sbuf_printf(sb, "\n");
7749 }
7750
7751 static const struct field_desc tp_la0[] = {
7752         { "RcfOpCodeOut", 60, 4 },
7753         { "State", 56, 4 },
7754         { "WcfState", 52, 4 },
7755         { "RcfOpcSrcOut", 50, 2 },
7756         { "CRxError", 49, 1 },
7757         { "ERxError", 48, 1 },
7758         { "SanityFailed", 47, 1 },
7759         { "SpuriousMsg", 46, 1 },
7760         { "FlushInputMsg", 45, 1 },
7761         { "FlushInputCpl", 44, 1 },
7762         { "RssUpBit", 43, 1 },
7763         { "RssFilterHit", 42, 1 },
7764         { "Tid", 32, 10 },
7765         { "InitTcb", 31, 1 },
7766         { "LineNumber", 24, 7 },
7767         { "Emsg", 23, 1 },
7768         { "EdataOut", 22, 1 },
7769         { "Cmsg", 21, 1 },
7770         { "CdataOut", 20, 1 },
7771         { "EreadPdu", 19, 1 },
7772         { "CreadPdu", 18, 1 },
7773         { "TunnelPkt", 17, 1 },
7774         { "RcfPeerFin", 16, 1 },
7775         { "RcfReasonOut", 12, 4 },
7776         { "TxCchannel", 10, 2 },
7777         { "RcfTxChannel", 8, 2 },
7778         { "RxEchannel", 6, 2 },
7779         { "RcfRxChannel", 5, 1 },
7780         { "RcfDataOutSrdy", 4, 1 },
7781         { "RxDvld", 3, 1 },
7782         { "RxOoDvld", 2, 1 },
7783         { "RxCongestion", 1, 1 },
7784         { "TxCongestion", 0, 1 },
7785         { NULL }
7786 };
7787
7788 static const struct field_desc tp_la1[] = {
7789         { "CplCmdIn", 56, 8 },
7790         { "CplCmdOut", 48, 8 },
7791         { "ESynOut", 47, 1 },
7792         { "EAckOut", 46, 1 },
7793         { "EFinOut", 45, 1 },
7794         { "ERstOut", 44, 1 },
7795         { "SynIn", 43, 1 },
7796         { "AckIn", 42, 1 },
7797         { "FinIn", 41, 1 },
7798         { "RstIn", 40, 1 },
7799         { "DataIn", 39, 1 },
7800         { "DataInVld", 38, 1 },
7801         { "PadIn", 37, 1 },
7802         { "RxBufEmpty", 36, 1 },
7803         { "RxDdp", 35, 1 },
7804         { "RxFbCongestion", 34, 1 },
7805         { "TxFbCongestion", 33, 1 },
7806         { "TxPktSumSrdy", 32, 1 },
7807         { "RcfUlpType", 28, 4 },
7808         { "Eread", 27, 1 },
7809         { "Ebypass", 26, 1 },
7810         { "Esave", 25, 1 },
7811         { "Static0", 24, 1 },
7812         { "Cread", 23, 1 },
7813         { "Cbypass", 22, 1 },
7814         { "Csave", 21, 1 },
7815         { "CPktOut", 20, 1 },
7816         { "RxPagePoolFull", 18, 2 },
7817         { "RxLpbkPkt", 17, 1 },
7818         { "TxLpbkPkt", 16, 1 },
7819         { "RxVfValid", 15, 1 },
7820         { "SynLearned", 14, 1 },
7821         { "SetDelEntry", 13, 1 },
7822         { "SetInvEntry", 12, 1 },
7823         { "CpcmdDvld", 11, 1 },
7824         { "CpcmdSave", 10, 1 },
7825         { "RxPstructsFull", 8, 2 },
7826         { "EpcmdDvld", 7, 1 },
7827         { "EpcmdFlush", 6, 1 },
7828         { "EpcmdTrimPrefix", 5, 1 },
7829         { "EpcmdTrimPostfix", 4, 1 },
7830         { "ERssIp4Pkt", 3, 1 },
7831         { "ERssIp6Pkt", 2, 1 },
7832         { "ERssTcpUdpPkt", 1, 1 },
7833         { "ERssFceFipPkt", 0, 1 },
7834         { NULL }
7835 };
7836
7837 static const struct field_desc tp_la2[] = {
7838         { "CplCmdIn", 56, 8 },
7839         { "MpsVfVld", 55, 1 },
7840         { "MpsPf", 52, 3 },
7841         { "MpsVf", 44, 8 },
7842         { "SynIn", 43, 1 },
7843         { "AckIn", 42, 1 },
7844         { "FinIn", 41, 1 },
7845         { "RstIn", 40, 1 },
7846         { "DataIn", 39, 1 },
7847         { "DataInVld", 38, 1 },
7848         { "PadIn", 37, 1 },
7849         { "RxBufEmpty", 36, 1 },
7850         { "RxDdp", 35, 1 },
7851         { "RxFbCongestion", 34, 1 },
7852         { "TxFbCongestion", 33, 1 },
7853         { "TxPktSumSrdy", 32, 1 },
7854         { "RcfUlpType", 28, 4 },
7855         { "Eread", 27, 1 },
7856         { "Ebypass", 26, 1 },
7857         { "Esave", 25, 1 },
7858         { "Static0", 24, 1 },
7859         { "Cread", 23, 1 },
7860         { "Cbypass", 22, 1 },
7861         { "Csave", 21, 1 },
7862         { "CPktOut", 20, 1 },
7863         { "RxPagePoolFull", 18, 2 },
7864         { "RxLpbkPkt", 17, 1 },
7865         { "TxLpbkPkt", 16, 1 },
7866         { "RxVfValid", 15, 1 },
7867         { "SynLearned", 14, 1 },
7868         { "SetDelEntry", 13, 1 },
7869         { "SetInvEntry", 12, 1 },
7870         { "CpcmdDvld", 11, 1 },
7871         { "CpcmdSave", 10, 1 },
7872         { "RxPstructsFull", 8, 2 },
7873         { "EpcmdDvld", 7, 1 },
7874         { "EpcmdFlush", 6, 1 },
7875         { "EpcmdTrimPrefix", 5, 1 },
7876         { "EpcmdTrimPostfix", 4, 1 },
7877         { "ERssIp4Pkt", 3, 1 },
7878         { "ERssIp6Pkt", 2, 1 },
7879         { "ERssTcpUdpPkt", 1, 1 },
7880         { "ERssFceFipPkt", 0, 1 },
7881         { NULL }
7882 };
7883
7884 static void
7885 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
7886 {
7887
7888         field_desc_show(sb, *p, tp_la0);
7889 }
7890
7891 static void
7892 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
7893 {
7894
7895         if (idx)
7896                 sbuf_printf(sb, "\n");
7897         field_desc_show(sb, p[0], tp_la0);
7898         if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
7899                 field_desc_show(sb, p[1], tp_la0);
7900 }
7901
7902 static void
7903 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
7904 {
7905
7906         if (idx)
7907                 sbuf_printf(sb, "\n");
7908         field_desc_show(sb, p[0], tp_la0);
7909         if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
7910                 field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
7911 }
7912
7913 static int
7914 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
7915 {
7916         struct adapter *sc = arg1;
7917         struct sbuf *sb;
7918         uint64_t *buf, *p;
7919         int rc;
7920         u_int i, inc;
7921         void (*show_func)(struct sbuf *, uint64_t *, int);
7922
7923         rc = sysctl_wire_old_buffer(req, 0);
7924         if (rc != 0)
7925                 return (rc);
7926
7927         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7928         if (sb == NULL)
7929                 return (ENOMEM);
7930
7931         buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
7932
7933         t4_tp_read_la(sc, buf, NULL);
7934         p = buf;
7935
7936         switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
7937         case 2:
7938                 inc = 2;
7939                 show_func = tp_la_show2;
7940                 break;
7941         case 3:
7942                 inc = 2;
7943                 show_func = tp_la_show3;
7944                 break;
7945         default:
7946                 inc = 1;
7947                 show_func = tp_la_show;
7948         }
7949
7950         for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
7951                 (*show_func)(sb, p, i);
7952
7953         rc = sbuf_finish(sb);
7954         sbuf_delete(sb);
7955         free(buf, M_CXGBE);
7956         return (rc);
7957 }
7958
7959 static int
7960 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
7961 {
7962         struct adapter *sc = arg1;
7963         struct sbuf *sb;
7964         int rc;
7965         u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
7966
7967         rc = sysctl_wire_old_buffer(req, 0);
7968         if (rc != 0)
7969                 return (rc);
7970
7971         sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7972         if (sb == NULL)
7973                 return (ENOMEM);
7974
7975         t4_get_chan_txrate(sc, nrate, orate);
7976
7977         if (sc->chip_params->nchan > 2) {
7978                 sbuf_printf(sb, "              channel 0   channel 1"
7979                     "   channel 2   channel 3\n");
7980                 sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
7981                     nrate[0], nrate[1], nrate[2], nrate[3]);
7982                 sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
7983                     orate[0], orate[1], orate[2], orate[3]);
7984         } else {
7985                 sbuf_printf(sb, "              channel 0   channel 1\n");
7986                 sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
7987                     nrate[0], nrate[1]);
7988                 sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
7989                     orate[0], orate[1]);
7990         }
7991
7992         rc = sbuf_finish(sb);
7993         sbuf_delete(sb);
7994
7995         return (rc);
7996 }
7997
7998 static int
7999 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
8000 {
8001         struct adapter *sc = arg1;
8002         struct sbuf *sb;
8003         uint32_t *buf, *p;
8004         int rc, i;
8005
8006         rc = sysctl_wire_old_buffer(req, 0);
8007         if (rc != 0)
8008                 return (rc);
8009
8010         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8011         if (sb == NULL)
8012                 return (ENOMEM);
8013
8014         buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
8015             M_ZERO | M_WAITOK);
8016
8017         t4_ulprx_read_la(sc, buf);
8018         p = buf;
8019
8020         sbuf_printf(sb, "      Pcmd        Type   Message"
8021             "                Data");
8022         for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
8023                 sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
8024                     p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
8025         }
8026
8027         rc = sbuf_finish(sb);
8028         sbuf_delete(sb);
8029         free(buf, M_CXGBE);
8030         return (rc);
8031 }
8032
8033 static int
8034 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
8035 {
8036         struct adapter *sc = arg1;
8037         struct sbuf *sb;
8038         int rc, v;
8039
8040         MPASS(chip_id(sc) >= CHELSIO_T5);
8041
8042         rc = sysctl_wire_old_buffer(req, 0);
8043         if (rc != 0)
8044                 return (rc);
8045
8046         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8047         if (sb == NULL)
8048                 return (ENOMEM);
8049
8050         v = t4_read_reg(sc, A_SGE_STAT_CFG);
8051         if (G_STATSOURCE_T5(v) == 7) {
8052                 int mode;
8053
8054                 mode = is_t5(sc) ? G_STATMODE(v) : G_T6_STATMODE(v);
8055                 if (mode == 0) {
8056                         sbuf_printf(sb, "total %d, incomplete %d",
8057                             t4_read_reg(sc, A_SGE_STAT_TOTAL),
8058                             t4_read_reg(sc, A_SGE_STAT_MATCH));
8059                 } else if (mode == 1) {
8060                         sbuf_printf(sb, "total %d, data overflow %d",
8061                             t4_read_reg(sc, A_SGE_STAT_TOTAL),
8062                             t4_read_reg(sc, A_SGE_STAT_MATCH));
8063                 } else {
8064                         sbuf_printf(sb, "unknown mode %d", mode);
8065                 }
8066         }
8067         rc = sbuf_finish(sb);
8068         sbuf_delete(sb);
8069
8070         return (rc);
8071 }
8072
8073 static int
8074 sysctl_tc_params(SYSCTL_HANDLER_ARGS)
8075 {
8076         struct adapter *sc = arg1;
8077         struct tx_cl_rl_params tc;
8078         struct sbuf *sb;
8079         int i, rc, port_id, mbps, gbps;
8080
8081         rc = sysctl_wire_old_buffer(req, 0);
8082         if (rc != 0)
8083                 return (rc);
8084
8085         sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8086         if (sb == NULL)
8087                 return (ENOMEM);
8088
8089         port_id = arg2 >> 16;
8090         MPASS(port_id < sc->params.nports);
8091         MPASS(sc->port[port_id] != NULL);
8092         i = arg2 & 0xffff;
8093         MPASS(i < sc->chip_params->nsched_cls);
8094
8095         mtx_lock(&sc->tc_lock);
8096         tc = sc->port[port_id]->sched_params->cl_rl[i];
8097         mtx_unlock(&sc->tc_lock);
8098
8099         if (tc.flags & TX_CLRL_ERROR) {
8100                 sbuf_printf(sb, "error");
8101                 goto done;
8102         }
8103
8104         if (tc.ratemode == SCHED_CLASS_RATEMODE_REL) {
8105                 /* XXX: top speed or actual link speed? */
8106                 gbps = port_top_speed(sc->port[port_id]);
8107                 sbuf_printf(sb, " %u%% of %uGbps", tc.maxrate, gbps);
8108         } else if (tc.ratemode == SCHED_CLASS_RATEMODE_ABS) {
8109                 switch (tc.rateunit) {
8110                 case SCHED_CLASS_RATEUNIT_BITS:
8111                         mbps = tc.maxrate / 1000;
8112                         gbps = tc.maxrate / 1000000;
8113                         if (tc.maxrate == gbps * 1000000)
8114                                 sbuf_printf(sb, " %uGbps", gbps);
8115                         else if (tc.maxrate == mbps * 1000)
8116                                 sbuf_printf(sb, " %uMbps", mbps);
8117                         else
8118                                 sbuf_printf(sb, " %uKbps", tc.maxrate);
8119                         break;
8120                 case SCHED_CLASS_RATEUNIT_PKTS:
8121                         sbuf_printf(sb, " %upps", tc.maxrate);
8122                         break;
8123                 default:
8124                         rc = ENXIO;
8125                         goto done;
8126                 }
8127         }
8128
8129         switch (tc.mode) {
8130         case SCHED_CLASS_MODE_CLASS:
8131                 sbuf_printf(sb, " aggregate");
8132                 break;
8133         case SCHED_CLASS_MODE_FLOW:
8134                 sbuf_printf(sb, " per-flow");
8135                 break;
8136         default:
8137                 rc = ENXIO;
8138                 goto done;
8139         }
8140
8141 done:
8142         if (rc == 0)
8143                 rc = sbuf_finish(sb);
8144         sbuf_delete(sb);
8145
8146         return (rc);
8147 }
8148 #endif
8149
8150 #ifdef TCP_OFFLOAD
8151 static void
8152 unit_conv(char *buf, size_t len, u_int val, u_int factor)
8153 {
8154         u_int rem = val % factor;
8155
8156         if (rem == 0)
8157                 snprintf(buf, len, "%u", val / factor);
8158         else {
8159                 while (rem % 10 == 0)
8160                         rem /= 10;
8161                 snprintf(buf, len, "%u.%u", val / factor, rem);
8162         }
8163 }
8164
8165 static int
8166 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
8167 {
8168         struct adapter *sc = arg1;
8169         char buf[16];
8170         u_int res, re;
8171         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
8172
8173         res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
8174         switch (arg2) {
8175         case 0:
8176                 /* timer_tick */
8177                 re = G_TIMERRESOLUTION(res);
8178                 break;
8179         case 1:
8180                 /* TCP timestamp tick */
8181                 re = G_TIMESTAMPRESOLUTION(res);
8182                 break;
8183         case 2:
8184                 /* DACK tick */
8185                 re = G_DELAYEDACKRESOLUTION(res);
8186                 break;
8187         default:
8188                 return (EDOOFUS);
8189         }
8190
8191         unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
8192
8193         return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
8194 }
8195
8196 static int
8197 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
8198 {
8199         struct adapter *sc = arg1;
8200         u_int res, dack_re, v;
8201         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
8202
8203         res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
8204         dack_re = G_DELAYEDACKRESOLUTION(res);
8205         v = ((cclk_ps << dack_re) / 1000000) * t4_read_reg(sc, A_TP_DACK_TIMER);
8206
8207         return (sysctl_handle_int(oidp, &v, 0, req));
8208 }
8209
8210 static int
8211 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
8212 {
8213         struct adapter *sc = arg1;
8214         int reg = arg2;
8215         u_int tre;
8216         u_long tp_tick_us, v;
8217         u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
8218
8219         MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
8220             reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
8221             reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
8222             reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
8223
8224         tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
8225         tp_tick_us = (cclk_ps << tre) / 1000000;
8226
8227         if (reg == A_TP_INIT_SRTT)
8228                 v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
8229         else
8230                 v = tp_tick_us * t4_read_reg(sc, reg);
8231
8232         return (sysctl_handle_long(oidp, &v, 0, req));
8233 }
8234
8235 /*
8236  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
8237  * passed to this function.
8238  */
8239 static int
8240 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
8241 {
8242         struct adapter *sc = arg1;
8243         int idx = arg2;
8244         u_int v;
8245
8246         MPASS(idx >= 0 && idx <= 24);
8247
8248         v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
8249
8250         return (sysctl_handle_int(oidp, &v, 0, req));
8251 }
8252
8253 static int
8254 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
8255 {
8256         struct adapter *sc = arg1;
8257         int idx = arg2;
8258         u_int shift, v, r;
8259
8260         MPASS(idx >= 0 && idx < 16);
8261
8262         r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
8263         shift = (idx & 3) << 3;
8264         v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
8265
8266         return (sysctl_handle_int(oidp, &v, 0, req));
8267 }
8268 #endif
8269
8270 static uint32_t
8271 fconf_iconf_to_mode(uint32_t fconf, uint32_t iconf)
8272 {
8273         uint32_t mode;
8274
8275         mode = T4_FILTER_IPv4 | T4_FILTER_IPv6 | T4_FILTER_IP_SADDR |
8276             T4_FILTER_IP_DADDR | T4_FILTER_IP_SPORT | T4_FILTER_IP_DPORT;
8277
8278         if (fconf & F_FRAGMENTATION)
8279                 mode |= T4_FILTER_IP_FRAGMENT;
8280
8281         if (fconf & F_MPSHITTYPE)
8282                 mode |= T4_FILTER_MPS_HIT_TYPE;
8283
8284         if (fconf & F_MACMATCH)
8285                 mode |= T4_FILTER_MAC_IDX;
8286
8287         if (fconf & F_ETHERTYPE)
8288                 mode |= T4_FILTER_ETH_TYPE;
8289
8290         if (fconf & F_PROTOCOL)
8291                 mode |= T4_FILTER_IP_PROTO;
8292
8293         if (fconf & F_TOS)
8294                 mode |= T4_FILTER_IP_TOS;
8295
8296         if (fconf & F_VLAN)
8297                 mode |= T4_FILTER_VLAN;
8298
8299         if (fconf & F_VNIC_ID) {
8300                 mode |= T4_FILTER_VNIC;
8301                 if (iconf & F_VNIC)
8302                         mode |= T4_FILTER_IC_VNIC;
8303         }
8304
8305         if (fconf & F_PORT)
8306                 mode |= T4_FILTER_PORT;
8307
8308         if (fconf & F_FCOE)
8309                 mode |= T4_FILTER_FCoE;
8310
8311         return (mode);
8312 }
8313
8314 static uint32_t
8315 mode_to_fconf(uint32_t mode)
8316 {
8317         uint32_t fconf = 0;
8318
8319         if (mode & T4_FILTER_IP_FRAGMENT)
8320                 fconf |= F_FRAGMENTATION;
8321
8322         if (mode & T4_FILTER_MPS_HIT_TYPE)
8323                 fconf |= F_MPSHITTYPE;
8324
8325         if (mode & T4_FILTER_MAC_IDX)
8326                 fconf |= F_MACMATCH;
8327
8328         if (mode & T4_FILTER_ETH_TYPE)
8329                 fconf |= F_ETHERTYPE;
8330
8331         if (mode & T4_FILTER_IP_PROTO)
8332                 fconf |= F_PROTOCOL;
8333
8334         if (mode & T4_FILTER_IP_TOS)
8335                 fconf |= F_TOS;
8336
8337         if (mode & T4_FILTER_VLAN)
8338                 fconf |= F_VLAN;
8339
8340         if (mode & T4_FILTER_VNIC)
8341                 fconf |= F_VNIC_ID;
8342
8343         if (mode & T4_FILTER_PORT)
8344                 fconf |= F_PORT;
8345
8346         if (mode & T4_FILTER_FCoE)
8347                 fconf |= F_FCOE;
8348
8349         return (fconf);
8350 }
8351
8352 static uint32_t
8353 mode_to_iconf(uint32_t mode)
8354 {
8355
8356         if (mode & T4_FILTER_IC_VNIC)
8357                 return (F_VNIC);
8358         return (0);
8359 }
8360
8361 static int check_fspec_against_fconf_iconf(struct adapter *sc,
8362     struct t4_filter_specification *fs)
8363 {
8364         struct tp_params *tpp = &sc->params.tp;
8365         uint32_t fconf = 0;
8366
8367         if (fs->val.frag || fs->mask.frag)
8368                 fconf |= F_FRAGMENTATION;
8369
8370         if (fs->val.matchtype || fs->mask.matchtype)
8371                 fconf |= F_MPSHITTYPE;
8372
8373         if (fs->val.macidx || fs->mask.macidx)
8374                 fconf |= F_MACMATCH;
8375
8376         if (fs->val.ethtype || fs->mask.ethtype)
8377                 fconf |= F_ETHERTYPE;
8378
8379         if (fs->val.proto || fs->mask.proto)
8380                 fconf |= F_PROTOCOL;
8381
8382         if (fs->val.tos || fs->mask.tos)
8383                 fconf |= F_TOS;
8384
8385         if (fs->val.vlan_vld || fs->mask.vlan_vld)
8386                 fconf |= F_VLAN;
8387
8388         if (fs->val.ovlan_vld || fs->mask.ovlan_vld) {
8389                 fconf |= F_VNIC_ID;
8390                 if (tpp->ingress_config & F_VNIC)
8391                         return (EINVAL);
8392         }
8393
8394         if (fs->val.pfvf_vld || fs->mask.pfvf_vld) {
8395                 fconf |= F_VNIC_ID;
8396                 if ((tpp->ingress_config & F_VNIC) == 0)
8397                         return (EINVAL);
8398         }
8399
8400         if (fs->val.iport || fs->mask.iport)
8401                 fconf |= F_PORT;
8402
8403         if (fs->val.fcoe || fs->mask.fcoe)
8404                 fconf |= F_FCOE;
8405
8406         if ((tpp->vlan_pri_map | fconf) != tpp->vlan_pri_map)
8407                 return (E2BIG);
8408
8409         return (0);
8410 }
8411
8412 static int
8413 get_filter_mode(struct adapter *sc, uint32_t *mode)
8414 {
8415         struct tp_params *tpp = &sc->params.tp;
8416
8417         /*
8418          * We trust the cached values of the relevant TP registers.  This means
8419          * things work reliably only if writes to those registers are always via
8420          * t4_set_filter_mode.
8421          */
8422         *mode = fconf_iconf_to_mode(tpp->vlan_pri_map, tpp->ingress_config);
8423
8424         return (0);
8425 }
8426
8427 static int
8428 set_filter_mode(struct adapter *sc, uint32_t mode)
8429 {
8430         struct tp_params *tpp = &sc->params.tp;
8431         uint32_t fconf, iconf;
8432         int rc;
8433
8434         iconf = mode_to_iconf(mode);
8435         if ((iconf ^ tpp->ingress_config) & F_VNIC) {
8436                 /*
8437                  * For now we just complain if A_TP_INGRESS_CONFIG is not
8438                  * already set to the correct value for the requested filter
8439                  * mode.  It's not clear if it's safe to write to this register
8440                  * on the fly.  (And we trust the cached value of the register).
8441                  */
8442                 return (EBUSY);
8443         }
8444
8445         fconf = mode_to_fconf(mode);
8446
8447         rc = begin_synchronized_op(sc, NULL, HOLD_LOCK | SLEEP_OK | INTR_OK,
8448             "t4setfm");
8449         if (rc)
8450                 return (rc);
8451
8452         if (sc->tids.ftids_in_use > 0) {
8453                 rc = EBUSY;
8454                 goto done;
8455         }
8456
8457 #ifdef TCP_OFFLOAD
8458         if (uld_active(sc, ULD_TOM)) {
8459                 rc = EBUSY;
8460                 goto done;
8461         }
8462 #endif
8463
8464         rc = -t4_set_filter_mode(sc, fconf, true);
8465 done:
8466         end_synchronized_op(sc, LOCK_HELD);
8467         return (rc);
8468 }
8469
8470 static inline uint64_t
8471 get_filter_hits(struct adapter *sc, uint32_t fid)
8472 {
8473         uint32_t tcb_addr;
8474
8475         tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE) +
8476             (fid + sc->tids.ftid_base) * TCB_SIZE;
8477
8478         if (is_t4(sc)) {
8479                 uint64_t hits;
8480
8481                 read_via_memwin(sc, 0, tcb_addr + 16, (uint32_t *)&hits, 8);
8482                 return (be64toh(hits));
8483         } else {
8484                 uint32_t hits;
8485
8486                 read_via_memwin(sc, 0, tcb_addr + 24, &hits, 4);
8487                 return (be32toh(hits));
8488         }
8489 }
8490
8491 static int
8492 get_filter(struct adapter *sc, struct t4_filter *t)
8493 {
8494         int i, rc, nfilters = sc->tids.nftids;
8495         struct filter_entry *f;
8496
8497         rc = begin_synchronized_op(sc, NULL, HOLD_LOCK | SLEEP_OK | INTR_OK,
8498             "t4getf");
8499         if (rc)
8500                 return (rc);
8501
8502         if (sc->tids.ftids_in_use == 0 || sc->tids.ftid_tab == NULL ||
8503             t->idx >= nfilters) {
8504                 t->idx = 0xffffffff;
8505                 goto done;
8506         }
8507
8508         f = &sc->tids.ftid_tab[t->idx];
8509         for (i = t->idx; i < nfilters; i++, f++) {
8510                 if (f->valid) {
8511                         t->idx = i;
8512                         t->l2tidx = f->l2t ? f->l2t->idx : 0;
8513                         t->smtidx = f->smtidx;
8514                         if (f->fs.hitcnts)
8515                                 t->hits = get_filter_hits(sc, t->idx);
8516                         else
8517                                 t->hits = UINT64_MAX;
8518                         t->fs = f->fs;
8519
8520                         goto done;
8521                 }
8522         }
8523
8524         t->idx = 0xffffffff;
8525 done:
8526         end_synchronized_op(sc, LOCK_HELD);
8527         return (0);
8528 }
8529
8530 static int
8531 set_filter(struct adapter *sc, struct t4_filter *t)
8532 {
8533         unsigned int nfilters, nports;
8534         struct filter_entry *f;
8535         int i, rc;
8536
8537         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4setf");
8538         if (rc)
8539                 return (rc);
8540
8541         nfilters = sc->tids.nftids;
8542         nports = sc->params.nports;
8543
8544         if (nfilters == 0) {
8545                 rc = ENOTSUP;
8546                 goto done;
8547         }
8548
8549         if (t->idx >= nfilters) {
8550                 rc = EINVAL;
8551                 goto done;
8552         }
8553
8554         /* Validate against the global filter mode and ingress config */
8555         rc = check_fspec_against_fconf_iconf(sc, &t->fs);
8556         if (rc != 0)
8557                 goto done;
8558
8559         if (t->fs.action == FILTER_SWITCH && t->fs.eport >= nports) {
8560                 rc = EINVAL;
8561                 goto done;
8562         }
8563
8564         if (t->fs.val.iport >= nports) {
8565                 rc = EINVAL;
8566                 goto done;
8567         }
8568
8569         /* Can't specify an iq if not steering to it */
8570         if (!t->fs.dirsteer && t->fs.iq) {
8571                 rc = EINVAL;
8572                 goto done;
8573         }
8574
8575         /* IPv6 filter idx must be 4 aligned */
8576         if (t->fs.type == 1 &&
8577             ((t->idx & 0x3) || t->idx + 4 >= nfilters)) {
8578                 rc = EINVAL;
8579                 goto done;
8580         }
8581
8582         if (!(sc->flags & FULL_INIT_DONE) &&
8583             ((rc = adapter_full_init(sc)) != 0))
8584                 goto done;
8585
8586         if (sc->tids.ftid_tab == NULL) {
8587                 KASSERT(sc->tids.ftids_in_use == 0,
8588                     ("%s: no memory allocated but filters_in_use > 0",
8589                     __func__));
8590
8591                 sc->tids.ftid_tab = malloc(sizeof (struct filter_entry) *
8592                     nfilters, M_CXGBE, M_NOWAIT | M_ZERO);
8593                 if (sc->tids.ftid_tab == NULL) {
8594                         rc = ENOMEM;
8595                         goto done;
8596                 }
8597                 mtx_init(&sc->tids.ftid_lock, "T4 filters", 0, MTX_DEF);
8598         }
8599
8600         for (i = 0; i < 4; i++) {
8601                 f = &sc->tids.ftid_tab[t->idx + i];
8602
8603                 if (f->pending || f->valid) {
8604                         rc = EBUSY;
8605                         goto done;
8606                 }
8607                 if (f->locked) {
8608                         rc = EPERM;
8609                         goto done;
8610                 }
8611
8612                 if (t->fs.type == 0)
8613                         break;
8614         }
8615
8616         f = &sc->tids.ftid_tab[t->idx];
8617         f->fs = t->fs;
8618
8619         rc = set_filter_wr(sc, t->idx);
8620 done:
8621         end_synchronized_op(sc, 0);
8622
8623         if (rc == 0) {
8624                 mtx_lock(&sc->tids.ftid_lock);
8625                 for (;;) {
8626                         if (f->pending == 0) {
8627                                 rc = f->valid ? 0 : EIO;
8628                                 break;
8629                         }
8630
8631                         if (mtx_sleep(&sc->tids.ftid_tab, &sc->tids.ftid_lock,
8632                             PCATCH, "t4setfw", 0)) {
8633                                 rc = EINPROGRESS;
8634                                 break;
8635                         }
8636                 }
8637                 mtx_unlock(&sc->tids.ftid_lock);
8638         }
8639         return (rc);
8640 }
8641
8642 static int
8643 del_filter(struct adapter *sc, struct t4_filter *t)
8644 {
8645         unsigned int nfilters;
8646         struct filter_entry *f;
8647         int rc;
8648
8649         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4delf");
8650         if (rc)
8651                 return (rc);
8652
8653         nfilters = sc->tids.nftids;
8654
8655         if (nfilters == 0) {
8656                 rc = ENOTSUP;
8657                 goto done;
8658         }
8659
8660         if (sc->tids.ftid_tab == NULL || sc->tids.ftids_in_use == 0 ||
8661             t->idx >= nfilters) {
8662                 rc = EINVAL;
8663                 goto done;
8664         }
8665
8666         if (!(sc->flags & FULL_INIT_DONE)) {
8667                 rc = EAGAIN;
8668                 goto done;
8669         }
8670
8671         f = &sc->tids.ftid_tab[t->idx];
8672
8673         if (f->pending) {
8674                 rc = EBUSY;
8675                 goto done;
8676         }
8677         if (f->locked) {
8678                 rc = EPERM;
8679                 goto done;
8680         }
8681
8682         if (f->valid) {
8683                 t->fs = f->fs;  /* extra info for the caller */
8684                 rc = del_filter_wr(sc, t->idx);
8685         }
8686
8687 done:
8688         end_synchronized_op(sc, 0);
8689
8690         if (rc == 0) {
8691                 mtx_lock(&sc->tids.ftid_lock);
8692                 for (;;) {
8693                         if (f->pending == 0) {
8694                                 rc = f->valid ? EIO : 0;
8695                                 break;
8696                         }
8697
8698                         if (mtx_sleep(&sc->tids.ftid_tab, &sc->tids.ftid_lock,
8699                             PCATCH, "t4delfw", 0)) {
8700                                 rc = EINPROGRESS;
8701                                 break;
8702                         }
8703                 }
8704                 mtx_unlock(&sc->tids.ftid_lock);
8705         }
8706
8707         return (rc);
8708 }
8709
8710 static void
8711 clear_filter(struct filter_entry *f)
8712 {
8713         if (f->l2t)
8714                 t4_l2t_release(f->l2t);
8715
8716         bzero(f, sizeof (*f));
8717 }
8718
8719 static int
8720 set_filter_wr(struct adapter *sc, int fidx)
8721 {
8722         struct filter_entry *f = &sc->tids.ftid_tab[fidx];
8723         struct fw_filter_wr *fwr;
8724         unsigned int ftid, vnic_vld, vnic_vld_mask;
8725         struct wrq_cookie cookie;
8726
8727         ASSERT_SYNCHRONIZED_OP(sc);
8728
8729         if (f->fs.newdmac || f->fs.newvlan) {
8730                 /* This filter needs an L2T entry; allocate one. */
8731                 f->l2t = t4_l2t_alloc_switching(sc->l2t);
8732                 if (f->l2t == NULL)
8733                         return (EAGAIN);
8734                 if (t4_l2t_set_switching(sc, f->l2t, f->fs.vlan, f->fs.eport,
8735                     f->fs.dmac)) {
8736                         t4_l2t_release(f->l2t);
8737                         f->l2t = NULL;
8738                         return (ENOMEM);
8739                 }
8740         }
8741
8742         /* Already validated against fconf, iconf */
8743         MPASS((f->fs.val.pfvf_vld & f->fs.val.ovlan_vld) == 0);
8744         MPASS((f->fs.mask.pfvf_vld & f->fs.mask.ovlan_vld) == 0);
8745         if (f->fs.val.pfvf_vld || f->fs.val.ovlan_vld)
8746                 vnic_vld = 1;
8747         else
8748                 vnic_vld = 0;
8749         if (f->fs.mask.pfvf_vld || f->fs.mask.ovlan_vld)
8750                 vnic_vld_mask = 1;
8751         else
8752                 vnic_vld_mask = 0;
8753
8754         ftid = sc->tids.ftid_base + fidx;
8755
8756         fwr = start_wrq_wr(&sc->sge.mgmtq, howmany(sizeof(*fwr), 16), &cookie);
8757         if (fwr == NULL)
8758                 return (ENOMEM);
8759         bzero(fwr, sizeof(*fwr));
8760
8761         fwr->op_pkd = htobe32(V_FW_WR_OP(FW_FILTER_WR));
8762         fwr->len16_pkd = htobe32(FW_LEN16(*fwr));
8763         fwr->tid_to_iq =
8764             htobe32(V_FW_FILTER_WR_TID(ftid) |
8765                 V_FW_FILTER_WR_RQTYPE(f->fs.type) |
8766                 V_FW_FILTER_WR_NOREPLY(0) |
8767                 V_FW_FILTER_WR_IQ(f->fs.iq));
8768         fwr->del_filter_to_l2tix =
8769             htobe32(V_FW_FILTER_WR_RPTTID(f->fs.rpttid) |
8770                 V_FW_FILTER_WR_DROP(f->fs.action == FILTER_DROP) |
8771                 V_FW_FILTER_WR_DIRSTEER(f->fs.dirsteer) |
8772                 V_FW_FILTER_WR_MASKHASH(f->fs.maskhash) |
8773                 V_FW_FILTER_WR_DIRSTEERHASH(f->fs.dirsteerhash) |
8774                 V_FW_FILTER_WR_LPBK(f->fs.action == FILTER_SWITCH) |
8775                 V_FW_FILTER_WR_DMAC(f->fs.newdmac) |
8776                 V_FW_FILTER_WR_SMAC(f->fs.newsmac) |
8777                 V_FW_FILTER_WR_INSVLAN(f->fs.newvlan == VLAN_INSERT ||
8778                     f->fs.newvlan == VLAN_REWRITE) |
8779                 V_FW_FILTER_WR_RMVLAN(f->fs.newvlan == VLAN_REMOVE ||
8780                     f->fs.newvlan == VLAN_REWRITE) |
8781                 V_FW_FILTER_WR_HITCNTS(f->fs.hitcnts) |
8782                 V_FW_FILTER_WR_TXCHAN(f->fs.eport) |
8783                 V_FW_FILTER_WR_PRIO(f->fs.prio) |
8784                 V_FW_FILTER_WR_L2TIX(f->l2t ? f->l2t->idx : 0));
8785         fwr->ethtype = htobe16(f->fs.val.ethtype);
8786         fwr->ethtypem = htobe16(f->fs.mask.ethtype);
8787         fwr->frag_to_ovlan_vldm =
8788             (V_FW_FILTER_WR_FRAG(f->fs.val.frag) |
8789                 V_FW_FILTER_WR_FRAGM(f->fs.mask.frag) |
8790                 V_FW_FILTER_WR_IVLAN_VLD(f->fs.val.vlan_vld) |
8791                 V_FW_FILTER_WR_OVLAN_VLD(vnic_vld) |
8792                 V_FW_FILTER_WR_IVLAN_VLDM(f->fs.mask.vlan_vld) |
8793                 V_FW_FILTER_WR_OVLAN_VLDM(vnic_vld_mask));
8794         fwr->smac_sel = 0;
8795         fwr->rx_chan_rx_rpl_iq = htobe16(V_FW_FILTER_WR_RX_CHAN(0) |
8796             V_FW_FILTER_WR_RX_RPL_IQ(sc->sge.fwq.abs_id));
8797         fwr->maci_to_matchtypem =
8798             htobe32(V_FW_FILTER_WR_MACI(f->fs.val.macidx) |
8799                 V_FW_FILTER_WR_MACIM(f->fs.mask.macidx) |
8800                 V_FW_FILTER_WR_FCOE(f->fs.val.fcoe) |
8801                 V_FW_FILTER_WR_FCOEM(f->fs.mask.fcoe) |
8802                 V_FW_FILTER_WR_PORT(f->fs.val.iport) |
8803                 V_FW_FILTER_WR_PORTM(f->fs.mask.iport) |
8804                 V_FW_FILTER_WR_MATCHTYPE(f->fs.val.matchtype) |
8805                 V_FW_FILTER_WR_MATCHTYPEM(f->fs.mask.matchtype));
8806         fwr->ptcl = f->fs.val.proto;
8807         fwr->ptclm = f->fs.mask.proto;
8808         fwr->ttyp = f->fs.val.tos;
8809         fwr->ttypm = f->fs.mask.tos;
8810         fwr->ivlan = htobe16(f->fs.val.vlan);
8811         fwr->ivlanm = htobe16(f->fs.mask.vlan);
8812         fwr->ovlan = htobe16(f->fs.val.vnic);
8813         fwr->ovlanm = htobe16(f->fs.mask.vnic);
8814         bcopy(f->fs.val.dip, fwr->lip, sizeof (fwr->lip));
8815         bcopy(f->fs.mask.dip, fwr->lipm, sizeof (fwr->lipm));
8816         bcopy(f->fs.val.sip, fwr->fip, sizeof (fwr->fip));
8817         bcopy(f->fs.mask.sip, fwr->fipm, sizeof (fwr->fipm));
8818         fwr->lp = htobe16(f->fs.val.dport);
8819         fwr->lpm = htobe16(f->fs.mask.dport);
8820         fwr->fp = htobe16(f->fs.val.sport);
8821         fwr->fpm = htobe16(f->fs.mask.sport);
8822         if (f->fs.newsmac)
8823                 bcopy(f->fs.smac, fwr->sma, sizeof (fwr->sma));
8824
8825         f->pending = 1;
8826         sc->tids.ftids_in_use++;
8827
8828         commit_wrq_wr(&sc->sge.mgmtq, fwr, &cookie);
8829         return (0);
8830 }
8831
8832 static int
8833 del_filter_wr(struct adapter *sc, int fidx)
8834 {
8835         struct filter_entry *f = &sc->tids.ftid_tab[fidx];
8836         struct fw_filter_wr *fwr;
8837         unsigned int ftid;
8838         struct wrq_cookie cookie;
8839
8840         ftid = sc->tids.ftid_base + fidx;
8841
8842         fwr = start_wrq_wr(&sc->sge.mgmtq, howmany(sizeof(*fwr), 16), &cookie);
8843         if (fwr == NULL)
8844                 return (ENOMEM);
8845         bzero(fwr, sizeof (*fwr));
8846
8847         t4_mk_filtdelwr(ftid, fwr, sc->sge.fwq.abs_id);
8848
8849         f->pending = 1;
8850         commit_wrq_wr(&sc->sge.mgmtq, fwr, &cookie);
8851         return (0);
8852 }
8853
8854 int
8855 t4_filter_rpl(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
8856 {
8857         struct adapter *sc = iq->adapter;
8858         const struct cpl_set_tcb_rpl *rpl = (const void *)(rss + 1);
8859         unsigned int idx = GET_TID(rpl);
8860         unsigned int rc;
8861         struct filter_entry *f;
8862
8863         KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
8864             rss->opcode));
8865         MPASS(iq == &sc->sge.fwq);
8866         MPASS(is_ftid(sc, idx));
8867
8868         idx -= sc->tids.ftid_base;
8869         f = &sc->tids.ftid_tab[idx];
8870         rc = G_COOKIE(rpl->cookie);
8871
8872         mtx_lock(&sc->tids.ftid_lock);
8873         if (rc == FW_FILTER_WR_FLT_ADDED) {
8874                 KASSERT(f->pending, ("%s: filter[%u] isn't pending.",
8875                     __func__, idx));
8876                 f->smtidx = (be64toh(rpl->oldval) >> 24) & 0xff;
8877                 f->pending = 0;  /* asynchronous setup completed */
8878                 f->valid = 1;
8879         } else {
8880                 if (rc != FW_FILTER_WR_FLT_DELETED) {
8881                         /* Add or delete failed, display an error */
8882                         log(LOG_ERR,
8883                             "filter %u setup failed with error %u\n",
8884                             idx, rc);
8885                 }
8886
8887                 clear_filter(f);
8888                 sc->tids.ftids_in_use--;
8889         }
8890         wakeup(&sc->tids.ftid_tab);
8891         mtx_unlock(&sc->tids.ftid_lock);
8892
8893         return (0);
8894 }
8895
8896 static int
8897 set_tcb_rpl(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
8898 {
8899
8900         MPASS(iq->set_tcb_rpl != NULL);
8901         return (iq->set_tcb_rpl(iq, rss, m));
8902 }
8903
8904 static int
8905 l2t_write_rpl(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
8906 {
8907
8908         MPASS(iq->l2t_write_rpl != NULL);
8909         return (iq->l2t_write_rpl(iq, rss, m));
8910 }
8911
8912 static int
8913 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
8914 {
8915         int rc;
8916
8917         if (cntxt->cid > M_CTXTQID)
8918                 return (EINVAL);
8919
8920         if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
8921             cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
8922                 return (EINVAL);
8923
8924         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
8925         if (rc)
8926                 return (rc);
8927
8928         if (sc->flags & FW_OK) {
8929                 rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
8930                     &cntxt->data[0]);
8931                 if (rc == 0)
8932                         goto done;
8933         }
8934
8935         /*
8936          * Read via firmware failed or wasn't even attempted.  Read directly via
8937          * the backdoor.
8938          */
8939         rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
8940 done:
8941         end_synchronized_op(sc, 0);
8942         return (rc);
8943 }
8944
8945 static int
8946 load_fw(struct adapter *sc, struct t4_data *fw)
8947 {
8948         int rc;
8949         uint8_t *fw_data;
8950
8951         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
8952         if (rc)
8953                 return (rc);
8954
8955         if (sc->flags & FULL_INIT_DONE) {
8956                 rc = EBUSY;
8957                 goto done;
8958         }
8959
8960         fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
8961         if (fw_data == NULL) {
8962                 rc = ENOMEM;
8963                 goto done;
8964         }
8965
8966         rc = copyin(fw->data, fw_data, fw->len);
8967         if (rc == 0)
8968                 rc = -t4_load_fw(sc, fw_data, fw->len);
8969
8970         free(fw_data, M_CXGBE);
8971 done:
8972         end_synchronized_op(sc, 0);
8973         return (rc);
8974 }
8975
8976 static int
8977 load_cfg(struct adapter *sc, struct t4_data *cfg)
8978 {
8979         int rc;
8980         uint8_t *cfg_data = NULL;
8981
8982         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
8983         if (rc)
8984                 return (rc);
8985
8986         if (cfg->len == 0) {
8987                 /* clear */
8988                 rc = -t4_load_cfg(sc, NULL, 0);
8989                 goto done;
8990         }
8991
8992         cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
8993         if (cfg_data == NULL) {
8994                 rc = ENOMEM;
8995                 goto done;
8996         }
8997
8998         rc = copyin(cfg->data, cfg_data, cfg->len);
8999         if (rc == 0)
9000                 rc = -t4_load_cfg(sc, cfg_data, cfg->len);
9001
9002         free(cfg_data, M_CXGBE);
9003 done:
9004         end_synchronized_op(sc, 0);
9005         return (rc);
9006 }
9007
9008 static int
9009 load_boot(struct adapter *sc, struct t4_bootrom *br)
9010 {
9011         int rc;
9012         uint8_t *br_data = NULL;
9013         u_int offset;
9014
9015         if (br->len > 1024 * 1024)
9016                 return (EFBIG);
9017
9018         if (br->pf_offset == 0) {
9019                 /* pfidx */
9020                 if (br->pfidx_addr > 7)
9021                         return (EINVAL);
9022                 offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
9023                     A_PCIE_PF_EXPROM_OFST)));
9024         } else if (br->pf_offset == 1) {
9025                 /* offset */
9026                 offset = G_OFFSET(br->pfidx_addr);
9027         } else {
9028                 return (EINVAL);
9029         }
9030
9031         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
9032         if (rc)
9033                 return (rc);
9034
9035         if (br->len == 0) {
9036                 /* clear */
9037                 rc = -t4_load_boot(sc, NULL, offset, 0);
9038                 goto done;
9039         }
9040
9041         br_data = malloc(br->len, M_CXGBE, M_WAITOK);
9042         if (br_data == NULL) {
9043                 rc = ENOMEM;
9044                 goto done;
9045         }
9046
9047         rc = copyin(br->data, br_data, br->len);
9048         if (rc == 0)
9049                 rc = -t4_load_boot(sc, br_data, offset, br->len);
9050
9051         free(br_data, M_CXGBE);
9052 done:
9053         end_synchronized_op(sc, 0);
9054         return (rc);
9055 }
9056
9057 static int
9058 load_bootcfg(struct adapter *sc, struct t4_data *bc)
9059 {
9060         int rc;
9061         uint8_t *bc_data = NULL;
9062
9063         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
9064         if (rc)
9065                 return (rc);
9066
9067         if (bc->len == 0) {
9068                 /* clear */
9069                 rc = -t4_load_bootcfg(sc, NULL, 0);
9070                 goto done;
9071         }
9072
9073         bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
9074         if (bc_data == NULL) {
9075                 rc = ENOMEM;
9076                 goto done;
9077         }
9078
9079         rc = copyin(bc->data, bc_data, bc->len);
9080         if (rc == 0)
9081                 rc = -t4_load_bootcfg(sc, bc_data, bc->len);
9082
9083         free(bc_data, M_CXGBE);
9084 done:
9085         end_synchronized_op(sc, 0);
9086         return (rc);
9087 }
9088
9089 static int
9090 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
9091 {
9092         int rc;
9093         struct cudbg_init *cudbg;
9094         void *handle, *buf;
9095
9096         /* buf is large, don't block if no memory is available */
9097         buf = malloc(dump->len, M_CXGBE, M_NOWAIT);
9098         if (buf == NULL)
9099                 return (ENOMEM);
9100
9101         handle = cudbg_alloc_handle();
9102         if (handle == NULL) {
9103                 rc = ENOMEM;
9104                 goto done;
9105         }
9106
9107         cudbg = cudbg_get_init(handle);
9108         cudbg->adap = sc;
9109         cudbg->print = (cudbg_print_cb)printf;
9110
9111 #ifndef notyet
9112         device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
9113             __func__, dump->wr_flash, dump->len, dump->data);
9114 #endif
9115
9116         if (dump->wr_flash)
9117                 cudbg->use_flash = 1;
9118         MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
9119         memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
9120
9121         rc = cudbg_collect(handle, buf, &dump->len);
9122         if (rc != 0)
9123                 goto done;
9124
9125         rc = copyout(buf, dump->data, dump->len);
9126 done:
9127         cudbg_free_handle(handle);
9128         free(buf, M_CXGBE);
9129         return (rc);
9130 }
9131
9132 #define MAX_READ_BUF_SIZE (128 * 1024)
9133 static int
9134 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
9135 {
9136         uint32_t addr, remaining, n;
9137         uint32_t *buf;
9138         int rc;
9139         uint8_t *dst;
9140
9141         rc = validate_mem_range(sc, mr->addr, mr->len);
9142         if (rc != 0)
9143                 return (rc);
9144
9145         buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
9146         addr = mr->addr;
9147         remaining = mr->len;
9148         dst = (void *)mr->data;
9149
9150         while (remaining) {
9151                 n = min(remaining, MAX_READ_BUF_SIZE);
9152                 read_via_memwin(sc, 2, addr, buf, n);
9153
9154                 rc = copyout(buf, dst, n);
9155                 if (rc != 0)
9156                         break;
9157
9158                 dst += n;
9159                 remaining -= n;
9160                 addr += n;
9161         }
9162
9163         free(buf, M_CXGBE);
9164         return (rc);
9165 }
9166 #undef MAX_READ_BUF_SIZE
9167
9168 static int
9169 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
9170 {
9171         int rc;
9172
9173         if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
9174                 return (EINVAL);
9175
9176         if (i2cd->len > sizeof(i2cd->data))
9177                 return (EFBIG);
9178
9179         rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
9180         if (rc)
9181                 return (rc);
9182         rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
9183             i2cd->offset, i2cd->len, &i2cd->data[0]);
9184         end_synchronized_op(sc, 0);
9185
9186         return (rc);
9187 }
9188
9189 int
9190 t4_os_find_pci_capability(struct adapter *sc, int cap)
9191 {
9192         int i;
9193
9194         return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
9195 }
9196
9197 int
9198 t4_os_pci_save_state(struct adapter *sc)
9199 {
9200         device_t dev;
9201         struct pci_devinfo *dinfo;
9202
9203         dev = sc->dev;
9204         dinfo = device_get_ivars(dev);
9205
9206         pci_cfg_save(dev, dinfo, 0);
9207         return (0);
9208 }
9209
9210 int
9211 t4_os_pci_restore_state(struct adapter *sc)
9212 {
9213         device_t dev;
9214         struct pci_devinfo *dinfo;
9215
9216         dev = sc->dev;
9217         dinfo = device_get_ivars(dev);
9218
9219         pci_cfg_restore(dev, dinfo);
9220         return (0);
9221 }
9222
9223 void
9224 t4_os_portmod_changed(struct port_info *pi, int old_ptype, int old_mtype,
9225     struct link_config *old_lc)
9226 {
9227         struct vi_info *vi;
9228         struct ifnet *ifp;
9229         int v;
9230         static const char *mod_str[] = {
9231                 NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
9232         };
9233
9234         PORT_LOCK(pi);
9235         for_each_vi(pi, v, vi) {
9236                 build_medialist(pi, &vi->media);
9237         }
9238         PORT_UNLOCK(pi);
9239         vi = &pi->vi[0];
9240         if (begin_synchronized_op(pi->adapter, vi, HOLD_LOCK, "t4mod") == 0) {
9241                 init_l1cfg(pi);
9242                 end_synchronized_op(pi->adapter, LOCK_HELD);
9243         }
9244
9245         ifp = vi->ifp;
9246         if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
9247                 if_printf(ifp, "transceiver unplugged.\n");
9248         else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
9249                 if_printf(ifp, "unknown transceiver inserted.\n");
9250         else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
9251                 if_printf(ifp, "unsupported transceiver inserted.\n");
9252         else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
9253                 if_printf(ifp, "%dGbps %s transceiver inserted.\n",
9254                     port_top_speed(pi), mod_str[pi->mod_type]);
9255         } else {
9256                 if_printf(ifp, "transceiver (type %d) inserted.\n",
9257                     pi->mod_type);
9258         }
9259 }
9260
9261 void
9262 t4_os_link_changed(struct port_info *pi, struct link_config *old_lc)
9263 {
9264         struct vi_info *vi;
9265         struct ifnet *ifp;
9266         struct link_config *lc;
9267         int v;
9268
9269         for_each_vi(pi, v, vi) {
9270                 ifp = vi->ifp;
9271                 if (ifp == NULL)
9272                         continue;
9273
9274                 lc = &pi->link_cfg;
9275                 if (lc->link_ok) {
9276                         ifp->if_baudrate = IF_Mbps(lc->speed);
9277                         if_link_state_change(ifp, LINK_STATE_UP);
9278                 } else {
9279                         if_link_state_change(ifp, LINK_STATE_DOWN);
9280                 }
9281         }
9282 }
9283
9284 void
9285 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
9286 {
9287         struct adapter *sc;
9288
9289         sx_slock(&t4_list_lock);
9290         SLIST_FOREACH(sc, &t4_list, link) {
9291                 /*
9292                  * func should not make any assumptions about what state sc is
9293                  * in - the only guarantee is that sc->sc_lock is a valid lock.
9294                  */
9295                 func(sc, arg);
9296         }
9297         sx_sunlock(&t4_list_lock);
9298 }
9299
9300 static int
9301 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
9302     struct thread *td)
9303 {
9304         int rc;
9305         struct adapter *sc = dev->si_drv1;
9306
9307         rc = priv_check(td, PRIV_DRIVER);
9308         if (rc != 0)
9309                 return (rc);
9310
9311         switch (cmd) {
9312         case CHELSIO_T4_GETREG: {
9313                 struct t4_reg *edata = (struct t4_reg *)data;
9314
9315                 if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
9316                         return (EFAULT);
9317
9318                 if (edata->size == 4)
9319                         edata->val = t4_read_reg(sc, edata->addr);
9320                 else if (edata->size == 8)
9321                         edata->val = t4_read_reg64(sc, edata->addr);
9322                 else
9323                         return (EINVAL);
9324
9325                 break;
9326         }
9327         case CHELSIO_T4_SETREG: {
9328                 struct t4_reg *edata = (struct t4_reg *)data;
9329
9330                 if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
9331                         return (EFAULT);
9332
9333                 if (edata->size == 4) {
9334                         if (edata->val & 0xffffffff00000000)
9335                                 return (EINVAL);
9336                         t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
9337                 } else if (edata->size == 8)
9338                         t4_write_reg64(sc, edata->addr, edata->val);
9339                 else
9340                         return (EINVAL);
9341                 break;
9342         }
9343         case CHELSIO_T4_REGDUMP: {
9344                 struct t4_regdump *regs = (struct t4_regdump *)data;
9345                 int reglen = t4_get_regs_len(sc);
9346                 uint8_t *buf;
9347
9348                 if (regs->len < reglen) {
9349                         regs->len = reglen; /* hint to the caller */
9350                         return (ENOBUFS);
9351                 }
9352
9353                 regs->len = reglen;
9354                 buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
9355                 get_regs(sc, regs, buf);
9356                 rc = copyout(buf, regs->data, reglen);
9357                 free(buf, M_CXGBE);
9358                 break;
9359         }
9360         case CHELSIO_T4_GET_FILTER_MODE:
9361                 rc = get_filter_mode(sc, (uint32_t *)data);
9362                 break;
9363         case CHELSIO_T4_SET_FILTER_MODE:
9364                 rc = set_filter_mode(sc, *(uint32_t *)data);
9365                 break;
9366         case CHELSIO_T4_GET_FILTER:
9367                 rc = get_filter(sc, (struct t4_filter *)data);
9368                 break;
9369         case CHELSIO_T4_SET_FILTER:
9370                 rc = set_filter(sc, (struct t4_filter *)data);
9371                 break;
9372         case CHELSIO_T4_DEL_FILTER:
9373                 rc = del_filter(sc, (struct t4_filter *)data);
9374                 break;
9375         case CHELSIO_T4_GET_SGE_CONTEXT:
9376                 rc = get_sge_context(sc, (struct t4_sge_context *)data);
9377                 break;
9378         case CHELSIO_T4_LOAD_FW:
9379                 rc = load_fw(sc, (struct t4_data *)data);
9380                 break;
9381         case CHELSIO_T4_GET_MEM:
9382                 rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
9383                 break;
9384         case CHELSIO_T4_GET_I2C:
9385                 rc = read_i2c(sc, (struct t4_i2c_data *)data);
9386                 break;
9387         case CHELSIO_T4_CLEAR_STATS: {
9388                 int i, v;
9389                 u_int port_id = *(uint32_t *)data;
9390                 struct port_info *pi;
9391                 struct vi_info *vi;
9392
9393                 if (port_id >= sc->params.nports)
9394                         return (EINVAL);
9395                 pi = sc->port[port_id];
9396                 if (pi == NULL)
9397                         return (EIO);
9398
9399                 /* MAC stats */
9400                 t4_clr_port_stats(sc, pi->tx_chan);
9401                 pi->tx_parse_error = 0;
9402                 mtx_lock(&sc->reg_lock);
9403                 for_each_vi(pi, v, vi) {
9404                         if (vi->flags & VI_INIT_DONE)
9405                                 t4_clr_vi_stats(sc, vi->viid);
9406                 }
9407                 mtx_unlock(&sc->reg_lock);
9408
9409                 /*
9410                  * Since this command accepts a port, clear stats for
9411                  * all VIs on this port.
9412                  */
9413                 for_each_vi(pi, v, vi) {
9414                         if (vi->flags & VI_INIT_DONE) {
9415                                 struct sge_rxq *rxq;
9416                                 struct sge_txq *txq;
9417                                 struct sge_wrq *wrq;
9418
9419                                 for_each_rxq(vi, i, rxq) {
9420 #if defined(INET) || defined(INET6)
9421                                         rxq->lro.lro_queued = 0;
9422                                         rxq->lro.lro_flushed = 0;
9423 #endif
9424                                         rxq->rxcsum = 0;
9425                                         rxq->vlan_extraction = 0;
9426                                 }
9427
9428                                 for_each_txq(vi, i, txq) {
9429                                         txq->txcsum = 0;
9430                                         txq->tso_wrs = 0;
9431                                         txq->vlan_insertion = 0;
9432                                         txq->imm_wrs = 0;
9433                                         txq->sgl_wrs = 0;
9434                                         txq->txpkt_wrs = 0;
9435                                         txq->txpkts0_wrs = 0;
9436                                         txq->txpkts1_wrs = 0;
9437                                         txq->txpkts0_pkts = 0;
9438                                         txq->txpkts1_pkts = 0;
9439                                         mp_ring_reset_stats(txq->r);
9440                                 }
9441
9442 #ifdef TCP_OFFLOAD
9443                                 /* nothing to clear for each ofld_rxq */
9444
9445                                 for_each_ofld_txq(vi, i, wrq) {
9446                                         wrq->tx_wrs_direct = 0;
9447                                         wrq->tx_wrs_copied = 0;
9448                                 }
9449 #endif
9450
9451                                 if (IS_MAIN_VI(vi)) {
9452                                         wrq = &sc->sge.ctrlq[pi->port_id];
9453                                         wrq->tx_wrs_direct = 0;
9454                                         wrq->tx_wrs_copied = 0;
9455                                 }
9456                         }
9457                 }
9458                 break;
9459         }
9460         case CHELSIO_T4_SCHED_CLASS:
9461                 rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
9462                 break;
9463         case CHELSIO_T4_SCHED_QUEUE:
9464                 rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
9465                 break;
9466         case CHELSIO_T4_GET_TRACER:
9467                 rc = t4_get_tracer(sc, (struct t4_tracer *)data);
9468                 break;
9469         case CHELSIO_T4_SET_TRACER:
9470                 rc = t4_set_tracer(sc, (struct t4_tracer *)data);
9471                 break;
9472         case CHELSIO_T4_LOAD_CFG:
9473                 rc = load_cfg(sc, (struct t4_data *)data);
9474                 break;
9475         case CHELSIO_T4_LOAD_BOOT:
9476                 rc = load_boot(sc, (struct t4_bootrom *)data);
9477                 break;
9478         case CHELSIO_T4_LOAD_BOOTCFG:
9479                 rc = load_bootcfg(sc, (struct t4_data *)data);
9480                 break;
9481         case CHELSIO_T4_CUDBG_DUMP:
9482                 rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
9483                 break;
9484         default:
9485                 rc = ENOTTY;
9486         }
9487
9488         return (rc);
9489 }
9490
9491 void
9492 t4_db_full(struct adapter *sc)
9493 {
9494
9495         CXGBE_UNIMPLEMENTED(__func__);
9496 }
9497
9498 void
9499 t4_db_dropped(struct adapter *sc)
9500 {
9501
9502         CXGBE_UNIMPLEMENTED(__func__);
9503 }
9504
9505 #ifdef TCP_OFFLOAD
9506 static int
9507 toe_capability(struct vi_info *vi, int enable)
9508 {
9509         int rc;
9510         struct port_info *pi = vi->pi;
9511         struct adapter *sc = pi->adapter;
9512
9513         ASSERT_SYNCHRONIZED_OP(sc);
9514
9515         if (!is_offload(sc))
9516                 return (ENODEV);
9517
9518         if (enable) {
9519                 if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
9520                         /* TOE is already enabled. */
9521                         return (0);
9522                 }
9523
9524                 /*
9525                  * We need the port's queues around so that we're able to send
9526                  * and receive CPLs to/from the TOE even if the ifnet for this
9527                  * port has never been UP'd administratively.
9528                  */
9529                 if (!(vi->flags & VI_INIT_DONE)) {
9530                         rc = vi_full_init(vi);
9531                         if (rc)
9532                                 return (rc);
9533                 }
9534                 if (!(pi->vi[0].flags & VI_INIT_DONE)) {
9535                         rc = vi_full_init(&pi->vi[0]);
9536                         if (rc)
9537                                 return (rc);
9538                 }
9539
9540                 if (isset(&sc->offload_map, pi->port_id)) {
9541                         /* TOE is enabled on another VI of this port. */
9542                         pi->uld_vis++;
9543                         return (0);
9544                 }
9545
9546                 if (!uld_active(sc, ULD_TOM)) {
9547                         rc = t4_activate_uld(sc, ULD_TOM);
9548                         if (rc == EAGAIN) {
9549                                 log(LOG_WARNING,
9550                                     "You must kldload t4_tom.ko before trying "
9551                                     "to enable TOE on a cxgbe interface.\n");
9552                         }
9553                         if (rc != 0)
9554                                 return (rc);
9555                         KASSERT(sc->tom_softc != NULL,
9556                             ("%s: TOM activated but softc NULL", __func__));
9557                         KASSERT(uld_active(sc, ULD_TOM),
9558                             ("%s: TOM activated but flag not set", __func__));
9559                 }
9560
9561                 /* Activate iWARP and iSCSI too, if the modules are loaded. */
9562                 if (!uld_active(sc, ULD_IWARP))
9563                         (void) t4_activate_uld(sc, ULD_IWARP);
9564                 if (!uld_active(sc, ULD_ISCSI))
9565                         (void) t4_activate_uld(sc, ULD_ISCSI);
9566
9567                 pi->uld_vis++;
9568                 setbit(&sc->offload_map, pi->port_id);
9569         } else {
9570                 pi->uld_vis--;
9571
9572                 if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
9573                         return (0);
9574
9575                 KASSERT(uld_active(sc, ULD_TOM),
9576                     ("%s: TOM never initialized?", __func__));
9577                 clrbit(&sc->offload_map, pi->port_id);
9578         }
9579
9580         return (0);
9581 }
9582
9583 /*
9584  * Add an upper layer driver to the global list.
9585  */
9586 int
9587 t4_register_uld(struct uld_info *ui)
9588 {
9589         int rc = 0;
9590         struct uld_info *u;
9591
9592         sx_xlock(&t4_uld_list_lock);
9593         SLIST_FOREACH(u, &t4_uld_list, link) {
9594             if (u->uld_id == ui->uld_id) {
9595                     rc = EEXIST;
9596                     goto done;
9597             }
9598         }
9599
9600         SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
9601         ui->refcount = 0;
9602 done:
9603         sx_xunlock(&t4_uld_list_lock);
9604         return (rc);
9605 }
9606
9607 int
9608 t4_unregister_uld(struct uld_info *ui)
9609 {
9610         int rc = EINVAL;
9611         struct uld_info *u;
9612
9613         sx_xlock(&t4_uld_list_lock);
9614
9615         SLIST_FOREACH(u, &t4_uld_list, link) {
9616             if (u == ui) {
9617                     if (ui->refcount > 0) {
9618                             rc = EBUSY;
9619                             goto done;
9620                     }
9621
9622                     SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
9623                     rc = 0;
9624                     goto done;
9625             }
9626         }
9627 done:
9628         sx_xunlock(&t4_uld_list_lock);
9629         return (rc);
9630 }
9631
9632 int
9633 t4_activate_uld(struct adapter *sc, int id)
9634 {
9635         int rc;
9636         struct uld_info *ui;
9637
9638         ASSERT_SYNCHRONIZED_OP(sc);
9639
9640         if (id < 0 || id > ULD_MAX)
9641                 return (EINVAL);
9642         rc = EAGAIN;    /* kldoad the module with this ULD and try again. */
9643
9644         sx_slock(&t4_uld_list_lock);
9645
9646         SLIST_FOREACH(ui, &t4_uld_list, link) {
9647                 if (ui->uld_id == id) {
9648                         if (!(sc->flags & FULL_INIT_DONE)) {
9649                                 rc = adapter_full_init(sc);
9650                                 if (rc != 0)
9651                                         break;
9652                         }
9653
9654                         rc = ui->activate(sc);
9655                         if (rc == 0) {
9656                                 setbit(&sc->active_ulds, id);
9657                                 ui->refcount++;
9658                         }
9659                         break;
9660                 }
9661         }
9662
9663         sx_sunlock(&t4_uld_list_lock);
9664
9665         return (rc);
9666 }
9667
9668 int
9669 t4_deactivate_uld(struct adapter *sc, int id)
9670 {
9671         int rc;
9672         struct uld_info *ui;
9673
9674         ASSERT_SYNCHRONIZED_OP(sc);
9675
9676         if (id < 0 || id > ULD_MAX)
9677                 return (EINVAL);
9678         rc = ENXIO;
9679
9680         sx_slock(&t4_uld_list_lock);
9681
9682         SLIST_FOREACH(ui, &t4_uld_list, link) {
9683                 if (ui->uld_id == id) {
9684                         rc = ui->deactivate(sc);
9685                         if (rc == 0) {
9686                                 clrbit(&sc->active_ulds, id);
9687                                 ui->refcount--;
9688                         }
9689                         break;
9690                 }
9691         }
9692
9693         sx_sunlock(&t4_uld_list_lock);
9694
9695         return (rc);
9696 }
9697
9698 int
9699 uld_active(struct adapter *sc, int uld_id)
9700 {
9701
9702         MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
9703
9704         return (isset(&sc->active_ulds, uld_id));
9705 }
9706 #endif
9707
9708 /*
9709  * t  = ptr to tunable.
9710  * nc = number of CPUs.
9711  * c  = compiled in default for that tunable.
9712  */
9713 static void
9714 calculate_nqueues(int *t, int nc, const int c)
9715 {
9716         int nq;
9717
9718         if (*t > 0)
9719                 return;
9720         nq = *t < 0 ? -*t : c;
9721         *t = min(nc, nq);
9722 }
9723
9724 /*
9725  * Come up with reasonable defaults for some of the tunables, provided they're
9726  * not set by the user (in which case we'll use the values as is).
9727  */
9728 static void
9729 tweak_tunables(void)
9730 {
9731         int nc = mp_ncpus;      /* our snapshot of the number of CPUs */
9732
9733         if (t4_ntxq10g < 1) {
9734 #ifdef RSS
9735                 t4_ntxq10g = rss_getnumbuckets();
9736 #else
9737                 calculate_nqueues(&t4_ntxq10g, nc, NTXQ_10G);
9738 #endif
9739         }
9740
9741         if (t4_ntxq1g < 1) {
9742 #ifdef RSS
9743                 /* XXX: way too many for 1GbE? */
9744                 t4_ntxq1g = rss_getnumbuckets();
9745 #else
9746                 calculate_nqueues(&t4_ntxq1g, nc, NTXQ_1G);
9747 #endif
9748         }
9749
9750         calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
9751
9752         if (t4_nrxq10g < 1) {
9753 #ifdef RSS
9754                 t4_nrxq10g = rss_getnumbuckets();
9755 #else
9756                 calculate_nqueues(&t4_nrxq10g, nc, NRXQ_10G);
9757 #endif
9758         }
9759
9760         if (t4_nrxq1g < 1) {
9761 #ifdef RSS
9762                 /* XXX: way too many for 1GbE? */
9763                 t4_nrxq1g = rss_getnumbuckets();
9764 #else
9765                 calculate_nqueues(&t4_nrxq1g, nc, NRXQ_1G);
9766 #endif
9767         }
9768
9769         calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
9770
9771 #ifdef TCP_OFFLOAD
9772         calculate_nqueues(&t4_nofldtxq10g, nc, NOFLDTXQ_10G);
9773         calculate_nqueues(&t4_nofldtxq1g, nc, NOFLDTXQ_1G);
9774         calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
9775         calculate_nqueues(&t4_nofldrxq10g, nc, NOFLDRXQ_10G);
9776         calculate_nqueues(&t4_nofldrxq1g, nc, NOFLDRXQ_1G);
9777         calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
9778
9779         if (t4_toecaps_allowed == -1)
9780                 t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
9781
9782         if (t4_rdmacaps_allowed == -1) {
9783                 t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
9784                     FW_CAPS_CONFIG_RDMA_RDMAC;
9785         }
9786
9787         if (t4_iscsicaps_allowed == -1) {
9788                 t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
9789                     FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
9790                     FW_CAPS_CONFIG_ISCSI_T10DIF;
9791         }
9792 #else
9793         if (t4_toecaps_allowed == -1)
9794                 t4_toecaps_allowed = 0;
9795
9796         if (t4_rdmacaps_allowed == -1)
9797                 t4_rdmacaps_allowed = 0;
9798
9799         if (t4_iscsicaps_allowed == -1)
9800                 t4_iscsicaps_allowed = 0;
9801 #endif
9802
9803 #ifdef DEV_NETMAP
9804         calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
9805         calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
9806 #endif
9807
9808         if (t4_tmr_idx_10g < 0 || t4_tmr_idx_10g >= SGE_NTIMERS)
9809                 t4_tmr_idx_10g = TMR_IDX_10G;
9810
9811         if (t4_pktc_idx_10g < -1 || t4_pktc_idx_10g >= SGE_NCOUNTERS)
9812                 t4_pktc_idx_10g = PKTC_IDX_10G;
9813
9814         if (t4_tmr_idx_1g < 0 || t4_tmr_idx_1g >= SGE_NTIMERS)
9815                 t4_tmr_idx_1g = TMR_IDX_1G;
9816
9817         if (t4_pktc_idx_1g < -1 || t4_pktc_idx_1g >= SGE_NCOUNTERS)
9818                 t4_pktc_idx_1g = PKTC_IDX_1G;
9819
9820         if (t4_qsize_txq < 128)
9821                 t4_qsize_txq = 128;
9822
9823         if (t4_qsize_rxq < 128)
9824                 t4_qsize_rxq = 128;
9825         while (t4_qsize_rxq & 7)
9826                 t4_qsize_rxq++;
9827
9828         t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
9829 }
9830
9831 #ifdef DDB
9832 static void
9833 t4_dump_tcb(struct adapter *sc, int tid)
9834 {
9835         uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
9836
9837         reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
9838         save = t4_read_reg(sc, reg);
9839         base = sc->memwin[2].mw_base;
9840
9841         /* Dump TCB for the tid */
9842         tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9843         tcb_addr += tid * TCB_SIZE;
9844
9845         if (is_t4(sc)) {
9846                 pf = 0;
9847                 win_pos = tcb_addr & ~0xf;      /* start must be 16B aligned */
9848         } else {
9849                 pf = V_PFNUM(sc->pf);
9850                 win_pos = tcb_addr & ~0x7f;     /* start must be 128B aligned */
9851         }
9852         t4_write_reg(sc, reg, win_pos | pf);
9853         t4_read_reg(sc, reg);
9854
9855         off = tcb_addr - win_pos;
9856         for (i = 0; i < 4; i++) {
9857                 uint32_t buf[8];
9858                 for (j = 0; j < 8; j++, off += 4)
9859                         buf[j] = htonl(t4_read_reg(sc, base + off));
9860
9861                 db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
9862                     buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
9863                     buf[7]);
9864         }
9865
9866         t4_write_reg(sc, reg, save);
9867         t4_read_reg(sc, reg);
9868 }
9869
9870 static void
9871 t4_dump_devlog(struct adapter *sc)
9872 {
9873         struct devlog_params *dparams = &sc->params.devlog;
9874         struct fw_devlog_e e;
9875         int i, first, j, m, nentries, rc;
9876         uint64_t ftstamp = UINT64_MAX;
9877
9878         if (dparams->start == 0) {
9879                 db_printf("devlog params not valid\n");
9880                 return;
9881         }
9882
9883         nentries = dparams->size / sizeof(struct fw_devlog_e);
9884         m = fwmtype_to_hwmtype(dparams->memtype);
9885
9886         /* Find the first entry. */
9887         first = -1;
9888         for (i = 0; i < nentries && !db_pager_quit; i++) {
9889                 rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
9890                     sizeof(e), (void *)&e);
9891                 if (rc != 0)
9892                         break;
9893
9894                 if (e.timestamp == 0)
9895                         break;
9896
9897                 e.timestamp = be64toh(e.timestamp);
9898                 if (e.timestamp < ftstamp) {
9899                         ftstamp = e.timestamp;
9900                         first = i;
9901                 }
9902         }
9903
9904         if (first == -1)
9905                 return;
9906
9907         i = first;
9908         do {
9909                 rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
9910                     sizeof(e), (void *)&e);
9911                 if (rc != 0)
9912                         return;
9913
9914                 if (e.timestamp == 0)
9915                         return;
9916
9917                 e.timestamp = be64toh(e.timestamp);
9918                 e.seqno = be32toh(e.seqno);
9919                 for (j = 0; j < 8; j++)
9920                         e.params[j] = be32toh(e.params[j]);
9921
9922                 db_printf("%10d  %15ju  %8s  %8s  ",
9923                     e.seqno, e.timestamp,
9924                     (e.level < nitems(devlog_level_strings) ?
9925                         devlog_level_strings[e.level] : "UNKNOWN"),
9926                     (e.facility < nitems(devlog_facility_strings) ?
9927                         devlog_facility_strings[e.facility] : "UNKNOWN"));
9928                 db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
9929                     e.params[3], e.params[4], e.params[5], e.params[6],
9930                     e.params[7]);
9931
9932                 if (++i == nentries)
9933                         i = 0;
9934         } while (i != first && !db_pager_quit);
9935 }
9936
9937 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
9938 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
9939
9940 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
9941 {
9942         device_t dev;
9943         int t;
9944         bool valid;
9945
9946         valid = false;
9947         t = db_read_token();
9948         if (t == tIDENT) {
9949                 dev = device_lookup_by_name(db_tok_string);
9950                 valid = true;
9951         }
9952         db_skip_to_eol();
9953         if (!valid) {
9954                 db_printf("usage: show t4 devlog <nexus>\n");
9955                 return;
9956         }
9957
9958         if (dev == NULL) {
9959                 db_printf("device not found\n");
9960                 return;
9961         }
9962
9963         t4_dump_devlog(device_get_softc(dev));
9964 }
9965
9966 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
9967 {
9968         device_t dev;
9969         int radix, tid, t;
9970         bool valid;
9971
9972         valid = false;
9973         radix = db_radix;
9974         db_radix = 10;
9975         t = db_read_token();
9976         if (t == tIDENT) {
9977                 dev = device_lookup_by_name(db_tok_string);
9978                 t = db_read_token();
9979                 if (t == tNUMBER) {
9980                         tid = db_tok_number;
9981                         valid = true;
9982                 }
9983         }       
9984         db_radix = radix;
9985         db_skip_to_eol();
9986         if (!valid) {
9987                 db_printf("usage: show t4 tcb <nexus> <tid>\n");
9988                 return;
9989         }
9990
9991         if (dev == NULL) {
9992                 db_printf("device not found\n");
9993                 return;
9994         }
9995         if (tid < 0) {
9996                 db_printf("invalid tid\n");
9997                 return;
9998         }
9999
10000         t4_dump_tcb(device_get_softc(dev), tid);
10001 }
10002 #endif
10003
10004 static struct sx mlu;   /* mod load unload */
10005 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
10006
10007 static int
10008 mod_event(module_t mod, int cmd, void *arg)
10009 {
10010         int rc = 0;
10011         static int loaded = 0;
10012
10013         switch (cmd) {
10014         case MOD_LOAD:
10015                 sx_xlock(&mlu);
10016                 if (loaded++ == 0) {
10017                         t4_sge_modload();
10018                         t4_register_cpl_handler(CPL_SET_TCB_RPL, set_tcb_rpl);
10019                         t4_register_cpl_handler(CPL_L2T_WRITE_RPL, l2t_write_rpl);
10020                         t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
10021                         t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
10022                         sx_init(&t4_list_lock, "T4/T5 adapters");
10023                         SLIST_INIT(&t4_list);
10024 #ifdef TCP_OFFLOAD
10025                         sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
10026                         SLIST_INIT(&t4_uld_list);
10027 #endif
10028                         t4_tracer_modload();
10029                         tweak_tunables();
10030                 }
10031                 sx_xunlock(&mlu);
10032                 break;
10033
10034         case MOD_UNLOAD:
10035                 sx_xlock(&mlu);
10036                 if (--loaded == 0) {
10037                         int tries;
10038
10039                         sx_slock(&t4_list_lock);
10040                         if (!SLIST_EMPTY(&t4_list)) {
10041                                 rc = EBUSY;
10042                                 sx_sunlock(&t4_list_lock);
10043                                 goto done_unload;
10044                         }
10045 #ifdef TCP_OFFLOAD
10046                         sx_slock(&t4_uld_list_lock);
10047                         if (!SLIST_EMPTY(&t4_uld_list)) {
10048                                 rc = EBUSY;
10049                                 sx_sunlock(&t4_uld_list_lock);
10050                                 sx_sunlock(&t4_list_lock);
10051                                 goto done_unload;
10052                         }
10053 #endif
10054                         tries = 0;
10055                         while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
10056                                 uprintf("%ju clusters with custom free routine "
10057                                     "still is use.\n", t4_sge_extfree_refs());
10058                                 pause("t4unload", 2 * hz);
10059                         }
10060 #ifdef TCP_OFFLOAD
10061                         sx_sunlock(&t4_uld_list_lock);
10062 #endif
10063                         sx_sunlock(&t4_list_lock);
10064
10065                         if (t4_sge_extfree_refs() == 0) {
10066                                 t4_tracer_modunload();
10067 #ifdef TCP_OFFLOAD
10068                                 sx_destroy(&t4_uld_list_lock);
10069 #endif
10070                                 sx_destroy(&t4_list_lock);
10071                                 t4_sge_modunload();
10072                                 loaded = 0;
10073                         } else {
10074                                 rc = EBUSY;
10075                                 loaded++;       /* undo earlier decrement */
10076                         }
10077                 }
10078 done_unload:
10079                 sx_xunlock(&mlu);
10080                 break;
10081         }
10082
10083         return (rc);
10084 }
10085
10086 static devclass_t t4_devclass, t5_devclass, t6_devclass;
10087 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
10088 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
10089
10090 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
10091 MODULE_VERSION(t4nex, 1);
10092 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
10093 #ifdef DEV_NETMAP
10094 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
10095 #endif /* DEV_NETMAP */
10096
10097 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
10098 MODULE_VERSION(t5nex, 1);
10099 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
10100 #ifdef DEV_NETMAP
10101 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
10102 #endif /* DEV_NETMAP */
10103
10104 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
10105 MODULE_VERSION(t6nex, 1);
10106 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
10107 #ifdef DEV_NETMAP
10108 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
10109 #endif /* DEV_NETMAP */
10110
10111 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
10112 MODULE_VERSION(cxgbe, 1);
10113
10114 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
10115 MODULE_VERSION(cxl, 1);
10116
10117 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
10118 MODULE_VERSION(cc, 1);
10119
10120 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
10121 MODULE_VERSION(vcxgbe, 1);
10122
10123 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
10124 MODULE_VERSION(vcxl, 1);
10125
10126 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
10127 MODULE_VERSION(vcc, 1);