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