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