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