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