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