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