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