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