xref: /netbsd-src/sys/dev/bluetooth/bthidev.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /*	$NetBSD: bthidev.c,v 1.16 2008/08/06 15:01:23 plunky 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.16 2008/08/06 15:01:23 plunky Exp $");
36 
37 #include <sys/param.h>
38 #include <sys/conf.h>
39 #include <sys/device.h>
40 #include <sys/fcntl.h>
41 #include <sys/kernel.h>
42 #include <sys/queue.h>
43 #include <sys/malloc.h>
44 #include <sys/mbuf.h>
45 #include <sys/proc.h>
46 #include <sys/socketvar.h>
47 #include <sys/systm.h>
48 
49 #include <prop/proplib.h>
50 
51 #include <netbt/bluetooth.h>
52 #include <netbt/l2cap.h>
53 
54 #include <dev/usb/hid.h>
55 #include <dev/bluetooth/btdev.h>
56 #include <dev/bluetooth/bthid.h>
57 #include <dev/bluetooth/bthidev.h>
58 
59 #include "locators.h"
60 
61 /*****************************************************************************
62  *
63  *	Bluetooth HID device
64  */
65 
66 #define MAX_DESCRIPTOR_LEN	1024		/* sanity check */
67 
68 /* bthidev softc */
69 struct bthidev_softc {
70 	uint16_t		sc_state;
71 	uint16_t		sc_flags;
72 	device_t		sc_dev;
73 
74 	bdaddr_t		sc_laddr;	/* local address */
75 	bdaddr_t		sc_raddr;	/* remote address */
76 	struct sockopt		sc_mode;	/* link mode sockopt */
77 
78 	uint16_t		sc_ctlpsm;	/* control PSM */
79 	struct l2cap_channel	*sc_ctl;	/* control channel */
80 	struct l2cap_channel	*sc_ctl_l;	/* control listen */
81 
82 	uint16_t		sc_intpsm;	/* interrupt PSM */
83 	struct l2cap_channel	*sc_int;	/* interrupt channel */
84 	struct l2cap_channel	*sc_int_l;	/* interrupt listen */
85 
86 	LIST_HEAD(,bthidev)	sc_list;	/* child list */
87 
88 	callout_t		sc_reconnect;
89 	int			sc_attempts;	/* connection attempts */
90 };
91 
92 /* sc_flags */
93 #define BTHID_RECONNECT		(1 << 0)	/* reconnect on link loss */
94 #define BTHID_CONNECTING	(1 << 1)	/* we are connecting */
95 
96 /* device state */
97 #define BTHID_CLOSED		0
98 #define BTHID_WAIT_CTL		1
99 #define BTHID_WAIT_INT		2
100 #define BTHID_OPEN		3
101 
102 #define	BTHID_RETRY_INTERVAL	5	/* seconds between connection attempts */
103 
104 /* bthidev internals */
105 static void bthidev_timeout(void *);
106 static int  bthidev_listen(struct bthidev_softc *);
107 static int  bthidev_connect(struct bthidev_softc *);
108 static int  bthidev_output(struct bthidev *, uint8_t *, int);
109 static void bthidev_null(struct bthidev *, uint8_t *, int);
110 
111 /* autoconf(9) glue */
112 static int  bthidev_match(device_t, struct cfdata *, void *);
113 static void bthidev_attach(device_t, device_t, void *);
114 static int  bthidev_detach(device_t, int);
115 static int  bthidev_print(void *, const char *);
116 
117 CFATTACH_DECL_NEW(bthidev, sizeof(struct bthidev_softc),
118     bthidev_match, bthidev_attach, bthidev_detach, NULL);
119 
120 /* bluetooth(9) protocol methods for L2CAP */
121 static void  bthidev_connecting(void *);
122 static void  bthidev_ctl_connected(void *);
123 static void  bthidev_int_connected(void *);
124 static void  bthidev_ctl_disconnected(void *, int);
125 static void  bthidev_int_disconnected(void *, int);
126 static void *bthidev_ctl_newconn(void *, struct sockaddr_bt *, struct sockaddr_bt *);
127 static void *bthidev_int_newconn(void *, struct sockaddr_bt *, struct sockaddr_bt *);
128 static void  bthidev_complete(void *, int);
129 static void  bthidev_linkmode(void *, int);
130 static void  bthidev_input(void *, struct mbuf *);
131 
132 static const struct btproto bthidev_ctl_proto = {
133 	bthidev_connecting,
134 	bthidev_ctl_connected,
135 	bthidev_ctl_disconnected,
136 	bthidev_ctl_newconn,
137 	bthidev_complete,
138 	bthidev_linkmode,
139 	bthidev_input,
140 };
141 
142 static const struct btproto bthidev_int_proto = {
143 	bthidev_connecting,
144 	bthidev_int_connected,
145 	bthidev_int_disconnected,
146 	bthidev_int_newconn,
147 	bthidev_complete,
148 	bthidev_linkmode,
149 	bthidev_input,
150 };
151 
152 /*****************************************************************************
153  *
154  *	bthidev autoconf(9) routines
155  */
156 
157 static int
158 bthidev_match(device_t self, struct cfdata *cfdata, void *aux)
159 {
160 	prop_dictionary_t dict = aux;
161 	prop_object_t obj;
162 
163 	obj = prop_dictionary_get(dict, BTDEVservice);
164 	if (prop_string_equals_cstring(obj, "HID"))
165 		return 1;
166 
167 	return 0;
168 }
169 
170 static void
171 bthidev_attach(device_t parent, device_t self, void *aux)
172 {
173 	struct bthidev_softc *sc = device_private(self);
174 	prop_dictionary_t dict = aux;
175 	prop_object_t obj;
176 	device_t dev;
177 	struct bthidev_attach_args bha;
178 	struct bthidev *hidev;
179 	struct hid_data *d;
180 	struct hid_item h;
181 	const void *desc;
182 	int locs[BTHIDBUSCF_NLOCS];
183 	int maxid, rep, dlen;
184 
185 	/*
186 	 * Init softc
187 	 */
188 	sc->sc_dev = self;
189 	LIST_INIT(&sc->sc_list);
190 	callout_init(&sc->sc_reconnect, 0);
191 	callout_setfunc(&sc->sc_reconnect, bthidev_timeout, sc);
192 	sc->sc_state = BTHID_CLOSED;
193 	sc->sc_flags = BTHID_CONNECTING;
194 	sc->sc_ctlpsm = L2CAP_PSM_HID_CNTL;
195 	sc->sc_intpsm = L2CAP_PSM_HID_INTR;
196 
197 	sockopt_init(&sc->sc_mode, BTPROTO_L2CAP, SO_L2CAP_LM, 0);
198 
199 	/*
200 	 * extract config from proplist
201 	 */
202 	obj = prop_dictionary_get(dict, BTDEVladdr);
203 	bdaddr_copy(&sc->sc_laddr, prop_data_data_nocopy(obj));
204 
205 	obj = prop_dictionary_get(dict, BTDEVraddr);
206 	bdaddr_copy(&sc->sc_raddr, prop_data_data_nocopy(obj));
207 
208 	obj = prop_dictionary_get(dict, BTDEVmode);
209 	if (prop_object_type(obj) == PROP_TYPE_STRING) {
210 		if (prop_string_equals_cstring(obj, BTDEVauth))
211 			sockopt_setint(&sc->sc_mode, L2CAP_LM_AUTH);
212 		else if (prop_string_equals_cstring(obj, BTDEVencrypt))
213 			sockopt_setint(&sc->sc_mode, L2CAP_LM_ENCRYPT);
214 		else if (prop_string_equals_cstring(obj, BTDEVsecure))
215 			sockopt_setint(&sc->sc_mode, L2CAP_LM_SECURE);
216 		else  {
217 			aprint_error(" unknown %s\n", BTDEVmode);
218 			return;
219 		}
220 
221 		aprint_verbose(" %s %s", BTDEVmode,
222 					 prop_string_cstring_nocopy(obj));
223 	}
224 
225 	obj = prop_dictionary_get(dict, BTHIDEVcontrolpsm);
226 	if (prop_object_type(obj) == PROP_TYPE_NUMBER) {
227 		sc->sc_ctlpsm = prop_number_integer_value(obj);
228 		if (L2CAP_PSM_INVALID(sc->sc_ctlpsm)) {
229 			aprint_error(" invalid %s\n", BTHIDEVcontrolpsm);
230 			return;
231 		}
232 	}
233 
234 	obj = prop_dictionary_get(dict, BTHIDEVinterruptpsm);
235 	if (prop_object_type(obj) == PROP_TYPE_NUMBER) {
236 		sc->sc_intpsm = prop_number_integer_value(obj);
237 		if (L2CAP_PSM_INVALID(sc->sc_intpsm)) {
238 			aprint_error(" invalid %s\n", BTHIDEVinterruptpsm);
239 			return;
240 		}
241 	}
242 
243 	obj = prop_dictionary_get(dict, BTHIDEVdescriptor);
244 	if (prop_object_type(obj) == PROP_TYPE_DATA) {
245 		dlen = prop_data_size(obj);
246 		desc = prop_data_data_nocopy(obj);
247 	} else {
248 		aprint_error(" no %s\n", BTHIDEVdescriptor);
249 		return;
250 	}
251 
252 	obj = prop_dictionary_get(dict, BTHIDEVreconnect);
253 	if (prop_object_type(obj) == PROP_TYPE_BOOL
254 	    && !prop_bool_true(obj))
255 		sc->sc_flags |= BTHID_RECONNECT;
256 
257 	/*
258 	 * Parse the descriptor and attach child devices, one per report.
259 	 */
260 	maxid = -1;
261 	h.report_ID = 0;
262 	d = hid_start_parse(desc, dlen, hid_none);
263 	while (hid_get_item(d, &h)) {
264 		if (h.report_ID > maxid)
265 			maxid = h.report_ID;
266 	}
267 	hid_end_parse(d);
268 
269 	if (maxid < 0) {
270 		aprint_error(" no reports found\n");
271 		return;
272 	}
273 
274 	aprint_normal("\n");
275 
276 	for (rep = 0 ; rep <= maxid ; rep++) {
277 		if (hid_report_size(desc, dlen, hid_feature, rep) == 0
278 		    && hid_report_size(desc, dlen, hid_input, rep) == 0
279 		    && hid_report_size(desc, dlen, hid_output, rep) == 0)
280 			continue;
281 
282 		bha.ba_desc = desc;
283 		bha.ba_dlen = dlen;
284 		bha.ba_input = bthidev_null;
285 		bha.ba_feature = bthidev_null;
286 		bha.ba_output = bthidev_output;
287 		bha.ba_id = rep;
288 
289 		locs[BTHIDBUSCF_REPORTID] = rep;
290 
291 		dev = config_found_sm_loc(self, "bthidbus",
292 					locs, &bha, bthidev_print, config_stdsubmatch);
293 		if (dev != NULL) {
294 			hidev = device_private(dev);
295 			hidev->sc_dev = dev;
296 			hidev->sc_parent = self;
297 			hidev->sc_id = rep;
298 			hidev->sc_input = bha.ba_input;
299 			hidev->sc_feature = bha.ba_feature;
300 			LIST_INSERT_HEAD(&sc->sc_list, hidev, sc_next);
301 		}
302 	}
303 
304 	/*
305 	 * start bluetooth connections
306 	 */
307 	mutex_enter(bt_lock);
308 	if ((sc->sc_flags & BTHID_RECONNECT) == 0)
309 		bthidev_listen(sc);
310 
311 	if (sc->sc_flags & BTHID_CONNECTING)
312 		bthidev_connect(sc);
313 	mutex_exit(bt_lock);
314 }
315 
316 static int
317 bthidev_detach(device_t self, int flags)
318 {
319 	struct bthidev_softc *sc = device_private(self);
320 	struct bthidev *hidev;
321 
322 	mutex_enter(bt_lock);
323 	sc->sc_flags = 0;	/* disable reconnecting */
324 
325 	/* release interrupt listen */
326 	if (sc->sc_int_l != NULL) {
327 		l2cap_detach(&sc->sc_int_l);
328 		sc->sc_int_l = NULL;
329 	}
330 
331 	/* release control listen */
332 	if (sc->sc_ctl_l != NULL) {
333 		l2cap_detach(&sc->sc_ctl_l);
334 		sc->sc_ctl_l = NULL;
335 	}
336 
337 	/* close interrupt channel */
338 	if (sc->sc_int != NULL) {
339 		l2cap_disconnect(sc->sc_int, 0);
340 		l2cap_detach(&sc->sc_int);
341 		sc->sc_int = NULL;
342 	}
343 
344 	/* close control channel */
345 	if (sc->sc_ctl != NULL) {
346 		l2cap_disconnect(sc->sc_ctl, 0);
347 		l2cap_detach(&sc->sc_ctl);
348 		sc->sc_ctl = NULL;
349 	}
350 
351 	callout_halt(&sc->sc_reconnect, bt_lock);
352 	callout_destroy(&sc->sc_reconnect);
353 
354 	mutex_exit(bt_lock);
355 
356 	/* detach children */
357 	while ((hidev = LIST_FIRST(&sc->sc_list)) != NULL) {
358 		LIST_REMOVE(hidev, sc_next);
359 		config_detach(hidev->sc_dev, flags);
360 	}
361 
362 	sockopt_destroy(&sc->sc_mode);
363 
364 	return 0;
365 }
366 
367 /*
368  * bthidev config print
369  */
370 static int
371 bthidev_print(void *aux, const char *pnp)
372 {
373 	struct bthidev_attach_args *ba = aux;
374 
375 	if (pnp != NULL)
376 		aprint_normal("%s:", pnp);
377 
378 	if (ba->ba_id > 0)
379 		aprint_normal(" reportid %d", ba->ba_id);
380 
381 	return UNCONF;
382 }
383 
384 /*****************************************************************************
385  *
386  *	bluetooth(4) HID attach/detach routines
387  */
388 
389 /*
390  * callouts are scheduled after connections have been lost, in order
391  * to clean up and reconnect.
392  */
393 static void
394 bthidev_timeout(void *arg)
395 {
396 	struct bthidev_softc *sc = arg;
397 
398 	mutex_enter(bt_lock);
399 	callout_ack(&sc->sc_reconnect);
400 
401 	switch (sc->sc_state) {
402 	case BTHID_CLOSED:
403 		if (sc->sc_int != NULL) {
404 			l2cap_disconnect(sc->sc_int, 0);
405 			break;
406 		}
407 
408 		if (sc->sc_ctl != NULL) {
409 			l2cap_disconnect(sc->sc_ctl, 0);
410 			break;
411 		}
412 
413 		if (sc->sc_flags & BTHID_RECONNECT) {
414 			sc->sc_flags |= BTHID_CONNECTING;
415 			bthidev_connect(sc);
416 			break;
417 		}
418 
419 		break;
420 
421 	case BTHID_WAIT_CTL:
422 		break;
423 
424 	case BTHID_WAIT_INT:
425 		break;
426 
427 	case BTHID_OPEN:
428 		break;
429 
430 	default:
431 		break;
432 	}
433 	mutex_exit(bt_lock);
434 }
435 
436 /*
437  * listen for our device
438  */
439 static int
440 bthidev_listen(struct bthidev_softc *sc)
441 {
442 	struct sockaddr_bt sa;
443 	int err;
444 
445 	memset(&sa, 0, sizeof(sa));
446 	sa.bt_len = sizeof(sa);
447 	sa.bt_family = AF_BLUETOOTH;
448 	bdaddr_copy(&sa.bt_bdaddr, &sc->sc_laddr);
449 
450 	/*
451 	 * Listen on control PSM
452 	 */
453 	err = l2cap_attach(&sc->sc_ctl_l, &bthidev_ctl_proto, sc);
454 	if (err)
455 		return err;
456 
457 	err = l2cap_setopt(sc->sc_ctl_l, &sc->sc_mode);
458 	if (err)
459 		return err;
460 
461 	sa.bt_psm = sc->sc_ctlpsm;
462 	err = l2cap_bind(sc->sc_ctl_l, &sa);
463 	if (err)
464 		return err;
465 
466 	err = l2cap_listen(sc->sc_ctl_l);
467 	if (err)
468 		return err;
469 
470 	/*
471 	 * Listen on interrupt PSM
472 	 */
473 	err = l2cap_attach(&sc->sc_int_l, &bthidev_int_proto, sc);
474 	if (err)
475 		return err;
476 
477 	err = l2cap_setopt(sc->sc_int_l, &sc->sc_mode);
478 	if (err)
479 		return err;
480 
481 	sa.bt_psm = sc->sc_intpsm;
482 	err = l2cap_bind(sc->sc_int_l, &sa);
483 	if (err)
484 		return err;
485 
486 	err = l2cap_listen(sc->sc_int_l);
487 	if (err)
488 		return err;
489 
490 	sc->sc_state = BTHID_WAIT_CTL;
491 	return 0;
492 }
493 
494 /*
495  * start connecting to our device
496  */
497 static int
498 bthidev_connect(struct bthidev_softc *sc)
499 {
500 	struct sockaddr_bt sa;
501 	int err;
502 
503 	if (sc->sc_attempts++ > 0)
504 		aprint_verbose_dev(sc->sc_dev, "connect (#%d)\n", sc->sc_attempts);
505 
506 	memset(&sa, 0, sizeof(sa));
507 	sa.bt_len = sizeof(sa);
508 	sa.bt_family = AF_BLUETOOTH;
509 
510 	err = l2cap_attach(&sc->sc_ctl, &bthidev_ctl_proto, sc);
511 	if (err) {
512 		aprint_error_dev(sc->sc_dev, "l2cap_attach failed (%d)\n", err);
513 		return err;
514 	}
515 
516 	err = l2cap_setopt(sc->sc_ctl, &sc->sc_mode);
517 	if (err)
518 		return err;
519 
520 	bdaddr_copy(&sa.bt_bdaddr, &sc->sc_laddr);
521 	err = l2cap_bind(sc->sc_ctl, &sa);
522 	if (err) {
523 		aprint_error_dev(sc->sc_dev, "l2cap_bind failed (%d)\n", err);
524 		return err;
525 	}
526 
527 	sa.bt_psm = sc->sc_ctlpsm;
528 	bdaddr_copy(&sa.bt_bdaddr, &sc->sc_raddr);
529 	err = l2cap_connect(sc->sc_ctl, &sa);
530 	if (err) {
531 		aprint_error_dev(sc->sc_dev, "l2cap_connect failed (%d)\n", err);
532 		return err;
533 	}
534 
535 	sc->sc_state = BTHID_WAIT_CTL;
536 	return 0;
537 }
538 
539 /*****************************************************************************
540  *
541  *	bluetooth(9) callback methods for L2CAP
542  *
543  *	All these are called from Bluetooth Protocol code, in a soft
544  *	interrupt context at IPL_SOFTNET.
545  */
546 
547 static void
548 bthidev_connecting(void *arg)
549 {
550 
551 	/* dont care */
552 }
553 
554 static void
555 bthidev_ctl_connected(void *arg)
556 {
557 	struct sockaddr_bt sa;
558 	struct bthidev_softc *sc = arg;
559 	int err;
560 
561 	if (sc->sc_state != BTHID_WAIT_CTL)
562 		return;
563 
564 	KASSERT(sc->sc_ctl != NULL);
565 	KASSERT(sc->sc_int == NULL);
566 
567 	if (sc->sc_flags & BTHID_CONNECTING) {
568 		/* initiate connect on interrupt PSM */
569 		err = l2cap_attach(&sc->sc_int, &bthidev_int_proto, sc);
570 		if (err)
571 			goto fail;
572 
573 		err = l2cap_setopt(sc->sc_int, &sc->sc_mode);
574 		if (err)
575 			goto fail;
576 
577 		memset(&sa, 0, sizeof(sa));
578 		sa.bt_len = sizeof(sa);
579 		sa.bt_family = AF_BLUETOOTH;
580 		bdaddr_copy(&sa.bt_bdaddr, &sc->sc_laddr);
581 
582 		err = l2cap_bind(sc->sc_int, &sa);
583 		if (err)
584 			goto fail;
585 
586 		sa.bt_psm = sc->sc_intpsm;
587 		bdaddr_copy(&sa.bt_bdaddr, &sc->sc_raddr);
588 		err = l2cap_connect(sc->sc_int, &sa);
589 		if (err)
590 			goto fail;
591 	}
592 
593 	sc->sc_state = BTHID_WAIT_INT;
594 	return;
595 
596 fail:
597 	l2cap_detach(&sc->sc_ctl);
598 	sc->sc_ctl = NULL;
599 
600 	aprint_error_dev(sc->sc_dev, "connect failed (%d)\n", err);
601 }
602 
603 static void
604 bthidev_int_connected(void *arg)
605 {
606 	struct bthidev_softc *sc = arg;
607 
608 	if (sc->sc_state != BTHID_WAIT_INT)
609 		return;
610 
611 	KASSERT(sc->sc_ctl != NULL);
612 	KASSERT(sc->sc_int != NULL);
613 
614 	sc->sc_attempts = 0;
615 	sc->sc_flags &= ~BTHID_CONNECTING;
616 	sc->sc_state = BTHID_OPEN;
617 
618 	aprint_normal_dev(sc->sc_dev, "connected\n");
619 }
620 
621 /*
622  * Disconnected
623  *
624  * Depending on our state, this could mean several things, but essentially
625  * we are lost. If both channels are closed, and we are marked to reconnect,
626  * schedule another try otherwise just give up. They will contact us.
627  */
628 static void
629 bthidev_ctl_disconnected(void *arg, int err)
630 {
631 	struct bthidev_softc *sc = arg;
632 
633 	if (sc->sc_ctl != NULL) {
634 		l2cap_detach(&sc->sc_ctl);
635 		sc->sc_ctl = NULL;
636 	}
637 
638 	sc->sc_state = BTHID_CLOSED;
639 
640 	if (sc->sc_int == NULL) {
641 		aprint_normal_dev(sc->sc_dev, "disconnected\n");
642 		sc->sc_flags &= ~BTHID_CONNECTING;
643 
644 		if (sc->sc_flags & BTHID_RECONNECT)
645 			callout_schedule(&sc->sc_reconnect,
646 					BTHID_RETRY_INTERVAL * hz);
647 		else
648 			sc->sc_state = BTHID_WAIT_CTL;
649 	} else {
650 		/*
651 		 * The interrupt channel should have been closed first,
652 		 * but its potentially unsafe to detach that from here.
653 		 * Give them a second to do the right thing or let the
654 		 * callout handle it.
655 		 */
656 		callout_schedule(&sc->sc_reconnect, hz);
657 	}
658 }
659 
660 static void
661 bthidev_int_disconnected(void *arg, int err)
662 {
663 	struct bthidev_softc *sc = arg;
664 
665 	if (sc->sc_int != NULL) {
666 		l2cap_detach(&sc->sc_int);
667 		sc->sc_int = NULL;
668 	}
669 
670 	sc->sc_state = BTHID_CLOSED;
671 
672 	if (sc->sc_ctl == NULL) {
673 		aprint_normal_dev(sc->sc_dev, "disconnected\n");
674 		sc->sc_flags &= ~BTHID_CONNECTING;
675 
676 		if (sc->sc_flags & BTHID_RECONNECT)
677 			callout_schedule(&sc->sc_reconnect,
678 					BTHID_RETRY_INTERVAL * hz);
679 		else
680 			sc->sc_state = BTHID_WAIT_CTL;
681 	} else {
682 		/*
683 		 * The control channel should be closing also, allow
684 		 * them a chance to do that before we force it.
685 		 */
686 		callout_schedule(&sc->sc_reconnect, hz);
687 	}
688 }
689 
690 /*
691  * New Connections
692  *
693  * We give a new L2CAP handle back if this matches the BDADDR we are
694  * listening for and we are in the right state. bthidev_connected will
695  * be called when the connection is open, so nothing else to do here
696  */
697 static void *
698 bthidev_ctl_newconn(void *arg, struct sockaddr_bt *laddr,
699     struct sockaddr_bt *raddr)
700 {
701 	struct bthidev_softc *sc = arg;
702 
703 	if (bdaddr_same(&raddr->bt_bdaddr, &sc->sc_raddr) == 0
704 	    || (sc->sc_flags & BTHID_CONNECTING)
705 	    || sc->sc_state != BTHID_WAIT_CTL
706 	    || sc->sc_ctl != NULL
707 	    || sc->sc_int != NULL)
708 		return NULL;
709 
710 	l2cap_attach(&sc->sc_ctl, &bthidev_ctl_proto, sc);
711 	return sc->sc_ctl;
712 }
713 
714 static void *
715 bthidev_int_newconn(void *arg, struct sockaddr_bt *laddr,
716     struct sockaddr_bt *raddr)
717 {
718 	struct bthidev_softc *sc = arg;
719 
720 	if (bdaddr_same(&raddr->bt_bdaddr, &sc->sc_raddr) == 0
721 	    || (sc->sc_flags & BTHID_CONNECTING)
722 	    || sc->sc_state != BTHID_WAIT_INT
723 	    || sc->sc_ctl == NULL
724 	    || sc->sc_int != NULL)
725 		return NULL;
726 
727 	l2cap_attach(&sc->sc_int, &bthidev_int_proto, sc);
728 	return sc->sc_int;
729 }
730 
731 static void
732 bthidev_complete(void *arg, int count)
733 {
734 
735 	/* dont care */
736 }
737 
738 static void
739 bthidev_linkmode(void *arg, int new)
740 {
741 	struct bthidev_softc *sc = arg;
742 	int mode;
743 
744 	(void)sockopt_getint(&sc->sc_mode, &mode);
745 
746 	if ((mode & L2CAP_LM_AUTH) && !(new & L2CAP_LM_AUTH))
747 		aprint_error_dev(sc->sc_dev, "auth failed\n");
748 	else if ((mode & L2CAP_LM_ENCRYPT) && !(new & L2CAP_LM_ENCRYPT))
749 		aprint_error_dev(sc->sc_dev, "encrypt off\n");
750 	else if ((mode & L2CAP_LM_SECURE) && !(new & L2CAP_LM_SECURE))
751 		aprint_error_dev(sc->sc_dev, "insecure\n");
752 	else
753 		return;
754 
755 	if (sc->sc_int != NULL)
756 		l2cap_disconnect(sc->sc_int, 0);
757 
758 	if (sc->sc_ctl != NULL)
759 		l2cap_disconnect(sc->sc_ctl, 0);
760 }
761 
762 /*
763  * Receive reports from the protocol stack.
764  */
765 static void
766 bthidev_input(void *arg, struct mbuf *m)
767 {
768 	struct bthidev_softc *sc = arg;
769 	struct bthidev *hidev;
770 	uint8_t *data;
771 	int len;
772 
773 	if (sc->sc_state != BTHID_OPEN)
774 		goto release;
775 
776 	if (m->m_pkthdr.len > m->m_len)
777 		aprint_error_dev(sc->sc_dev, "truncating HID report\n");
778 
779 	len = m->m_len;
780 	data = mtod(m, uint8_t *);
781 
782 	if (BTHID_TYPE(data[0]) == BTHID_DATA) {
783 		/*
784 		 * data[0] == type / parameter
785 		 * data[1] == id
786 		 * data[2..len] == report
787 		 */
788 		if (len < 3)
789 			goto release;
790 
791 		LIST_FOREACH(hidev, &sc->sc_list, sc_next) {
792 			if (data[1] == hidev->sc_id) {
793 				switch (BTHID_DATA_PARAM(data[0])) {
794 				case BTHID_DATA_INPUT:
795 					(*hidev->sc_input)(hidev, data + 2, len - 2);
796 					break;
797 
798 				case BTHID_DATA_FEATURE:
799 					(*hidev->sc_feature)(hidev, data + 2, len - 2);
800 					break;
801 
802 				default:
803 					break;
804 				}
805 
806 				goto release;
807 			}
808 		}
809 		aprint_error_dev(sc->sc_dev, "report id %d, len = %d ignored\n",
810 		    data[1], len - 2);
811 
812 		goto release;
813 	}
814 
815 	if (BTHID_TYPE(data[0]) == BTHID_CONTROL) {
816 		if (len < 1)
817 			goto release;
818 
819 		if (BTHID_DATA_PARAM(data[0]) == BTHID_CONTROL_UNPLUG) {
820 			aprint_normal_dev(sc->sc_dev, "unplugged\n");
821 
822 			/* close interrupt channel */
823 			if (sc->sc_int != NULL) {
824 				l2cap_disconnect(sc->sc_int, 0);
825 				l2cap_detach(&sc->sc_int);
826 				sc->sc_int = NULL;
827 			}
828 
829 			/* close control channel */
830 			if (sc->sc_ctl != NULL) {
831 				l2cap_disconnect(sc->sc_ctl, 0);
832 				l2cap_detach(&sc->sc_ctl);
833 				sc->sc_ctl = NULL;
834 			}
835 		}
836 
837 		goto release;
838 	}
839 
840 release:
841 	m_freem(m);
842 }
843 
844 /*****************************************************************************
845  *
846  *	IO routines
847  */
848 
849 static void
850 bthidev_null(struct bthidev *hidev, uint8_t *report, int len)
851 {
852 
853 	/*
854 	 * empty routine just in case the device
855 	 * provided no method to handle this report
856 	 */
857 }
858 
859 static int
860 bthidev_output(struct bthidev *hidev, uint8_t *report, int rlen)
861 {
862 	struct bthidev_softc *sc = device_private(hidev->sc_parent);
863 	struct mbuf *m;
864 	int err;
865 
866 	if (sc == NULL || sc->sc_state != BTHID_OPEN)
867 		return ENOTCONN;
868 
869 	KASSERT(sc->sc_ctl != NULL);
870 	KASSERT(sc->sc_int != NULL);
871 
872 	if (rlen == 0 || report == NULL)
873 		return 0;
874 
875 	if (rlen > MHLEN - 2) {
876 		aprint_error_dev(sc->sc_dev,
877 		    "output report too long (%d)!\n", rlen);
878 		return EMSGSIZE;
879 	}
880 
881 	m = m_gethdr(M_DONTWAIT, MT_DATA);
882 	if (m == NULL)
883 		return ENOMEM;
884 
885 	/*
886 	 * data[0] = type / parameter
887 	 * data[1] = id
888 	 * data[2..N] = report
889 	 */
890 	mtod(m, uint8_t *)[0] = (uint8_t)((BTHID_DATA << 4) | BTHID_DATA_OUTPUT);
891 	mtod(m, uint8_t *)[1] = hidev->sc_id;
892 	memcpy(mtod(m, uint8_t *) + 2, report, rlen);
893 	m->m_pkthdr.len = m->m_len = rlen + 2;
894 
895 	mutex_enter(bt_lock);
896 	err = l2cap_send(sc->sc_int, m);
897 	mutex_exit(bt_lock);
898 
899 	return err;
900 }
901