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