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