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