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