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