1 /*        $NetBSD: if_gscan.c,v 1.3 2025/04/26 07:09:13 skrll Exp $   */
2 
3 /*
4  * Copyright (c) 2025 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Manuel Bouyer.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 
33 #include <sys/cdefs.h>
34 __KERNEL_RCSID(0, "$NetBSD: if_gscan.c,v 1.3 2025/04/26 07:09:13 skrll Exp $");
35 
36 #ifdef _KERNEL_OPT
37 #include "opt_usb.h"
38 #include "opt_net_mpsafe.h"
39 #include "opt_can.h"
40 #endif
41 
42 #include <sys/param.h>
43 
44 #include <sys/device.h>
45 #include <sys/mbuf.h>
46 #include <sys/rndsource.h>
47 #include <sys/mutex.h>
48 #include <sys/module.h>
49 #include <sys/syslog.h>
50 
51 #include <net/bpf.h>
52 #include <net/if.h>
53 #include <net/if_types.h>
54 
55 #include <netcan/can.h>
56 #include <netcan/can_var.h>
57 
58 #include <dev/usb/usb.h>
59 #include <dev/usb/usbdi.h>
60 #include <dev/usb/usbdivar.h>
61 #include <dev/usb/usbdi_util.h>
62 #include <dev/usb/usbdevs.h>
63 
64 #include <dev/usb/usbhist.h>
65 #include <dev/usb/if_gscanreg.h>
66 
67 #ifdef USB_DEBUG
68 #ifndef GSCAN_DEBUG
69 #define gscandebug 0
70 #else
71 static int gscandebug = 0;
72 SYSCTL_SETUP(sysctl_hw_gscan_setup, "sysctl hw.gscan setup")
73 {
74           int err;
75           const struct sysctlnode *rnode;
76           const struct sysctlnode *cnode;
77 
78           err = sysctl_createv(clog, 0, NULL, &rnode,
79               CTLFLAG_PERMANENT, CTLTYPE_NODE, "gscan",
80               SYSCTL_DESCR("gscan global controls"),
81               NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL);
82 
83           if (err)
84                     goto fail;
85           /* control debugging printfs */
86           err = sysctl_createv(clog, 0, &rnode, &cnode,
87               CTLFLAG_PERMANENT | CTLFLAG_READWRITE, CTLTYPE_INT,
88               "debug", SYSCTL_DESCR("Enable debugging output"),
89               NULL, 0, &gscandebug, sizeof(gscandebug), CTL_CREATE, CTL_EOL);
90           if (err)
91                     goto fail;
92 
93           return;
94 fail:
95           aprint_error("%s: sysctl_createv failed (err = %d)\n", __func__, err);
96 }
97 
98 #endif /* GSCAN_DEBUG */
99 #endif /* USB_DEBUG */
100 
101 #define DPRINTF(FMT,A,B,C,D)  USBHIST_LOGN(gscandebug,1,FMT,A,B,C,D)
102 #define DPRINTFN(N,FMT,A,B,C,D)         USBHIST_LOGN(gscandebug,N,FMT,A,B,C,D)
103 #define GSCANHIST_FUNC()      USBHIST_FUNC()
104 #define GSCANHIST_CALLED(name)          USBHIST_CALLED(gscandebug)
105 #define GSCANHIST_CALLARGS(FMT,A,B,C,D) \
106                     USBHIST_CALLARGS(gscandebug,FMT,A,B,C,D)
107 
108 struct gscan_softc {
109           struct canif_softc sc_cansc;
110           struct usbd_interface *sc_iface;
111           struct usbd_device    *sc_udev;
112           uByte sc_ed_tx;
113           uByte sc_ed_rx;
114           struct usbd_pipe *sc_tx_pipe;
115           struct usbd_pipe *sc_rx_pipe;
116           struct usbd_xfer *sc_tx_xfer;
117           struct usbd_xfer *sc_rx_xfer;
118           struct gscan_frame *sc_tx_frame;
119           struct gscan_frame *sc_rx_frame;
120           kmutex_t sc_txlock;
121           kmutex_t sc_rxlock;
122           bool sc_txstopped;
123           bool sc_rxstopped;
124           int sc_rx_nerr;
125           struct ifnet *sc_ifp;
126           struct if_percpuq *sc_ipq;
127           volatile bool sc_dying;
128           krndsource_t sc_rnd_source;
129           struct mbuf *sc_m_transmit; /* mbuf being transmitted */
130 };
131 
132 #define sc_dev        sc_cansc.csc_dev
133 #define sc_timecaps     sc_cansc.csc_timecaps
134 #define sc_timings      sc_cansc.csc_timings
135 #define sc_linkmodes    sc_cansc.csc_linkmodes
136 
137 static bool
gscan_isdying(struct gscan_softc * sc)138 gscan_isdying(struct gscan_softc *sc)
139 {
140           return atomic_load_relaxed(&sc->sc_dying);
141 }
142 
143 static int
gscan_write_device(struct gscan_softc * sc,int breq,void * v,int len)144 gscan_write_device(struct gscan_softc *sc, int breq, void *v, int len)
145 {
146           usb_device_request_t req;
147           req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
148           req.bRequest =  breq;
149           USETW(req.wValue, 0);
150           USETW(req.wIndex, 0);
151           USETW(req.wLength, len);
152           return usbd_do_request(sc->sc_udev, &req, v);
153 }
154 
155 static int
gscan_read_device(struct gscan_softc * sc,int breq,void * v,int len)156 gscan_read_device(struct gscan_softc *sc, int breq, void *v, int len)
157 {
158           usb_device_request_t req;
159           req.bmRequestType = UT_READ_VENDOR_DEVICE;
160           req.bRequest =  breq;
161           USETW(req.wValue, 0);
162           USETW(req.wIndex, 0);
163           USETW(req.wLength, len);
164           return usbd_do_request(sc->sc_udev, &req, v);
165 }
166 
167 static int          gscan_match(device_t, cfdata_t, void *);
168 static void         gscan_attach(device_t, device_t, void *);
169 static int      gscan_detach(device_t, int);
170 static int          gscan_activate(device_t, devact_t);
171 
172 static void         gscan_ifstart(struct ifnet *);
173 static int          gscan_ifioctl(struct ifnet *, u_long, void *);
174 static void         gscan_ifwatchdog(struct ifnet *);
175 
176 static int          gscan_ifup(struct gscan_softc * const);
177 static void         gscan_stop(struct gscan_softc * const, struct ifnet *, int);
178 static void         gscan_startrx(struct gscan_softc * const);
179 
180 CFATTACH_DECL_NEW(gscan, sizeof(struct gscan_softc),
181           gscan_match, gscan_attach, gscan_detach, gscan_activate);
182 
183 static void
gscan_rx(struct usbd_xfer * xfer,void * priv,usbd_status status)184 gscan_rx(struct usbd_xfer *xfer, void *priv, usbd_status status)
185 {
186           GSCANHIST_FUNC();
187           struct gscan_softc *sc = priv;
188           struct gscan_frame *gsframe;
189           struct can_frame *cf;
190           uint32_t len,  dlc, can_id;
191           int32_t echo_id;
192           struct ifnet *ifp = sc->sc_ifp;
193           struct mbuf *m;
194 
195           GSCANHIST_CALLARGS("status: %d", status, 0, 0, 0);
196 
197           mutex_enter(&sc->sc_rxlock);
198           if (sc->sc_rxstopped || gscan_isdying(sc) ||
199               status == USBD_NOT_STARTED || status == USBD_CANCELLED ||
200               status == USBD_INVAL) {
201                     mutex_exit(&sc->sc_rxlock);
202                     return;
203           }
204           if (status != USBD_NORMAL_COMPLETION) {
205                     DPRINTF("rx error: %jd", status, 0, 0, 0);
206                     if (status == USBD_STALLED)
207                               usbd_clear_endpoint_stall_async(sc->sc_rx_pipe);
208                     if (++sc->sc_rx_nerr > 100) {
209                               log(LOG_ERR, "%s: too many rx errors, disabling\n",
210                                   device_xname(sc->sc_dev));
211                               gscan_activate(sc->sc_dev, DVACT_DEACTIVATE);
212                     }
213                     goto out;
214           }
215           sc->sc_rx_nerr = 0;
216           usbd_get_xfer_status(xfer, NULL, (void **)&gsframe, &len, NULL);
217           if (len < sizeof(struct gscan_frame) - 8) {
218                     if_statinc(ifp, if_ierrors);
219                     goto out;
220           }
221           if (gsframe->gsframe_flags & GSFRAME_FLAG_OVER) {
222                     if_statinc(ifp, if_ierrors);
223                     goto out;
224           }
225           dlc = le32toh(gsframe->gsframe_can_dlc);
226           if (dlc > CAN_MAX_DLC) {
227                     if_statinc(ifp, if_ierrors);
228                     goto out;
229           }
230           echo_id = le32toh(gsframe->gsframe_echo_id);
231           if (echo_id != -1) {
232                     /* echo of a frame we sent */
233                     goto out;
234           }
235           can_id = le32toh(gsframe->gsframe_can_id);
236           /* for now ignore error frames */
237           if (can_id & CAN_ERR_FLAG) {
238                     goto out;
239           }
240           m = m_gethdr(M_NOWAIT, MT_HEADER);
241           if (m == NULL) {
242                     if_statinc(ifp, if_ierrors);
243                     goto out;
244           }
245           cf = mtod(m, struct can_frame *);
246           memset(cf, 0, sizeof(struct can_frame));
247           cf->can_id = can_id;
248           cf->can_dlc = dlc;
249           memcpy(&cf->data[0], &gsframe->gsframe_can_data[0], 8);
250           /* done with the buffer, get next frame */
251           mutex_exit(&sc->sc_rxlock);
252           gscan_startrx(sc);
253 
254           m->m_len = m->m_pkthdr.len = CAN_MTU;
255           m_set_rcvif(m, ifp);
256           if_statadd(ifp, if_ibytes, m->m_len);
257           can_bpf_mtap(ifp, m, 1);
258           can_input(ifp, m);
259           return;
260 
261 out:
262           mutex_exit(&sc->sc_rxlock);
263           gscan_startrx(sc);
264 }
265 
266 static void
gscan_startrx(struct gscan_softc * const sc)267 gscan_startrx(struct gscan_softc * const sc)
268 {
269           usbd_setup_xfer(sc->sc_rx_xfer, sc, sc->sc_rx_frame,
270               sizeof(struct gscan_frame), USBD_SHORT_XFER_OK,
271               USBD_NO_TIMEOUT, gscan_rx);
272           usbd_transfer(sc->sc_rx_xfer);
273 }
274 
275 static void
gscan_tx(struct usbd_xfer * xfer,void * priv,usbd_status status)276 gscan_tx(struct usbd_xfer *xfer, void *priv, usbd_status status)
277 {
278           GSCANHIST_FUNC();
279           struct gscan_softc *sc = priv;
280           struct ifnet *ifp = sc->sc_ifp;
281           struct mbuf *m;
282 
283           GSCANHIST_CALLARGS("status: %d", status, 0, 0, 0);
284           mutex_enter(&sc->sc_txlock);
285           if (sc->sc_txstopped || gscan_isdying(sc)) {
286                     mutex_exit(&sc->sc_txlock);
287                     return;
288           }
289           ifp->if_timer = 0;
290           m = sc->sc_m_transmit;
291           sc->sc_m_transmit = NULL;
292           if (m != NULL) {
293                     if (status == USBD_NORMAL_COMPLETION)
294                               if_statadd2(ifp, if_obytes, m->m_len, if_opackets, 1);
295                     can_mbuf_tag_clean(m);
296                     m_set_rcvif(m, ifp);
297                     can_input(ifp, m); /* loopback */
298           }
299           if (status != USBD_NORMAL_COMPLETION) {
300                     if (status == USBD_NOT_STARTED || status == USBD_CANCELLED) {
301                               mutex_exit(&sc->sc_txlock);
302                               return;
303                     }
304                     DPRINTF("rx error: %jd", status, 0, 0, 0);
305                     if (status == USBD_STALLED)
306                               usbd_clear_endpoint_stall_async(sc->sc_rx_pipe);
307           }
308           if_schedule_deferred_start(ifp);
309           mutex_exit(&sc->sc_txlock);
310 }
311 
312 static void
gscan_ifstart(struct ifnet * ifp)313 gscan_ifstart(struct ifnet *ifp)
314 {
315           GSCANHIST_FUNC();
316           struct gscan_softc * const sc = ifp->if_softc;
317           struct mbuf *m;
318           struct can_frame *cf;
319           int err;
320           GSCANHIST_CALLED();
321 
322           mutex_enter(&sc->sc_txlock);
323           if (sc->sc_txstopped || gscan_isdying(sc))
324                     goto out;
325 
326           if (sc->sc_m_transmit != NULL)
327                     goto out;
328           IF_DEQUEUE(&ifp->if_snd, m);
329           if (m == NULL)
330                     goto out;
331 
332           MCLAIM(m, ifp->if_mowner);
333 
334           KASSERT((m->m_flags & M_PKTHDR) != 0);
335           KASSERT(m->m_len == m->m_pkthdr.len);
336 
337           cf = mtod(m, struct can_frame *);
338           memset(sc->sc_tx_frame, 0, sizeof(struct gscan_frame));
339           sc->sc_tx_frame->gsframe_echo_id = 0;
340           sc->sc_tx_frame->gsframe_can_id = htole32(cf->can_id);
341           sc->sc_tx_frame->gsframe_can_dlc = htole32(cf->can_dlc);
342           memcpy(&sc->sc_tx_frame->gsframe_can_data[0], &cf->data[0], 8);
343 
344           usbd_setup_xfer(sc->sc_tx_xfer, sc, sc->sc_tx_frame,
345               sizeof(struct gscan_frame), 0, 10000, gscan_tx);
346         err = usbd_transfer(sc->sc_tx_xfer);
347           if (err != USBD_IN_PROGRESS) {
348                     DPRINTF("start tx error: %jd", err, 0, 0, 0);
349                     if_statadd(ifp, if_oerrors, 1);
350           } else {
351                     sc->sc_m_transmit = m;
352                     ifp->if_timer = 5;
353           }
354           can_bpf_mtap(ifp, m, 0);
355 out:
356           mutex_exit(&sc->sc_txlock);
357 }
358 
359 static int
gscan_ifup(struct gscan_softc * const sc)360 gscan_ifup(struct gscan_softc * const sc)
361 {
362           struct gscan_bt gscan_bt;
363           struct gscan_set_mode gscan_set_mode;
364           int err;
365           struct ifnet * const ifp = sc->sc_ifp;
366 
367           KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
368 
369           gscan_set_mode.mode_mode = MODE_START;
370           gscan_set_mode.mode_flags = 0;
371 
372           if (sc->sc_linkmodes & CAN_LINKMODE_LISTENONLY) {
373                     if ((sc->sc_timecaps.cltc_linkmode_caps & CAN_LINKMODE_LISTENONLY) == 0)
374                               return EINVAL;
375                     gscan_set_mode.mode_flags |= FLAGS_LISTEN_ONLY;
376           }
377           if (sc->sc_linkmodes & CAN_LINKMODE_LOOPBACK) {
378                     if ((sc->sc_timecaps.cltc_linkmode_caps & CAN_LINKMODE_LOOPBACK) == 0)
379                               return EINVAL;
380                     gscan_set_mode.mode_flags |= FLAGS_LOOPBACK;
381           }
382           if (sc->sc_linkmodes & CAN_LINKMODE_3SAMPLES) {
383                     if ((sc->sc_timecaps.cltc_linkmode_caps & CAN_LINKMODE_3SAMPLES) == 0)
384                               return EINVAL;
385                     gscan_set_mode.mode_flags |= FLAGS_TRIPLE_SAMPLE;
386           }
387           if (sc->sc_timings.clt_prop != 0)
388                     return EINVAL;
389           gscan_bt.bt_prop_seg = 0;
390 
391           if (sc->sc_timings.clt_brp > sc->sc_timecaps.cltc_brp_max ||
392              sc->sc_timings.clt_brp < sc->sc_timecaps.cltc_brp_min)
393                     return EINVAL;
394           gscan_bt.bt_brp = sc->sc_timings.clt_brp;
395 
396           if (sc->sc_timings.clt_ps1 > sc->sc_timecaps.cltc_ps1_max ||
397              sc->sc_timings.clt_ps1 < sc->sc_timecaps.cltc_ps1_min)
398                     return EINVAL;
399           gscan_bt.bt_phase_seg1 = sc->sc_timings.clt_ps1;
400           if (sc->sc_timings.clt_ps2 > sc->sc_timecaps.cltc_ps2_max ||
401              sc->sc_timings.clt_ps2 < sc->sc_timecaps.cltc_ps2_min)
402                     return EINVAL;
403           gscan_bt.bt_phase_seg2 = sc->sc_timings.clt_ps2;
404           if (sc->sc_timings.clt_sjw > sc->sc_timecaps.cltc_sjw_max ||
405               sc->sc_timings.clt_sjw < 1)
406                     return EINVAL;
407           gscan_bt.bt_swj = sc->sc_timings.clt_sjw;
408 
409           err = gscan_write_device(sc, GSCAN_SET_BITTIMING,
410                &gscan_bt, sizeof(gscan_bt));
411           if (err) {
412                     aprint_error_dev(sc->sc_dev, "SET_BITTIMING: %s\n",
413                         usbd_errstr(err));
414                     return EIO;
415           }
416           err = gscan_write_device(sc, GSCAN_SET_MODE,
417                &gscan_set_mode, sizeof(gscan_set_mode));
418           if (err) {
419                     aprint_error_dev(sc->sc_dev, "SET_MODE start: %s\n",
420                         usbd_errstr(err));
421                     return EIO;
422           }
423 
424           if ((err = usbd_open_pipe(sc->sc_iface, sc->sc_ed_rx,
425               USBD_EXCLUSIVE_USE | USBD_MPSAFE, &sc->sc_rx_pipe)) != 0) {
426                     aprint_error_dev(sc->sc_dev, "open rx pipe: %s\n",
427                         usbd_errstr(err));
428                     goto fail;
429           }
430           if ((err = usbd_open_pipe(sc->sc_iface, sc->sc_ed_tx,
431               USBD_EXCLUSIVE_USE | USBD_MPSAFE, &sc->sc_tx_pipe)) != 0) {
432                     aprint_error_dev(sc->sc_dev, "open tx pipe: %s\n",
433                         usbd_errstr(err));
434                     goto fail;
435           }
436 
437           if ((err = usbd_create_xfer(sc->sc_rx_pipe, sizeof(struct gscan_frame),
438               0, 0, &sc->sc_rx_xfer)) != 0) {
439                     aprint_error_dev(sc->sc_dev, "create rx xfer: %s\n",
440                         usbd_errstr(err));
441                     goto fail;
442           }
443           if ((err = usbd_create_xfer(sc->sc_tx_pipe, sizeof(struct gscan_frame),
444               0, 0, &sc->sc_tx_xfer)) != 0) {
445                     aprint_error_dev(sc->sc_dev, "create tx xfer: %s\n",
446                         usbd_errstr(err));
447                     goto fail;
448           }
449 
450           sc->sc_rx_frame = usbd_get_buffer(sc->sc_rx_xfer);
451           sc->sc_tx_frame = usbd_get_buffer(sc->sc_tx_xfer);
452           sc->sc_ifp->if_flags |= IFF_RUNNING;
453 
454           mutex_enter(&sc->sc_rxlock);
455           sc->sc_rxstopped = false;
456           sc->sc_rx_nerr = 0;
457           mutex_exit(&sc->sc_rxlock);
458           gscan_startrx(sc);
459           mutex_enter(&sc->sc_txlock);
460           sc->sc_txstopped = false;
461           mutex_exit(&sc->sc_txlock);
462           return 0;
463 
464 fail:
465           gscan_stop(sc, ifp, 1);
466           return EIO;
467 }
468 
469 static void
gscan_stop(struct gscan_softc * const sc,struct ifnet * ifp,int disable)470 gscan_stop(struct gscan_softc * const sc, struct ifnet *ifp, int disable)
471 {
472           struct gscan_set_mode gscan_set_mode;
473           int err;
474 
475           KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
476           mutex_enter(&sc->sc_txlock);
477           sc->sc_txstopped = true;
478           ifp->if_timer = 0;
479           if (sc->sc_m_transmit != NULL) {
480                     m_freem(sc->sc_m_transmit);
481                     sc->sc_m_transmit = NULL;
482           }
483           mutex_exit(&sc->sc_txlock);
484           mutex_enter(&sc->sc_rxlock);
485           sc->sc_rxstopped = true;
486           mutex_exit(&sc->sc_rxlock);
487           if (ifp->if_flags & IFF_RUNNING) {
488                     if (sc->sc_tx_pipe)
489                               usbd_abort_pipe(sc->sc_tx_pipe);
490                     if (sc->sc_rx_pipe)
491                               usbd_abort_pipe(sc->sc_rx_pipe);
492           }
493           if (sc->sc_rx_pipe) {
494                     usbd_close_pipe(sc->sc_rx_pipe);
495                     sc->sc_rx_pipe = NULL;
496           }
497           if (sc->sc_tx_pipe) {
498                     usbd_close_pipe(sc->sc_tx_pipe);
499                     sc->sc_tx_pipe = NULL;
500           }
501           if (sc->sc_rx_xfer != NULL) {
502                     usbd_destroy_xfer(sc->sc_rx_xfer);
503                     sc->sc_rx_xfer = NULL;
504                     sc->sc_rx_pipe = NULL;
505           }
506           if (sc->sc_tx_xfer != NULL) {
507                     usbd_destroy_xfer(sc->sc_tx_xfer);
508                     sc->sc_tx_xfer = NULL;
509                     sc->sc_tx_pipe = NULL;
510           }
511 
512           gscan_set_mode.mode_mode = MODE_RESET;
513           gscan_set_mode.mode_flags = 0;
514           err = gscan_write_device(sc, GSCAN_SET_MODE,
515                &gscan_set_mode, sizeof(gscan_set_mode));
516           if (err != 0 && err  != USBD_CANCELLED) {
517                     aprint_error_dev(sc->sc_dev, "SET_MODE stop: %s\n",
518                         usbd_errstr(err));
519           }
520           KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
521           ifp->if_flags &= ~IFF_RUNNING;
522 }
523 
524 static void
gscan_ifstop(struct ifnet * ifp,int disable)525 gscan_ifstop(struct ifnet *ifp, int disable)
526 {
527           struct gscan_softc * const sc = ifp->if_softc;
528           KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
529           gscan_stop(sc, ifp, disable);
530 }
531 
532 
533 static int
gscan_ifioctl(struct ifnet * ifp,u_long cmd,void * data)534 gscan_ifioctl(struct ifnet *ifp, u_long cmd, void *data)
535 {
536           struct gscan_softc * const sc = ifp->if_softc;
537           struct ifreq *ifr = (struct ifreq *)data;
538           int error = 0;
539 
540           KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
541           if (gscan_isdying(sc))
542                     return EIO;
543 
544           switch (cmd) {
545           case SIOCINITIFADDR:
546                     error = EAFNOSUPPORT;
547                     break;
548           case SIOCSIFMTU:
549                     if ((unsigned)ifr->ifr_mtu != sizeof(struct can_frame))
550                               error = EINVAL;
551                     break;
552           case SIOCADDMULTI:
553           case SIOCDELMULTI:
554                     error = EAFNOSUPPORT;
555                     break;
556           default:
557                     error = ifioctl_common(ifp, cmd, data);
558                     if (error == 0) {
559                               if ((ifp->if_flags & IFF_UP) != 0 &&
560                                   (ifp->if_flags & IFF_RUNNING) == 0) {
561                                         error = gscan_ifup(sc);
562                                         if (error) {
563                                                   ifp->if_flags &= ~IFF_UP;
564                                         }
565                               } else if ((ifp->if_flags & IFF_UP) == 0 &&
566                                   (ifp->if_flags & IFF_RUNNING) != 0) {
567                                         gscan_stop(sc, sc->sc_ifp, 1);
568                               }
569                     }
570                     break;
571           }
572           return error;
573 }
574 
575 static void
gscan_ifwatchdog(struct ifnet * ifp)576 gscan_ifwatchdog(struct ifnet *ifp)
577 {
578           struct gscan_softc * const sc = ifp->if_softc;
579           printf("%s: watchdog timeout\n", device_xname(sc->sc_dev));
580 #if 0
581           /* if there is a transmit in progress abort */
582           if (gscan_tx_abort(sc)) {
583                     if_statinc(ifp, if_oerrors);
584           }
585 #endif
586 }
587 
588 static const struct usb_devno gscan_devs[] = {
589     {USB_VENDOR_FUTUREBITS, USB_PRODUCT_FUTUREBITS_CDL_CAN},
590     {USB_VENDOR_INTERBIO, USB_PRODUCT_INTERBIO_CDL_CAN},
591 };
592 
593 static int
gscan_match(device_t parent,cfdata_t match,void * aux)594 gscan_match(device_t parent, cfdata_t match, void *aux)
595 {
596           struct usb_attach_arg *uaa = aux;
597 
598           return
599               (usb_lookup(gscan_devs, uaa->uaa_vendor, uaa->uaa_product) != NULL ?
600                UMATCH_VENDOR_PRODUCT : UMATCH_NONE);
601 }
602 
603 static void
gscan_attach(device_t parent,device_t self,void * aux)604 gscan_attach(device_t parent, device_t self, void *aux)
605 {
606           GSCANHIST_FUNC(); GSCANHIST_CALLED();
607           struct gscan_softc *sc = device_private(self);
608           struct usb_attach_arg *uaa = aux;
609           struct usbd_device *dev = uaa->uaa_device;
610           usbd_status err;
611           usb_interface_descriptor_t *id;
612           usb_endpoint_descriptor_t *ed;
613           char *devinfop;
614           uint32_t val32;
615           struct gscan_config gscan_config;
616           struct gscan_bt_const gscan_bt_const;
617           struct ifnet *ifp;
618 
619           aprint_naive("\n");
620           aprint_normal("\n");
621           devinfop = usbd_devinfo_alloc(dev, 0);
622           aprint_normal_dev(self, "%s\n", devinfop);
623           usbd_devinfo_free(devinfop);
624 
625           sc->sc_dev = self;
626           sc->sc_udev = dev;
627 
628           err = usbd_set_config_no(dev, 1, 0);
629           if (err) {
630                     aprint_error_dev(self, "failed to set configuration"
631                         ", err=%s\n", usbd_errstr(err));
632                     return;
633           }
634 
635           err = usbd_device2interface_handle(dev, 0, &sc->sc_iface);
636           if (err) {
637                     aprint_error_dev(self, "getting interface handle failed\n");
638                     return;
639           }
640 
641           id = usbd_get_interface_descriptor(sc->sc_iface);
642           if (id->bNumEndpoints < 2) {
643                     aprint_error_dev(self, "%d endpoints < 2\n", id->bNumEndpoints);
644                     return;
645           }
646 
647           val32 = htole32(0x0000beef);
648           err = gscan_write_device(sc, GSCAN_SET_HOST_FORMAT,
649               &val32, sizeof(val32));
650 
651           if (err) {
652                     aprint_error_dev(self, "SET_HOST_FORMAT: %s\n",
653                         usbd_errstr(err));
654                     return;
655           }
656 
657           err = gscan_read_device(sc, GSCAN_GET_DEVICE_CONFIG,
658               &gscan_config, sizeof(struct gscan_config));
659           if (err) {
660                     aprint_error_dev(self, "GET_DEVICE_CONFIG: %s\n",
661                         usbd_errstr(err));
662                     return;
663           }
664           aprint_normal_dev(self, "%d port%s, sw version %d, hw version %d\n",
665               gscan_config.conf_count + 1, gscan_config.conf_count ? "s" : "",
666               le32toh(gscan_config.sw_version), le32toh(gscan_config.hw_version));
667 
668           err = gscan_read_device(sc, GSCAN_GET_BT_CONST,
669               &gscan_bt_const, sizeof(struct gscan_bt_const));
670           if (err) {
671                     aprint_error_dev(self, "GET_BT_CONST: %s\n",
672                         usbd_errstr(err));
673                     return;
674           }
675           aprint_debug_dev(self, "feat 0x%x clk %dHz tseg1 %d -> %d tseg2 %d -> %d max swj %d brp %d -> %d/%d\n",
676               le32toh(gscan_bt_const.btc_features),
677               le32toh(gscan_bt_const.btc_fclk),
678               le32toh(gscan_bt_const.btc_tseg1_min),
679               le32toh(gscan_bt_const.btc_tseg1_max),
680               le32toh(gscan_bt_const.btc_tseg2_min),
681               le32toh(gscan_bt_const.btc_tseg2_max),
682               le32toh(gscan_bt_const.btc_swj_max),
683               le32toh(gscan_bt_const.btc_brp_min),
684               le32toh(gscan_bt_const.btc_brp_max),
685               le32toh(gscan_bt_const.btc_brp_inc));
686 
687           sc->sc_timecaps.cltc_prop_min = 0;
688           sc->sc_timecaps.cltc_prop_max = 0;
689           sc->sc_timecaps.cltc_ps1_min = le32toh(gscan_bt_const.btc_tseg1_min);
690           sc->sc_timecaps.cltc_ps1_max = le32toh(gscan_bt_const.btc_tseg1_max);
691           sc->sc_timecaps.cltc_ps2_min = le32toh(gscan_bt_const.btc_tseg2_min);
692           sc->sc_timecaps.cltc_ps2_max = le32toh(gscan_bt_const.btc_tseg2_max);
693           sc->sc_timecaps.cltc_sjw_max = le32toh(gscan_bt_const.btc_swj_max);
694           sc->sc_timecaps.cltc_brp_min = le32toh(gscan_bt_const.btc_brp_min);
695           sc->sc_timecaps.cltc_brp_max = le32toh(gscan_bt_const.btc_brp_max);
696           sc->sc_timecaps.cltc_brp_inc = le32toh(gscan_bt_const.btc_brp_inc);
697           sc->sc_timecaps.cltc_clock_freq = le32toh(gscan_bt_const.btc_fclk);
698           sc->sc_timecaps.cltc_linkmode_caps = 0;
699           if (le32toh(gscan_bt_const.btc_features) & FEAT_LISTEN_ONLY)
700                     sc->sc_timecaps.cltc_linkmode_caps |= CAN_LINKMODE_LISTENONLY;
701           if (le32toh(gscan_bt_const.btc_features) & FEAT_LOOPBACK)
702                     sc->sc_timecaps.cltc_linkmode_caps |= CAN_LINKMODE_LOOPBACK;
703           if (le32toh(gscan_bt_const.btc_features) & FEAT_TRIPLE_SAMPLE)
704                     sc->sc_timecaps.cltc_linkmode_caps |= CAN_LINKMODE_3SAMPLES;
705 
706           can_ifinit_timings(&sc->sc_cansc);
707           sc->sc_timings.clt_prop = 0;
708           sc->sc_timings.clt_sjw = 1;
709 
710           /* Find endpoints. */
711           ed = usbd_interface2endpoint_descriptor(sc->sc_iface, 0);
712           if (ed == NULL) {
713                     aprint_error_dev(self, "couldn't get ep 1\n");
714                     return;
715           }
716           const uint8_t xt1 = UE_GET_XFERTYPE(ed->bmAttributes);
717           const uint8_t dir1 = UE_GET_DIR(ed->bEndpointAddress);
718 
719           if (dir1 != UE_DIR_IN || xt1 != UE_BULK) {
720                     aprint_error_dev(self,
721                         "ep 1 wrong dir %d or xt %d\n", dir1, xt1);
722                     return;
723           }
724           sc->sc_ed_rx = ed->bEndpointAddress;
725 
726           ed = usbd_interface2endpoint_descriptor(sc->sc_iface, 1);
727           if (ed == NULL) {
728                     aprint_error_dev(self, "couldn't get ep 2\n");
729                     return;
730           }
731           const uint8_t xt2 = UE_GET_XFERTYPE(ed->bmAttributes);
732           const uint8_t dir2 = UE_GET_DIR(ed->bEndpointAddress);
733 
734           if (dir2 != UE_DIR_OUT || xt2 != UE_BULK) {
735                     aprint_error_dev(self,
736                         "ep 2 wrong dir %d or xt %d\n", dir2, xt2);
737                     return;
738           }
739           sc->sc_ed_tx = ed->bEndpointAddress;
740 
741           mutex_init(&sc->sc_txlock, MUTEX_DEFAULT, IPL_SOFTUSB);
742           mutex_init(&sc->sc_rxlock, MUTEX_DEFAULT, IPL_SOFTUSB);
743           sc->sc_rxstopped = true;
744           sc->sc_txstopped = true;
745 
746 
747           ifp = if_alloc(IFT_OTHER);
748           strlcpy(ifp->if_xname, device_xname(self), IFNAMSIZ);
749           ifp->if_softc = sc;
750           ifp->if_capabilities = 0;
751           ifp->if_flags = 0;
752           ifp->if_extflags = IFEF_MPSAFE;
753           ifp->if_start = gscan_ifstart;
754           ifp->if_ioctl = gscan_ifioctl;
755           ifp->if_stop = gscan_ifstop;
756           ifp->if_watchdog = gscan_ifwatchdog;
757           IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
758 
759           sc->sc_ifp = ifp;
760           can_ifattach(ifp);
761           if_deferred_start_init(ifp, NULL);
762           bpf_mtap_softint_init(ifp);
763           rnd_attach_source(&sc->sc_rnd_source, device_xname(self),
764               RND_TYPE_NET, RND_FLAG_DEFAULT);
765 #ifdef MBUFTRACE
766           ifp->if_mowner = kmem_zalloc(sizeof(*ifp->if_mowner), KM_SLEEP);
767           strlcpy(ifp->if_mowner->mo_name, ifp->if_xname,
768                     sizeof(ifp->if_mowner->mo_name));
769           MOWNER_ATTACH(ifp->if_mowner);
770 #endif
771           usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
772 };
773 
774 static int
gscan_detach(device_t self,int flags)775 gscan_detach(device_t self, int flags)
776 {
777           GSCANHIST_FUNC(); GSCANHIST_CALLED();
778           struct gscan_softc * const sc = device_private(self);
779 
780           struct ifnet * const ifp = sc->sc_ifp;
781           /*
782            * Prevent new activity.  After we stop the interface, it
783            * cannot be brought back up.
784            */
785           atomic_store_relaxed(&sc->sc_dying, true);
786 
787           /*
788            * If we're still running on the network, stop and wait for all
789            * asynchronous activity to finish.
790            *
791            * If _attach_ifp never ran, IFNET_LOCK won't work, but
792            * no activity is possible, so just skip this part.
793            */
794           if (ifp != NULL) {
795                     IFNET_LOCK(ifp);
796                     if (ifp->if_flags & IFF_RUNNING) {
797                               gscan_stop(sc, ifp, 1);
798                     }
799                     IFNET_UNLOCK(ifp);
800                     bpf_detach(ifp);
801                     if_detach(ifp);
802           }
803           rnd_detach_source(&sc->sc_rnd_source);
804           mutex_destroy(&sc->sc_txlock);
805           mutex_destroy(&sc->sc_rxlock);
806 
807           pmf_device_deregister(sc->sc_dev);
808           if (ifp != NULL) {
809                     usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
810                         sc->sc_dev);
811           }
812           return 0;
813 }
814 
815 static int
gscan_activate(device_t self,devact_t act)816 gscan_activate(device_t self, devact_t act)
817 {
818           GSCANHIST_FUNC(); GSCANHIST_CALLED();
819           struct gscan_softc * const sc = device_private(self);
820           struct ifnet * const ifp = sc->sc_ifp;
821 
822           switch (act) {
823           case DVACT_DEACTIVATE:
824                     if_deactivate(ifp);
825                     atomic_store_relaxed(&sc->sc_dying, true);
826                     mutex_enter(&sc->sc_txlock);
827                     sc->sc_txstopped = true;
828                     if (sc->sc_m_transmit != NULL) {
829                               m_freem(sc->sc_m_transmit);
830                               sc->sc_m_transmit = NULL;
831                     }
832                     mutex_exit(&sc->sc_txlock);
833                     mutex_enter(&sc->sc_rxlock);
834                     sc->sc_rxstopped = true;
835                     mutex_exit(&sc->sc_rxlock);
836                     return 0;
837           default:
838                     return EOPNOTSUPP;
839           }
840 }
841 
842 #ifdef _MODULE
843 #include "ioconf.c"
844 #endif
845 
846 MODULE(MODULE_CLASS_DRIVER, gscan, NULL);
847 
848 static int
gscan_modcmd(modcmd_t cmd,void * aux)849 gscan_modcmd(modcmd_t cmd, void *aux)
850 {
851           int error = 0;
852 
853           switch (cmd) {
854           case MODULE_CMD_INIT:
855 #ifdef _MODULE
856                     error = config_init_component(cfdriver_ioconf_gscan,
857                         cfattach_ioconf_gscan, cfdata_ioconf_gscan);
858 #endif
859                     return error;
860           case MODULE_CMD_FINI:
861 #ifdef _MODULE
862                     error = config_fini_component(cfdriver_ioconf_gscan,
863                         cfattach_ioconf_gscan, cfdata_ioconf_gscan);
864 #endif
865                     return error;
866           default:
867                     return ENOTTY;
868           }
869 }
870