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