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