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