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