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