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