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