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