xref: /freebsd/sys/netgraph/bluetooth/socket/ng_btsocket_sco.c (revision 36712a94975f5bd0d26c85377283b49a2369c82f)
1 /*
2  * ng_btsocket_sco.c
3  */
4 
5 /*-
6  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
7  *
8  * Copyright (c) 2001-2002 Maksim Yevmenkin <m_evmenkin@yahoo.com>
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $Id: ng_btsocket_sco.c,v 1.2 2005/10/31 18:08:51 max Exp $
33  * $FreeBSD$
34  */
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/bitstring.h>
39 #include <sys/domain.h>
40 #include <sys/endian.h>
41 #include <sys/errno.h>
42 #include <sys/filedesc.h>
43 #include <sys/ioccom.h>
44 #include <sys/kernel.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/mutex.h>
49 #include <sys/protosw.h>
50 #include <sys/queue.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/sysctl.h>
54 #include <sys/taskqueue.h>
55 
56 #include <net/vnet.h>
57 
58 #include <netgraph/ng_message.h>
59 #include <netgraph/netgraph.h>
60 #include <netgraph/bluetooth/include/ng_bluetooth.h>
61 #include <netgraph/bluetooth/include/ng_hci.h>
62 #include <netgraph/bluetooth/include/ng_l2cap.h>
63 #include <netgraph/bluetooth/include/ng_btsocket.h>
64 #include <netgraph/bluetooth/include/ng_btsocket_sco.h>
65 
66 /* MALLOC define */
67 #ifdef NG_SEPARATE_MALLOC
68 static MALLOC_DEFINE(M_NETGRAPH_BTSOCKET_SCO, "netgraph_btsocks_sco",
69 		"Netgraph Bluetooth SCO sockets");
70 #else
71 #define M_NETGRAPH_BTSOCKET_SCO M_NETGRAPH
72 #endif /* NG_SEPARATE_MALLOC */
73 
74 /* Netgraph node methods */
75 static ng_constructor_t	ng_btsocket_sco_node_constructor;
76 static ng_rcvmsg_t	ng_btsocket_sco_node_rcvmsg;
77 static ng_shutdown_t	ng_btsocket_sco_node_shutdown;
78 static ng_newhook_t	ng_btsocket_sco_node_newhook;
79 static ng_connect_t	ng_btsocket_sco_node_connect;
80 static ng_rcvdata_t	ng_btsocket_sco_node_rcvdata;
81 static ng_disconnect_t	ng_btsocket_sco_node_disconnect;
82 
83 static void		ng_btsocket_sco_input   (void *, int);
84 static void		ng_btsocket_sco_rtclean (void *, int);
85 
86 /* Netgraph type descriptor */
87 static struct ng_type	typestruct = {
88 	.version =	NG_ABI_VERSION,
89 	.name =		NG_BTSOCKET_SCO_NODE_TYPE,
90 	.constructor =	ng_btsocket_sco_node_constructor,
91 	.rcvmsg =	ng_btsocket_sco_node_rcvmsg,
92 	.shutdown =	ng_btsocket_sco_node_shutdown,
93 	.newhook =	ng_btsocket_sco_node_newhook,
94 	.connect =	ng_btsocket_sco_node_connect,
95 	.rcvdata =	ng_btsocket_sco_node_rcvdata,
96 	.disconnect =	ng_btsocket_sco_node_disconnect,
97 };
98 
99 /* Globals */
100 static u_int32_t				ng_btsocket_sco_debug_level;
101 static node_p					ng_btsocket_sco_node;
102 static struct ng_bt_itemq			ng_btsocket_sco_queue;
103 static struct mtx				ng_btsocket_sco_queue_mtx;
104 static struct task				ng_btsocket_sco_queue_task;
105 static struct mtx				ng_btsocket_sco_sockets_mtx;
106 static LIST_HEAD(, ng_btsocket_sco_pcb)		ng_btsocket_sco_sockets;
107 static LIST_HEAD(, ng_btsocket_sco_rtentry)	ng_btsocket_sco_rt;
108 static struct mtx				ng_btsocket_sco_rt_mtx;
109 static struct task				ng_btsocket_sco_rt_task;
110 static struct timeval				ng_btsocket_sco_lasttime;
111 static int					ng_btsocket_sco_curpps;
112 
113 /* Sysctl tree */
114 SYSCTL_DECL(_net_bluetooth_sco_sockets);
115 static SYSCTL_NODE(_net_bluetooth_sco_sockets, OID_AUTO, seq, CTLFLAG_RW,
116 	0, "Bluetooth SEQPACKET SCO sockets family");
117 SYSCTL_UINT(_net_bluetooth_sco_sockets_seq, OID_AUTO, debug_level,
118 	CTLFLAG_RW,
119 	&ng_btsocket_sco_debug_level, NG_BTSOCKET_WARN_LEVEL,
120 	"Bluetooth SEQPACKET SCO sockets debug level");
121 SYSCTL_UINT(_net_bluetooth_sco_sockets_seq, OID_AUTO, queue_len,
122 	CTLFLAG_RD,
123 	&ng_btsocket_sco_queue.len, 0,
124 	"Bluetooth SEQPACKET SCO sockets input queue length");
125 SYSCTL_UINT(_net_bluetooth_sco_sockets_seq, OID_AUTO, queue_maxlen,
126 	CTLFLAG_RD,
127 	&ng_btsocket_sco_queue.maxlen, 0,
128 	"Bluetooth SEQPACKET SCO sockets input queue max. length");
129 SYSCTL_UINT(_net_bluetooth_sco_sockets_seq, OID_AUTO, queue_drops,
130 	CTLFLAG_RD,
131 	&ng_btsocket_sco_queue.drops, 0,
132 	"Bluetooth SEQPACKET SCO sockets input queue drops");
133 
134 /* Debug */
135 #define NG_BTSOCKET_SCO_INFO \
136 	if (ng_btsocket_sco_debug_level >= NG_BTSOCKET_INFO_LEVEL && \
137 	    ppsratecheck(&ng_btsocket_sco_lasttime, &ng_btsocket_sco_curpps, 1)) \
138 		printf
139 
140 #define NG_BTSOCKET_SCO_WARN \
141 	if (ng_btsocket_sco_debug_level >= NG_BTSOCKET_WARN_LEVEL && \
142 	    ppsratecheck(&ng_btsocket_sco_lasttime, &ng_btsocket_sco_curpps, 1)) \
143 		printf
144 
145 #define NG_BTSOCKET_SCO_ERR \
146 	if (ng_btsocket_sco_debug_level >= NG_BTSOCKET_ERR_LEVEL && \
147 	    ppsratecheck(&ng_btsocket_sco_lasttime, &ng_btsocket_sco_curpps, 1)) \
148 		printf
149 
150 #define NG_BTSOCKET_SCO_ALERT \
151 	if (ng_btsocket_sco_debug_level >= NG_BTSOCKET_ALERT_LEVEL && \
152 	    ppsratecheck(&ng_btsocket_sco_lasttime, &ng_btsocket_sco_curpps, 1)) \
153 		printf
154 
155 /*
156  * Netgraph message processing routines
157  */
158 
159 static int ng_btsocket_sco_process_lp_con_cfm
160 	(struct ng_mesg *, ng_btsocket_sco_rtentry_p);
161 static int ng_btsocket_sco_process_lp_con_ind
162 	(struct ng_mesg *, ng_btsocket_sco_rtentry_p);
163 static int ng_btsocket_sco_process_lp_discon_ind
164 	(struct ng_mesg *, ng_btsocket_sco_rtentry_p);
165 
166 /*
167  * Send LP messages to the lower layer
168  */
169 
170 static int  ng_btsocket_sco_send_lp_con_req
171 	(ng_btsocket_sco_pcb_p);
172 static int  ng_btsocket_sco_send_lp_con_rsp
173 	(ng_btsocket_sco_rtentry_p, bdaddr_p, int);
174 static int  ng_btsocket_sco_send_lp_discon_req
175 	(ng_btsocket_sco_pcb_p);
176 
177 static int ng_btsocket_sco_send2
178 	(ng_btsocket_sco_pcb_p);
179 
180 /*
181  * Timeout processing routines
182  */
183 
184 static void ng_btsocket_sco_timeout         (ng_btsocket_sco_pcb_p);
185 static void ng_btsocket_sco_untimeout       (ng_btsocket_sco_pcb_p);
186 static void ng_btsocket_sco_process_timeout (void *);
187 
188 /*
189  * Other stuff
190  */
191 
192 static ng_btsocket_sco_pcb_p	ng_btsocket_sco_pcb_by_addr(bdaddr_p);
193 static ng_btsocket_sco_pcb_p	ng_btsocket_sco_pcb_by_handle(bdaddr_p, int);
194 static ng_btsocket_sco_pcb_p	ng_btsocket_sco_pcb_by_addrs(bdaddr_p, bdaddr_p);
195 
196 #define ng_btsocket_sco_wakeup_input_task() \
197 	taskqueue_enqueue(taskqueue_swi, &ng_btsocket_sco_queue_task)
198 
199 #define ng_btsocket_sco_wakeup_route_task() \
200 	taskqueue_enqueue(taskqueue_swi, &ng_btsocket_sco_rt_task)
201 
202 /*****************************************************************************
203  *****************************************************************************
204  **                        Netgraph node interface
205  *****************************************************************************
206  *****************************************************************************/
207 
208 /*
209  * Netgraph node constructor. Do not allow to create node of this type.
210  */
211 
212 static int
213 ng_btsocket_sco_node_constructor(node_p node)
214 {
215 	return (EINVAL);
216 } /* ng_btsocket_sco_node_constructor */
217 
218 /*
219  * Do local shutdown processing. Let old node go and create new fresh one.
220  */
221 
222 static int
223 ng_btsocket_sco_node_shutdown(node_p node)
224 {
225 	int	error = 0;
226 
227 	NG_NODE_UNREF(node);
228 
229 	/* Create new node */
230 	error = ng_make_node_common(&typestruct, &ng_btsocket_sco_node);
231 	if (error != 0) {
232 		NG_BTSOCKET_SCO_ALERT(
233 "%s: Could not create Netgraph node, error=%d\n", __func__, error);
234 
235 		ng_btsocket_sco_node = NULL;
236 
237 		return (error);
238 	}
239 
240 	error = ng_name_node(ng_btsocket_sco_node,
241 				NG_BTSOCKET_SCO_NODE_TYPE);
242 	if (error != 0) {
243 		NG_BTSOCKET_SCO_ALERT(
244 "%s: Could not name Netgraph node, error=%d\n", __func__, error);
245 
246 		NG_NODE_UNREF(ng_btsocket_sco_node);
247 		ng_btsocket_sco_node = NULL;
248 
249 		return (error);
250 	}
251 
252 	return (0);
253 } /* ng_btsocket_sco_node_shutdown */
254 
255 /*
256  * We allow any hook to be connected to the node.
257  */
258 
259 static int
260 ng_btsocket_sco_node_newhook(node_p node, hook_p hook, char const *name)
261 {
262 	return (0);
263 } /* ng_btsocket_sco_node_newhook */
264 
265 /*
266  * Just say "YEP, that's OK by me!"
267  */
268 
269 static int
270 ng_btsocket_sco_node_connect(hook_p hook)
271 {
272 	NG_HOOK_SET_PRIVATE(hook, NULL);
273 	NG_HOOK_REF(hook); /* Keep extra reference to the hook */
274 
275 #if 0
276 	NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));
277 	NG_HOOK_FORCE_QUEUE(hook);
278 #endif
279 
280 	return (0);
281 } /* ng_btsocket_sco_node_connect */
282 
283 /*
284  * Hook disconnection. Schedule route cleanup task
285  */
286 
287 static int
288 ng_btsocket_sco_node_disconnect(hook_p hook)
289 {
290 	/*
291 	 * If hook has private information than we must have this hook in
292 	 * the routing table and must schedule cleaning for the routing table.
293 	 * Otherwise hook was connected but we never got "hook_info" message,
294 	 * so we have never added this hook to the routing table and it save
295 	 * to just delete it.
296 	 */
297 
298 	if (NG_HOOK_PRIVATE(hook) != NULL)
299 		return (ng_btsocket_sco_wakeup_route_task());
300 
301 	NG_HOOK_UNREF(hook); /* Remove extra reference */
302 
303 	return (0);
304 } /* ng_btsocket_sco_node_disconnect */
305 
306 /*
307  * Process incoming messages
308  */
309 
310 static int
311 ng_btsocket_sco_node_rcvmsg(node_p node, item_p item, hook_p hook)
312 {
313 	struct ng_mesg	*msg = NGI_MSG(item); /* item still has message */
314 	int		 error = 0;
315 
316 	if (msg != NULL && msg->header.typecookie == NGM_HCI_COOKIE) {
317 		mtx_lock(&ng_btsocket_sco_queue_mtx);
318 		if (NG_BT_ITEMQ_FULL(&ng_btsocket_sco_queue)) {
319 			NG_BTSOCKET_SCO_ERR(
320 "%s: Input queue is full (msg)\n", __func__);
321 
322 			NG_BT_ITEMQ_DROP(&ng_btsocket_sco_queue);
323 			NG_FREE_ITEM(item);
324 			error = ENOBUFS;
325 		} else {
326 			if (hook != NULL) {
327 				NG_HOOK_REF(hook);
328 				NGI_SET_HOOK(item, hook);
329 			}
330 
331 			NG_BT_ITEMQ_ENQUEUE(&ng_btsocket_sco_queue, item);
332 			error = ng_btsocket_sco_wakeup_input_task();
333 		}
334 		mtx_unlock(&ng_btsocket_sco_queue_mtx);
335 	} else {
336 		NG_FREE_ITEM(item);
337 		error = EINVAL;
338 	}
339 
340 	return (error);
341 } /* ng_btsocket_sco_node_rcvmsg */
342 
343 /*
344  * Receive data on a hook
345  */
346 
347 static int
348 ng_btsocket_sco_node_rcvdata(hook_p hook, item_p item)
349 {
350 	int	error = 0;
351 
352 	mtx_lock(&ng_btsocket_sco_queue_mtx);
353 	if (NG_BT_ITEMQ_FULL(&ng_btsocket_sco_queue)) {
354 		NG_BTSOCKET_SCO_ERR(
355 "%s: Input queue is full (data)\n", __func__);
356 
357 		NG_BT_ITEMQ_DROP(&ng_btsocket_sco_queue);
358 		NG_FREE_ITEM(item);
359 		error = ENOBUFS;
360 	} else {
361 		NG_HOOK_REF(hook);
362 		NGI_SET_HOOK(item, hook);
363 
364 		NG_BT_ITEMQ_ENQUEUE(&ng_btsocket_sco_queue, item);
365 		error = ng_btsocket_sco_wakeup_input_task();
366 	}
367 	mtx_unlock(&ng_btsocket_sco_queue_mtx);
368 
369 	return (error);
370 } /* ng_btsocket_sco_node_rcvdata */
371 
372 /*
373  * Process LP_ConnectCfm event from the lower layer protocol
374  */
375 
376 static int
377 ng_btsocket_sco_process_lp_con_cfm(struct ng_mesg *msg,
378 		ng_btsocket_sco_rtentry_p rt)
379 {
380 	ng_hci_lp_con_cfm_ep	*ep = NULL;
381 	ng_btsocket_sco_pcb_t	*pcb = NULL;
382 	int			 error = 0;
383 
384 	if (msg->header.arglen != sizeof(*ep))
385 		return (EMSGSIZE);
386 
387 	ep = (ng_hci_lp_con_cfm_ep *)(msg->data);
388 
389 	mtx_lock(&ng_btsocket_sco_sockets_mtx);
390 
391 	/* Look for the socket with the token */
392 	pcb = ng_btsocket_sco_pcb_by_addrs(&rt->src, &ep->bdaddr);
393 	if (pcb == NULL) {
394 		mtx_unlock(&ng_btsocket_sco_sockets_mtx);
395 		return (ENOENT);
396 	}
397 
398 	/* pcb is locked */
399 
400 	NG_BTSOCKET_SCO_INFO(
401 "%s: Got LP_ConnectCfm response, src bdaddr=%x:%x:%x:%x:%x:%x, " \
402 "dst bdaddr=%x:%x:%x:%x:%x:%x, status=%d, handle=%d, state=%d\n",
403 		__func__,
404 		pcb->src.b[5], pcb->src.b[4], pcb->src.b[3],
405 		pcb->src.b[2], pcb->src.b[1], pcb->src.b[0],
406 		pcb->dst.b[5], pcb->dst.b[4], pcb->dst.b[3],
407 		pcb->dst.b[2], pcb->dst.b[1], pcb->dst.b[0],
408 		ep->status, ep->con_handle, pcb->state);
409 
410 	if (pcb->state != NG_BTSOCKET_SCO_CONNECTING) {
411 		mtx_unlock(&pcb->pcb_mtx);
412 		mtx_unlock(&ng_btsocket_sco_sockets_mtx);
413 
414 		return (ENOENT);
415 	}
416 
417 	ng_btsocket_sco_untimeout(pcb);
418 
419 	if (ep->status == 0) {
420 		/*
421 		 * Connection is open. Update connection handle and
422 		 * socket state
423 		 */
424 
425 		pcb->con_handle = ep->con_handle;
426 		pcb->state = NG_BTSOCKET_SCO_OPEN;
427 		soisconnected(pcb->so);
428 	} else {
429 		/*
430 		 * We have failed to open connection, so disconnect the socket
431 		 */
432 
433 		pcb->so->so_error = ECONNREFUSED; /* XXX convert status ??? */
434 		pcb->state = NG_BTSOCKET_SCO_CLOSED;
435 		soisdisconnected(pcb->so);
436 	}
437 
438 	mtx_unlock(&pcb->pcb_mtx);
439 	mtx_unlock(&ng_btsocket_sco_sockets_mtx);
440 
441 	return (error);
442 } /* ng_btsocket_sco_process_lp_con_cfm */
443 
444 /*
445  * Process LP_ConnectInd indicator. Find socket that listens on address.
446  * Find exact or closest match.
447  */
448 
449 static int
450 ng_btsocket_sco_process_lp_con_ind(struct ng_mesg *msg,
451 		ng_btsocket_sco_rtentry_p rt)
452 {
453 	ng_hci_lp_con_ind_ep	*ep = NULL;
454 	ng_btsocket_sco_pcb_t	*pcb = NULL, *pcb1 = NULL;
455 	int			 error = 0;
456 	u_int16_t		 status = 0;
457 
458 	if (msg->header.arglen != sizeof(*ep))
459 		return (EMSGSIZE);
460 
461 	ep = (ng_hci_lp_con_ind_ep *)(msg->data);
462 
463 	NG_BTSOCKET_SCO_INFO(
464 "%s: Got LP_ConnectInd indicator, src bdaddr=%x:%x:%x:%x:%x:%x, " \
465 "dst bdaddr=%x:%x:%x:%x:%x:%x\n",
466 		__func__,
467 		rt->src.b[5], rt->src.b[4], rt->src.b[3],
468 		rt->src.b[2], rt->src.b[1], rt->src.b[0],
469 		ep->bdaddr.b[5], ep->bdaddr.b[4], ep->bdaddr.b[3],
470 		ep->bdaddr.b[2], ep->bdaddr.b[1], ep->bdaddr.b[0]);
471 
472 	mtx_lock(&ng_btsocket_sco_sockets_mtx);
473 
474 	pcb = ng_btsocket_sco_pcb_by_addr(&rt->src);
475 	if (pcb != NULL) {
476 		struct socket *so1;
477 
478 		/* pcb is locked */
479 
480 		CURVNET_SET(pcb->so->so_vnet);
481 		so1 = sonewconn(pcb->so, 0);
482 		CURVNET_RESTORE();
483 
484 		if (so1 == NULL) {
485 			status = 0x0d; /* Rejected due to limited resources */
486 			goto respond;
487 		}
488 
489 		/*
490 		 * If we got here than we have created new socket. So complete
491 		 * connection. If we we listening on specific address then copy
492 		 * source address from listening socket, otherwise copy source
493 		 * address from hook's routing information.
494 		 */
495 
496 		pcb1 = so2sco_pcb(so1);
497 		KASSERT((pcb1 != NULL),
498 ("%s: pcb1 == NULL\n", __func__));
499 
500  		mtx_lock(&pcb1->pcb_mtx);
501 
502 		if (bcmp(&pcb->src, NG_HCI_BDADDR_ANY, sizeof(pcb->src)) != 0)
503 			bcopy(&pcb->src, &pcb1->src, sizeof(pcb1->src));
504 		else
505 			bcopy(&rt->src, &pcb1->src, sizeof(pcb1->src));
506 
507 		pcb1->flags &= ~NG_BTSOCKET_SCO_CLIENT;
508 
509 		bcopy(&ep->bdaddr, &pcb1->dst, sizeof(pcb1->dst));
510 		pcb1->rt = rt;
511 	} else
512 		/* Nobody listens on requested BDADDR */
513 		status = 0x1f; /* Unspecified Error */
514 
515 respond:
516 	error = ng_btsocket_sco_send_lp_con_rsp(rt, &ep->bdaddr, status);
517 	if (pcb1 != NULL) {
518 		if (error != 0) {
519 			pcb1->so->so_error = error;
520 			pcb1->state = NG_BTSOCKET_SCO_CLOSED;
521 			soisdisconnected(pcb1->so);
522 		} else {
523 			pcb1->state = NG_BTSOCKET_SCO_CONNECTING;
524 			soisconnecting(pcb1->so);
525 
526 			ng_btsocket_sco_timeout(pcb1);
527 		}
528 
529 		mtx_unlock(&pcb1->pcb_mtx);
530 	}
531 
532 	if (pcb != NULL)
533 		mtx_unlock(&pcb->pcb_mtx);
534 
535 	mtx_unlock(&ng_btsocket_sco_sockets_mtx);
536 
537 	return (error);
538 } /* ng_btsocket_sco_process_lp_con_ind */
539 
540 /*
541  * Process LP_DisconnectInd indicator
542  */
543 
544 static int
545 ng_btsocket_sco_process_lp_discon_ind(struct ng_mesg *msg,
546 		ng_btsocket_sco_rtentry_p rt)
547 {
548 	ng_hci_lp_discon_ind_ep	*ep = NULL;
549 	ng_btsocket_sco_pcb_t	*pcb = NULL;
550 
551 	/* Check message */
552 	if (msg->header.arglen != sizeof(*ep))
553 		return (EMSGSIZE);
554 
555 	ep = (ng_hci_lp_discon_ind_ep *)(msg->data);
556 
557 	mtx_lock(&ng_btsocket_sco_sockets_mtx);
558 
559 	/* Look for the socket with given channel ID */
560 	pcb = ng_btsocket_sco_pcb_by_handle(&rt->src, ep->con_handle);
561 	if (pcb == NULL) {
562 		mtx_unlock(&ng_btsocket_sco_sockets_mtx);
563 		return (0);
564 	}
565 
566 	/*
567 	 * Disconnect the socket. If there was any pending request we can
568 	 * not do anything here anyway.
569 	 */
570 
571 	/* pcb is locked */
572 
573        	NG_BTSOCKET_SCO_INFO(
574 "%s: Got LP_DisconnectInd indicator, src bdaddr=%x:%x:%x:%x:%x:%x, " \
575 "dst bdaddr=%x:%x:%x:%x:%x:%x, handle=%d, state=%d\n",
576 		__func__,
577 		pcb->src.b[5], pcb->src.b[4], pcb->src.b[3],
578 		pcb->src.b[2], pcb->src.b[1], pcb->src.b[0],
579 		pcb->dst.b[5], pcb->dst.b[4], pcb->dst.b[3],
580 		pcb->dst.b[2], pcb->dst.b[1], pcb->dst.b[0],
581 		pcb->con_handle, pcb->state);
582 
583 	if (pcb->flags & NG_BTSOCKET_SCO_TIMO)
584 		ng_btsocket_sco_untimeout(pcb);
585 
586 	pcb->state = NG_BTSOCKET_SCO_CLOSED;
587 	soisdisconnected(pcb->so);
588 
589 	mtx_unlock(&pcb->pcb_mtx);
590 	mtx_unlock(&ng_btsocket_sco_sockets_mtx);
591 
592 	return (0);
593 } /* ng_btsocket_sco_process_lp_discon_ind */
594 
595 /*
596  * Send LP_ConnectReq request
597  */
598 
599 static int
600 ng_btsocket_sco_send_lp_con_req(ng_btsocket_sco_pcb_p pcb)
601 {
602 	struct ng_mesg		*msg = NULL;
603 	ng_hci_lp_con_req_ep	*ep = NULL;
604 	int			 error = 0;
605 
606 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
607 
608 	if (pcb->rt == NULL ||
609 	    pcb->rt->hook == NULL || NG_HOOK_NOT_VALID(pcb->rt->hook))
610 		return (ENETDOWN);
611 
612 	NG_MKMESSAGE(msg, NGM_HCI_COOKIE, NGM_HCI_LP_CON_REQ,
613 		sizeof(*ep), M_NOWAIT);
614 	if (msg == NULL)
615 		return (ENOMEM);
616 
617 	ep = (ng_hci_lp_con_req_ep *)(msg->data);
618 	ep->link_type = NG_HCI_LINK_SCO;
619 	bcopy(&pcb->dst, &ep->bdaddr, sizeof(ep->bdaddr));
620 
621 	NG_SEND_MSG_HOOK(error, ng_btsocket_sco_node, msg, pcb->rt->hook, 0);
622 
623 	return (error);
624 } /* ng_btsocket_sco_send_lp_con_req */
625 
626 /*
627  * Send LP_ConnectRsp response
628  */
629 
630 static int
631 ng_btsocket_sco_send_lp_con_rsp(ng_btsocket_sco_rtentry_p rt, bdaddr_p dst, int status)
632 {
633 	struct ng_mesg		*msg = NULL;
634 	ng_hci_lp_con_rsp_ep	*ep = NULL;
635 	int			 error = 0;
636 
637 	if (rt == NULL || rt->hook == NULL || NG_HOOK_NOT_VALID(rt->hook))
638 		return (ENETDOWN);
639 
640 	NG_MKMESSAGE(msg, NGM_HCI_COOKIE, NGM_HCI_LP_CON_RSP,
641 		sizeof(*ep), M_NOWAIT);
642 	if (msg == NULL)
643 		return (ENOMEM);
644 
645 	ep = (ng_hci_lp_con_rsp_ep *)(msg->data);
646 	ep->status = status;
647 	ep->link_type = NG_HCI_LINK_SCO;
648 	bcopy(dst, &ep->bdaddr, sizeof(ep->bdaddr));
649 
650 	NG_SEND_MSG_HOOK(error, ng_btsocket_sco_node, msg, rt->hook, 0);
651 
652 	return (error);
653 } /* ng_btsocket_sco_send_lp_con_rsp */
654 
655 /*
656  * Send LP_DisconReq request
657  */
658 
659 static int
660 ng_btsocket_sco_send_lp_discon_req(ng_btsocket_sco_pcb_p pcb)
661 {
662 	struct ng_mesg		*msg = NULL;
663 	ng_hci_lp_discon_req_ep	*ep = NULL;
664 	int			 error = 0;
665 
666 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
667 
668 	if (pcb->rt == NULL ||
669 	    pcb->rt->hook == NULL || NG_HOOK_NOT_VALID(pcb->rt->hook))
670 		return (ENETDOWN);
671 
672 	NG_MKMESSAGE(msg, NGM_HCI_COOKIE, NGM_HCI_LP_DISCON_REQ,
673 		sizeof(*ep), M_NOWAIT);
674 	if (msg == NULL)
675 		return (ENOMEM);
676 
677 	ep = (ng_hci_lp_discon_req_ep *)(msg->data);
678 	ep->con_handle = pcb->con_handle;
679 	ep->reason = 0x13; /* User Ended Connection */
680 
681 	NG_SEND_MSG_HOOK(error, ng_btsocket_sco_node, msg, pcb->rt->hook, 0);
682 
683 	return (error);
684 } /* ng_btsocket_sco_send_lp_discon_req */
685 
686 /*****************************************************************************
687  *****************************************************************************
688  **                              Socket interface
689  *****************************************************************************
690  *****************************************************************************/
691 
692 /*
693  * SCO sockets data input routine
694  */
695 
696 static void
697 ng_btsocket_sco_data_input(struct mbuf *m, hook_p hook)
698 {
699 	ng_hci_scodata_pkt_t		*hdr = NULL;
700 	ng_btsocket_sco_pcb_t		*pcb = NULL;
701 	ng_btsocket_sco_rtentry_t	*rt = NULL;
702 	u_int16_t			 con_handle;
703 
704 	if (hook == NULL) {
705 		NG_BTSOCKET_SCO_ALERT(
706 "%s: Invalid source hook for SCO data packet\n", __func__);
707 		goto drop;
708 	}
709 
710 	rt = (ng_btsocket_sco_rtentry_t *) NG_HOOK_PRIVATE(hook);
711 	if (rt == NULL) {
712 		NG_BTSOCKET_SCO_ALERT(
713 "%s: Could not find out source bdaddr for SCO data packet\n", __func__);
714 		goto drop;
715 	}
716 
717 	/* Make sure we can access header */
718 	if (m->m_pkthdr.len < sizeof(*hdr)) {
719 		NG_BTSOCKET_SCO_ERR(
720 "%s: SCO data packet too small, len=%d\n", __func__, m->m_pkthdr.len);
721 		goto drop;
722 	}
723 
724 	if (m->m_len < sizeof(*hdr)) {
725 		m = m_pullup(m, sizeof(*hdr));
726 		if (m == NULL)
727 			goto drop;
728 	}
729 
730 	/* Strip SCO packet header and verify packet length */
731 	hdr = mtod(m, ng_hci_scodata_pkt_t *);
732 	m_adj(m, sizeof(*hdr));
733 
734 	if (hdr->length != m->m_pkthdr.len) {
735 		NG_BTSOCKET_SCO_ERR(
736 "%s: Bad SCO data packet length, len=%d, length=%d\n",
737 			__func__, m->m_pkthdr.len, hdr->length);
738 		goto drop;
739 	}
740 
741 	/*
742 	 * Now process packet
743 	 */
744 
745 	con_handle = NG_HCI_CON_HANDLE(le16toh(hdr->con_handle));
746 
747 	NG_BTSOCKET_SCO_INFO(
748 "%s: Received SCO data packet: src bdaddr=%x:%x:%x:%x:%x:%x, handle=%d, " \
749 "length=%d\n",	__func__,
750 		rt->src.b[5], rt->src.b[4], rt->src.b[3],
751 		rt->src.b[2], rt->src.b[1], rt->src.b[0],
752 		con_handle, hdr->length);
753 
754 	mtx_lock(&ng_btsocket_sco_sockets_mtx);
755 
756 	/* Find socket */
757 	pcb = ng_btsocket_sco_pcb_by_handle(&rt->src, con_handle);
758 	if (pcb == NULL) {
759 		mtx_unlock(&ng_btsocket_sco_sockets_mtx);
760 		goto drop;
761 	}
762 
763 	/* pcb is locked */
764 
765 	if (pcb->state != NG_BTSOCKET_SCO_OPEN) {
766 		NG_BTSOCKET_SCO_ERR(
767 "%s: No connected socket found, src bdaddr=%x:%x:%x:%x:%x:%x, state=%d\n",
768 			__func__,
769 			rt->src.b[5], rt->src.b[4], rt->src.b[3],
770 			rt->src.b[2], rt->src.b[1], rt->src.b[0],
771 			pcb->state);
772 
773 		mtx_unlock(&pcb->pcb_mtx);
774 		mtx_unlock(&ng_btsocket_sco_sockets_mtx);
775 		goto drop;
776 	}
777 
778 	/* Check if we have enough space in socket receive queue */
779 	if (m->m_pkthdr.len > sbspace(&pcb->so->so_rcv)) {
780 		NG_BTSOCKET_SCO_ERR(
781 "%s: Not enough space in socket receive queue. Dropping SCO data packet, " \
782 "src bdaddr=%x:%x:%x:%x:%x:%x, len=%d, space=%ld\n",
783 			__func__,
784 			rt->src.b[5], rt->src.b[4], rt->src.b[3],
785 			rt->src.b[2], rt->src.b[1], rt->src.b[0],
786 			m->m_pkthdr.len,
787 			sbspace(&pcb->so->so_rcv));
788 
789 		mtx_unlock(&pcb->pcb_mtx);
790 		mtx_unlock(&ng_btsocket_sco_sockets_mtx);
791 		goto drop;
792 	}
793 
794 	/* Append packet to the socket receive queue and wakeup */
795 	sbappendrecord(&pcb->so->so_rcv, m);
796 	m = NULL;
797 
798 	sorwakeup(pcb->so);
799 
800 	mtx_unlock(&pcb->pcb_mtx);
801 	mtx_unlock(&ng_btsocket_sco_sockets_mtx);
802 drop:
803 	NG_FREE_M(m); /* checks for m != NULL */
804 } /* ng_btsocket_sco_data_input */
805 
806 /*
807  * SCO sockets default message input routine
808  */
809 
810 static void
811 ng_btsocket_sco_default_msg_input(struct ng_mesg *msg, hook_p hook)
812 {
813 	ng_btsocket_sco_rtentry_t	*rt = NULL;
814 
815 	if (hook == NULL || NG_HOOK_NOT_VALID(hook))
816 		return;
817 
818 	rt = (ng_btsocket_sco_rtentry_t *) NG_HOOK_PRIVATE(hook);
819 
820 	switch (msg->header.cmd) {
821 	case NGM_HCI_NODE_UP: {
822 		ng_hci_node_up_ep	*ep = NULL;
823 
824 		if (msg->header.arglen != sizeof(*ep))
825 			break;
826 
827 		ep = (ng_hci_node_up_ep *)(msg->data);
828 		if (bcmp(&ep->bdaddr, NG_HCI_BDADDR_ANY, sizeof(bdaddr_t)) == 0)
829 			break;
830 
831 		if (rt == NULL) {
832 			rt = malloc(sizeof(*rt),
833 				M_NETGRAPH_BTSOCKET_SCO, M_NOWAIT|M_ZERO);
834 			if (rt == NULL)
835 				break;
836 
837 			NG_HOOK_SET_PRIVATE(hook, rt);
838 
839 			mtx_lock(&ng_btsocket_sco_rt_mtx);
840 
841 			LIST_INSERT_HEAD(&ng_btsocket_sco_rt, rt, next);
842 		} else
843 			mtx_lock(&ng_btsocket_sco_rt_mtx);
844 
845 		bcopy(&ep->bdaddr, &rt->src, sizeof(rt->src));
846 		rt->pkt_size = (ep->pkt_size == 0)? 60 : ep->pkt_size;
847 		rt->num_pkts = ep->num_pkts;
848 		rt->hook = hook;
849 
850 		mtx_unlock(&ng_btsocket_sco_rt_mtx);
851 
852 		NG_BTSOCKET_SCO_INFO(
853 "%s: Updating hook \"%s\", src bdaddr=%x:%x:%x:%x:%x:%x, pkt_size=%d, " \
854 "num_pkts=%d\n",	__func__, NG_HOOK_NAME(hook),
855 			rt->src.b[5], rt->src.b[4], rt->src.b[3],
856 			rt->src.b[2], rt->src.b[1], rt->src.b[0],
857 			rt->pkt_size, rt->num_pkts);
858 		} break;
859 
860 	case NGM_HCI_SYNC_CON_QUEUE: {
861 		ng_hci_sync_con_queue_ep	*ep = NULL;
862 		ng_btsocket_sco_pcb_t		*pcb = NULL;
863 
864 		if (rt == NULL || msg->header.arglen != sizeof(*ep))
865 			break;
866 
867 		ep = (ng_hci_sync_con_queue_ep *)(msg->data);
868 
869 		rt->pending -= ep->completed;
870 		if (rt->pending < 0) {
871 			NG_BTSOCKET_SCO_WARN(
872 "%s: Pending packet counter is out of sync! bdaddr=%x:%x:%x:%x:%x:%x, " \
873 "handle=%d, pending=%d, completed=%d\n",
874 				__func__,
875 				rt->src.b[5], rt->src.b[4], rt->src.b[3],
876 				rt->src.b[2], rt->src.b[1], rt->src.b[0],
877 				ep->con_handle, rt->pending,
878 				ep->completed);
879 
880 			rt->pending = 0;
881 		}
882 
883 		mtx_lock(&ng_btsocket_sco_sockets_mtx);
884 
885 		/* Find socket */
886 		pcb = ng_btsocket_sco_pcb_by_handle(&rt->src, ep->con_handle);
887 		if (pcb == NULL) {
888 			mtx_unlock(&ng_btsocket_sco_sockets_mtx);
889 			break;
890 		}
891 
892 		/* pcb is locked */
893 
894 		/* Check state */
895 		if (pcb->state == NG_BTSOCKET_SCO_OPEN) {
896 			/* Remove timeout */
897 			ng_btsocket_sco_untimeout(pcb);
898 
899 			/* Drop completed packets from the send queue */
900 			for (; ep->completed > 0; ep->completed --)
901 				sbdroprecord(&pcb->so->so_snd);
902 
903 			/* Send more if we have any */
904 			if (sbavail(&pcb->so->so_snd) > 0)
905 				if (ng_btsocket_sco_send2(pcb) == 0)
906 					ng_btsocket_sco_timeout(pcb);
907 
908 			/* Wake up writers */
909 			sowwakeup(pcb->so);
910 		}
911 
912 		mtx_unlock(&pcb->pcb_mtx);
913 		mtx_unlock(&ng_btsocket_sco_sockets_mtx);
914 	} break;
915 
916 	default:
917 		NG_BTSOCKET_SCO_WARN(
918 "%s: Unknown message, cmd=%d\n", __func__, msg->header.cmd);
919 		break;
920 	}
921 
922 	NG_FREE_MSG(msg); /* Checks for msg != NULL */
923 } /* ng_btsocket_sco_default_msg_input */
924 
925 /*
926  * SCO sockets LP message input routine
927  */
928 
929 static void
930 ng_btsocket_sco_lp_msg_input(struct ng_mesg *msg, hook_p hook)
931 {
932 	ng_btsocket_sco_rtentry_p	 rt = NULL;
933 
934 	if (hook == NULL) {
935 		NG_BTSOCKET_SCO_ALERT(
936 "%s: Invalid source hook for LP message\n", __func__);
937 		goto drop;
938 	}
939 
940 	rt = (ng_btsocket_sco_rtentry_p) NG_HOOK_PRIVATE(hook);
941 	if (rt == NULL) {
942 		NG_BTSOCKET_SCO_ALERT(
943 "%s: Could not find out source bdaddr for LP message\n", __func__);
944 		goto drop;
945 	}
946 
947 	switch (msg->header.cmd) {
948 	case NGM_HCI_LP_CON_CFM: /* Connection Confirmation Event */
949 		ng_btsocket_sco_process_lp_con_cfm(msg, rt);
950 		break;
951 
952 	case NGM_HCI_LP_CON_IND: /* Connection Indication Event */
953 		ng_btsocket_sco_process_lp_con_ind(msg, rt);
954 		break;
955 
956 	case NGM_HCI_LP_DISCON_IND: /* Disconnection Indication Event */
957 		ng_btsocket_sco_process_lp_discon_ind(msg, rt);
958 		break;
959 
960 	/* XXX FIXME add other LP messages */
961 
962 	default:
963 		NG_BTSOCKET_SCO_WARN(
964 "%s: Unknown LP message, cmd=%d\n", __func__, msg->header.cmd);
965 		break;
966 	}
967 drop:
968 	NG_FREE_MSG(msg);
969 } /* ng_btsocket_sco_lp_msg_input */
970 
971 /*
972  * SCO sockets input routine
973  */
974 
975 static void
976 ng_btsocket_sco_input(void *context, int pending)
977 {
978 	item_p	item = NULL;
979 	hook_p	hook = NULL;
980 
981 	for (;;) {
982 		mtx_lock(&ng_btsocket_sco_queue_mtx);
983 		NG_BT_ITEMQ_DEQUEUE(&ng_btsocket_sco_queue, item);
984 		mtx_unlock(&ng_btsocket_sco_queue_mtx);
985 
986 		if (item == NULL)
987 			break;
988 
989 		NGI_GET_HOOK(item, hook);
990 		if (hook != NULL && NG_HOOK_NOT_VALID(hook))
991 			goto drop;
992 
993 		switch(item->el_flags & NGQF_TYPE) {
994 		case NGQF_DATA: {
995 			struct mbuf     *m = NULL;
996 
997 			NGI_GET_M(item, m);
998 			ng_btsocket_sco_data_input(m, hook);
999 			} break;
1000 
1001 		case NGQF_MESG: {
1002 			struct ng_mesg  *msg = NULL;
1003 
1004 			NGI_GET_MSG(item, msg);
1005 
1006 			switch (msg->header.cmd) {
1007 			case NGM_HCI_LP_CON_CFM:
1008 			case NGM_HCI_LP_CON_IND:
1009 			case NGM_HCI_LP_DISCON_IND:
1010 			/* XXX FIXME add other LP messages */
1011 				ng_btsocket_sco_lp_msg_input(msg, hook);
1012 				break;
1013 
1014 			default:
1015 				ng_btsocket_sco_default_msg_input(msg, hook);
1016 				break;
1017 			}
1018 			} break;
1019 
1020 		default:
1021 			KASSERT(0,
1022 ("%s: invalid item type=%ld\n", __func__, (item->el_flags & NGQF_TYPE)));
1023 			break;
1024 		}
1025 drop:
1026 		if (hook != NULL)
1027 			NG_HOOK_UNREF(hook);
1028 
1029 		NG_FREE_ITEM(item);
1030 	}
1031 } /* ng_btsocket_sco_input */
1032 
1033 /*
1034  * Route cleanup task. Gets scheduled when hook is disconnected. Here we
1035  * will find all sockets that use "invalid" hook and disconnect them.
1036  */
1037 
1038 static void
1039 ng_btsocket_sco_rtclean(void *context, int pending)
1040 {
1041 	ng_btsocket_sco_pcb_p		pcb = NULL, pcb_next = NULL;
1042 	ng_btsocket_sco_rtentry_p	rt = NULL;
1043 
1044 	/*
1045 	 * First disconnect all sockets that use "invalid" hook
1046 	 */
1047 
1048 	mtx_lock(&ng_btsocket_sco_sockets_mtx);
1049 
1050 	for(pcb = LIST_FIRST(&ng_btsocket_sco_sockets); pcb != NULL; ) {
1051 		mtx_lock(&pcb->pcb_mtx);
1052 		pcb_next = LIST_NEXT(pcb, next);
1053 
1054 		if (pcb->rt != NULL &&
1055 		    pcb->rt->hook != NULL && NG_HOOK_NOT_VALID(pcb->rt->hook)) {
1056 			if (pcb->flags & NG_BTSOCKET_SCO_TIMO)
1057 				ng_btsocket_sco_untimeout(pcb);
1058 
1059 			pcb->rt = NULL;
1060 			pcb->so->so_error = ENETDOWN;
1061 			pcb->state = NG_BTSOCKET_SCO_CLOSED;
1062 			soisdisconnected(pcb->so);
1063 		}
1064 
1065 		mtx_unlock(&pcb->pcb_mtx);
1066 		pcb = pcb_next;
1067 	}
1068 
1069 	mtx_unlock(&ng_btsocket_sco_sockets_mtx);
1070 
1071 	/*
1072 	 * Now cleanup routing table
1073 	 */
1074 
1075 	mtx_lock(&ng_btsocket_sco_rt_mtx);
1076 
1077 	for (rt = LIST_FIRST(&ng_btsocket_sco_rt); rt != NULL; ) {
1078 		ng_btsocket_sco_rtentry_p	rt_next = LIST_NEXT(rt, next);
1079 
1080 		if (rt->hook != NULL && NG_HOOK_NOT_VALID(rt->hook)) {
1081 			LIST_REMOVE(rt, next);
1082 
1083 			NG_HOOK_SET_PRIVATE(rt->hook, NULL);
1084 			NG_HOOK_UNREF(rt->hook); /* Remove extra reference */
1085 
1086 			bzero(rt, sizeof(*rt));
1087 			free(rt, M_NETGRAPH_BTSOCKET_SCO);
1088 		}
1089 
1090 		rt = rt_next;
1091 	}
1092 
1093 	mtx_unlock(&ng_btsocket_sco_rt_mtx);
1094 } /* ng_btsocket_sco_rtclean */
1095 
1096 /*
1097  * Initialize everything
1098  */
1099 
1100 void
1101 ng_btsocket_sco_init(void)
1102 {
1103 	int	error = 0;
1104 
1105 	/* Skip initialization of globals for non-default instances. */
1106 	if (!IS_DEFAULT_VNET(curvnet))
1107 		return;
1108 
1109 	ng_btsocket_sco_node = NULL;
1110 	ng_btsocket_sco_debug_level = NG_BTSOCKET_WARN_LEVEL;
1111 
1112 	/* Register Netgraph node type */
1113 	error = ng_newtype(&typestruct);
1114 	if (error != 0) {
1115 		NG_BTSOCKET_SCO_ALERT(
1116 "%s: Could not register Netgraph node type, error=%d\n", __func__, error);
1117 
1118                 return;
1119 	}
1120 
1121 	/* Create Netgrapg node */
1122 	error = ng_make_node_common(&typestruct, &ng_btsocket_sco_node);
1123 	if (error != 0) {
1124 		NG_BTSOCKET_SCO_ALERT(
1125 "%s: Could not create Netgraph node, error=%d\n", __func__, error);
1126 
1127 		ng_btsocket_sco_node = NULL;
1128 
1129 		return;
1130 	}
1131 
1132 	error = ng_name_node(ng_btsocket_sco_node, NG_BTSOCKET_SCO_NODE_TYPE);
1133 	if (error != 0) {
1134 		NG_BTSOCKET_SCO_ALERT(
1135 "%s: Could not name Netgraph node, error=%d\n", __func__, error);
1136 
1137 		NG_NODE_UNREF(ng_btsocket_sco_node);
1138 		ng_btsocket_sco_node = NULL;
1139 
1140 		return;
1141 	}
1142 
1143 	/* Create input queue */
1144 	NG_BT_ITEMQ_INIT(&ng_btsocket_sco_queue, 300);
1145 	mtx_init(&ng_btsocket_sco_queue_mtx,
1146 		"btsocks_sco_queue_mtx", NULL, MTX_DEF);
1147 	TASK_INIT(&ng_btsocket_sco_queue_task, 0,
1148 		ng_btsocket_sco_input, NULL);
1149 
1150 	/* Create list of sockets */
1151 	LIST_INIT(&ng_btsocket_sco_sockets);
1152 	mtx_init(&ng_btsocket_sco_sockets_mtx,
1153 		"btsocks_sco_sockets_mtx", NULL, MTX_DEF);
1154 
1155 	/* Routing table */
1156 	LIST_INIT(&ng_btsocket_sco_rt);
1157 	mtx_init(&ng_btsocket_sco_rt_mtx,
1158 		"btsocks_sco_rt_mtx", NULL, MTX_DEF);
1159 	TASK_INIT(&ng_btsocket_sco_rt_task, 0,
1160 		ng_btsocket_sco_rtclean, NULL);
1161 } /* ng_btsocket_sco_init */
1162 
1163 /*
1164  * Abort connection on socket
1165  */
1166 
1167 void
1168 ng_btsocket_sco_abort(struct socket *so)
1169 {
1170 	so->so_error = ECONNABORTED;
1171 
1172 	(void) ng_btsocket_sco_disconnect(so);
1173 } /* ng_btsocket_sco_abort */
1174 
1175 void
1176 ng_btsocket_sco_close(struct socket *so)
1177 {
1178 	(void) ng_btsocket_sco_disconnect(so);
1179 } /* ng_btsocket_sco_close */
1180 
1181 /*
1182  * Accept connection on socket. Nothing to do here, socket must be connected
1183  * and ready, so just return peer address and be done with it.
1184  */
1185 
1186 int
1187 ng_btsocket_sco_accept(struct socket *so, struct sockaddr **nam)
1188 {
1189 	if (ng_btsocket_sco_node == NULL)
1190 		return (EINVAL);
1191 
1192 	return (ng_btsocket_sco_peeraddr(so, nam));
1193 } /* ng_btsocket_sco_accept */
1194 
1195 /*
1196  * Create and attach new socket
1197  */
1198 
1199 int
1200 ng_btsocket_sco_attach(struct socket *so, int proto, struct thread *td)
1201 {
1202 	ng_btsocket_sco_pcb_p	pcb = so2sco_pcb(so);
1203 	int			error;
1204 
1205 	/* Check socket and protocol */
1206 	if (ng_btsocket_sco_node == NULL)
1207 		return (EPROTONOSUPPORT);
1208 	if (so->so_type != SOCK_SEQPACKET)
1209 		return (ESOCKTNOSUPPORT);
1210 
1211 #if 0 /* XXX sonewconn() calls "pru_attach" with proto == 0 */
1212 	if (proto != 0)
1213 		if (proto != BLUETOOTH_PROTO_SCO)
1214 			return (EPROTONOSUPPORT);
1215 #endif /* XXX */
1216 
1217 	if (pcb != NULL)
1218 		return (EISCONN);
1219 
1220 	/* Reserve send and receive space if it is not reserved yet */
1221 	if ((so->so_snd.sb_hiwat == 0) || (so->so_rcv.sb_hiwat == 0)) {
1222 		error = soreserve(so, NG_BTSOCKET_SCO_SENDSPACE,
1223 					NG_BTSOCKET_SCO_RECVSPACE);
1224 		if (error != 0)
1225 			return (error);
1226 	}
1227 
1228 	/* Allocate the PCB */
1229         pcb = malloc(sizeof(*pcb),
1230 		M_NETGRAPH_BTSOCKET_SCO, M_NOWAIT | M_ZERO);
1231         if (pcb == NULL)
1232                 return (ENOMEM);
1233 
1234 	/* Link the PCB and the socket */
1235 	so->so_pcb = (caddr_t) pcb;
1236 	pcb->so = so;
1237 	pcb->state = NG_BTSOCKET_SCO_CLOSED;
1238 
1239 	callout_init(&pcb->timo, 1);
1240 
1241 	/*
1242 	 * Mark PCB mutex as DUPOK to prevent "duplicated lock of
1243 	 * the same type" message. When accepting new SCO connection
1244 	 * ng_btsocket_sco_process_lp_con_ind() holds both PCB mutexes
1245 	 * for "old" (accepting) PCB and "new" (created) PCB.
1246 	 */
1247 
1248 	mtx_init(&pcb->pcb_mtx, "btsocks_sco_pcb_mtx", NULL,
1249 		MTX_DEF|MTX_DUPOK);
1250 
1251 	/*
1252 	 * Add the PCB to the list
1253 	 *
1254 	 * XXX FIXME VERY IMPORTANT!
1255 	 *
1256 	 * This is totally FUBAR. We could get here in two cases:
1257 	 *
1258 	 * 1) When user calls socket()
1259 	 * 2) When we need to accept new incoming connection and call
1260 	 *    sonewconn()
1261 	 *
1262 	 * In the first case we must acquire ng_btsocket_sco_sockets_mtx.
1263 	 * In the second case we hold ng_btsocket_sco_sockets_mtx already.
1264 	 * So we now need to distinguish between these cases. From reading
1265 	 * /sys/kern/uipc_socket2.c we can find out that sonewconn() calls
1266 	 * pru_attach with proto == 0 and td == NULL. For now use this fact
1267 	 * to figure out if we were called from socket() or from sonewconn().
1268 	 */
1269 
1270 	if (td != NULL)
1271 		mtx_lock(&ng_btsocket_sco_sockets_mtx);
1272 	else
1273 		mtx_assert(&ng_btsocket_sco_sockets_mtx, MA_OWNED);
1274 
1275 	LIST_INSERT_HEAD(&ng_btsocket_sco_sockets, pcb, next);
1276 
1277 	if (td != NULL)
1278 		mtx_unlock(&ng_btsocket_sco_sockets_mtx);
1279 
1280         return (0);
1281 } /* ng_btsocket_sco_attach */
1282 
1283 /*
1284  * Bind socket
1285  */
1286 
1287 int
1288 ng_btsocket_sco_bind(struct socket *so, struct sockaddr *nam,
1289 		struct thread *td)
1290 {
1291 	ng_btsocket_sco_pcb_t	*pcb = NULL;
1292 	struct sockaddr_sco	*sa = (struct sockaddr_sco *) nam;
1293 
1294 	if (ng_btsocket_sco_node == NULL)
1295 		return (EINVAL);
1296 
1297 	/* Verify address */
1298 	if (sa == NULL)
1299 		return (EINVAL);
1300 	if (sa->sco_family != AF_BLUETOOTH)
1301 		return (EAFNOSUPPORT);
1302 	if (sa->sco_len != sizeof(*sa))
1303 		return (EINVAL);
1304 
1305 	mtx_lock(&ng_btsocket_sco_sockets_mtx);
1306 
1307 	/*
1308 	 * Check if other socket has this address already (look for exact
1309 	 * match in bdaddr) and assign socket address if it's available.
1310 	 */
1311 
1312 	if (bcmp(&sa->sco_bdaddr, NG_HCI_BDADDR_ANY, sizeof(sa->sco_bdaddr)) != 0) {
1313  		LIST_FOREACH(pcb, &ng_btsocket_sco_sockets, next) {
1314 			mtx_lock(&pcb->pcb_mtx);
1315 
1316 			if (bcmp(&pcb->src, &sa->sco_bdaddr, sizeof(bdaddr_t)) == 0) {
1317 				mtx_unlock(&pcb->pcb_mtx);
1318 				mtx_unlock(&ng_btsocket_sco_sockets_mtx);
1319 
1320 				return (EADDRINUSE);
1321 			}
1322 
1323 			mtx_unlock(&pcb->pcb_mtx);
1324 		}
1325 
1326 	}
1327 
1328 	pcb = so2sco_pcb(so);
1329 	if (pcb == NULL) {
1330 		mtx_unlock(&ng_btsocket_sco_sockets_mtx);
1331 		return (EINVAL);
1332 	}
1333 
1334 	mtx_lock(&pcb->pcb_mtx);
1335 	bcopy(&sa->sco_bdaddr, &pcb->src, sizeof(pcb->src));
1336 	mtx_unlock(&pcb->pcb_mtx);
1337 
1338 	mtx_unlock(&ng_btsocket_sco_sockets_mtx);
1339 
1340 	return (0);
1341 } /* ng_btsocket_sco_bind */
1342 
1343 /*
1344  * Connect socket
1345  */
1346 
1347 int
1348 ng_btsocket_sco_connect(struct socket *so, struct sockaddr *nam,
1349 		struct thread *td)
1350 {
1351 	ng_btsocket_sco_pcb_t		*pcb = so2sco_pcb(so);
1352 	struct sockaddr_sco		*sa = (struct sockaddr_sco *) nam;
1353 	ng_btsocket_sco_rtentry_t	*rt = NULL;
1354 	int				 have_src, error = 0;
1355 
1356 	/* Check socket */
1357 	if (pcb == NULL)
1358 		return (EINVAL);
1359 	if (ng_btsocket_sco_node == NULL)
1360 		return (EINVAL);
1361 
1362 	/* Verify address */
1363 	if (sa == NULL)
1364 		return (EINVAL);
1365 	if (sa->sco_family != AF_BLUETOOTH)
1366 		return (EAFNOSUPPORT);
1367 	if (sa->sco_len != sizeof(*sa))
1368 		return (EINVAL);
1369 	if (bcmp(&sa->sco_bdaddr, NG_HCI_BDADDR_ANY, sizeof(bdaddr_t)) == 0)
1370 		return (EDESTADDRREQ);
1371 
1372 	/*
1373 	 * Routing. Socket should be bound to some source address. The source
1374 	 * address can be ANY. Destination address must be set and it must not
1375 	 * be ANY. If source address is ANY then find first rtentry that has
1376 	 * src != dst.
1377 	 */
1378 
1379 	mtx_lock(&ng_btsocket_sco_rt_mtx);
1380 	mtx_lock(&pcb->pcb_mtx);
1381 
1382 	if (pcb->state == NG_BTSOCKET_SCO_CONNECTING) {
1383 		mtx_unlock(&pcb->pcb_mtx);
1384 		mtx_unlock(&ng_btsocket_sco_rt_mtx);
1385 
1386 		return (EINPROGRESS);
1387 	}
1388 
1389 	if (bcmp(&sa->sco_bdaddr, &pcb->src, sizeof(pcb->src)) == 0) {
1390 		mtx_unlock(&pcb->pcb_mtx);
1391 		mtx_unlock(&ng_btsocket_sco_rt_mtx);
1392 
1393 		return (EINVAL);
1394 	}
1395 
1396 	/* Send destination address and PSM */
1397 	bcopy(&sa->sco_bdaddr, &pcb->dst, sizeof(pcb->dst));
1398 
1399 	pcb->rt = NULL;
1400 	have_src = bcmp(&pcb->src, NG_HCI_BDADDR_ANY, sizeof(pcb->src));
1401 
1402 	LIST_FOREACH(rt, &ng_btsocket_sco_rt, next) {
1403 		if (rt->hook == NULL || NG_HOOK_NOT_VALID(rt->hook))
1404 			continue;
1405 
1406 		/* Match src and dst */
1407 		if (have_src) {
1408 			if (bcmp(&pcb->src, &rt->src, sizeof(rt->src)) == 0)
1409 				break;
1410 		} else {
1411 			if (bcmp(&pcb->dst, &rt->src, sizeof(rt->src)) != 0)
1412 				break;
1413 		}
1414 	}
1415 
1416 	if (rt != NULL) {
1417 		pcb->rt = rt;
1418 
1419 		if (!have_src)
1420 			bcopy(&rt->src, &pcb->src, sizeof(pcb->src));
1421 	} else
1422 		error = EHOSTUNREACH;
1423 
1424 	/*
1425 	 * Send LP_Connect request
1426 	 */
1427 
1428 	if (error == 0) {
1429 		error = ng_btsocket_sco_send_lp_con_req(pcb);
1430 		if (error == 0) {
1431 			pcb->flags |= NG_BTSOCKET_SCO_CLIENT;
1432 			pcb->state = NG_BTSOCKET_SCO_CONNECTING;
1433 			soisconnecting(pcb->so);
1434 
1435 			ng_btsocket_sco_timeout(pcb);
1436 		}
1437 	}
1438 
1439 	mtx_unlock(&pcb->pcb_mtx);
1440 	mtx_unlock(&ng_btsocket_sco_rt_mtx);
1441 
1442 	return (error);
1443 } /* ng_btsocket_sco_connect */
1444 
1445 /*
1446  * Process ioctl's calls on socket
1447  */
1448 
1449 int
1450 ng_btsocket_sco_control(struct socket *so, u_long cmd, caddr_t data,
1451 		struct ifnet *ifp, struct thread *td)
1452 {
1453 	return (EINVAL);
1454 } /* ng_btsocket_sco_control */
1455 
1456 /*
1457  * Process getsockopt/setsockopt system calls
1458  */
1459 
1460 int
1461 ng_btsocket_sco_ctloutput(struct socket *so, struct sockopt *sopt)
1462 {
1463 	ng_btsocket_sco_pcb_p	pcb = so2sco_pcb(so);
1464         int			error, tmp;
1465 
1466 	if (ng_btsocket_sco_node == NULL)
1467 		return (EINVAL);
1468 	if (pcb == NULL)
1469 		return (EINVAL);
1470 
1471 	if (sopt->sopt_level != SOL_SCO)
1472 		return (0);
1473 
1474 	mtx_lock(&pcb->pcb_mtx);
1475 
1476 	switch (sopt->sopt_dir) {
1477 	case SOPT_GET:
1478 		if (pcb->state != NG_BTSOCKET_SCO_OPEN) {
1479 			error = ENOTCONN;
1480 			break;
1481 		}
1482 
1483 		switch (sopt->sopt_name) {
1484 		case SO_SCO_MTU:
1485 			tmp = pcb->rt->pkt_size;
1486 			error = sooptcopyout(sopt, &tmp, sizeof(tmp));
1487 			break;
1488 
1489 		case SO_SCO_CONNINFO:
1490 			tmp = pcb->con_handle;
1491 			error = sooptcopyout(sopt, &tmp, sizeof(tmp));
1492 			break;
1493 
1494 		default:
1495 			error = EINVAL;
1496 			break;
1497 		}
1498 		break;
1499 
1500 	case SOPT_SET:
1501 		error = ENOPROTOOPT;
1502 		break;
1503 
1504 	default:
1505 		error = EINVAL;
1506 		break;
1507 	}
1508 
1509 	mtx_unlock(&pcb->pcb_mtx);
1510 
1511 	return (error);
1512 } /* ng_btsocket_sco_ctloutput */
1513 
1514 /*
1515  * Detach and destroy socket
1516  */
1517 
1518 void
1519 ng_btsocket_sco_detach(struct socket *so)
1520 {
1521 	ng_btsocket_sco_pcb_p	pcb = so2sco_pcb(so);
1522 
1523 	KASSERT(pcb != NULL, ("ng_btsocket_sco_detach: pcb == NULL"));
1524 
1525 	if (ng_btsocket_sco_node == NULL)
1526 		return;
1527 
1528 	mtx_lock(&ng_btsocket_sco_sockets_mtx);
1529 	mtx_lock(&pcb->pcb_mtx);
1530 
1531 	if (pcb->flags & NG_BTSOCKET_SCO_TIMO)
1532 		ng_btsocket_sco_untimeout(pcb);
1533 
1534 	if (pcb->state == NG_BTSOCKET_SCO_OPEN)
1535 		ng_btsocket_sco_send_lp_discon_req(pcb);
1536 
1537 	pcb->state = NG_BTSOCKET_SCO_CLOSED;
1538 
1539 	LIST_REMOVE(pcb, next);
1540 
1541 	mtx_unlock(&pcb->pcb_mtx);
1542 	mtx_unlock(&ng_btsocket_sco_sockets_mtx);
1543 
1544 	mtx_destroy(&pcb->pcb_mtx);
1545 	bzero(pcb, sizeof(*pcb));
1546 	free(pcb, M_NETGRAPH_BTSOCKET_SCO);
1547 
1548 	soisdisconnected(so);
1549 	so->so_pcb = NULL;
1550 } /* ng_btsocket_sco_detach */
1551 
1552 /*
1553  * Disconnect socket
1554  */
1555 
1556 int
1557 ng_btsocket_sco_disconnect(struct socket *so)
1558 {
1559 	ng_btsocket_sco_pcb_p	pcb = so2sco_pcb(so);
1560 
1561 	if (pcb == NULL)
1562 		return (EINVAL);
1563 	if (ng_btsocket_sco_node == NULL)
1564 		return (EINVAL);
1565 
1566 	mtx_lock(&pcb->pcb_mtx);
1567 
1568 	if (pcb->state == NG_BTSOCKET_SCO_DISCONNECTING) {
1569 		mtx_unlock(&pcb->pcb_mtx);
1570 
1571 		return (EINPROGRESS);
1572 	}
1573 
1574 	if (pcb->flags & NG_BTSOCKET_SCO_TIMO)
1575 		ng_btsocket_sco_untimeout(pcb);
1576 
1577 	if (pcb->state == NG_BTSOCKET_SCO_OPEN) {
1578 		ng_btsocket_sco_send_lp_discon_req(pcb);
1579 
1580 		pcb->state = NG_BTSOCKET_SCO_DISCONNECTING;
1581 		soisdisconnecting(so);
1582 
1583 		ng_btsocket_sco_timeout(pcb);
1584 	} else {
1585 		pcb->state = NG_BTSOCKET_SCO_CLOSED;
1586 		soisdisconnected(so);
1587 	}
1588 
1589 	mtx_unlock(&pcb->pcb_mtx);
1590 
1591 	return (0);
1592 } /* ng_btsocket_sco_disconnect */
1593 
1594 /*
1595  * Listen on socket
1596  */
1597 
1598 int
1599 ng_btsocket_sco_listen(struct socket *so, int backlog, struct thread *td)
1600 {
1601 	ng_btsocket_sco_pcb_p	pcb = so2sco_pcb(so);
1602 	int			error;
1603 
1604 	if (pcb == NULL)
1605 		return (EINVAL);
1606 	if (ng_btsocket_sco_node == NULL)
1607 		return (EINVAL);
1608 
1609 	SOCK_LOCK(so);
1610 	mtx_lock(&pcb->pcb_mtx);
1611 
1612 	error = solisten_proto_check(so);
1613 	if (error != 0)
1614 		goto out;
1615 #if 0
1616 	if (bcmp(&pcb->src, NG_HCI_BDADDR_ANY, sizeof(bdaddr_t)) == 0) {
1617 		error = EDESTADDRREQ;
1618 		goto out;
1619 	}
1620 #endif
1621 	solisten_proto(so, backlog);
1622 out:
1623 	mtx_unlock(&pcb->pcb_mtx);
1624 	SOCK_UNLOCK(so);
1625 
1626 	return (error);
1627 } /* ng_btsocket_listen */
1628 
1629 /*
1630  * Get peer address
1631  */
1632 
1633 int
1634 ng_btsocket_sco_peeraddr(struct socket *so, struct sockaddr **nam)
1635 {
1636 	ng_btsocket_sco_pcb_p	pcb = so2sco_pcb(so);
1637 	struct sockaddr_sco	sa;
1638 
1639 	if (pcb == NULL)
1640 		return (EINVAL);
1641 	if (ng_btsocket_sco_node == NULL)
1642 		return (EINVAL);
1643 
1644 	mtx_lock(&pcb->pcb_mtx);
1645 	bcopy(&pcb->dst, &sa.sco_bdaddr, sizeof(sa.sco_bdaddr));
1646 	mtx_unlock(&pcb->pcb_mtx);
1647 
1648 	sa.sco_len = sizeof(sa);
1649 	sa.sco_family = AF_BLUETOOTH;
1650 
1651 	*nam = sodupsockaddr((struct sockaddr *) &sa, M_NOWAIT);
1652 
1653 	return ((*nam == NULL)? ENOMEM : 0);
1654 } /* ng_btsocket_sco_peeraddr */
1655 
1656 /*
1657  * Send data to socket
1658  */
1659 
1660 int
1661 ng_btsocket_sco_send(struct socket *so, int flags, struct mbuf *m,
1662 		struct sockaddr *nam, struct mbuf *control, struct thread *td)
1663 {
1664 	ng_btsocket_sco_pcb_t	*pcb = so2sco_pcb(so);
1665 	int			 error = 0;
1666 
1667 	if (ng_btsocket_sco_node == NULL) {
1668 		error = ENETDOWN;
1669 		goto drop;
1670 	}
1671 
1672 	/* Check socket and input */
1673 	if (pcb == NULL || m == NULL || control != NULL) {
1674 		error = EINVAL;
1675 		goto drop;
1676 	}
1677 
1678 	mtx_lock(&pcb->pcb_mtx);
1679 
1680 	/* Make sure socket is connected */
1681 	if (pcb->state != NG_BTSOCKET_SCO_OPEN) {
1682 		mtx_unlock(&pcb->pcb_mtx);
1683 		error = ENOTCONN;
1684 		goto drop;
1685 	}
1686 
1687 	/* Check route */
1688 	if (pcb->rt == NULL ||
1689 	    pcb->rt->hook == NULL || NG_HOOK_NOT_VALID(pcb->rt->hook)) {
1690 		mtx_unlock(&pcb->pcb_mtx);
1691 		error = ENETDOWN;
1692 		goto drop;
1693 	}
1694 
1695 	/* Check packet size */
1696 	if (m->m_pkthdr.len > pcb->rt->pkt_size) {
1697 		NG_BTSOCKET_SCO_ERR(
1698 "%s: Packet too big, len=%d, pkt_size=%d\n",
1699 			__func__, m->m_pkthdr.len, pcb->rt->pkt_size);
1700 
1701 		mtx_unlock(&pcb->pcb_mtx);
1702 		error = EMSGSIZE;
1703 		goto drop;
1704 	}
1705 
1706 	/*
1707 	 * First put packet on socket send queue. Then check if we have
1708 	 * pending timeout. If we do not have timeout then we must send
1709 	 * packet and schedule timeout. Otherwise do nothing and wait for
1710 	 * NGM_HCI_SYNC_CON_QUEUE message.
1711 	 */
1712 
1713 	sbappendrecord(&pcb->so->so_snd, m);
1714 	m = NULL;
1715 
1716 	if (!(pcb->flags & NG_BTSOCKET_SCO_TIMO)) {
1717 		error = ng_btsocket_sco_send2(pcb);
1718 		if (error == 0)
1719 			ng_btsocket_sco_timeout(pcb);
1720 		else
1721 			sbdroprecord(&pcb->so->so_snd); /* XXX */
1722 	}
1723 
1724 	mtx_unlock(&pcb->pcb_mtx);
1725 drop:
1726 	NG_FREE_M(m); /* checks for != NULL */
1727 	NG_FREE_M(control);
1728 
1729 	return (error);
1730 } /* ng_btsocket_sco_send */
1731 
1732 /*
1733  * Send first packet in the socket queue to the SCO layer
1734  */
1735 
1736 static int
1737 ng_btsocket_sco_send2(ng_btsocket_sco_pcb_p pcb)
1738 {
1739 	struct  mbuf		*m = NULL;
1740 	ng_hci_scodata_pkt_t	*hdr = NULL;
1741 	int			 error = 0;
1742 
1743 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
1744 
1745 	while (pcb->rt->pending < pcb->rt->num_pkts &&
1746 	       sbavail(&pcb->so->so_snd) > 0) {
1747 		/* Get a copy of the first packet on send queue */
1748 		m = m_dup(pcb->so->so_snd.sb_mb, M_NOWAIT);
1749 		if (m == NULL) {
1750 			error = ENOBUFS;
1751 			break;
1752 		}
1753 
1754 		/* Create SCO packet header */
1755 		M_PREPEND(m, sizeof(*hdr), M_NOWAIT);
1756 		if (m != NULL)
1757 			if (m->m_len < sizeof(*hdr))
1758 				m = m_pullup(m, sizeof(*hdr));
1759 
1760 		if (m == NULL) {
1761 			error = ENOBUFS;
1762 			break;
1763 		}
1764 
1765 		/* Fill in the header */
1766 		hdr = mtod(m, ng_hci_scodata_pkt_t *);
1767 		hdr->type = NG_HCI_SCO_DATA_PKT;
1768 		hdr->con_handle = htole16(NG_HCI_MK_CON_HANDLE(pcb->con_handle, 0, 0));
1769 		hdr->length = m->m_pkthdr.len - sizeof(*hdr);
1770 
1771 		/* Send packet */
1772 		NG_SEND_DATA_ONLY(error, pcb->rt->hook, m);
1773 		if (error != 0)
1774 			break;
1775 
1776 		pcb->rt->pending ++;
1777 	}
1778 
1779 	return ((pcb->rt->pending > 0)? 0 : error);
1780 } /* ng_btsocket_sco_send2 */
1781 
1782 /*
1783  * Get socket address
1784  */
1785 
1786 int
1787 ng_btsocket_sco_sockaddr(struct socket *so, struct sockaddr **nam)
1788 {
1789 	ng_btsocket_sco_pcb_p	pcb = so2sco_pcb(so);
1790 	struct sockaddr_sco	sa;
1791 
1792 	if (pcb == NULL)
1793 		return (EINVAL);
1794 	if (ng_btsocket_sco_node == NULL)
1795 		return (EINVAL);
1796 
1797 	mtx_lock(&pcb->pcb_mtx);
1798 	bcopy(&pcb->src, &sa.sco_bdaddr, sizeof(sa.sco_bdaddr));
1799 	mtx_unlock(&pcb->pcb_mtx);
1800 
1801 	sa.sco_len = sizeof(sa);
1802 	sa.sco_family = AF_BLUETOOTH;
1803 
1804 	*nam = sodupsockaddr((struct sockaddr *) &sa, M_NOWAIT);
1805 
1806 	return ((*nam == NULL)? ENOMEM : 0);
1807 } /* ng_btsocket_sco_sockaddr */
1808 
1809 /*****************************************************************************
1810  *****************************************************************************
1811  **                              Misc. functions
1812  *****************************************************************************
1813  *****************************************************************************/
1814 
1815 /*
1816  * Look for the socket that listens on given bdaddr.
1817  * Returns exact or close match (if any).
1818  * Caller must hold ng_btsocket_sco_sockets_mtx.
1819  * Returns with locked pcb.
1820  */
1821 
1822 static ng_btsocket_sco_pcb_p
1823 ng_btsocket_sco_pcb_by_addr(bdaddr_p bdaddr)
1824 {
1825 	ng_btsocket_sco_pcb_p	p = NULL, p1 = NULL;
1826 
1827 	mtx_assert(&ng_btsocket_sco_sockets_mtx, MA_OWNED);
1828 
1829 	LIST_FOREACH(p, &ng_btsocket_sco_sockets, next) {
1830 		mtx_lock(&p->pcb_mtx);
1831 
1832 		if (p->so == NULL || !(p->so->so_options & SO_ACCEPTCONN)) {
1833 			mtx_unlock(&p->pcb_mtx);
1834 			continue;
1835 		}
1836 
1837 		if (bcmp(&p->src, bdaddr, sizeof(p->src)) == 0)
1838 			return (p); /* return with locked pcb */
1839 
1840 		if (bcmp(&p->src, NG_HCI_BDADDR_ANY, sizeof(p->src)) == 0)
1841 			p1 = p;
1842 
1843 		mtx_unlock(&p->pcb_mtx);
1844 	}
1845 
1846 	if (p1 != NULL)
1847 		mtx_lock(&p1->pcb_mtx);
1848 
1849 	return (p1);
1850 } /* ng_btsocket_sco_pcb_by_addr */
1851 
1852 /*
1853  * Look for the socket that assigned to given source address and handle.
1854  * Caller must hold ng_btsocket_sco_sockets_mtx.
1855  * Returns with locked pcb.
1856  */
1857 
1858 static ng_btsocket_sco_pcb_p
1859 ng_btsocket_sco_pcb_by_handle(bdaddr_p src, int con_handle)
1860 {
1861 	ng_btsocket_sco_pcb_p	p = NULL;
1862 
1863 	mtx_assert(&ng_btsocket_sco_sockets_mtx, MA_OWNED);
1864 
1865 	LIST_FOREACH(p, &ng_btsocket_sco_sockets, next) {
1866 		mtx_lock(&p->pcb_mtx);
1867 
1868 		if (p->con_handle == con_handle &&
1869 		    bcmp(src, &p->src, sizeof(p->src)) == 0)
1870 			return (p); /* return with locked pcb */
1871 
1872 		mtx_unlock(&p->pcb_mtx);
1873 	}
1874 
1875 	return (NULL);
1876 } /* ng_btsocket_sco_pcb_by_handle */
1877 
1878 /*
1879  * Look for the socket in CONNECTING state with given source and destination
1880  * addresses. Caller must hold ng_btsocket_sco_sockets_mtx.
1881  * Returns with locked pcb.
1882  */
1883 
1884 static ng_btsocket_sco_pcb_p
1885 ng_btsocket_sco_pcb_by_addrs(bdaddr_p src, bdaddr_p dst)
1886 {
1887 	ng_btsocket_sco_pcb_p	p = NULL;
1888 
1889 	mtx_assert(&ng_btsocket_sco_sockets_mtx, MA_OWNED);
1890 
1891 	LIST_FOREACH(p, &ng_btsocket_sco_sockets, next) {
1892 		mtx_lock(&p->pcb_mtx);
1893 
1894 		if (p->state == NG_BTSOCKET_SCO_CONNECTING &&
1895 		    bcmp(src, &p->src, sizeof(p->src)) == 0 &&
1896 		    bcmp(dst, &p->dst, sizeof(p->dst)) == 0)
1897 			return (p); /* return with locked pcb */
1898 
1899 		mtx_unlock(&p->pcb_mtx);
1900 	}
1901 
1902 	return (NULL);
1903 } /* ng_btsocket_sco_pcb_by_addrs */
1904 
1905 /*
1906  * Set timeout on socket
1907  */
1908 
1909 static void
1910 ng_btsocket_sco_timeout(ng_btsocket_sco_pcb_p pcb)
1911 {
1912 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
1913 
1914 	if (!(pcb->flags & NG_BTSOCKET_SCO_TIMO)) {
1915 		pcb->flags |= NG_BTSOCKET_SCO_TIMO;
1916 		callout_reset(&pcb->timo, bluetooth_sco_rtx_timeout(),
1917 					ng_btsocket_sco_process_timeout, pcb);
1918 	} else
1919 		KASSERT(0,
1920 ("%s: Duplicated socket timeout?!\n", __func__));
1921 } /* ng_btsocket_sco_timeout */
1922 
1923 /*
1924  * Unset timeout on socket
1925  */
1926 
1927 static void
1928 ng_btsocket_sco_untimeout(ng_btsocket_sco_pcb_p pcb)
1929 {
1930 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
1931 
1932 	if (pcb->flags & NG_BTSOCKET_SCO_TIMO) {
1933 		callout_stop(&pcb->timo);
1934 		pcb->flags &= ~NG_BTSOCKET_SCO_TIMO;
1935 	} else
1936 		KASSERT(0,
1937 ("%s: No socket timeout?!\n", __func__));
1938 } /* ng_btsocket_sco_untimeout */
1939 
1940 /*
1941  * Process timeout on socket
1942  */
1943 
1944 static void
1945 ng_btsocket_sco_process_timeout(void *xpcb)
1946 {
1947 	ng_btsocket_sco_pcb_p	 pcb = (ng_btsocket_sco_pcb_p) xpcb;
1948 
1949 	mtx_lock(&pcb->pcb_mtx);
1950 
1951 	pcb->flags &= ~NG_BTSOCKET_SCO_TIMO;
1952 	pcb->so->so_error = ETIMEDOUT;
1953 
1954 	switch (pcb->state) {
1955 	case NG_BTSOCKET_SCO_CONNECTING:
1956 		/* Connect timeout - close the socket */
1957 		pcb->state = NG_BTSOCKET_SCO_CLOSED;
1958 		soisdisconnected(pcb->so);
1959 		break;
1960 
1961 	case NG_BTSOCKET_SCO_OPEN:
1962 		/* Send timeout - did not get NGM_HCI_SYNC_CON_QUEUE */
1963 		sbdroprecord(&pcb->so->so_snd);
1964 		sowwakeup(pcb->so);
1965 		/* XXX FIXME what to do with pcb->rt->pending??? */
1966 		break;
1967 
1968 	case NG_BTSOCKET_SCO_DISCONNECTING:
1969 		/* Disconnect timeout - disconnect the socket anyway */
1970 		pcb->state = NG_BTSOCKET_SCO_CLOSED;
1971 		soisdisconnected(pcb->so);
1972 		break;
1973 
1974 	default:
1975 		NG_BTSOCKET_SCO_ERR(
1976 "%s: Invalid socket state=%d\n", __func__, pcb->state);
1977 		break;
1978 	}
1979 
1980 	mtx_unlock(&pcb->pcb_mtx);
1981 } /* ng_btsocket_sco_process_timeout */
1982 
1983