1 /*        $NetBSD: bthidev.c,v 1.34 2021/08/07 16:19:09 thorpej Exp $ */
2 
3 /*-
4  * Copyright (c) 2006 Itronix Inc.
5  * All rights reserved.
6  *
7  * Written by Iain Hibbert for Itronix Inc.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. The name of Itronix Inc. may not be used to endorse
18  *    or promote products derived from this software without specific
19  *    prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY ITRONIX INC. ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL ITRONIX INC. BE LIABLE FOR ANY
25  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
28  * ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __KERNEL_RCSID(0, "$NetBSD: bthidev.c,v 1.34 2021/08/07 16:19:09 thorpej Exp $");
36 
37 #include <sys/param.h>
38 #include <sys/condvar.h>
39 #include <sys/conf.h>
40 #include <sys/device.h>
41 #include <sys/fcntl.h>
42 #include <sys/kernel.h>
43 #include <sys/kthread.h>
44 #include <sys/queue.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/mutex.h>
48 #include <sys/proc.h>
49 #include <sys/socketvar.h>
50 #include <sys/systm.h>
51 
52 #include <prop/proplib.h>
53 
54 #include <netbt/bluetooth.h>
55 #include <netbt/l2cap.h>
56 
57 #include <dev/hid/hid.h>
58 #include <dev/bluetooth/btdev.h>
59 #include <dev/bluetooth/bthid.h>
60 #include <dev/bluetooth/bthidev.h>
61 
62 #include "locators.h"
63 
64 /*****************************************************************************
65  *
66  *        Bluetooth HID device
67  */
68 
69 #define MAX_DESCRIPTOR_LEN    1024                /* sanity check */
70 
71 /* bthidev softc */
72 struct bthidev_softc {
73           uint16_t            sc_state;
74           uint16_t            sc_flags;
75           device_t            sc_dev;
76 
77           bdaddr_t            sc_laddr; /* local address */
78           bdaddr_t            sc_raddr; /* remote address */
79           struct sockopt                sc_mode;  /* link mode sockopt */
80 
81           uint16_t            sc_ctlpsm;          /* control PSM */
82           struct l2cap_channel          *sc_ctl;  /* control channel */
83           struct l2cap_channel          *sc_ctl_l;          /* control listen */
84 
85           uint16_t            sc_intpsm;          /* interrupt PSM */
86           struct l2cap_channel          *sc_int;  /* interrupt channel */
87           struct l2cap_channel          *sc_int_l;          /* interrupt listen */
88 
89           MBUFQ_HEAD()                  sc_inq;             /* input queue */
90           kmutex_t            sc_lock;  /* input queue lock */
91           kcondvar_t                    sc_cv;              /* input queue trigger */
92           lwp_t                         *sc_lwp;  /* input queue processor */
93           int                           sc_detach;
94 
95           LIST_HEAD(,bthidev) sc_list;  /* child list */
96 
97           callout_t           sc_reconnect;
98           int                           sc_attempts;        /* connection attempts */
99 };
100 
101 /* sc_flags */
102 #define BTHID_RECONNECT                 (1 << 0)  /* reconnect on link loss */
103 #define BTHID_CONNECTING      (1 << 1)  /* we are connecting */
104 
105 /* device state */
106 #define BTHID_CLOSED                    0
107 #define BTHID_WAIT_CTL                  1
108 #define BTHID_WAIT_INT                  2
109 #define BTHID_OPEN            3
110 
111 #define   BTHID_RETRY_INTERVAL          5         /* seconds between connection attempts */
112 
113 /* bthidev internals */
114 static void bthidev_timeout(void *);
115 static int  bthidev_listen(struct bthidev_softc *);
116 static int  bthidev_connect(struct bthidev_softc *);
117 static int  bthidev_output(struct bthidev *, uint8_t *, int);
118 static void bthidev_null(struct bthidev *, uint8_t *, int);
119 static void bthidev_process(void *);
120 static void bthidev_process_one(struct bthidev_softc *, struct mbuf *);
121 
122 /* autoconf(9) glue */
123 static int  bthidev_match(device_t, cfdata_t, void *);
124 static void bthidev_attach(device_t, device_t, void *);
125 static int  bthidev_detach(device_t, int);
126 static int  bthidev_print(void *, const char *);
127 
128 CFATTACH_DECL_NEW(bthidev, sizeof(struct bthidev_softc),
129     bthidev_match, bthidev_attach, bthidev_detach, NULL);
130 
131 /* bluetooth(9) protocol methods for L2CAP */
132 static void  bthidev_connecting(void *);
133 static void  bthidev_ctl_connected(void *);
134 static void  bthidev_int_connected(void *);
135 static void  bthidev_ctl_disconnected(void *, int);
136 static void  bthidev_int_disconnected(void *, int);
137 static void *bthidev_ctl_newconn(void *, struct sockaddr_bt *, struct sockaddr_bt *);
138 static void *bthidev_int_newconn(void *, struct sockaddr_bt *, struct sockaddr_bt *);
139 static void  bthidev_complete(void *, int);
140 static void  bthidev_linkmode(void *, int);
141 static void  bthidev_input(void *, struct mbuf *);
142 
143 static const struct btproto bthidev_ctl_proto = {
144           bthidev_connecting,
145           bthidev_ctl_connected,
146           bthidev_ctl_disconnected,
147           bthidev_ctl_newconn,
148           bthidev_complete,
149           bthidev_linkmode,
150           bthidev_input,
151 };
152 
153 static const struct btproto bthidev_int_proto = {
154           bthidev_connecting,
155           bthidev_int_connected,
156           bthidev_int_disconnected,
157           bthidev_int_newconn,
158           bthidev_complete,
159           bthidev_linkmode,
160           bthidev_input,
161 };
162 
163 /*****************************************************************************
164  *
165  *        bthidev autoconf(9) routines
166  */
167 
168 static int
bthidev_match(device_t self,cfdata_t cfdata,void * aux)169 bthidev_match(device_t self, cfdata_t cfdata, void *aux)
170 {
171           prop_dictionary_t dict = aux;
172           prop_object_t obj;
173 
174           obj = prop_dictionary_get(dict, BTDEVservice);
175           if (prop_string_equals_string(obj, "HID"))
176                     return 1;
177 
178           return 0;
179 }
180 
181 static void
bthidev_attach(device_t parent,device_t self,void * aux)182 bthidev_attach(device_t parent, device_t self, void *aux)
183 {
184           struct bthidev_softc *sc = device_private(self);
185           prop_dictionary_t dict = aux;
186           prop_object_t obj;
187           device_t dev;
188           struct bthidev_attach_args bha;
189           struct bthidev *hidev;
190           struct hid_data *d;
191           struct hid_item h;
192           const void *desc;
193           int locs[BTHIDBUSCF_NLOCS];
194           int maxid, rep, dlen;
195           int vendor, product;
196           int err;
197 
198           /*
199            * Init softc
200            */
201           sc->sc_dev = self;
202           LIST_INIT(&sc->sc_list);
203           MBUFQ_INIT(&sc->sc_inq);
204           callout_init(&sc->sc_reconnect, 0);
205           callout_setfunc(&sc->sc_reconnect, bthidev_timeout, sc);
206           sc->sc_state = BTHID_CLOSED;
207           sc->sc_flags = BTHID_CONNECTING;
208           sc->sc_ctlpsm = L2CAP_PSM_HID_CNTL;
209           sc->sc_intpsm = L2CAP_PSM_HID_INTR;
210 
211           sockopt_init(&sc->sc_mode, BTPROTO_L2CAP, SO_L2CAP_LM, 0);
212           mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_NONE);
213           cv_init(&sc->sc_cv, device_xname(self));
214 
215           /*
216            * extract config from proplist
217            */
218           obj = prop_dictionary_get(dict, BTDEVladdr);
219           bdaddr_copy(&sc->sc_laddr, prop_data_value(obj));
220 
221           obj = prop_dictionary_get(dict, BTDEVraddr);
222           bdaddr_copy(&sc->sc_raddr, prop_data_value(obj));
223 
224           obj = prop_dictionary_get(dict, BTDEVvendor);
225           vendor = (int)prop_number_signed_value(obj);
226 
227           obj = prop_dictionary_get(dict, BTDEVproduct);
228           product = (int)prop_number_signed_value(obj);
229 
230           obj = prop_dictionary_get(dict, BTDEVmode);
231           if (prop_object_type(obj) == PROP_TYPE_STRING) {
232                     if (prop_string_equals_string(obj, BTDEVauth))
233                               sockopt_setint(&sc->sc_mode, L2CAP_LM_AUTH);
234                     else if (prop_string_equals_string(obj, BTDEVencrypt))
235                               sockopt_setint(&sc->sc_mode, L2CAP_LM_ENCRYPT);
236                     else if (prop_string_equals_string(obj, BTDEVsecure))
237                               sockopt_setint(&sc->sc_mode, L2CAP_LM_SECURE);
238                     else  {
239                               aprint_error(" unknown %s\n", BTDEVmode);
240                               return;
241                     }
242 
243                     aprint_verbose(" %s %s", BTDEVmode,
244                                                    prop_string_value(obj));
245           } else
246                     sockopt_setint(&sc->sc_mode, 0);
247 
248           obj = prop_dictionary_get(dict, BTHIDEVcontrolpsm);
249           if (prop_object_type(obj) == PROP_TYPE_NUMBER) {
250                     sc->sc_ctlpsm = prop_number_signed_value(obj);
251                     if (L2CAP_PSM_INVALID(sc->sc_ctlpsm)) {
252                               aprint_error(" invalid %s\n", BTHIDEVcontrolpsm);
253                               return;
254                     }
255           }
256 
257           obj = prop_dictionary_get(dict, BTHIDEVinterruptpsm);
258           if (prop_object_type(obj) == PROP_TYPE_NUMBER) {
259                     sc->sc_intpsm = prop_number_signed_value(obj);
260                     if (L2CAP_PSM_INVALID(sc->sc_intpsm)) {
261                               aprint_error(" invalid %s\n", BTHIDEVinterruptpsm);
262                               return;
263                     }
264           }
265 
266           obj = prop_dictionary_get(dict, BTHIDEVdescriptor);
267           if (prop_object_type(obj) == PROP_TYPE_DATA) {
268                     dlen = prop_data_size(obj);
269                     desc = prop_data_value(obj);
270           } else {
271                     aprint_error(" no %s\n", BTHIDEVdescriptor);
272                     return;
273           }
274 
275           obj = prop_dictionary_get(dict, BTHIDEVreconnect);
276           if (prop_object_type(obj) == PROP_TYPE_BOOL
277               && !prop_bool_true(obj))
278                     sc->sc_flags |= BTHID_RECONNECT;
279 
280           /*
281            * Parse the descriptor and attach child devices, one per report.
282            */
283           maxid = -1;
284           h.report_ID = 0;
285           d = hid_start_parse(desc, dlen, hid_none);
286           while (hid_get_item(d, &h)) {
287                     if ((int)h.report_ID > maxid)
288                               maxid = h.report_ID;
289           }
290           hid_end_parse(d);
291 
292           if (maxid < 0) {
293                     aprint_error(" no reports found\n");
294                     return;
295           }
296 
297           aprint_normal("\n");
298 
299           if (kthread_create(PRI_NONE, KTHREAD_MUSTJOIN, NULL, bthidev_process,
300               sc, &sc->sc_lwp, "%s", device_xname(self)) != 0) {
301                     aprint_error_dev(self, "failed to create input thread\n");
302                     return;
303           }
304 
305           for (rep = 0 ; rep <= maxid ; rep++) {
306                     if (hid_report_size(desc, dlen, hid_feature, rep) == 0
307                         && hid_report_size(desc, dlen, hid_input, rep) == 0
308                         && hid_report_size(desc, dlen, hid_output, rep) == 0)
309                               continue;
310 
311                     bha.ba_vendor = vendor;
312                     bha.ba_product = product;
313                     bha.ba_desc = desc;
314                     bha.ba_dlen = dlen;
315                     bha.ba_input = bthidev_null;
316                     bha.ba_feature = bthidev_null;
317                     bha.ba_output = bthidev_output;
318                     bha.ba_id = rep;
319 
320                     locs[BTHIDBUSCF_REPORTID] = rep;
321 
322                     dev = config_found(self, &bha, bthidev_print,
323                         CFARGS(.submatch = config_stdsubmatch,
324                                  .iattr = "bthidbus",
325                                  .locators = locs));
326                     if (dev != NULL) {
327                               hidev = device_private(dev);
328                               hidev->sc_dev = dev;
329                               hidev->sc_parent = self;
330                               hidev->sc_id = rep;
331                               hidev->sc_input = bha.ba_input;
332                               hidev->sc_feature = bha.ba_feature;
333                               LIST_INSERT_HEAD(&sc->sc_list, hidev, sc_next);
334                     }
335           }
336 
337           pmf_device_register(self, NULL, NULL);
338 
339           /*
340            * start bluetooth connections
341            */
342           mutex_enter(bt_lock);
343           if ((sc->sc_flags & BTHID_RECONNECT) == 0
344               && (err = bthidev_listen(sc)) != 0)
345                     aprint_error_dev(self, "failed to listen (%d)\n", err);
346 
347           if (sc->sc_flags & BTHID_CONNECTING)
348                     bthidev_connect(sc);
349           mutex_exit(bt_lock);
350 }
351 
352 static int
bthidev_detach(device_t self,int flags)353 bthidev_detach(device_t self, int flags)
354 {
355           struct bthidev_softc *sc = device_private(self);
356           struct bthidev *hidev;
357 
358           mutex_enter(bt_lock);
359           sc->sc_flags = 0;   /* disable reconnecting */
360 
361           /* release interrupt listen */
362           if (sc->sc_int_l != NULL) {
363                     l2cap_detach_pcb(&sc->sc_int_l);
364                     sc->sc_int_l = NULL;
365           }
366 
367           /* release control listen */
368           if (sc->sc_ctl_l != NULL) {
369                     l2cap_detach_pcb(&sc->sc_ctl_l);
370                     sc->sc_ctl_l = NULL;
371           }
372 
373           /* close interrupt channel */
374           if (sc->sc_int != NULL) {
375                     l2cap_disconnect_pcb(sc->sc_int, 0);
376                     l2cap_detach_pcb(&sc->sc_int);
377                     sc->sc_int = NULL;
378           }
379 
380           /* close control channel */
381           if (sc->sc_ctl != NULL) {
382                     l2cap_disconnect_pcb(sc->sc_ctl, 0);
383                     l2cap_detach_pcb(&sc->sc_ctl);
384                     sc->sc_ctl = NULL;
385           }
386 
387           callout_halt(&sc->sc_reconnect, bt_lock);
388           callout_destroy(&sc->sc_reconnect);
389 
390           mutex_exit(bt_lock);
391 
392           pmf_device_deregister(self);
393 
394           /* kill off the input processor */
395           if (sc->sc_lwp != NULL) {
396                     mutex_enter(&sc->sc_lock);
397                     sc->sc_detach = 1;
398                     cv_signal(&sc->sc_cv);
399                     mutex_exit(&sc->sc_lock);
400                     kthread_join(sc->sc_lwp);
401                     sc->sc_lwp = NULL;
402           }
403 
404           /* detach children */
405           while ((hidev = LIST_FIRST(&sc->sc_list)) != NULL) {
406                     LIST_REMOVE(hidev, sc_next);
407                     config_detach(hidev->sc_dev, flags);
408           }
409 
410           MBUFQ_DRAIN(&sc->sc_inq);
411           cv_destroy(&sc->sc_cv);
412           mutex_destroy(&sc->sc_lock);
413           sockopt_destroy(&sc->sc_mode);
414 
415           return 0;
416 }
417 
418 /*
419  * bthidev config print
420  */
421 static int
bthidev_print(void * aux,const char * pnp)422 bthidev_print(void *aux, const char *pnp)
423 {
424           struct bthidev_attach_args *ba = aux;
425 
426           if (pnp != NULL)
427                     aprint_normal("%s:", pnp);
428 
429           if (ba->ba_id > 0)
430                     aprint_normal(" reportid %d", ba->ba_id);
431 
432           return UNCONF;
433 }
434 
435 /*****************************************************************************
436  *
437  *        bluetooth(4) HID attach/detach routines
438  */
439 
440 /*
441  * callouts are scheduled after connections have been lost, in order
442  * to clean up and reconnect.
443  */
444 static void
bthidev_timeout(void * arg)445 bthidev_timeout(void *arg)
446 {
447           struct bthidev_softc *sc = arg;
448 
449           mutex_enter(bt_lock);
450           callout_ack(&sc->sc_reconnect);
451 
452           switch (sc->sc_state) {
453           case BTHID_CLOSED:
454                     if (sc->sc_int != NULL) {
455                               l2cap_disconnect_pcb(sc->sc_int, 0);
456                               break;
457                     }
458 
459                     if (sc->sc_ctl != NULL) {
460                               l2cap_disconnect_pcb(sc->sc_ctl, 0);
461                               break;
462                     }
463 
464                     if (sc->sc_flags & BTHID_RECONNECT) {
465                               sc->sc_flags |= BTHID_CONNECTING;
466                               bthidev_connect(sc);
467                               break;
468                     }
469 
470                     break;
471 
472           case BTHID_WAIT_CTL:
473                     break;
474 
475           case BTHID_WAIT_INT:
476                     break;
477 
478           case BTHID_OPEN:
479                     break;
480 
481           default:
482                     break;
483           }
484           mutex_exit(bt_lock);
485 }
486 
487 /*
488  * listen for our device
489  */
490 static int
bthidev_listen(struct bthidev_softc * sc)491 bthidev_listen(struct bthidev_softc *sc)
492 {
493           struct sockaddr_bt sa;
494           int err;
495 
496           memset(&sa, 0, sizeof(sa));
497           sa.bt_len = sizeof(sa);
498           sa.bt_family = AF_BLUETOOTH;
499           bdaddr_copy(&sa.bt_bdaddr, &sc->sc_laddr);
500 
501           /*
502            * Listen on control PSM
503            */
504           err = l2cap_attach_pcb(&sc->sc_ctl_l, &bthidev_ctl_proto, sc);
505           if (err)
506                     return err;
507 
508           err = l2cap_setopt(sc->sc_ctl_l, &sc->sc_mode);
509           if (err)
510                     return err;
511 
512           sa.bt_psm = sc->sc_ctlpsm;
513           err = l2cap_bind_pcb(sc->sc_ctl_l, &sa);
514           if (err)
515                     return err;
516 
517           err = l2cap_listen_pcb(sc->sc_ctl_l);
518           if (err)
519                     return err;
520 
521           /*
522            * Listen on interrupt PSM
523            */
524           err = l2cap_attach_pcb(&sc->sc_int_l, &bthidev_int_proto, sc);
525           if (err)
526                     return err;
527 
528           err = l2cap_setopt(sc->sc_int_l, &sc->sc_mode);
529           if (err)
530                     return err;
531 
532           sa.bt_psm = sc->sc_intpsm;
533           err = l2cap_bind_pcb(sc->sc_int_l, &sa);
534           if (err)
535                     return err;
536 
537           err = l2cap_listen_pcb(sc->sc_int_l);
538           if (err)
539                     return err;
540 
541           sc->sc_state = BTHID_WAIT_CTL;
542           return 0;
543 }
544 
545 /*
546  * start connecting to our device
547  */
548 static int
bthidev_connect(struct bthidev_softc * sc)549 bthidev_connect(struct bthidev_softc *sc)
550 {
551           struct sockaddr_bt sa;
552           int err;
553 
554           if (sc->sc_attempts++ > 0)
555                     aprint_verbose_dev(sc->sc_dev, "connect (#%d)\n", sc->sc_attempts);
556 
557           memset(&sa, 0, sizeof(sa));
558           sa.bt_len = sizeof(sa);
559           sa.bt_family = AF_BLUETOOTH;
560 
561           err = l2cap_attach_pcb(&sc->sc_ctl, &bthidev_ctl_proto, sc);
562           if (err) {
563                     aprint_error_dev(sc->sc_dev, "l2cap_attach failed (%d)\n", err);
564                     return err;
565           }
566 
567           err = l2cap_setopt(sc->sc_ctl, &sc->sc_mode);
568           if (err) {
569                     aprint_error_dev(sc->sc_dev, "l2cap_setopt failed (%d)\n", err);
570                     return err;
571           }
572 
573           bdaddr_copy(&sa.bt_bdaddr, &sc->sc_laddr);
574           err = l2cap_bind_pcb(sc->sc_ctl, &sa);
575           if (err) {
576                     aprint_error_dev(sc->sc_dev, "l2cap_bind_pcb failed (%d)\n", err);
577                     return err;
578           }
579 
580           sa.bt_psm = sc->sc_ctlpsm;
581           bdaddr_copy(&sa.bt_bdaddr, &sc->sc_raddr);
582           err = l2cap_connect_pcb(sc->sc_ctl, &sa);
583           if (err) {
584                     aprint_error_dev(sc->sc_dev, "l2cap_connect_pcb failed (%d)\n", err);
585                     return err;
586           }
587 
588           sc->sc_state = BTHID_WAIT_CTL;
589           return 0;
590 }
591 
592 /*
593  * The LWP which processes input reports, forwarding to child devices.
594  * We are always either processing input reports, holding the lock, or
595  * waiting for a signal on condvar.
596  */
597 static void
bthidev_process(void * arg)598 bthidev_process(void *arg)
599 {
600           struct bthidev_softc *sc = arg;
601           struct mbuf *m;
602 
603           mutex_enter(&sc->sc_lock);
604           while (sc->sc_detach == 0) {
605                     MBUFQ_DEQUEUE(&sc->sc_inq, m);
606                     if (m == NULL) {
607                               cv_wait(&sc->sc_cv, &sc->sc_lock);
608                               continue;
609                     }
610 
611                     mutex_exit(&sc->sc_lock);
612                     bthidev_process_one(sc, m);
613                     m_freem(m);
614                     mutex_enter(&sc->sc_lock);
615           }
616           mutex_exit(&sc->sc_lock);
617           kthread_exit(0);
618 }
619 
620 static void
bthidev_process_one(struct bthidev_softc * sc,struct mbuf * m)621 bthidev_process_one(struct bthidev_softc *sc, struct mbuf *m)
622 {
623           struct bthidev *hidev;
624           uint8_t *data;
625           int len;
626 
627           if (sc->sc_state != BTHID_OPEN)
628                     return;
629 
630           if (m->m_pkthdr.len > m->m_len)
631                     aprint_error_dev(sc->sc_dev, "truncating HID report\n");
632 
633           len = m->m_len;
634           data = mtod(m, uint8_t *);
635 
636           switch (BTHID_TYPE(data[0])) {
637           case BTHID_DATA:
638                     /*
639                      * data[0] == type / parameter
640                      * data[1] == id
641                      * data[2..len] == report
642                      */
643                     if (len < 3)
644                               break;
645 
646                     LIST_FOREACH(hidev, &sc->sc_list, sc_next)
647                               if (data[1] == hidev->sc_id)
648                                         break;
649 
650                     if (hidev == NULL) {
651                               aprint_error_dev(sc->sc_dev,
652                                   "report id %d, len = %d ignored\n", data[1], len - 2);
653 
654                               break;
655                     }
656 
657                     switch (BTHID_DATA_PARAM(data[0])) {
658                     case BTHID_DATA_INPUT:
659                               (*hidev->sc_input)(hidev, data + 2, len - 2);
660                               break;
661 
662                     case BTHID_DATA_FEATURE:
663                               (*hidev->sc_feature)(hidev, data + 2, len - 2);
664                               break;
665 
666                     default:
667                               break;
668                     }
669 
670                     break;
671 
672           case BTHID_CONTROL:
673                     if (len < 1)
674                               break;
675 
676                     switch (BTHID_DATA_PARAM(data[0])) {
677                     case BTHID_CONTROL_UNPLUG:
678                               aprint_normal_dev(sc->sc_dev, "unplugged\n");
679 
680                               mutex_enter(bt_lock);
681                               /* close interrupt channel */
682                               if (sc->sc_int != NULL) {
683                                         l2cap_disconnect_pcb(sc->sc_int, 0);
684                                         l2cap_detach_pcb(&sc->sc_int);
685                                         sc->sc_int = NULL;
686                               }
687 
688                               /* close control channel */
689                               if (sc->sc_ctl != NULL) {
690                                         l2cap_disconnect_pcb(sc->sc_ctl, 0);
691                                         l2cap_detach_pcb(&sc->sc_ctl);
692                                         sc->sc_ctl = NULL;
693                               }
694                               mutex_exit(bt_lock);
695 
696                               break;
697 
698                     default:
699                               break;
700                     }
701 
702                     break;
703 
704           default:
705                     break;
706           }
707 }
708 
709 /*****************************************************************************
710  *
711  *        bluetooth(9) callback methods for L2CAP
712  *
713  *        All these are called from Bluetooth Protocol code, in a soft
714  *        interrupt context at IPL_SOFTNET.
715  */
716 
717 static void
bthidev_connecting(void * arg)718 bthidev_connecting(void *arg)
719 {
720 
721           /* dont care */
722 }
723 
724 static void
bthidev_ctl_connected(void * arg)725 bthidev_ctl_connected(void *arg)
726 {
727           struct sockaddr_bt sa;
728           struct bthidev_softc *sc = arg;
729           int err;
730 
731           if (sc->sc_state != BTHID_WAIT_CTL)
732                     return;
733 
734           KASSERT(sc->sc_ctl != NULL);
735           KASSERT(sc->sc_int == NULL);
736 
737           if (sc->sc_flags & BTHID_CONNECTING) {
738                     /* initiate connect on interrupt PSM */
739                     err = l2cap_attach_pcb(&sc->sc_int, &bthidev_int_proto, sc);
740                     if (err)
741                               goto fail;
742 
743                     err = l2cap_setopt(sc->sc_int, &sc->sc_mode);
744                     if (err)
745                               goto fail;
746 
747                     memset(&sa, 0, sizeof(sa));
748                     sa.bt_len = sizeof(sa);
749                     sa.bt_family = AF_BLUETOOTH;
750                     bdaddr_copy(&sa.bt_bdaddr, &sc->sc_laddr);
751 
752                     err = l2cap_bind_pcb(sc->sc_int, &sa);
753                     if (err)
754                               goto fail;
755 
756                     sa.bt_psm = sc->sc_intpsm;
757                     bdaddr_copy(&sa.bt_bdaddr, &sc->sc_raddr);
758                     err = l2cap_connect_pcb(sc->sc_int, &sa);
759                     if (err)
760                               goto fail;
761           }
762 
763           sc->sc_state = BTHID_WAIT_INT;
764           return;
765 
766 fail:
767           l2cap_detach_pcb(&sc->sc_ctl);
768           sc->sc_ctl = NULL;
769 
770           aprint_error_dev(sc->sc_dev, "connect failed (%d)\n", err);
771 }
772 
773 static void
bthidev_int_connected(void * arg)774 bthidev_int_connected(void *arg)
775 {
776           struct bthidev_softc *sc = arg;
777 
778           if (sc->sc_state != BTHID_WAIT_INT)
779                     return;
780 
781           KASSERT(sc->sc_ctl != NULL);
782           KASSERT(sc->sc_int != NULL);
783 
784           sc->sc_attempts = 0;
785           sc->sc_flags &= ~BTHID_CONNECTING;
786           sc->sc_state = BTHID_OPEN;
787 
788           aprint_normal_dev(sc->sc_dev, "connected\n");
789 }
790 
791 /*
792  * Disconnected
793  *
794  * Depending on our state, this could mean several things, but essentially
795  * we are lost. If both channels are closed, and we are marked to reconnect,
796  * schedule another try otherwise just give up. They will contact us.
797  */
798 static void
bthidev_ctl_disconnected(void * arg,int err)799 bthidev_ctl_disconnected(void *arg, int err)
800 {
801           struct bthidev_softc *sc = arg;
802 
803           if (sc->sc_ctl != NULL) {
804                     l2cap_detach_pcb(&sc->sc_ctl);
805                     sc->sc_ctl = NULL;
806           }
807 
808           sc->sc_state = BTHID_CLOSED;
809 
810           if (sc->sc_int == NULL) {
811                     aprint_normal_dev(sc->sc_dev, "disconnected (%d)\n", err);
812                     sc->sc_flags &= ~BTHID_CONNECTING;
813 
814                     if (sc->sc_flags & BTHID_RECONNECT)
815                               callout_schedule(&sc->sc_reconnect,
816                                                   BTHID_RETRY_INTERVAL * hz);
817                     else
818                               sc->sc_state = BTHID_WAIT_CTL;
819           } else {
820                     /*
821                      * The interrupt channel should have been closed first,
822                      * but its potentially unsafe to detach that from here.
823                      * Give them a second to do the right thing or let the
824                      * callout handle it.
825                      */
826                     callout_schedule(&sc->sc_reconnect, hz);
827           }
828 }
829 
830 static void
bthidev_int_disconnected(void * arg,int err)831 bthidev_int_disconnected(void *arg, int err)
832 {
833           struct bthidev_softc *sc = arg;
834 
835           if (sc->sc_int != NULL) {
836                     l2cap_detach_pcb(&sc->sc_int);
837                     sc->sc_int = NULL;
838           }
839 
840           sc->sc_state = BTHID_CLOSED;
841 
842           if (sc->sc_ctl == NULL) {
843                     aprint_normal_dev(sc->sc_dev, "disconnected (%d)\n", err);
844                     sc->sc_flags &= ~BTHID_CONNECTING;
845 
846                     if (sc->sc_flags & BTHID_RECONNECT)
847                               callout_schedule(&sc->sc_reconnect,
848                                                   BTHID_RETRY_INTERVAL * hz);
849                     else
850                               sc->sc_state = BTHID_WAIT_CTL;
851           } else {
852                     /*
853                      * The control channel should be closing also, allow
854                      * them a chance to do that before we force it.
855                      */
856                     callout_schedule(&sc->sc_reconnect, hz);
857           }
858 }
859 
860 /*
861  * New Connections
862  *
863  * We give a new L2CAP handle back if this matches the BDADDR we are
864  * listening for and we are in the right state. bthidev_connected will
865  * be called when the connection is open, so nothing else to do here
866  */
867 static void *
bthidev_ctl_newconn(void * arg,struct sockaddr_bt * laddr,struct sockaddr_bt * raddr)868 bthidev_ctl_newconn(void *arg, struct sockaddr_bt *laddr,
869     struct sockaddr_bt *raddr)
870 {
871           struct bthidev_softc *sc = arg;
872 
873           if (bdaddr_same(&raddr->bt_bdaddr, &sc->sc_raddr) == 0)
874                     return NULL;
875 
876           if ((sc->sc_flags & BTHID_CONNECTING)
877               || sc->sc_state != BTHID_WAIT_CTL
878               || sc->sc_ctl != NULL
879               || sc->sc_int != NULL) {
880                     aprint_verbose_dev(sc->sc_dev, "reject ctl newconn %s%s%s%s\n",
881                         (sc->sc_flags & BTHID_CONNECTING) ? " (CONNECTING)" : "",
882                         (sc->sc_state == BTHID_WAIT_CTL) ? " (WAITING)": "",
883                         (sc->sc_ctl != NULL) ? " (GOT CONTROL)" : "",
884                         (sc->sc_int != NULL) ? " (GOT INTERRUPT)" : "");
885 
886                     return NULL;
887           }
888 
889           l2cap_attach_pcb(&sc->sc_ctl, &bthidev_ctl_proto, sc);
890           return sc->sc_ctl;
891 }
892 
893 static void *
bthidev_int_newconn(void * arg,struct sockaddr_bt * laddr,struct sockaddr_bt * raddr)894 bthidev_int_newconn(void *arg, struct sockaddr_bt *laddr,
895     struct sockaddr_bt *raddr)
896 {
897           struct bthidev_softc *sc = arg;
898 
899           if (bdaddr_same(&raddr->bt_bdaddr, &sc->sc_raddr) == 0)
900                     return NULL;
901 
902           if ((sc->sc_flags & BTHID_CONNECTING)
903               || sc->sc_state != BTHID_WAIT_INT
904               || sc->sc_ctl == NULL
905               || sc->sc_int != NULL) {
906                     aprint_verbose_dev(sc->sc_dev, "reject int newconn %s%s%s%s\n",
907                         (sc->sc_flags & BTHID_CONNECTING) ? " (CONNECTING)" : "",
908                         (sc->sc_state == BTHID_WAIT_INT) ? " (WAITING)": "",
909                         (sc->sc_ctl == NULL) ? " (NO CONTROL)" : "",
910                         (sc->sc_int != NULL) ? " (GOT INTERRUPT)" : "");
911 
912                     return NULL;
913           }
914 
915           l2cap_attach_pcb(&sc->sc_int, &bthidev_int_proto, sc);
916           return sc->sc_int;
917 }
918 
919 static void
bthidev_complete(void * arg,int count)920 bthidev_complete(void *arg, int count)
921 {
922 
923           /* dont care */
924 }
925 
926 static void
bthidev_linkmode(void * arg,int new)927 bthidev_linkmode(void *arg, int new)
928 {
929           struct bthidev_softc *sc = arg;
930           int mode;
931 
932           (void)sockopt_getint(&sc->sc_mode, &mode);
933 
934           if ((mode & L2CAP_LM_AUTH) && !(new & L2CAP_LM_AUTH))
935                     aprint_error_dev(sc->sc_dev, "auth failed\n");
936           else if ((mode & L2CAP_LM_ENCRYPT) && !(new & L2CAP_LM_ENCRYPT))
937                     aprint_error_dev(sc->sc_dev, "encrypt off\n");
938           else if ((mode & L2CAP_LM_SECURE) && !(new & L2CAP_LM_SECURE))
939                     aprint_error_dev(sc->sc_dev, "insecure\n");
940           else
941                     return;
942 
943           if (sc->sc_int != NULL)
944                     l2cap_disconnect_pcb(sc->sc_int, 0);
945 
946           if (sc->sc_ctl != NULL)
947                     l2cap_disconnect_pcb(sc->sc_ctl, 0);
948 }
949 
950 /*
951  * Receive reports from the protocol stack. Because this will be called
952  * with bt_lock held, we queue the mbuf and process it with a kernel thread
953  */
954 static void
bthidev_input(void * arg,struct mbuf * m)955 bthidev_input(void *arg, struct mbuf *m)
956 {
957           struct bthidev_softc *sc = arg;
958 
959           if (sc->sc_state != BTHID_OPEN) {
960                     m_freem(m);
961                     return;
962           }
963 
964           mutex_enter(&sc->sc_lock);
965           MBUFQ_ENQUEUE(&sc->sc_inq, m);
966           cv_signal(&sc->sc_cv);
967           mutex_exit(&sc->sc_lock);
968 }
969 
970 /*****************************************************************************
971  *
972  *        IO routines
973  */
974 
975 static void
bthidev_null(struct bthidev * hidev,uint8_t * report,int len)976 bthidev_null(struct bthidev *hidev, uint8_t *report, int len)
977 {
978 
979           /*
980            * empty routine just in case the device
981            * provided no method to handle this report
982            */
983 }
984 
985 static int
bthidev_output(struct bthidev * hidev,uint8_t * report,int rlen)986 bthidev_output(struct bthidev *hidev, uint8_t *report, int rlen)
987 {
988           struct bthidev_softc *sc = device_private(hidev->sc_parent);
989           struct mbuf *m;
990           int err;
991 
992           if (sc == NULL || sc->sc_state != BTHID_OPEN)
993                     return ENOTCONN;
994 
995           KASSERT(sc->sc_ctl != NULL);
996           KASSERT(sc->sc_int != NULL);
997 
998           if (rlen == 0 || report == NULL)
999                     return 0;
1000 
1001           if (rlen > MHLEN - 2) {
1002                     aprint_error_dev(sc->sc_dev,
1003                         "output report too long (%d)!\n", rlen);
1004                     return EMSGSIZE;
1005           }
1006 
1007           m = m_gethdr(M_DONTWAIT, MT_DATA);
1008           if (m == NULL)
1009                     return ENOMEM;
1010 
1011           /*
1012            * data[0] = type / parameter
1013            * data[1] = id
1014            * data[2..N] = report
1015            */
1016           mtod(m, uint8_t *)[0] = (uint8_t)((BTHID_DATA << 4) | BTHID_DATA_OUTPUT);
1017           mtod(m, uint8_t *)[1] = hidev->sc_id;
1018           memcpy(mtod(m, uint8_t *) + 2, report, rlen);
1019           m->m_pkthdr.len = m->m_len = rlen + 2;
1020 
1021           mutex_enter(bt_lock);
1022           err = l2cap_send_pcb(sc->sc_int, m);
1023           mutex_exit(bt_lock);
1024 
1025           return err;
1026 }
1027