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