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