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