xref: /freebsd/sys/netgraph/bluetooth/socket/ng_btsocket_l2cap.c (revision 39ee7a7a6bdd1557b1c3532abf60d139798ac88b)
1 /*
2  * ng_btsocket_l2cap.c
3  */
4 
5 /*-
6  * Copyright (c) 2001-2002 Maksim Yevmenkin <m_evmenkin@yahoo.com>
7  * All rights reserved.
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  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  * $Id: ng_btsocket_l2cap.c,v 1.16 2003/09/14 23:29:06 max Exp $
31  * $FreeBSD$
32  */
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/bitstring.h>
37 #include <sys/domain.h>
38 #include <sys/endian.h>
39 #include <sys/errno.h>
40 #include <sys/filedesc.h>
41 #include <sys/ioccom.h>
42 #include <sys/kernel.h>
43 #include <sys/lock.h>
44 #include <sys/malloc.h>
45 #include <sys/mbuf.h>
46 #include <sys/mutex.h>
47 #include <sys/protosw.h>
48 #include <sys/queue.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/taskqueue.h>
53 
54 #include <net/vnet.h>
55 
56 #include <netgraph/ng_message.h>
57 #include <netgraph/netgraph.h>
58 #include <netgraph/bluetooth/include/ng_bluetooth.h>
59 #include <netgraph/bluetooth/include/ng_hci.h>
60 #include <netgraph/bluetooth/include/ng_l2cap.h>
61 #include <netgraph/bluetooth/include/ng_btsocket.h>
62 #include <netgraph/bluetooth/include/ng_btsocket_l2cap.h>
63 
64 /* MALLOC define */
65 #ifdef NG_SEPARATE_MALLOC
66 static MALLOC_DEFINE(M_NETGRAPH_BTSOCKET_L2CAP, "netgraph_btsocks_l2cap",
67 		"Netgraph Bluetooth L2CAP sockets");
68 #else
69 #define M_NETGRAPH_BTSOCKET_L2CAP M_NETGRAPH
70 #endif /* NG_SEPARATE_MALLOC */
71 
72 /* Netgraph node methods */
73 static ng_constructor_t	ng_btsocket_l2cap_node_constructor;
74 static ng_rcvmsg_t	ng_btsocket_l2cap_node_rcvmsg;
75 static ng_shutdown_t	ng_btsocket_l2cap_node_shutdown;
76 static ng_newhook_t	ng_btsocket_l2cap_node_newhook;
77 static ng_connect_t	ng_btsocket_l2cap_node_connect;
78 static ng_rcvdata_t	ng_btsocket_l2cap_node_rcvdata;
79 static ng_disconnect_t	ng_btsocket_l2cap_node_disconnect;
80 
81 static void		ng_btsocket_l2cap_input   (void *, int);
82 static void		ng_btsocket_l2cap_rtclean (void *, int);
83 
84 /* Netgraph type descriptor */
85 static struct ng_type	typestruct = {
86 	.version =	NG_ABI_VERSION,
87 	.name =		NG_BTSOCKET_L2CAP_NODE_TYPE,
88 	.constructor =	ng_btsocket_l2cap_node_constructor,
89 	.rcvmsg =	ng_btsocket_l2cap_node_rcvmsg,
90 	.shutdown =	ng_btsocket_l2cap_node_shutdown,
91 	.newhook =	ng_btsocket_l2cap_node_newhook,
92 	.connect =	ng_btsocket_l2cap_node_connect,
93 	.rcvdata =	ng_btsocket_l2cap_node_rcvdata,
94 	.disconnect =	ng_btsocket_l2cap_node_disconnect,
95 };
96 
97 /* Globals */
98 extern int					ifqmaxlen;
99 static u_int32_t				ng_btsocket_l2cap_debug_level;
100 static node_p					ng_btsocket_l2cap_node;
101 static struct ng_bt_itemq			ng_btsocket_l2cap_queue;
102 static struct mtx				ng_btsocket_l2cap_queue_mtx;
103 static struct task				ng_btsocket_l2cap_queue_task;
104 static LIST_HEAD(, ng_btsocket_l2cap_pcb)	ng_btsocket_l2cap_sockets;
105 static struct mtx				ng_btsocket_l2cap_sockets_mtx;
106 static LIST_HEAD(, ng_btsocket_l2cap_rtentry)	ng_btsocket_l2cap_rt;
107 static struct mtx				ng_btsocket_l2cap_rt_mtx;
108 static struct task				ng_btsocket_l2cap_rt_task;
109 static struct timeval				ng_btsocket_l2cap_lasttime;
110 static int					ng_btsocket_l2cap_curpps;
111 
112 /* Sysctl tree */
113 SYSCTL_DECL(_net_bluetooth_l2cap_sockets);
114 static SYSCTL_NODE(_net_bluetooth_l2cap_sockets, OID_AUTO, seq, CTLFLAG_RW,
115 	0, "Bluetooth SEQPACKET L2CAP sockets family");
116 SYSCTL_UINT(_net_bluetooth_l2cap_sockets_seq, OID_AUTO, debug_level,
117 	CTLFLAG_RW,
118 	&ng_btsocket_l2cap_debug_level, NG_BTSOCKET_WARN_LEVEL,
119 	"Bluetooth SEQPACKET L2CAP sockets debug level");
120 SYSCTL_UINT(_net_bluetooth_l2cap_sockets_seq, OID_AUTO, queue_len,
121 	CTLFLAG_RD,
122 	&ng_btsocket_l2cap_queue.len, 0,
123 	"Bluetooth SEQPACKET L2CAP sockets input queue length");
124 SYSCTL_UINT(_net_bluetooth_l2cap_sockets_seq, OID_AUTO, queue_maxlen,
125 	CTLFLAG_RD,
126 	&ng_btsocket_l2cap_queue.maxlen, 0,
127 	"Bluetooth SEQPACKET L2CAP sockets input queue max. length");
128 SYSCTL_UINT(_net_bluetooth_l2cap_sockets_seq, OID_AUTO, queue_drops,
129 	CTLFLAG_RD,
130 	&ng_btsocket_l2cap_queue.drops, 0,
131 	"Bluetooth SEQPACKET L2CAP sockets input queue drops");
132 
133 /* Debug */
134 #define NG_BTSOCKET_L2CAP_INFO \
135 	if (ng_btsocket_l2cap_debug_level >= NG_BTSOCKET_INFO_LEVEL && \
136 	    ppsratecheck(&ng_btsocket_l2cap_lasttime, &ng_btsocket_l2cap_curpps, 1)) \
137 		printf
138 
139 #define NG_BTSOCKET_L2CAP_WARN \
140 	if (ng_btsocket_l2cap_debug_level >= NG_BTSOCKET_WARN_LEVEL && \
141 	    ppsratecheck(&ng_btsocket_l2cap_lasttime, &ng_btsocket_l2cap_curpps, 1)) \
142 		printf
143 
144 #define NG_BTSOCKET_L2CAP_ERR \
145 	if (ng_btsocket_l2cap_debug_level >= NG_BTSOCKET_ERR_LEVEL && \
146 	    ppsratecheck(&ng_btsocket_l2cap_lasttime, &ng_btsocket_l2cap_curpps, 1)) \
147 		printf
148 
149 #define NG_BTSOCKET_L2CAP_ALERT \
150 	if (ng_btsocket_l2cap_debug_level >= NG_BTSOCKET_ALERT_LEVEL && \
151 	    ppsratecheck(&ng_btsocket_l2cap_lasttime, &ng_btsocket_l2cap_curpps, 1)) \
152 		printf
153 
154 /*
155  * Netgraph message processing routines
156  */
157 
158 static int ng_btsocket_l2cap_process_l2ca_con_req_rsp
159 	(struct ng_mesg *, ng_btsocket_l2cap_rtentry_p);
160 static int ng_btsocket_l2cap_process_l2ca_con_rsp_rsp
161 	(struct ng_mesg *, ng_btsocket_l2cap_rtentry_p);
162 static int ng_btsocket_l2cap_process_l2ca_con_ind
163 	(struct ng_mesg *, ng_btsocket_l2cap_rtentry_p);
164 
165 static int ng_btsocket_l2cap_process_l2ca_cfg_req_rsp
166 	(struct ng_mesg *, ng_btsocket_l2cap_rtentry_p);
167 static int ng_btsocket_l2cap_process_l2ca_cfg_rsp_rsp
168 	(struct ng_mesg *, ng_btsocket_l2cap_rtentry_p);
169 static int ng_btsocket_l2cap_process_l2ca_cfg_ind
170 	(struct ng_mesg *, ng_btsocket_l2cap_rtentry_p);
171 
172 static int ng_btsocket_l2cap_process_l2ca_discon_rsp
173 	(struct ng_mesg *, ng_btsocket_l2cap_rtentry_p);
174 static int ng_btsocket_l2cap_process_l2ca_discon_ind
175 	(struct ng_mesg *, ng_btsocket_l2cap_rtentry_p);
176 
177 static int ng_btsocket_l2cap_process_l2ca_write_rsp
178 	(struct ng_mesg *, ng_btsocket_l2cap_rtentry_p);
179 
180 /*
181  * Send L2CA_xxx messages to the lower layer
182  */
183 
184 static int  ng_btsocket_l2cap_send_l2ca_con_req
185 	(ng_btsocket_l2cap_pcb_p);
186 static int  ng_btsocket_l2cap_send_l2ca_con_rsp_req
187 	(u_int32_t, ng_btsocket_l2cap_rtentry_p, bdaddr_p, int, int, int, int);
188 static int  ng_btsocket_l2cap_send_l2ca_cfg_req
189 	(ng_btsocket_l2cap_pcb_p);
190 static int  ng_btsocket_l2cap_send_l2ca_cfg_rsp
191 	(ng_btsocket_l2cap_pcb_p);
192 static int  ng_btsocket_l2cap_send_l2ca_discon_req
193 	(u_int32_t, ng_btsocket_l2cap_pcb_p);
194 
195 static int ng_btsocket_l2cap_send2
196 	(ng_btsocket_l2cap_pcb_p);
197 
198 /*
199  * Timeout processing routines
200  */
201 
202 static void ng_btsocket_l2cap_timeout         (ng_btsocket_l2cap_pcb_p);
203 static void ng_btsocket_l2cap_untimeout       (ng_btsocket_l2cap_pcb_p);
204 static void ng_btsocket_l2cap_process_timeout (void *);
205 
206 /*
207  * Other stuff
208  */
209 
210 static ng_btsocket_l2cap_pcb_p     ng_btsocket_l2cap_pcb_by_addr(bdaddr_p, int);
211 static ng_btsocket_l2cap_pcb_p     ng_btsocket_l2cap_pcb_by_token(u_int32_t);
212 static ng_btsocket_l2cap_pcb_p     ng_btsocket_l2cap_pcb_by_cid (bdaddr_p, int,int);
213 static int                         ng_btsocket_l2cap_result2errno(int);
214 
215 static int ng_btsock_l2cap_addrtype_to_linktype(int addrtype);
216 
217 #define ng_btsocket_l2cap_wakeup_input_task() \
218 	taskqueue_enqueue(taskqueue_swi_giant, &ng_btsocket_l2cap_queue_task)
219 
220 #define ng_btsocket_l2cap_wakeup_route_task() \
221 	taskqueue_enqueue(taskqueue_swi_giant, &ng_btsocket_l2cap_rt_task)
222 
223 
224 
225 int ng_btsock_l2cap_addrtype_to_linktype(int addrtype)
226 {
227 	switch(addrtype){
228 	case BDADDR_LE_PUBLIC:
229 		return NG_HCI_LINK_LE_PUBLIC;
230 	case BDADDR_LE_RANDOM:
231 		return NG_HCI_LINK_LE_RANDOM;
232 	default:
233 		return NG_HCI_LINK_ACL;
234 	}
235 }
236 
237 
238 /*****************************************************************************
239  *****************************************************************************
240  **                        Netgraph node interface
241  *****************************************************************************
242  *****************************************************************************/
243 
244 /*
245  * Netgraph node constructor. Do not allow to create node of this type.
246  */
247 
248 static int
249 ng_btsocket_l2cap_node_constructor(node_p node)
250 {
251 	return (EINVAL);
252 } /* ng_btsocket_l2cap_node_constructor */
253 
254 /*
255  * Do local shutdown processing. Let old node go and create new fresh one.
256  */
257 
258 static int
259 ng_btsocket_l2cap_node_shutdown(node_p node)
260 {
261 	int	error = 0;
262 
263 	NG_NODE_UNREF(node);
264 
265 	/* Create new node */
266 	error = ng_make_node_common(&typestruct, &ng_btsocket_l2cap_node);
267 	if (error != 0) {
268 		NG_BTSOCKET_L2CAP_ALERT(
269 "%s: Could not create Netgraph node, error=%d\n", __func__, error);
270 
271 		ng_btsocket_l2cap_node = NULL;
272 
273 		return (error);
274 	}
275 
276 	error = ng_name_node(ng_btsocket_l2cap_node,
277 				NG_BTSOCKET_L2CAP_NODE_TYPE);
278 	if (error != 0) {
279 		NG_BTSOCKET_L2CAP_ALERT(
280 "%s: Could not name Netgraph node, error=%d\n", __func__, error);
281 
282 		NG_NODE_UNREF(ng_btsocket_l2cap_node);
283 		ng_btsocket_l2cap_node = NULL;
284 
285 		return (error);
286 	}
287 
288 	return (0);
289 } /* ng_btsocket_l2cap_node_shutdown */
290 
291 /*
292  * We allow any hook to be connected to the node.
293  */
294 
295 static int
296 ng_btsocket_l2cap_node_newhook(node_p node, hook_p hook, char const *name)
297 {
298 	return (0);
299 } /* ng_btsocket_l2cap_node_newhook */
300 
301 /*
302  * Just say "YEP, that's OK by me!"
303  */
304 
305 static int
306 ng_btsocket_l2cap_node_connect(hook_p hook)
307 {
308 	NG_HOOK_SET_PRIVATE(hook, NULL);
309 	NG_HOOK_REF(hook); /* Keep extra reference to the hook */
310 
311 #if 0
312 	NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));
313 	NG_HOOK_FORCE_QUEUE(hook);
314 #endif
315 
316 	return (0);
317 } /* ng_btsocket_l2cap_node_connect */
318 
319 /*
320  * Hook disconnection. Schedule route cleanup task
321  */
322 
323 static int
324 ng_btsocket_l2cap_node_disconnect(hook_p hook)
325 {
326 	/*
327 	 * If hook has private information than we must have this hook in
328 	 * the routing table and must schedule cleaning for the routing table.
329 	 * Otherwise hook was connected but we never got "hook_info" message,
330 	 * so we have never added this hook to the routing table and it save
331 	 * to just delete it.
332 	 */
333 
334 	if (NG_HOOK_PRIVATE(hook) != NULL)
335 		return (ng_btsocket_l2cap_wakeup_route_task());
336 
337 	NG_HOOK_UNREF(hook); /* Remove extra reference */
338 
339 	return (0);
340 } /* ng_btsocket_l2cap_node_disconnect */
341 
342 /*
343  * Process incoming messages
344  */
345 
346 static int
347 ng_btsocket_l2cap_node_rcvmsg(node_p node, item_p item, hook_p hook)
348 {
349 	struct ng_mesg	*msg = NGI_MSG(item); /* item still has message */
350 	int		 error = 0;
351 
352 	if (msg != NULL && msg->header.typecookie == NGM_L2CAP_COOKIE) {
353 		mtx_lock(&ng_btsocket_l2cap_queue_mtx);
354 		if (NG_BT_ITEMQ_FULL(&ng_btsocket_l2cap_queue)) {
355 			NG_BTSOCKET_L2CAP_ERR(
356 "%s: Input queue is full (msg)\n", __func__);
357 
358 			NG_BT_ITEMQ_DROP(&ng_btsocket_l2cap_queue);
359 			NG_FREE_ITEM(item);
360 			error = ENOBUFS;
361 		} else {
362 			if (hook != NULL) {
363 				NG_HOOK_REF(hook);
364 				NGI_SET_HOOK(item, hook);
365 			}
366 
367 			NG_BT_ITEMQ_ENQUEUE(&ng_btsocket_l2cap_queue, item);
368 			error = ng_btsocket_l2cap_wakeup_input_task();
369 		}
370 		mtx_unlock(&ng_btsocket_l2cap_queue_mtx);
371 	} else {
372 		NG_FREE_ITEM(item);
373 		error = EINVAL;
374 	}
375 
376 	return (error);
377 } /* ng_btsocket_l2cap_node_rcvmsg */
378 
379 /*
380  * Receive data on a hook
381  */
382 
383 static int
384 ng_btsocket_l2cap_node_rcvdata(hook_p hook, item_p item)
385 {
386 	int	error = 0;
387 
388 	mtx_lock(&ng_btsocket_l2cap_queue_mtx);
389 	if (NG_BT_ITEMQ_FULL(&ng_btsocket_l2cap_queue)) {
390 		NG_BTSOCKET_L2CAP_ERR(
391 "%s: Input queue is full (data)\n", __func__);
392 
393 		NG_BT_ITEMQ_DROP(&ng_btsocket_l2cap_queue);
394 		NG_FREE_ITEM(item);
395 		error = ENOBUFS;
396 	} else {
397 		NG_HOOK_REF(hook);
398 		NGI_SET_HOOK(item, hook);
399 
400 		NG_BT_ITEMQ_ENQUEUE(&ng_btsocket_l2cap_queue, item);
401 		error = ng_btsocket_l2cap_wakeup_input_task();
402 	}
403 	mtx_unlock(&ng_btsocket_l2cap_queue_mtx);
404 
405 	return (error);
406 } /* ng_btsocket_l2cap_node_rcvdata */
407 
408 /*
409  * Process L2CA_Connect respose. Socket layer must have initiated connection,
410  * so we have to have a socket associated with message token.
411  */
412 
413 static int
414 ng_btsocket_l2cap_process_l2ca_con_req_rsp(struct ng_mesg *msg,
415 		ng_btsocket_l2cap_rtentry_p rt)
416 {
417 	ng_l2cap_l2ca_con_op	*op = NULL;
418 	ng_btsocket_l2cap_pcb_t	*pcb = NULL;
419 	int			 error = 0;
420 
421 	if (msg->header.arglen != sizeof(*op))
422 		return (EMSGSIZE);
423 
424 	op = (ng_l2cap_l2ca_con_op *)(msg->data);
425 
426 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
427 
428 	/* Look for the socket with the token */
429 	pcb = ng_btsocket_l2cap_pcb_by_token(msg->header.token);
430 	if (pcb == NULL) {
431 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
432 		return (ENOENT);
433 	}
434 
435 	mtx_lock(&pcb->pcb_mtx);
436 
437 	NG_BTSOCKET_L2CAP_INFO(
438 "%s: Got L2CA_Connect response, token=%d, src bdaddr=%x:%x:%x:%x:%x:%x, " \
439 "dst bdaddr=%x:%x:%x:%x:%x:%x, psm=%d, lcid=%d, result=%d, status=%d, " \
440 "state=%d\n",	__func__, msg->header.token,
441 		pcb->src.b[5], pcb->src.b[4], pcb->src.b[3],
442 		pcb->src.b[2], pcb->src.b[1], pcb->src.b[0],
443 		pcb->dst.b[5], pcb->dst.b[4], pcb->dst.b[3],
444 		pcb->dst.b[2], pcb->dst.b[1], pcb->dst.b[0],
445 		pcb->psm, op->lcid, op->result, op->status,
446 		pcb->state);
447 
448 	if (pcb->state != NG_BTSOCKET_L2CAP_CONNECTING) {
449 		mtx_unlock(&pcb->pcb_mtx);
450 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
451 
452 		return (ENOENT);
453 	}
454 
455 	ng_btsocket_l2cap_untimeout(pcb);
456 
457 	if (op->result == NG_L2CAP_PENDING) {
458 		ng_btsocket_l2cap_timeout(pcb);
459 		mtx_unlock(&pcb->pcb_mtx);
460 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
461 
462 		return (0);
463 	}
464 
465 	if (op->result == NG_L2CAP_SUCCESS){
466 		if((pcb->idtype == NG_L2CAP_L2CA_IDTYPE_ATT)||
467 		   (pcb->idtype == NG_L2CAP_L2CA_IDTYPE_SMP)){
468 			pcb->encryption = op->encryption;					pcb->cid = op->lcid;
469 			if(pcb->need_encrypt && !(pcb->encryption)){
470 				pcb->state = NG_BTSOCKET_L2CAP_W4_ENC_CHANGE;
471 			}else{
472 				pcb->state = NG_BTSOCKET_L2CAP_OPEN;
473 				soisconnected(pcb->so);
474 			}
475 		}else{
476 			/*
477 			 * Channel is now open, so update local channel ID and
478 			 * start configuration process. Source and destination
479 			 * addresses as well as route must be already set.
480 			 */
481 
482 			pcb->cid = op->lcid;
483 			pcb->encryption = op->encryption;
484 			error = ng_btsocket_l2cap_send_l2ca_cfg_req(pcb);
485 			if (error != 0) {
486 				/* Send disconnect request with "zero" token */
487 				ng_btsocket_l2cap_send_l2ca_discon_req(0, pcb);
488 
489 				/* ... and close the socket */
490 				pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
491 				soisdisconnected(pcb->so);
492 			} else {
493 				pcb->cfg_state = NG_BTSOCKET_L2CAP_CFG_IN_SENT;
494 				pcb->state = NG_BTSOCKET_L2CAP_CONFIGURING;
495 
496 				ng_btsocket_l2cap_timeout(pcb);
497 			}
498 		}
499 	} else {
500 		/*
501 		 * We have failed to open connection, so convert result
502 		 * code to "errno" code and disconnect the socket. Channel
503 		 * already has been closed.
504 		 */
505 
506 		pcb->so->so_error = ng_btsocket_l2cap_result2errno(op->result);
507 		pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
508 		soisdisconnected(pcb->so);
509 	}
510 	mtx_unlock(&pcb->pcb_mtx);
511 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
512 
513 	return (error);
514 } /* ng_btsocket_l2cap_process_l2ca_con_req_rsp */
515 
516 /*
517  * Process L2CA_ConnectRsp response
518  */
519 
520 static int
521 ng_btsocket_l2cap_process_l2ca_con_rsp_rsp(struct ng_mesg *msg,
522 		ng_btsocket_l2cap_rtentry_p rt)
523 {
524 	ng_l2cap_l2ca_con_rsp_op	*op = NULL;
525 	ng_btsocket_l2cap_pcb_t		*pcb = NULL;
526 
527 	if (msg->header.arglen != sizeof(*op))
528 		return (EMSGSIZE);
529 
530 	op = (ng_l2cap_l2ca_con_rsp_op *)(msg->data);
531 
532 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
533 
534 	/* Look for the socket with the token */
535 	pcb = ng_btsocket_l2cap_pcb_by_token(msg->header.token);
536 	if (pcb == NULL) {
537 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
538 		return (ENOENT);
539 	}
540 
541 	mtx_lock(&pcb->pcb_mtx);
542 
543 	NG_BTSOCKET_L2CAP_INFO(
544 "%s: Got L2CA_ConnectRsp response, token=%d, src bdaddr=%x:%x:%x:%x:%x:%x, " \
545 "dst bdaddr=%x:%x:%x:%x:%x:%x, psm=%d, lcid=%d, result=%d, state=%d\n",
546 		__func__, msg->header.token,
547 		pcb->src.b[5], pcb->src.b[4], pcb->src.b[3],
548 		pcb->src.b[2], pcb->src.b[1], pcb->src.b[0],
549 		pcb->dst.b[5], pcb->dst.b[4], pcb->dst.b[3],
550 		pcb->dst.b[2], pcb->dst.b[1], pcb->dst.b[0],
551 		pcb->psm, pcb->cid, op->result, pcb->state);
552 
553 	if (pcb->state != NG_BTSOCKET_L2CAP_CONNECTING) {
554 		mtx_unlock(&pcb->pcb_mtx);
555 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
556 
557 		return (ENOENT);
558 	}
559 
560 	ng_btsocket_l2cap_untimeout(pcb);
561 
562 	/* Check the result and disconnect the socket on failure */
563 	if (op->result != NG_L2CAP_SUCCESS) {
564 		/* Close the socket - channel already closed */
565 		pcb->so->so_error = ng_btsocket_l2cap_result2errno(op->result);
566 		pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
567 		soisdisconnected(pcb->so);
568 	} else {
569 		/* Move to CONFIGURING state and wait for CONFIG_IND */
570 		pcb->cfg_state = 0;
571 		pcb->state = NG_BTSOCKET_L2CAP_CONFIGURING;
572 		ng_btsocket_l2cap_timeout(pcb);
573 	}
574 
575 	mtx_unlock(&pcb->pcb_mtx);
576 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
577 
578 	return (0);
579 } /* ng_btsocket_process_l2ca_con_rsp_rsp */
580 
581 /*
582  * Process L2CA_Connect indicator. Find socket that listens on address
583  * and PSM. Find exact or closest match. Create new socket and initiate
584  * connection.
585  */
586 
587 static int
588 ng_btsocket_l2cap_process_l2ca_con_ind(struct ng_mesg *msg,
589 		ng_btsocket_l2cap_rtentry_p rt)
590 {
591 	ng_l2cap_l2ca_con_ind_ip	*ip = NULL;
592 	ng_btsocket_l2cap_pcb_t		*pcb = NULL, *pcb1 = NULL;
593 	int				 error = 0;
594 	u_int32_t			 token = 0;
595 	u_int16_t			 result = 0;
596 
597 	if (msg->header.arglen != sizeof(*ip))
598 		return (EMSGSIZE);
599 
600 	ip = (ng_l2cap_l2ca_con_ind_ip *)(msg->data);
601 
602 	NG_BTSOCKET_L2CAP_INFO(
603 "%s: Got L2CA_Connect indicator, src bdaddr=%x:%x:%x:%x:%x:%x, " \
604 "dst bdaddr=%x:%x:%x:%x:%x:%x, psm=%d, lcid=%d, ident=%d\n",
605 		__func__,
606 		rt->src.b[5], rt->src.b[4], rt->src.b[3],
607 		rt->src.b[2], rt->src.b[1], rt->src.b[0],
608 		ip->bdaddr.b[5], ip->bdaddr.b[4], ip->bdaddr.b[3],
609 		ip->bdaddr.b[2], ip->bdaddr.b[1], ip->bdaddr.b[0],
610 		ip->psm, ip->lcid, ip->ident);
611 
612 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
613 
614 	pcb = ng_btsocket_l2cap_pcb_by_addr(&rt->src, ip->psm);
615 	if (pcb != NULL) {
616 		struct socket	*so1 = NULL;
617 
618 		mtx_lock(&pcb->pcb_mtx);
619 
620 		/*
621 		 * First check the pending connections queue and if we have
622 		 * space then create new socket and set proper source address.
623 		 */
624 
625 		if (pcb->so->so_qlen <= pcb->so->so_qlimit) {
626 			CURVNET_SET(pcb->so->so_vnet);
627 			so1 = sonewconn(pcb->so, 0);
628 			CURVNET_RESTORE();
629 		}
630 
631 		if (so1 == NULL) {
632 			result = NG_L2CAP_NO_RESOURCES;
633 			goto respond;
634 		}
635 
636 		/*
637 		 * If we got here than we have created new socket. So complete
638 		 * connection. If we we listening on specific address then copy
639 		 * source address from listening socket, otherwise copy source
640 		 * address from hook's routing information.
641 		 */
642 
643 		pcb1 = so2l2cap_pcb(so1);
644 		KASSERT((pcb1 != NULL),
645 ("%s: pcb1 == NULL\n", __func__));
646 
647  		mtx_lock(&pcb1->pcb_mtx);
648 
649 		if (bcmp(&pcb->src, NG_HCI_BDADDR_ANY, sizeof(pcb->src)) != 0)
650 			bcopy(&pcb->src, &pcb1->src, sizeof(pcb1->src));
651 		else
652 			bcopy(&rt->src, &pcb1->src, sizeof(pcb1->src));
653 
654 		pcb1->flags &= ~NG_BTSOCKET_L2CAP_CLIENT;
655 
656 		bcopy(&ip->bdaddr, &pcb1->dst, sizeof(pcb1->dst));
657 		pcb1->psm = ip->psm;
658 		pcb1->cid = ip->lcid;
659 		pcb1->rt = rt;
660 
661 		/* Copy socket settings */
662 		pcb1->imtu = pcb->imtu;
663 		bcopy(&pcb->oflow, &pcb1->oflow, sizeof(pcb1->oflow));
664 		pcb1->flush_timo = pcb->flush_timo;
665 
666 		token = pcb1->token;
667 	} else
668 		/* Nobody listens on requested BDADDR/PSM */
669 		result = NG_L2CAP_PSM_NOT_SUPPORTED;
670 
671 respond:
672 	error = ng_btsocket_l2cap_send_l2ca_con_rsp_req(token, rt,
673 							&ip->bdaddr,
674 							ip->ident, ip->lcid,
675 							result,ip->linktype);
676 	if (pcb1 != NULL) {
677 		if (error != 0) {
678 			pcb1->so->so_error = error;
679 			pcb1->state = NG_BTSOCKET_L2CAP_CLOSED;
680 			soisdisconnected(pcb1->so);
681 		} else {
682 			pcb1->state = NG_BTSOCKET_L2CAP_CONNECTING;
683 			soisconnecting(pcb1->so);
684 
685 			ng_btsocket_l2cap_timeout(pcb1);
686 		}
687 
688 		mtx_unlock(&pcb1->pcb_mtx);
689 	}
690 
691 	if (pcb != NULL)
692 		mtx_unlock(&pcb->pcb_mtx);
693 
694 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
695 
696 	return (error);
697 } /* ng_btsocket_l2cap_process_l2ca_con_ind */
698 /*Encryption Change*/
699 static int ng_btsocket_l2cap_process_l2ca_enc_change(struct ng_mesg *msg, ng_btsocket_l2cap_rtentry_p rt)
700 {
701 	ng_l2cap_l2ca_enc_chg_op	*op = NULL;
702 	ng_btsocket_l2cap_pcb_t		*pcb = NULL;
703 
704 
705 	if (msg->header.arglen != sizeof(*op))
706 		return (EMSGSIZE);
707 
708 	op = (ng_l2cap_l2ca_enc_chg_op *)(msg->data);
709 
710 	pcb = ng_btsocket_l2cap_pcb_by_cid(&rt->src, op->lcid,
711 					   op->idtype);
712 	mtx_lock(&pcb->pcb_mtx);
713 	pcb->encryption = op->result;
714 
715 	if(pcb->need_encrypt){
716 		if(pcb->state != NG_BTSOCKET_L2CAP_W4_ENC_CHANGE){
717 			NG_BTSOCKET_L2CAP_WARN("%s: Invalid pcb status %d",
718 					       __func__, pcb->state);
719 		}else if(pcb->encryption){
720 			pcb->state = NG_BTSOCKET_L2CAP_OPEN;
721 			soisconnected(pcb->so);
722 		}else{
723 			pcb->so->so_error = EPERM;
724 			pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
725 			soisdisconnected(pcb->so);
726 		}
727 	}
728 	mtx_unlock(&pcb->pcb_mtx);
729 
730 	return 0;
731 }
732 /*
733  * Process L2CA_Config response
734  */
735 
736 static int
737 ng_btsocket_l2cap_process_l2ca_cfg_req_rsp(struct ng_mesg *msg,
738 		ng_btsocket_l2cap_rtentry_p rt)
739 {
740 	ng_l2cap_l2ca_cfg_op	*op = NULL;
741 	ng_btsocket_l2cap_pcb_p	 pcb = NULL;
742 
743 	if (msg->header.arglen != sizeof(*op))
744 		return (EMSGSIZE);
745 
746 	op = (ng_l2cap_l2ca_cfg_op *)(msg->data);
747 
748 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
749 
750 	/*
751 	 * Socket must have issued a Configure request, so we must have a
752 	 * socket that wants to be configured. Use Netgraph message token
753 	 * to find it
754 	 */
755 
756 	pcb = ng_btsocket_l2cap_pcb_by_token(msg->header.token);
757 	if (pcb == NULL) {
758 		/*
759 		 * XXX FIXME what to do here? We could not find a
760 		 * socket with requested token. We even can not send
761 		 * Disconnect, because we do not know channel ID
762 		 */
763 
764 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
765 		return (ENOENT);
766 	}
767 
768 	mtx_lock(&pcb->pcb_mtx);
769 
770         NG_BTSOCKET_L2CAP_INFO(
771 "%s: Got L2CA_Config response, token=%d, src bdaddr=%x:%x:%x:%x:%x:%x, " \
772 "dst bdaddr=%x:%x:%x:%x:%x:%x, psm=%d, lcid=%d, result=%d, state=%d, " \
773 "cfg_state=%x\n",
774 		__func__, msg->header.token,
775 		pcb->src.b[5], pcb->src.b[4], pcb->src.b[3],
776 		pcb->src.b[2], pcb->src.b[1], pcb->src.b[0],
777 		pcb->dst.b[5], pcb->dst.b[4], pcb->dst.b[3],
778 		pcb->dst.b[2], pcb->dst.b[1], pcb->dst.b[0],
779 		pcb->psm, pcb->cid, op->result, pcb->state, pcb->cfg_state);
780 
781 	if (pcb->state != NG_BTSOCKET_L2CAP_CONFIGURING) {
782 		mtx_unlock(&pcb->pcb_mtx);
783 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
784 
785 		return (ENOENT);
786 	}
787 
788 	if (op->result == NG_L2CAP_SUCCESS) {
789 		/*
790 		 * XXX FIXME Actually set flush and link timeout.
791 		 * Set QoS here if required. Resolve conficts (flush_timo).
792 		 * Save incoming MTU (peer's outgoing MTU) and outgoing flow
793 		 * spec.
794 		 */
795 
796 		pcb->imtu = op->imtu;
797 		bcopy(&op->oflow, &pcb->oflow, sizeof(pcb->oflow));
798 		pcb->flush_timo = op->flush_timo;
799 
800 		/*
801 		 * We have configured incoming side, so record it and check
802 		 * if configuration is complete. If complete then mark socket
803 		 * as connected, otherwise wait for the peer.
804 		 */
805 
806 		pcb->cfg_state &= ~NG_BTSOCKET_L2CAP_CFG_IN_SENT;
807 		pcb->cfg_state |= NG_BTSOCKET_L2CAP_CFG_IN;
808 
809 		if (pcb->cfg_state == NG_BTSOCKET_L2CAP_CFG_BOTH) {
810 			/* Configuration complete - mark socket as open */
811 			ng_btsocket_l2cap_untimeout(pcb);
812 			pcb->state = NG_BTSOCKET_L2CAP_OPEN;
813 			soisconnected(pcb->so);
814 		}
815 	} else {
816 		/*
817 		 * Something went wrong. Could be unacceptable parameters,
818 		 * reject or unknown option. That's too bad, but we will
819 		 * not negotiate. Send Disconnect and close the channel.
820 		 */
821 
822 		ng_btsocket_l2cap_untimeout(pcb);
823 
824 		switch (op->result) {
825 		case NG_L2CAP_UNACCEPTABLE_PARAMS:
826 		case NG_L2CAP_UNKNOWN_OPTION:
827 			pcb->so->so_error = EINVAL;
828 			break;
829 
830 		default:
831 			pcb->so->so_error = ECONNRESET;
832 			break;
833 		}
834 
835 		/* Send disconnect with "zero" token */
836 		ng_btsocket_l2cap_send_l2ca_discon_req(0, pcb);
837 
838 		/* ... and close the socket */
839 		pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
840 		soisdisconnected(pcb->so);
841 	}
842 
843 	mtx_unlock(&pcb->pcb_mtx);
844 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
845 
846 	return (0);
847 } /* ng_btsocket_l2cap_process_l2ca_cfg_req_rsp */
848 
849 /*
850  * Process L2CA_ConfigRsp response
851  */
852 
853 static int
854 ng_btsocket_l2cap_process_l2ca_cfg_rsp_rsp(struct ng_mesg *msg,
855 		ng_btsocket_l2cap_rtentry_p rt)
856 {
857 	ng_l2cap_l2ca_cfg_rsp_op	*op = NULL;
858 	ng_btsocket_l2cap_pcb_t		*pcb = NULL;
859 	int				 error = 0;
860 
861 	if (msg->header.arglen != sizeof(*op))
862 		return (EMSGSIZE);
863 
864 	op = (ng_l2cap_l2ca_cfg_rsp_op *)(msg->data);
865 
866 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
867 
868 	/* Look for the socket with the token */
869 	pcb = ng_btsocket_l2cap_pcb_by_token(msg->header.token);
870 	if (pcb == NULL) {
871 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
872 		return (ENOENT);
873 	}
874 
875 	mtx_lock(&pcb->pcb_mtx);
876 
877         NG_BTSOCKET_L2CAP_INFO(
878 "%s: Got L2CA_ConfigRsp response, token=%d, src bdaddr=%x:%x:%x:%x:%x:%x, " \
879 "dst bdaddr=%x:%x:%x:%x:%x:%x, psm=%d, lcid=%d, result=%d, state=%d, " \
880 "cfg_state=%x\n",
881 		__func__, msg->header.token,
882 		pcb->src.b[5], pcb->src.b[4], pcb->src.b[3],
883 		pcb->src.b[2], pcb->src.b[1], pcb->src.b[0],
884 		pcb->dst.b[5], pcb->dst.b[4], pcb->dst.b[3],
885 		pcb->dst.b[2], pcb->dst.b[1], pcb->dst.b[0],
886 		pcb->psm, pcb->cid, op->result, pcb->state, pcb->cfg_state);
887 
888 	if (pcb->state != NG_BTSOCKET_L2CAP_CONFIGURING) {
889 		mtx_unlock(&pcb->pcb_mtx);
890 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
891 
892 		return (ENOENT);
893 	}
894 
895 	/* Check the result and disconnect socket of failure */
896 	if (op->result != NG_L2CAP_SUCCESS)
897 		goto disconnect;
898 
899 	/*
900 	 * Now we done with remote side configuration. Configure local
901 	 * side if we have not done it yet.
902 	 */
903 
904 	pcb->cfg_state &= ~NG_BTSOCKET_L2CAP_CFG_OUT_SENT;
905 	pcb->cfg_state |= NG_BTSOCKET_L2CAP_CFG_OUT;
906 
907 	if (pcb->cfg_state == NG_BTSOCKET_L2CAP_CFG_BOTH) {
908 		/* Configuration complete - mask socket as open */
909 		ng_btsocket_l2cap_untimeout(pcb);
910 		pcb->state = NG_BTSOCKET_L2CAP_OPEN;
911 		soisconnected(pcb->so);
912 	} else {
913 		if (!(pcb->cfg_state & NG_BTSOCKET_L2CAP_CFG_IN_SENT)) {
914 			/* Send L2CA_Config request - incoming path */
915 			error = ng_btsocket_l2cap_send_l2ca_cfg_req(pcb);
916 			if (error != 0)
917 				goto disconnect;
918 
919 			pcb->cfg_state |= NG_BTSOCKET_L2CAP_CFG_IN_SENT;
920 		}
921 	}
922 
923 	mtx_unlock(&pcb->pcb_mtx);
924 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
925 
926 	return (error);
927 
928 disconnect:
929 	ng_btsocket_l2cap_untimeout(pcb);
930 
931 	/* Send disconnect with "zero" token */
932 	ng_btsocket_l2cap_send_l2ca_discon_req(0, pcb);
933 
934 	/* ... and close the socket */
935 	pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
936 	soisdisconnected(pcb->so);
937 
938 	mtx_unlock(&pcb->pcb_mtx);
939 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
940 
941 	return (error);
942 } /* ng_btsocket_l2cap_process_l2ca_cfg_rsp_rsp */
943 
944 /*
945  * Process L2CA_Config indicator
946  */
947 
948 static int
949 ng_btsocket_l2cap_process_l2ca_cfg_ind(struct ng_mesg *msg,
950 		ng_btsocket_l2cap_rtentry_p rt)
951 {
952 	ng_l2cap_l2ca_cfg_ind_ip	*ip = NULL;
953 	ng_btsocket_l2cap_pcb_t		*pcb = NULL;
954 	int				 error = 0;
955 
956 	if (msg->header.arglen != sizeof(*ip))
957 		return (EMSGSIZE);
958 
959 	ip = (ng_l2cap_l2ca_cfg_ind_ip *)(msg->data);
960 
961 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
962 
963 	/* Check for the open socket that has given channel ID */
964 	pcb = ng_btsocket_l2cap_pcb_by_cid(&rt->src, ip->lcid,
965 					   NG_L2CAP_L2CA_IDTYPE_BREDR);
966 	if (pcb == NULL) {
967 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
968 		return (ENOENT);
969 	}
970 
971 	mtx_lock(&pcb->pcb_mtx);
972 
973         NG_BTSOCKET_L2CAP_INFO(
974 "%s: Got L2CA_Config indicator, src bdaddr=%x:%x:%x:%x:%x:%x, " \
975 "dst bdaddr=%x:%x:%x:%x:%x:%x, psm=%d, lcid=%d, state=%d, cfg_state=%x\n",
976 		__func__,
977 		pcb->src.b[5], pcb->src.b[4], pcb->src.b[3],
978 		pcb->src.b[2], pcb->src.b[1], pcb->src.b[0],
979 		pcb->dst.b[5], pcb->dst.b[4], pcb->dst.b[3],
980 		pcb->dst.b[2], pcb->dst.b[1], pcb->dst.b[0],
981 		pcb->psm, pcb->cid, pcb->state, pcb->cfg_state);
982 
983 	/* XXX FIXME re-configuration on open socket */
984  	if (pcb->state != NG_BTSOCKET_L2CAP_CONFIGURING) {
985 		mtx_unlock(&pcb->pcb_mtx);
986 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
987 
988 		return (ENOENT);
989 	}
990 
991 	/*
992 	 * XXX FIXME Actually set flush and link timeout. Set QoS here if
993 	 * required. Resolve conficts (flush_timo). Note outgoing MTU (peer's
994 	 * incoming MTU) and incoming flow spec.
995 	 */
996 
997 	pcb->omtu = ip->omtu;
998 	bcopy(&ip->iflow, &pcb->iflow, sizeof(pcb->iflow));
999 	pcb->flush_timo = ip->flush_timo;
1000 
1001 	/*
1002 	 * Send L2CA_Config response to our peer and check for the errors,
1003 	 * if any send disconnect to close the channel.
1004 	 */
1005 
1006 	if (!(pcb->cfg_state & NG_BTSOCKET_L2CAP_CFG_OUT_SENT)) {
1007 		error = ng_btsocket_l2cap_send_l2ca_cfg_rsp(pcb);
1008 		if (error != 0) {
1009 			ng_btsocket_l2cap_untimeout(pcb);
1010 
1011 			pcb->so->so_error = error;
1012 
1013 			/* Send disconnect with "zero" token */
1014 			ng_btsocket_l2cap_send_l2ca_discon_req(0, pcb);
1015 
1016 			/* ... and close the socket */
1017 			pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
1018 			soisdisconnected(pcb->so);
1019 		} else
1020 			pcb->cfg_state |= NG_BTSOCKET_L2CAP_CFG_OUT_SENT;
1021 	}
1022 
1023 	mtx_unlock(&pcb->pcb_mtx);
1024 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1025 
1026 	return (error);
1027 } /* ng_btsocket_l2cap_process_l2cap_cfg_ind */
1028 
1029 /*
1030  * Process L2CA_Disconnect response
1031  */
1032 
1033 static int
1034 ng_btsocket_l2cap_process_l2ca_discon_rsp(struct ng_mesg *msg,
1035 		ng_btsocket_l2cap_rtentry_p rt)
1036 {
1037 	ng_l2cap_l2ca_discon_op	*op = NULL;
1038 	ng_btsocket_l2cap_pcb_t	*pcb = NULL;
1039 
1040 	/* Check message */
1041 	if (msg->header.arglen != sizeof(*op))
1042 		return (EMSGSIZE);
1043 
1044 	op = (ng_l2cap_l2ca_discon_op *)(msg->data);
1045 
1046 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
1047 
1048 	/*
1049 	 * Socket layer must have issued L2CA_Disconnect request, so there
1050 	 * must be a socket that wants to be disconnected. Use Netgraph
1051 	 * message token to find it.
1052 	 */
1053 
1054 	pcb = ng_btsocket_l2cap_pcb_by_token(msg->header.token);
1055 	if (pcb == NULL) {
1056 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1057 		return (0);
1058 	}
1059 
1060 	mtx_lock(&pcb->pcb_mtx);
1061 
1062 	/* XXX Close socket no matter what op->result says */
1063 	if (pcb->state != NG_BTSOCKET_L2CAP_CLOSED) {
1064        		NG_BTSOCKET_L2CAP_INFO(
1065 "%s: Got L2CA_Disconnect response, token=%d, src bdaddr=%x:%x:%x:%x:%x:%x, " \
1066 "dst bdaddr=%x:%x:%x:%x:%x:%x, psm=%d, lcid=%d, result=%d, state=%d\n",
1067 			__func__, msg->header.token,
1068 			pcb->src.b[5], pcb->src.b[4], pcb->src.b[3],
1069 			pcb->src.b[2], pcb->src.b[1], pcb->src.b[0],
1070 			pcb->dst.b[5], pcb->dst.b[4], pcb->dst.b[3],
1071 			pcb->dst.b[2], pcb->dst.b[1], pcb->dst.b[0],
1072 			pcb->psm, pcb->cid, op->result, pcb->state);
1073 
1074 		ng_btsocket_l2cap_untimeout(pcb);
1075 
1076 		pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
1077 		soisdisconnected(pcb->so);
1078 	}
1079 
1080 	mtx_unlock(&pcb->pcb_mtx);
1081 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1082 
1083 	return (0);
1084 } /* ng_btsocket_l2cap_process_l2ca_discon_rsp */
1085 
1086 /*
1087  * Process L2CA_Disconnect indicator
1088  */
1089 
1090 static int
1091 ng_btsocket_l2cap_process_l2ca_discon_ind(struct ng_mesg *msg,
1092 		ng_btsocket_l2cap_rtentry_p rt)
1093 {
1094 	ng_l2cap_l2ca_discon_ind_ip	*ip = NULL;
1095 	ng_btsocket_l2cap_pcb_t		*pcb = NULL;
1096 
1097 	/* Check message */
1098 	if (msg->header.arglen != sizeof(*ip))
1099 		return (EMSGSIZE);
1100 
1101 	ip = (ng_l2cap_l2ca_discon_ind_ip *)(msg->data);
1102 
1103 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
1104 
1105 	/* Look for the socket with given channel ID */
1106 	pcb = ng_btsocket_l2cap_pcb_by_cid(&rt->src, ip->lcid,
1107 					   NG_L2CAP_L2CA_IDTYPE_BREDR);
1108 	if (pcb == NULL) {
1109 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1110 		return (0);
1111 	}
1112 
1113 	/*
1114 	 * Channel has already been destroyed, so disconnect the socket
1115 	 * and be done with it. If there was any pending request we can
1116 	 * not do anything here anyway.
1117 	 */
1118 
1119 	mtx_lock(&pcb->pcb_mtx);
1120 
1121        	NG_BTSOCKET_L2CAP_INFO(
1122 "%s: Got L2CA_Disconnect indicator, src bdaddr=%x:%x:%x:%x:%x:%x, " \
1123 "dst bdaddr=%x:%x:%x:%x:%x:%x, psm=%d, lcid=%d, state=%d\n",
1124 		__func__,
1125 		pcb->src.b[5], pcb->src.b[4], pcb->src.b[3],
1126 		pcb->src.b[2], pcb->src.b[1], pcb->src.b[0],
1127 		pcb->dst.b[5], pcb->dst.b[4], pcb->dst.b[3],
1128 		pcb->dst.b[2], pcb->dst.b[1], pcb->dst.b[0],
1129 		pcb->psm, pcb->cid, pcb->state);
1130 
1131 	if (pcb->flags & NG_BTSOCKET_L2CAP_TIMO)
1132 		ng_btsocket_l2cap_untimeout(pcb);
1133 
1134 	pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
1135 	soisdisconnected(pcb->so);
1136 
1137 	mtx_unlock(&pcb->pcb_mtx);
1138 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1139 
1140 	return (0);
1141 } /* ng_btsocket_l2cap_process_l2ca_discon_ind */
1142 
1143 /*
1144  * Process L2CA_Write response
1145  */
1146 
1147 static int
1148 ng_btsocket_l2cap_process_l2ca_write_rsp(struct ng_mesg *msg,
1149 		ng_btsocket_l2cap_rtentry_p rt)
1150 {
1151 	ng_l2cap_l2ca_write_op	*op = NULL;
1152 	ng_btsocket_l2cap_pcb_t	*pcb = NULL;
1153 
1154 	/* Check message */
1155 	if (msg->header.arglen != sizeof(*op))
1156 		return (EMSGSIZE);
1157 
1158 	op = (ng_l2cap_l2ca_write_op *)(msg->data);
1159 
1160 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
1161 
1162 	/* Look for the socket with given token */
1163 	pcb = ng_btsocket_l2cap_pcb_by_token(msg->header.token);
1164 	if (pcb == NULL) {
1165 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1166 		return (ENOENT);
1167 	}
1168 
1169 	mtx_lock(&pcb->pcb_mtx);
1170 
1171        	NG_BTSOCKET_L2CAP_INFO(
1172 "%s: Got L2CA_Write response, src bdaddr=%x:%x:%x:%x:%x:%x, " \
1173 "dst bdaddr=%x:%x:%x:%x:%x:%x, psm=%d, lcid=%d, result=%d, length=%d, " \
1174 "state=%d\n",		__func__,
1175 			pcb->src.b[5], pcb->src.b[4], pcb->src.b[3],
1176 			pcb->src.b[2], pcb->src.b[1], pcb->src.b[0],
1177 			pcb->dst.b[5], pcb->dst.b[4], pcb->dst.b[3],
1178 			pcb->dst.b[2], pcb->dst.b[1], pcb->dst.b[0],
1179 			pcb->psm, pcb->cid, op->result, op->length,
1180 			pcb->state);
1181 
1182 	if (pcb->state != NG_BTSOCKET_L2CAP_OPEN) {
1183 		mtx_unlock(&pcb->pcb_mtx);
1184 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1185 
1186 		return (ENOENT);
1187 	}
1188 
1189 	ng_btsocket_l2cap_untimeout(pcb);
1190 
1191 	/*
1192  	 * Check if we have more data to send
1193  	 */
1194 	sbdroprecord(&pcb->so->so_snd);
1195 	if (sbavail(&pcb->so->so_snd) > 0) {
1196 		if (ng_btsocket_l2cap_send2(pcb) == 0)
1197 			ng_btsocket_l2cap_timeout(pcb);
1198 		else
1199 			sbdroprecord(&pcb->so->so_snd); /* XXX */
1200 	}
1201 
1202 	/*
1203 	 * Now set the result, drop packet from the socket send queue and
1204 	 * ask for more (wakeup sender)
1205 	 */
1206 
1207 	pcb->so->so_error = ng_btsocket_l2cap_result2errno(op->result);
1208 	sowwakeup(pcb->so);
1209 
1210 	mtx_unlock(&pcb->pcb_mtx);
1211 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1212 
1213 	return (0);
1214 } /* ng_btsocket_l2cap_process_l2ca_write_rsp */
1215 
1216 /*
1217  * Send L2CA_Connect request
1218  */
1219 
1220 static int
1221 ng_btsocket_l2cap_send_l2ca_con_req(ng_btsocket_l2cap_pcb_p pcb)
1222 {
1223 	struct ng_mesg		*msg = NULL;
1224 	ng_l2cap_l2ca_con_ip	*ip = NULL;
1225 	int			 error = 0;
1226 
1227 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
1228 
1229 	if (pcb->rt == NULL ||
1230 	    pcb->rt->hook == NULL || NG_HOOK_NOT_VALID(pcb->rt->hook))
1231 		return (ENETDOWN);
1232 
1233 	NG_MKMESSAGE(msg, NGM_L2CAP_COOKIE, NGM_L2CAP_L2CA_CON,
1234 		sizeof(*ip), M_NOWAIT);
1235 	if (msg == NULL)
1236 		return (ENOMEM);
1237 
1238 	msg->header.token = pcb->token;
1239 
1240 	ip = (ng_l2cap_l2ca_con_ip *)(msg->data);
1241 	bcopy(&pcb->dst, &ip->bdaddr, sizeof(ip->bdaddr));
1242 	ip->psm = pcb->psm;
1243 	ip->linktype = ng_btsock_l2cap_addrtype_to_linktype(pcb->dsttype);
1244 	ip->idtype = pcb->idtype;
1245 	NG_SEND_MSG_HOOK(error, ng_btsocket_l2cap_node, msg,pcb->rt->hook, 0);
1246 
1247 	return (error);
1248 } /* ng_btsocket_l2cap_send_l2ca_con_req */
1249 
1250 /*
1251  * Send L2CA_Connect response
1252  */
1253 
1254 static int
1255 ng_btsocket_l2cap_send_l2ca_con_rsp_req(u_int32_t token,
1256 		ng_btsocket_l2cap_rtentry_p rt, bdaddr_p dst, int ident,
1257 					int lcid, int result, int linktype)
1258 {
1259 	struct ng_mesg			*msg = NULL;
1260 	ng_l2cap_l2ca_con_rsp_ip	*ip = NULL;
1261 	int				 error = 0;
1262 
1263 	if (rt == NULL || rt->hook == NULL || NG_HOOK_NOT_VALID(rt->hook))
1264 		return (ENETDOWN);
1265 
1266 	NG_MKMESSAGE(msg, NGM_L2CAP_COOKIE, NGM_L2CAP_L2CA_CON_RSP,
1267 		sizeof(*ip), M_NOWAIT);
1268 	if (msg == NULL)
1269 		return (ENOMEM);
1270 
1271 	msg->header.token = token;
1272 
1273 	ip = (ng_l2cap_l2ca_con_rsp_ip *)(msg->data);
1274 	bcopy(dst, &ip->bdaddr, sizeof(ip->bdaddr));
1275 	ip->ident = ident;
1276 	ip->lcid = lcid;
1277 	ip->linktype = linktype;
1278 	ip->result = result;
1279 	ip->status = 0;
1280 
1281 	NG_SEND_MSG_HOOK(error, ng_btsocket_l2cap_node, msg, rt->hook, 0);
1282 
1283 	return (error);
1284 } /* ng_btsocket_l2cap_send_l2ca_con_rsp_req */
1285 
1286 /*
1287  * Send L2CA_Config request
1288  */
1289 
1290 static int
1291 ng_btsocket_l2cap_send_l2ca_cfg_req(ng_btsocket_l2cap_pcb_p pcb)
1292 {
1293 	struct ng_mesg		*msg = NULL;
1294 	ng_l2cap_l2ca_cfg_ip	*ip = NULL;
1295 	int			 error = 0;
1296 
1297 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
1298 
1299 	if (pcb->rt == NULL ||
1300 	    pcb->rt->hook == NULL || NG_HOOK_NOT_VALID(pcb->rt->hook))
1301 		return (ENETDOWN);
1302 
1303 	NG_MKMESSAGE(msg, NGM_L2CAP_COOKIE, NGM_L2CAP_L2CA_CFG,
1304 		sizeof(*ip), M_NOWAIT);
1305 	if (msg == NULL)
1306 		return (ENOMEM);
1307 
1308 	msg->header.token = pcb->token;
1309 
1310 	ip = (ng_l2cap_l2ca_cfg_ip *)(msg->data);
1311 	ip->lcid = pcb->cid;
1312 	ip->imtu = pcb->imtu;
1313 	bcopy(&pcb->oflow, &ip->oflow, sizeof(ip->oflow));
1314 	ip->flush_timo = pcb->flush_timo;
1315 	ip->link_timo = pcb->link_timo;
1316 
1317 	NG_SEND_MSG_HOOK(error, ng_btsocket_l2cap_node, msg,pcb->rt->hook, 0);
1318 
1319 	return (error);
1320 } /* ng_btsocket_l2cap_send_l2ca_cfg_req */
1321 
1322 /*
1323  * Send L2CA_Config response
1324  */
1325 
1326 static int
1327 ng_btsocket_l2cap_send_l2ca_cfg_rsp(ng_btsocket_l2cap_pcb_p pcb)
1328 {
1329 	struct ng_mesg			*msg = NULL;
1330 	ng_l2cap_l2ca_cfg_rsp_ip	*ip = NULL;
1331 	int				 error = 0;
1332 
1333 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
1334 
1335 	if (pcb->rt == NULL ||
1336 	    pcb->rt->hook == NULL || NG_HOOK_NOT_VALID(pcb->rt->hook))
1337 		return (ENETDOWN);
1338 
1339 	NG_MKMESSAGE(msg, NGM_L2CAP_COOKIE, NGM_L2CAP_L2CA_CFG_RSP,
1340 		sizeof(*ip), M_NOWAIT);
1341 	if (msg == NULL)
1342 		return (ENOMEM);
1343 
1344 	msg->header.token = pcb->token;
1345 
1346 	ip = (ng_l2cap_l2ca_cfg_rsp_ip *)(msg->data);
1347 	ip->lcid = pcb->cid;
1348 	ip->omtu = pcb->omtu;
1349 	bcopy(&pcb->iflow, &ip->iflow, sizeof(ip->iflow));
1350 
1351 	NG_SEND_MSG_HOOK(error, ng_btsocket_l2cap_node, msg, pcb->rt->hook, 0);
1352 
1353 	return (error);
1354 } /* ng_btsocket_l2cap_send_l2ca_cfg_rsp */
1355 
1356 /*
1357  * Send L2CA_Disconnect request
1358  */
1359 
1360 static int
1361 ng_btsocket_l2cap_send_l2ca_discon_req(u_int32_t token,
1362 		ng_btsocket_l2cap_pcb_p pcb)
1363 {
1364 	struct ng_mesg		*msg = NULL;
1365 	ng_l2cap_l2ca_discon_ip	*ip = NULL;
1366 	int			 error = 0;
1367 
1368 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
1369 
1370 	if (pcb->rt == NULL ||
1371 	    pcb->rt->hook == NULL || NG_HOOK_NOT_VALID(pcb->rt->hook))
1372 		return (ENETDOWN);
1373 
1374 	NG_MKMESSAGE(msg, NGM_L2CAP_COOKIE, NGM_L2CAP_L2CA_DISCON,
1375 		sizeof(*ip), M_NOWAIT);
1376 	if (msg == NULL)
1377 		return (ENOMEM);
1378 
1379 	msg->header.token = token;
1380 
1381 	ip = (ng_l2cap_l2ca_discon_ip *)(msg->data);
1382 	ip->lcid = pcb->cid;
1383 	ip->idtype = pcb->idtype;
1384 
1385 	NG_SEND_MSG_HOOK(error, ng_btsocket_l2cap_node, msg,pcb->rt->hook, 0);
1386 
1387 	return (error);
1388 } /* ng_btsocket_l2cap_send_l2ca_discon_req */
1389 
1390 /*****************************************************************************
1391  *****************************************************************************
1392  **                              Socket interface
1393  *****************************************************************************
1394  *****************************************************************************/
1395 
1396 /*
1397  * L2CAP sockets data input routine
1398  */
1399 
1400 static void
1401 ng_btsocket_l2cap_data_input(struct mbuf *m, hook_p hook)
1402 {
1403 	ng_l2cap_hdr_t			*hdr = NULL;
1404 	ng_l2cap_clt_hdr_t		*clt_hdr = NULL;
1405 	ng_btsocket_l2cap_pcb_t		*pcb = NULL;
1406 	ng_btsocket_l2cap_rtentry_t	*rt = NULL;
1407 	uint16_t idtype;
1408 
1409 	if (hook == NULL) {
1410 		NG_BTSOCKET_L2CAP_ALERT(
1411 "%s: Invalid source hook for L2CAP data packet\n", __func__);
1412 		goto drop;
1413 	}
1414 
1415 	rt = (ng_btsocket_l2cap_rtentry_t *) NG_HOOK_PRIVATE(hook);
1416 	if (rt == NULL) {
1417 		NG_BTSOCKET_L2CAP_ALERT(
1418 "%s: Could not find out source bdaddr for L2CAP data packet\n", __func__);
1419 		goto drop;
1420 	}
1421 
1422 	m = m_pullup(m, sizeof(uint16_t));
1423 	idtype = *mtod(m, uint16_t *);
1424 	m_adj(m, sizeof(uint16_t));
1425 
1426 	/* Make sure we can access header */
1427 	if (m->m_pkthdr.len < sizeof(*hdr)) {
1428 		NG_BTSOCKET_L2CAP_ERR(
1429 "%s: L2CAP data packet too small, len=%d\n", __func__, m->m_pkthdr.len);
1430 		goto drop;
1431 	}
1432 
1433 	if (m->m_len < sizeof(*hdr)) {
1434 		m = m_pullup(m, sizeof(*hdr));
1435 		if (m == NULL)
1436 			goto drop;
1437 	}
1438 
1439 	/* Strip L2CAP packet header and verify packet length */
1440 	hdr = mtod(m, ng_l2cap_hdr_t *);
1441 	m_adj(m, sizeof(*hdr));
1442 
1443 	if (hdr->length != m->m_pkthdr.len) {
1444 		NG_BTSOCKET_L2CAP_ERR(
1445 "%s: Bad L2CAP data packet length, len=%d, length=%d\n",
1446 			__func__, m->m_pkthdr.len, hdr->length);
1447 		goto drop;
1448 	}
1449 
1450 	/*
1451 	 * Now process packet. Two cases:
1452 	 *
1453 	 * 1) Normal packet (cid != 2) then find connected socket and append
1454 	 *    mbuf to the socket queue. Wakeup socket.
1455 	 *
1456 	 * 2) Broadcast packet (cid == 2) then find all sockets that connected
1457 	 *    to the given PSM and have SO_BROADCAST bit set and append mbuf
1458 	 *    to the socket queue. Wakeup socket.
1459 	 */
1460 
1461 	NG_BTSOCKET_L2CAP_INFO(
1462 "%s: Received L2CAP data packet: src bdaddr=%x:%x:%x:%x:%x:%x, " \
1463 "dcid=%d, length=%d\n",
1464 		__func__,
1465 		rt->src.b[5], rt->src.b[4], rt->src.b[3],
1466 		rt->src.b[2], rt->src.b[1], rt->src.b[0],
1467 		hdr->dcid, hdr->length);
1468 
1469 	if ((hdr->dcid >= NG_L2CAP_FIRST_CID) ||
1470 	    (idtype == NG_L2CAP_L2CA_IDTYPE_ATT)||
1471 	    (idtype == NG_L2CAP_L2CA_IDTYPE_SMP)
1472 	    ){
1473 
1474 		mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
1475 
1476 		/* Normal packet: find connected socket */
1477 		pcb = ng_btsocket_l2cap_pcb_by_cid(&rt->src, hdr->dcid,idtype);
1478 		if (pcb == NULL) {
1479 			mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1480 			goto drop;
1481 		}
1482 
1483 		mtx_lock(&pcb->pcb_mtx);
1484 
1485 		if (pcb->state != NG_BTSOCKET_L2CAP_OPEN) {
1486 			NG_BTSOCKET_L2CAP_ERR(
1487 "%s: No connected socket found, src bdaddr=%x:%x:%x:%x:%x:%x, dcid=%d, " \
1488 "state=%d\n",			__func__,
1489 				rt->src.b[5], rt->src.b[4], rt->src.b[3],
1490 				rt->src.b[2], rt->src.b[1], rt->src.b[0],
1491 				hdr->dcid, pcb->state);
1492 
1493 			mtx_unlock(&pcb->pcb_mtx);
1494 			mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1495 			goto drop;
1496 		}
1497 
1498 		/* Check packet size against socket's incoming MTU */
1499 		if (hdr->length > pcb->imtu) {
1500 			NG_BTSOCKET_L2CAP_ERR(
1501 "%s: L2CAP data packet too big, src bdaddr=%x:%x:%x:%x:%x:%x, " \
1502 "dcid=%d, length=%d, imtu=%d\n",
1503 				__func__,
1504 				rt->src.b[5], rt->src.b[4], rt->src.b[3],
1505 				rt->src.b[2], rt->src.b[1], rt->src.b[0],
1506 				hdr->dcid, hdr->length, pcb->imtu);
1507 
1508 			mtx_unlock(&pcb->pcb_mtx);
1509 			mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1510 			goto drop;
1511 		}
1512 
1513 		/* Check if we have enough space in socket receive queue */
1514 		if (m->m_pkthdr.len > sbspace(&pcb->so->so_rcv)) {
1515 
1516 			/*
1517 			 * This is really bad. Receive queue on socket does
1518 			 * not have enough space for the packet. We do not
1519 			 * have any other choice but drop the packet. L2CAP
1520 			 * does not provide any flow control.
1521 			 */
1522 
1523 			NG_BTSOCKET_L2CAP_ERR(
1524 "%s: Not enough space in socket receive queue. Dropping L2CAP data packet, " \
1525 "src bdaddr=%x:%x:%x:%x:%x:%x, dcid=%d, len=%d, space=%ld\n",
1526 				__func__,
1527 				rt->src.b[5], rt->src.b[4], rt->src.b[3],
1528 				rt->src.b[2], rt->src.b[1], rt->src.b[0],
1529 				hdr->dcid, m->m_pkthdr.len,
1530 				sbspace(&pcb->so->so_rcv));
1531 
1532 			mtx_unlock(&pcb->pcb_mtx);
1533 			mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1534 			goto drop;
1535 		}
1536 
1537 		/* Append packet to the socket receive queue and wakeup */
1538 		sbappendrecord(&pcb->so->so_rcv, m);
1539 		m = NULL;
1540 
1541 		sorwakeup(pcb->so);
1542 
1543 		mtx_unlock(&pcb->pcb_mtx);
1544 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1545 	} else if (hdr->dcid == NG_L2CAP_CLT_CID) {
1546 		/* Broadcast packet: give packet to all sockets  */
1547 
1548 		/* Check packet size against connectionless MTU */
1549 		if (hdr->length > NG_L2CAP_MTU_DEFAULT) {
1550 			NG_BTSOCKET_L2CAP_ERR(
1551 "%s: Connectionless L2CAP data packet too big, " \
1552 "src bdaddr=%x:%x:%x:%x:%x:%x, length=%d\n",
1553 				__func__,
1554 				rt->src.b[5], rt->src.b[4], rt->src.b[3],
1555 				rt->src.b[2], rt->src.b[1], rt->src.b[0],
1556 				hdr->length);
1557 			goto drop;
1558 		}
1559 
1560 		/* Make sure we can access connectionless header */
1561 		if (m->m_pkthdr.len < sizeof(*clt_hdr)) {
1562 			NG_BTSOCKET_L2CAP_ERR(
1563 "%s: Can not get L2CAP connectionless packet header, " \
1564 "src bdaddr=%x:%x:%x:%x:%x:%x, length=%d\n",
1565 				__func__,
1566 				rt->src.b[5], rt->src.b[4], rt->src.b[3],
1567 				rt->src.b[2], rt->src.b[1], rt->src.b[0],
1568 				hdr->length);
1569 			goto drop;
1570 		}
1571 
1572 		if (m->m_len < sizeof(*clt_hdr)) {
1573 			m = m_pullup(m, sizeof(*clt_hdr));
1574 			if (m == NULL)
1575 				goto drop;
1576 		}
1577 
1578 		/* Strip connectionless header and deliver packet */
1579 		clt_hdr = mtod(m, ng_l2cap_clt_hdr_t *);
1580 		m_adj(m, sizeof(*clt_hdr));
1581 
1582 		NG_BTSOCKET_L2CAP_INFO(
1583 "%s: Got L2CAP connectionless data packet, " \
1584 "src bdaddr=%x:%x:%x:%x:%x:%x, psm=%d, length=%d\n",
1585 			__func__,
1586 			rt->src.b[5], rt->src.b[4], rt->src.b[3],
1587 			rt->src.b[2], rt->src.b[1], rt->src.b[0],
1588 			clt_hdr->psm, hdr->length);
1589 
1590 		mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
1591 
1592 		LIST_FOREACH(pcb, &ng_btsocket_l2cap_sockets, next) {
1593 			struct mbuf	*copy = NULL;
1594 
1595 			mtx_lock(&pcb->pcb_mtx);
1596 
1597 			if (bcmp(&rt->src, &pcb->src, sizeof(pcb->src)) != 0 ||
1598 			    pcb->psm != clt_hdr->psm ||
1599 			    pcb->state != NG_BTSOCKET_L2CAP_OPEN ||
1600 			    (pcb->so->so_options & SO_BROADCAST) == 0 ||
1601 			    m->m_pkthdr.len > sbspace(&pcb->so->so_rcv))
1602 				goto next;
1603 
1604 			/*
1605 			 * Create a copy of the packet and append it to the
1606 			 * socket's queue. If m_dup() failed - no big deal
1607 			 * it is a broadcast traffic after all
1608 			 */
1609 
1610 			copy = m_dup(m, M_NOWAIT);
1611 			if (copy != NULL) {
1612 				sbappendrecord(&pcb->so->so_rcv, copy);
1613 				sorwakeup(pcb->so);
1614 			}
1615 next:
1616 			mtx_unlock(&pcb->pcb_mtx);
1617 		}
1618 
1619 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1620 	}
1621 drop:
1622 	NG_FREE_M(m); /* checks for m != NULL */
1623 } /* ng_btsocket_l2cap_data_input */
1624 
1625 /*
1626  * L2CAP sockets default message input routine
1627  */
1628 
1629 static void
1630 ng_btsocket_l2cap_default_msg_input(struct ng_mesg *msg, hook_p hook)
1631 {
1632 	switch (msg->header.cmd) {
1633 	case NGM_L2CAP_NODE_HOOK_INFO: {
1634 		ng_btsocket_l2cap_rtentry_t	*rt = NULL;
1635 		ng_l2cap_node_hook_info_ep *ep =
1636 		  (ng_l2cap_node_hook_info_ep *)msg->data;
1637 		if (hook == NULL || msg->header.arglen != sizeof(*ep))
1638 			break;
1639 
1640 		if (bcmp(&ep->addr, NG_HCI_BDADDR_ANY, sizeof(bdaddr_t)) == 0)
1641 			break;
1642 
1643 		mtx_lock(&ng_btsocket_l2cap_rt_mtx);
1644 
1645 		rt = (ng_btsocket_l2cap_rtentry_t *) NG_HOOK_PRIVATE(hook);
1646 		if (rt == NULL) {
1647 			rt = malloc(sizeof(*rt),
1648 				M_NETGRAPH_BTSOCKET_L2CAP, M_NOWAIT|M_ZERO);
1649 			if (rt == NULL) {
1650 				mtx_unlock(&ng_btsocket_l2cap_rt_mtx);
1651 				break;
1652 			}
1653 
1654 			LIST_INSERT_HEAD(&ng_btsocket_l2cap_rt, rt, next);
1655 
1656 			NG_HOOK_SET_PRIVATE(hook, rt);
1657 		}
1658 
1659 		bcopy(&ep->addr, &rt->src, sizeof(rt->src));
1660 		rt->hook = hook;
1661 
1662 		mtx_unlock(&ng_btsocket_l2cap_rt_mtx);
1663 
1664 		NG_BTSOCKET_L2CAP_INFO(
1665 "%s: Updating hook \"%s\", src bdaddr=%x:%x:%x:%x:%x:%x\n",
1666 			__func__, NG_HOOK_NAME(hook),
1667 			rt->src.b[5], rt->src.b[4], rt->src.b[3],
1668 			rt->src.b[2], rt->src.b[1], rt->src.b[0]);
1669 		} break;
1670 
1671 	default:
1672 		NG_BTSOCKET_L2CAP_WARN(
1673 "%s: Unknown message, cmd=%d\n", __func__, msg->header.cmd);
1674 		break;
1675 	}
1676 
1677 	NG_FREE_MSG(msg); /* Checks for msg != NULL */
1678 } /* ng_btsocket_l2cap_default_msg_input */
1679 
1680 /*
1681  * L2CAP sockets L2CA message input routine
1682  */
1683 
1684 static void
1685 ng_btsocket_l2cap_l2ca_msg_input(struct ng_mesg *msg, hook_p hook)
1686 {
1687 	ng_btsocket_l2cap_rtentry_p	rt = NULL;
1688 
1689 	if (hook == NULL) {
1690 		NG_BTSOCKET_L2CAP_ALERT(
1691 "%s: Invalid source hook for L2CA message\n", __func__);
1692 		goto drop;
1693 	}
1694 
1695 	rt = (ng_btsocket_l2cap_rtentry_p) NG_HOOK_PRIVATE(hook);
1696 	if (rt == NULL) {
1697 		NG_BTSOCKET_L2CAP_ALERT(
1698 "%s: Could not find out source bdaddr for L2CA message\n", __func__);
1699 		goto drop;
1700 	}
1701 
1702 	switch (msg->header.cmd) {
1703 	case NGM_L2CAP_L2CA_CON: /* L2CA_Connect response */
1704 		ng_btsocket_l2cap_process_l2ca_con_req_rsp(msg, rt);
1705 		break;
1706 
1707 	case NGM_L2CAP_L2CA_CON_RSP: /* L2CA_ConnectRsp response */
1708 		ng_btsocket_l2cap_process_l2ca_con_rsp_rsp(msg, rt);
1709 		break;
1710 
1711 	case NGM_L2CAP_L2CA_CON_IND: /* L2CA_Connect indicator */
1712 		ng_btsocket_l2cap_process_l2ca_con_ind(msg, rt);
1713 		break;
1714 
1715 	case NGM_L2CAP_L2CA_CFG: /* L2CA_Config response */
1716 		ng_btsocket_l2cap_process_l2ca_cfg_req_rsp(msg, rt);
1717 		break;
1718 
1719 	case NGM_L2CAP_L2CA_CFG_RSP: /* L2CA_ConfigRsp response */
1720 		ng_btsocket_l2cap_process_l2ca_cfg_rsp_rsp(msg, rt);
1721 		break;
1722 
1723 	case NGM_L2CAP_L2CA_CFG_IND: /* L2CA_Config indicator */
1724 		ng_btsocket_l2cap_process_l2ca_cfg_ind(msg, rt);
1725 		break;
1726 
1727 	case NGM_L2CAP_L2CA_DISCON: /* L2CA_Disconnect response */
1728 		ng_btsocket_l2cap_process_l2ca_discon_rsp(msg, rt);
1729 		break;
1730 
1731 	case NGM_L2CAP_L2CA_DISCON_IND: /* L2CA_Disconnect indicator */
1732 		ng_btsocket_l2cap_process_l2ca_discon_ind(msg, rt);
1733 		break;
1734 
1735 	case NGM_L2CAP_L2CA_WRITE: /* L2CA_Write response */
1736 		ng_btsocket_l2cap_process_l2ca_write_rsp(msg, rt);
1737 		break;
1738 	case NGM_L2CAP_L2CA_ENC_CHANGE:
1739 		ng_btsocket_l2cap_process_l2ca_enc_change(msg, rt);
1740 
1741 		break;
1742 	/* XXX FIXME add other L2CA messages */
1743 
1744 	default:
1745 		NG_BTSOCKET_L2CAP_WARN(
1746 "%s: Unknown L2CA message, cmd=%d\n", __func__, msg->header.cmd);
1747 		break;
1748 	}
1749 drop:
1750 	NG_FREE_MSG(msg);
1751 } /* ng_btsocket_l2cap_l2ca_msg_input */
1752 
1753 /*
1754  * L2CAP sockets input routine
1755  */
1756 
1757 static void
1758 ng_btsocket_l2cap_input(void *context, int pending)
1759 {
1760 	item_p	item = NULL;
1761 	hook_p	hook = NULL;
1762 
1763 	for (;;) {
1764 		mtx_lock(&ng_btsocket_l2cap_queue_mtx);
1765 		NG_BT_ITEMQ_DEQUEUE(&ng_btsocket_l2cap_queue, item);
1766 		mtx_unlock(&ng_btsocket_l2cap_queue_mtx);
1767 
1768 		if (item == NULL)
1769 			break;
1770 
1771 		NGI_GET_HOOK(item, hook);
1772 		if (hook != NULL && NG_HOOK_NOT_VALID(hook))
1773 			goto drop;
1774 
1775 		switch(item->el_flags & NGQF_TYPE) {
1776 		case NGQF_DATA: {
1777 			struct mbuf     *m = NULL;
1778 
1779 			NGI_GET_M(item, m);
1780 			ng_btsocket_l2cap_data_input(m, hook);
1781 			} break;
1782 
1783 		case NGQF_MESG: {
1784 			struct ng_mesg  *msg = NULL;
1785 
1786 			NGI_GET_MSG(item, msg);
1787 
1788 			switch (msg->header.cmd) {
1789 			case NGM_L2CAP_L2CA_CON:
1790 			case NGM_L2CAP_L2CA_CON_RSP:
1791 			case NGM_L2CAP_L2CA_CON_IND:
1792 			case NGM_L2CAP_L2CA_CFG:
1793 			case NGM_L2CAP_L2CA_CFG_RSP:
1794 			case NGM_L2CAP_L2CA_CFG_IND:
1795 			case NGM_L2CAP_L2CA_DISCON:
1796 			case NGM_L2CAP_L2CA_DISCON_IND:
1797 			case NGM_L2CAP_L2CA_WRITE:
1798 			case NGM_L2CAP_L2CA_ENC_CHANGE:
1799 			/* XXX FIXME add other L2CA messages */
1800 				ng_btsocket_l2cap_l2ca_msg_input(msg, hook);
1801 				break;
1802 
1803 			default:
1804 				ng_btsocket_l2cap_default_msg_input(msg, hook);
1805 				break;
1806 			}
1807 			} break;
1808 
1809 		default:
1810 			KASSERT(0,
1811 ("%s: invalid item type=%ld\n", __func__, (item->el_flags & NGQF_TYPE)));
1812 			break;
1813 		}
1814 drop:
1815 		if (hook != NULL)
1816 			NG_HOOK_UNREF(hook);
1817 
1818 		NG_FREE_ITEM(item);
1819 	}
1820 } /* ng_btsocket_l2cap_input */
1821 
1822 /*
1823  * Route cleanup task. Gets scheduled when hook is disconnected. Here we
1824  * will find all sockets that use "invalid" hook and disconnect them.
1825  */
1826 
1827 static void
1828 ng_btsocket_l2cap_rtclean(void *context, int pending)
1829 {
1830 	ng_btsocket_l2cap_pcb_p		pcb = NULL, pcb_next = NULL;
1831 	ng_btsocket_l2cap_rtentry_p	rt = NULL;
1832 
1833 	mtx_lock(&ng_btsocket_l2cap_rt_mtx);
1834 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
1835 
1836 	/*
1837 	 * First disconnect all sockets that use "invalid" hook
1838 	 */
1839 
1840 	for (pcb = LIST_FIRST(&ng_btsocket_l2cap_sockets); pcb != NULL; ) {
1841 		mtx_lock(&pcb->pcb_mtx);
1842 		pcb_next = LIST_NEXT(pcb, next);
1843 
1844 		if (pcb->rt != NULL &&
1845 		    pcb->rt->hook != NULL && NG_HOOK_NOT_VALID(pcb->rt->hook)) {
1846 			if (pcb->flags & NG_BTSOCKET_L2CAP_TIMO)
1847 				ng_btsocket_l2cap_untimeout(pcb);
1848 
1849 			pcb->so->so_error = ENETDOWN;
1850 			pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
1851 			soisdisconnected(pcb->so);
1852 
1853 			pcb->token = 0;
1854 			pcb->cid = 0;
1855 			pcb->rt = NULL;
1856 		}
1857 
1858 		mtx_unlock(&pcb->pcb_mtx);
1859 		pcb = pcb_next;
1860 	}
1861 
1862 	/*
1863 	 * Now cleanup routing table
1864 	 */
1865 
1866 	for (rt = LIST_FIRST(&ng_btsocket_l2cap_rt); rt != NULL; ) {
1867 		ng_btsocket_l2cap_rtentry_p	rt_next = LIST_NEXT(rt, next);
1868 
1869 		if (rt->hook != NULL && NG_HOOK_NOT_VALID(rt->hook)) {
1870 			LIST_REMOVE(rt, next);
1871 
1872 			NG_HOOK_SET_PRIVATE(rt->hook, NULL);
1873 			NG_HOOK_UNREF(rt->hook); /* Remove extra reference */
1874 
1875 			bzero(rt, sizeof(*rt));
1876 			free(rt, M_NETGRAPH_BTSOCKET_L2CAP);
1877 		}
1878 
1879 		rt = rt_next;
1880 	}
1881 
1882 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
1883 	mtx_unlock(&ng_btsocket_l2cap_rt_mtx);
1884 } /* ng_btsocket_l2cap_rtclean */
1885 
1886 /*
1887  * Initialize everything
1888  */
1889 
1890 void
1891 ng_btsocket_l2cap_init(void)
1892 {
1893 	int	error = 0;
1894 
1895 	/* Skip initialization of globals for non-default instances. */
1896 	if (!IS_DEFAULT_VNET(curvnet))
1897 		return;
1898 
1899 	ng_btsocket_l2cap_node = NULL;
1900 	ng_btsocket_l2cap_debug_level = NG_BTSOCKET_WARN_LEVEL;
1901 
1902 	/* Register Netgraph node type */
1903 	error = ng_newtype(&typestruct);
1904 	if (error != 0) {
1905 		NG_BTSOCKET_L2CAP_ALERT(
1906 "%s: Could not register Netgraph node type, error=%d\n", __func__, error);
1907 
1908                 return;
1909 	}
1910 
1911 	/* Create Netgrapg node */
1912 	error = ng_make_node_common(&typestruct, &ng_btsocket_l2cap_node);
1913 	if (error != 0) {
1914 		NG_BTSOCKET_L2CAP_ALERT(
1915 "%s: Could not create Netgraph node, error=%d\n", __func__, error);
1916 
1917 		ng_btsocket_l2cap_node = NULL;
1918 
1919 		return;
1920 	}
1921 
1922 	error = ng_name_node(ng_btsocket_l2cap_node,
1923 				NG_BTSOCKET_L2CAP_NODE_TYPE);
1924 	if (error != 0) {
1925 		NG_BTSOCKET_L2CAP_ALERT(
1926 "%s: Could not name Netgraph node, error=%d\n", __func__, error);
1927 
1928 		NG_NODE_UNREF(ng_btsocket_l2cap_node);
1929 		ng_btsocket_l2cap_node = NULL;
1930 
1931 		return;
1932 	}
1933 
1934 	/* Create input queue */
1935 	NG_BT_ITEMQ_INIT(&ng_btsocket_l2cap_queue, ifqmaxlen);
1936 	mtx_init(&ng_btsocket_l2cap_queue_mtx,
1937 		"btsocks_l2cap_queue_mtx", NULL, MTX_DEF);
1938 	TASK_INIT(&ng_btsocket_l2cap_queue_task, 0,
1939 		ng_btsocket_l2cap_input, NULL);
1940 
1941 	/* Create list of sockets */
1942 	LIST_INIT(&ng_btsocket_l2cap_sockets);
1943 	mtx_init(&ng_btsocket_l2cap_sockets_mtx,
1944 		"btsocks_l2cap_sockets_mtx", NULL, MTX_DEF);
1945 
1946 	/* Routing table */
1947 	LIST_INIT(&ng_btsocket_l2cap_rt);
1948 	mtx_init(&ng_btsocket_l2cap_rt_mtx,
1949 		"btsocks_l2cap_rt_mtx", NULL, MTX_DEF);
1950 	TASK_INIT(&ng_btsocket_l2cap_rt_task, 0,
1951 		ng_btsocket_l2cap_rtclean, NULL);
1952 } /* ng_btsocket_l2cap_init */
1953 
1954 /*
1955  * Abort connection on socket
1956  */
1957 
1958 void
1959 ng_btsocket_l2cap_abort(struct socket *so)
1960 {
1961 	so->so_error = ECONNABORTED;
1962 
1963 	(void)ng_btsocket_l2cap_disconnect(so);
1964 } /* ng_btsocket_l2cap_abort */
1965 
1966 void
1967 ng_btsocket_l2cap_close(struct socket *so)
1968 {
1969 
1970 	(void)ng_btsocket_l2cap_disconnect(so);
1971 } /* ng_btsocket_l2cap_close */
1972 
1973 /*
1974  * Accept connection on socket. Nothing to do here, socket must be connected
1975  * and ready, so just return peer address and be done with it.
1976  */
1977 
1978 int
1979 ng_btsocket_l2cap_accept(struct socket *so, struct sockaddr **nam)
1980 {
1981 	if (ng_btsocket_l2cap_node == NULL)
1982 		return (EINVAL);
1983 
1984 	return (ng_btsocket_l2cap_peeraddr(so, nam));
1985 } /* ng_btsocket_l2cap_accept */
1986 
1987 /*
1988  * Create and attach new socket
1989  */
1990 
1991 int
1992 ng_btsocket_l2cap_attach(struct socket *so, int proto, struct thread *td)
1993 {
1994 	static u_int32_t	token = 0;
1995 	ng_btsocket_l2cap_pcb_p	pcb = so2l2cap_pcb(so);
1996 	int			error;
1997 
1998 	/* Check socket and protocol */
1999 	if (ng_btsocket_l2cap_node == NULL)
2000 		return (EPROTONOSUPPORT);
2001 	if (so->so_type != SOCK_SEQPACKET)
2002 		return (ESOCKTNOSUPPORT);
2003 
2004 #if 0 /* XXX sonewconn() calls "pru_attach" with proto == 0 */
2005 	if (proto != 0)
2006 		if (proto != BLUETOOTH_PROTO_L2CAP)
2007 			return (EPROTONOSUPPORT);
2008 #endif /* XXX */
2009 
2010 	if (pcb != NULL)
2011 		return (EISCONN);
2012 
2013 	/* Reserve send and receive space if it is not reserved yet */
2014 	if ((so->so_snd.sb_hiwat == 0) || (so->so_rcv.sb_hiwat == 0)) {
2015 		error = soreserve(so, NG_BTSOCKET_L2CAP_SENDSPACE,
2016 					NG_BTSOCKET_L2CAP_RECVSPACE);
2017 		if (error != 0)
2018 			return (error);
2019 	}
2020 
2021 	/* Allocate the PCB */
2022         pcb = malloc(sizeof(*pcb),
2023 		M_NETGRAPH_BTSOCKET_L2CAP, M_NOWAIT | M_ZERO);
2024         if (pcb == NULL)
2025                 return (ENOMEM);
2026 
2027 	/* Link the PCB and the socket */
2028 	so->so_pcb = (caddr_t) pcb;
2029 	pcb->so = so;
2030 	pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
2031 
2032 	/* Initialize PCB */
2033 	pcb->imtu = pcb->omtu = NG_L2CAP_MTU_DEFAULT;
2034 
2035 	/* Default flow */
2036 	pcb->iflow.flags = 0x0;
2037 	pcb->iflow.service_type = NG_HCI_SERVICE_TYPE_BEST_EFFORT;
2038 	pcb->iflow.token_rate = 0xffffffff; /* maximum */
2039 	pcb->iflow.token_bucket_size = 0xffffffff; /* maximum */
2040 	pcb->iflow.peak_bandwidth = 0x00000000; /* maximum */
2041 	pcb->iflow.latency = 0xffffffff; /* don't care */
2042 	pcb->iflow.delay_variation = 0xffffffff; /* don't care */
2043 
2044 	bcopy(&pcb->iflow, &pcb->oflow, sizeof(pcb->oflow));
2045 
2046 	pcb->flush_timo = NG_L2CAP_FLUSH_TIMO_DEFAULT;
2047 	pcb->link_timo = NG_L2CAP_LINK_TIMO_DEFAULT;
2048 
2049 	/*
2050 	 * XXX Mark PCB mutex as DUPOK to prevent "duplicated lock of
2051 	 * the same type" message. When accepting new L2CAP connection
2052 	 * ng_btsocket_l2cap_process_l2ca_con_ind() holds both PCB mutexes
2053 	 * for "old" (accepting) PCB and "new" (created) PCB.
2054 	 */
2055 
2056 	mtx_init(&pcb->pcb_mtx, "btsocks_l2cap_pcb_mtx", NULL,
2057 		MTX_DEF|MTX_DUPOK);
2058 	callout_init_mtx(&pcb->timo, &pcb->pcb_mtx, 0);
2059 
2060         /*
2061 	 * Add the PCB to the list
2062 	 *
2063 	 * XXX FIXME VERY IMPORTANT!
2064 	 *
2065 	 * This is totally FUBAR. We could get here in two cases:
2066 	 *
2067 	 * 1) When user calls socket()
2068 	 * 2) When we need to accept new incomming connection and call
2069 	 *    sonewconn()
2070 	 *
2071 	 * In the first case we must acquire ng_btsocket_l2cap_sockets_mtx.
2072 	 * In the second case we hold ng_btsocket_l2cap_sockets_mtx already.
2073 	 * So we now need to distinguish between these cases. From reading
2074 	 * /sys/kern/uipc_socket.c we can find out that sonewconn() calls
2075 	 * pru_attach with proto == 0 and td == NULL. For now use this fact
2076 	 * to figure out if we were called from socket() or from sonewconn().
2077 	 */
2078 
2079 	if (td != NULL)
2080 		mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
2081 	else
2082 		mtx_assert(&ng_btsocket_l2cap_sockets_mtx, MA_OWNED);
2083 
2084 	/* Set PCB token. Use ng_btsocket_l2cap_sockets_mtx for protection */
2085 	if (++ token == 0)
2086 		token ++;
2087 
2088 	pcb->token = token;
2089 
2090 	LIST_INSERT_HEAD(&ng_btsocket_l2cap_sockets, pcb, next);
2091 
2092 	if (td != NULL)
2093 		mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
2094 
2095         return (0);
2096 } /* ng_btsocket_l2cap_attach */
2097 
2098 /*
2099  * Bind socket
2100  */
2101 
2102 int
2103 ng_btsocket_l2cap_bind(struct socket *so, struct sockaddr *nam,
2104 		struct thread *td)
2105 {
2106 	ng_btsocket_l2cap_pcb_t	*pcb = NULL;
2107 	struct sockaddr_l2cap	*sa = (struct sockaddr_l2cap *) nam;
2108 	int			 psm, error = 0;
2109 
2110 	if (ng_btsocket_l2cap_node == NULL)
2111 		return (EINVAL);
2112 
2113 	/* Verify address */
2114 	if (sa == NULL)
2115 		return (EINVAL);
2116 	if (sa->l2cap_family != AF_BLUETOOTH)
2117 		return (EAFNOSUPPORT);
2118 	/*For the time being, Not support LE binding.*/
2119 	if ((sa->l2cap_len != sizeof(*sa))&&
2120 	    (sa->l2cap_len != sizeof(struct sockaddr_l2cap_compat)))
2121 		return (EINVAL);
2122 
2123 	psm = le16toh(sa->l2cap_psm);
2124 
2125 	/*
2126 	 * Check if other socket has this address already (look for exact
2127 	 * match PSM and bdaddr) and assign socket address if it's available.
2128 	 *
2129 	 * Note: socket can be bound to ANY PSM (zero) thus allowing several
2130 	 * channels with the same PSM between the same pair of BD_ADDR'es.
2131 	 */
2132 
2133 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
2134 
2135 	LIST_FOREACH(pcb, &ng_btsocket_l2cap_sockets, next)
2136 		if (psm != 0 && psm == pcb->psm &&
2137 		    bcmp(&pcb->src, &sa->l2cap_bdaddr, sizeof(bdaddr_t)) == 0)
2138 			break;
2139 
2140 	if (pcb == NULL) {
2141 		/* Set socket address */
2142 		pcb = so2l2cap_pcb(so);
2143 		if (pcb != NULL) {
2144 			bcopy(&sa->l2cap_bdaddr, &pcb->src, sizeof(pcb->src));
2145 			pcb->psm = psm;
2146 		} else
2147 			error = EINVAL;
2148 	} else
2149 		error = EADDRINUSE;
2150 
2151 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
2152 
2153 	return (error);
2154 } /* ng_btsocket_l2cap_bind */
2155 
2156 /*
2157  * Connect socket
2158  */
2159 
2160 int
2161 ng_btsocket_l2cap_connect(struct socket *so, struct sockaddr *nam,
2162 		struct thread *td)
2163 {
2164 	ng_btsocket_l2cap_pcb_t		*pcb = so2l2cap_pcb(so);
2165 	struct sockaddr_l2cap_compat	*sal = (struct sockaddr_l2cap_compat *) nam;
2166 	struct sockaddr_l2cap *sa  = (struct sockaddr_l2cap *)nam;
2167 	struct sockaddr_l2cap  ba;
2168 	ng_btsocket_l2cap_rtentry_t	*rt = NULL;
2169 	int				 have_src, error = 0;
2170 	int idtype = NG_L2CAP_L2CA_IDTYPE_BREDR;
2171 	/* Check socket */
2172 	if (pcb == NULL)
2173 		return (EINVAL);
2174 	if (ng_btsocket_l2cap_node == NULL)
2175 		return (EINVAL);
2176 	if (pcb->state == NG_BTSOCKET_L2CAP_CONNECTING)
2177 		return (EINPROGRESS);
2178 
2179 	/* Verify address */
2180 	if (sa == NULL)
2181 		return (EINVAL);
2182 	if (sa->l2cap_family != AF_BLUETOOTH)
2183 		return (EAFNOSUPPORT);
2184 	if (sa->l2cap_len == sizeof(*sal)){
2185 		bcopy(sal, &ba, sizeof(*sal));
2186 		sa = &ba;
2187 		sa->l2cap_len = sizeof(*sa);
2188 		sa->l2cap_bdaddr_type = BDADDR_BREDR;
2189 	}
2190 	if (sa->l2cap_len != sizeof(*sa))
2191 		return (EINVAL);
2192 	if ((sa->l2cap_psm &&  sa->l2cap_cid))
2193 		return EINVAL;
2194 	if (bcmp(&sa->l2cap_bdaddr, NG_HCI_BDADDR_ANY, sizeof(bdaddr_t)) == 0)
2195 		return (EDESTADDRREQ);
2196 	if((sa->l2cap_bdaddr_type == BDADDR_BREDR)&&
2197 	   (sa->l2cap_psm == 0))
2198 		return EDESTADDRREQ;
2199 	if(sa->l2cap_bdaddr_type != BDADDR_BREDR){
2200 		if(sa->l2cap_cid == NG_L2CAP_ATT_CID){
2201 			idtype = NG_L2CAP_L2CA_IDTYPE_ATT;
2202 		}else if (sa->l2cap_cid == NG_L2CAP_SMP_CID){
2203 			idtype =NG_L2CAP_L2CA_IDTYPE_SMP;
2204 		}else{
2205 			//if cid == 0 idtype = NG_L2CAP_L2CA_IDTYPE_LE;
2206 			// Not supported yet
2207 			return EINVAL;
2208 		}
2209 	}
2210 	if (pcb->psm != 0 && pcb->psm != le16toh(sa->l2cap_psm))
2211 		return (EINVAL);
2212 	/*
2213 	 * Routing. Socket should be bound to some source address. The source
2214 	 * address can be ANY. Destination address must be set and it must not
2215 	 * be ANY. If source address is ANY then find first rtentry that has
2216 	 * src != dst.
2217 	 */
2218 
2219 	mtx_lock(&ng_btsocket_l2cap_rt_mtx);
2220 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
2221 	mtx_lock(&pcb->pcb_mtx);
2222 
2223 	/* Send destination address and PSM */
2224 	bcopy(&sa->l2cap_bdaddr, &pcb->dst, sizeof(pcb->dst));
2225 	pcb->psm = le16toh(sa->l2cap_psm);
2226 	pcb->dsttype = sa->l2cap_bdaddr_type;
2227 	pcb->cid = 0;
2228 	pcb->idtype = idtype;
2229 	pcb->rt = NULL;
2230 	have_src = bcmp(&pcb->src, NG_HCI_BDADDR_ANY, sizeof(pcb->src));
2231 
2232 	LIST_FOREACH(rt, &ng_btsocket_l2cap_rt, next) {
2233 		if (rt->hook == NULL || NG_HOOK_NOT_VALID(rt->hook))
2234 			continue;
2235 
2236 		/* Match src and dst */
2237 		if (have_src) {
2238 			if (bcmp(&pcb->src, &rt->src, sizeof(rt->src)) == 0)
2239 				break;
2240 		} else {
2241 			if (bcmp(&pcb->dst, &rt->src, sizeof(rt->src)) != 0)
2242 				break;
2243 		}
2244 	}
2245 
2246 	if (rt != NULL) {
2247 		pcb->rt = rt;
2248 
2249 		if (!have_src){
2250 			bcopy(&rt->src, &pcb->src, sizeof(pcb->src));
2251 			pcb->srctype =
2252 			  (sa->l2cap_bdaddr_type == BDADDR_BREDR)?
2253 			  BDADDR_BREDR : BDADDR_LE_PUBLIC;
2254 		}
2255 	} else
2256 		error = EHOSTUNREACH;
2257 
2258 	/*
2259 	 * Send L2CA_Connect request
2260 	 */
2261 
2262 	if (error == 0) {
2263 		error = ng_btsocket_l2cap_send_l2ca_con_req(pcb);
2264 		if (error == 0) {
2265 			pcb->flags |= NG_BTSOCKET_L2CAP_CLIENT;
2266 			pcb->state = NG_BTSOCKET_L2CAP_CONNECTING;
2267 			soisconnecting(pcb->so);
2268 
2269 			ng_btsocket_l2cap_timeout(pcb);
2270 		}
2271 	}
2272 
2273 	mtx_unlock(&pcb->pcb_mtx);
2274 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
2275 	mtx_unlock(&ng_btsocket_l2cap_rt_mtx);
2276 
2277 	return (error);
2278 } /* ng_btsocket_l2cap_connect */
2279 
2280 /*
2281  * Process ioctl's calls on socket
2282  */
2283 
2284 int
2285 ng_btsocket_l2cap_control(struct socket *so, u_long cmd, caddr_t data,
2286 		struct ifnet *ifp, struct thread *td)
2287 {
2288 	return (EINVAL);
2289 } /* ng_btsocket_l2cap_control */
2290 
2291 /*
2292  * Process getsockopt/setsockopt system calls
2293  */
2294 
2295 int
2296 ng_btsocket_l2cap_ctloutput(struct socket *so, struct sockopt *sopt)
2297 {
2298 	ng_btsocket_l2cap_pcb_p	pcb = so2l2cap_pcb(so);
2299 	int			error = 0;
2300 	ng_l2cap_cfg_opt_val_t	v;
2301 
2302 	if (pcb == NULL)
2303 		return (EINVAL);
2304 	if (ng_btsocket_l2cap_node == NULL)
2305 		return (EINVAL);
2306 
2307 	if (sopt->sopt_level != SOL_L2CAP)
2308 		return (0);
2309 
2310 	mtx_lock(&pcb->pcb_mtx);
2311 
2312 	switch (sopt->sopt_dir) {
2313 	case SOPT_GET:
2314 		switch (sopt->sopt_name) {
2315 		case SO_L2CAP_IMTU: /* get incoming MTU */
2316 			error = sooptcopyout(sopt, &pcb->imtu,
2317 						sizeof(pcb->imtu));
2318 			break;
2319 
2320 		case SO_L2CAP_OMTU: /* get outgoing (peer incoming) MTU */
2321 			error = sooptcopyout(sopt, &pcb->omtu,
2322 						sizeof(pcb->omtu));
2323 			break;
2324 
2325 		case SO_L2CAP_IFLOW: /* get incoming flow spec. */
2326 			error = sooptcopyout(sopt, &pcb->iflow,
2327 						sizeof(pcb->iflow));
2328 			break;
2329 
2330 		case SO_L2CAP_OFLOW: /* get outgoing flow spec. */
2331 			error = sooptcopyout(sopt, &pcb->oflow,
2332 						sizeof(pcb->oflow));
2333 			break;
2334 
2335 		case SO_L2CAP_FLUSH: /* get flush timeout */
2336 			error = sooptcopyout(sopt, &pcb->flush_timo,
2337 						sizeof(pcb->flush_timo));
2338 			break;
2339 		case SO_L2CAP_ENCRYPTED: /* get encrypt required */
2340 			error = sooptcopyout(sopt, &pcb->need_encrypt,
2341 						sizeof(pcb->need_encrypt));
2342 			break;
2343 
2344 
2345 		default:
2346 			error = ENOPROTOOPT;
2347 			break;
2348 		}
2349 		break;
2350 
2351 	case SOPT_SET:
2352 		/*
2353 		 * XXX
2354 		 * We do not allow to change these parameters while socket is
2355 		 * connected or we are in the process of creating a connection.
2356 		 * May be this should indicate re-configuration of the open
2357 		 * channel?
2358 		 */
2359 
2360 		if (pcb->state != NG_BTSOCKET_L2CAP_CLOSED) {
2361 			error = EACCES;
2362 			break;
2363 		}
2364 
2365 		switch (sopt->sopt_name) {
2366 		case SO_L2CAP_IMTU: /* set incoming MTU */
2367 			error = sooptcopyin(sopt, &v, sizeof(v), sizeof(v.mtu));
2368 			if (error == 0)
2369 				pcb->imtu = v.mtu;
2370 			break;
2371 
2372 		case SO_L2CAP_OFLOW: /* set outgoing flow spec. */
2373 			error = sooptcopyin(sopt, &v, sizeof(v),sizeof(v.flow));
2374 			if (error == 0)
2375 				bcopy(&v.flow, &pcb->oflow, sizeof(pcb->oflow));
2376 			break;
2377 
2378 		case SO_L2CAP_FLUSH: /* set flush timeout */
2379 			error = sooptcopyin(sopt, &v, sizeof(v),
2380 						sizeof(v.flush_timo));
2381 			if (error == 0)
2382 				pcb->flush_timo = v.flush_timo;
2383 			break;
2384 		case SO_L2CAP_ENCRYPTED: /*set connect encryption opt*/
2385 			if((pcb->state != NG_BTSOCKET_L2CAP_OPEN) &&
2386 			   (pcb->state != NG_BTSOCKET_L2CAP_W4_ENC_CHANGE)){
2387 				error = sooptcopyin(sopt, &v, sizeof(v),
2388 						    sizeof(v.encryption));
2389 				if(error == 0)
2390 					pcb->need_encrypt = (v.encryption)?1:0;
2391 			}else{
2392 				error = EINVAL;
2393 			}
2394 			break;
2395 		default:
2396 			error = ENOPROTOOPT;
2397 			break;
2398 		}
2399 		break;
2400 
2401 	default:
2402 		error = EINVAL;
2403 		break;
2404 	}
2405 
2406 	mtx_unlock(&pcb->pcb_mtx);
2407 
2408 	return (error);
2409 } /* ng_btsocket_l2cap_ctloutput */
2410 
2411 /*
2412  * Detach and destroy socket
2413  */
2414 
2415 void
2416 ng_btsocket_l2cap_detach(struct socket *so)
2417 {
2418 	ng_btsocket_l2cap_pcb_p	pcb = so2l2cap_pcb(so);
2419 
2420 	KASSERT(pcb != NULL, ("ng_btsocket_l2cap_detach: pcb == NULL"));
2421 
2422 	if (ng_btsocket_l2cap_node == NULL)
2423 		return;
2424 
2425 	mtx_lock(&ng_btsocket_l2cap_sockets_mtx);
2426 	mtx_lock(&pcb->pcb_mtx);
2427 
2428 	/* XXX what to do with pending request? */
2429 	if (pcb->flags & NG_BTSOCKET_L2CAP_TIMO)
2430 		ng_btsocket_l2cap_untimeout(pcb);
2431 
2432 	if (pcb->state != NG_BTSOCKET_L2CAP_CLOSED &&
2433 	    pcb->state != NG_BTSOCKET_L2CAP_DISCONNECTING)
2434 		/* Send disconnect request with "zero" token */
2435 		ng_btsocket_l2cap_send_l2ca_discon_req(0, pcb);
2436 
2437 	pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
2438 
2439 	LIST_REMOVE(pcb, next);
2440 
2441 	mtx_unlock(&pcb->pcb_mtx);
2442 	mtx_unlock(&ng_btsocket_l2cap_sockets_mtx);
2443 
2444 	mtx_destroy(&pcb->pcb_mtx);
2445 	bzero(pcb, sizeof(*pcb));
2446 	free(pcb, M_NETGRAPH_BTSOCKET_L2CAP);
2447 
2448 	soisdisconnected(so);
2449 	so->so_pcb = NULL;
2450 } /* ng_btsocket_l2cap_detach */
2451 
2452 /*
2453  * Disconnect socket
2454  */
2455 
2456 int
2457 ng_btsocket_l2cap_disconnect(struct socket *so)
2458 {
2459 	ng_btsocket_l2cap_pcb_p	pcb = so2l2cap_pcb(so);
2460 	int			error = 0;
2461 
2462 	if (pcb == NULL)
2463 		return (EINVAL);
2464 	if (ng_btsocket_l2cap_node == NULL)
2465 		return (EINVAL);
2466 
2467 	mtx_lock(&pcb->pcb_mtx);
2468 
2469 	if (pcb->state == NG_BTSOCKET_L2CAP_DISCONNECTING) {
2470 		mtx_unlock(&pcb->pcb_mtx);
2471 		return (EINPROGRESS);
2472 	}
2473 
2474 	if (pcb->state != NG_BTSOCKET_L2CAP_CLOSED) {
2475 		/* XXX FIXME what to do with pending request? */
2476 		if (pcb->flags & NG_BTSOCKET_L2CAP_TIMO)
2477 			ng_btsocket_l2cap_untimeout(pcb);
2478 
2479 		error = ng_btsocket_l2cap_send_l2ca_discon_req(pcb->token, pcb);
2480 		if (error == 0) {
2481 			pcb->state = NG_BTSOCKET_L2CAP_DISCONNECTING;
2482 			soisdisconnecting(so);
2483 
2484 			ng_btsocket_l2cap_timeout(pcb);
2485 		}
2486 
2487 		/* XXX FIXME what to do if error != 0 */
2488 	}
2489 
2490 	mtx_unlock(&pcb->pcb_mtx);
2491 
2492 	return (error);
2493 } /* ng_btsocket_l2cap_disconnect */
2494 
2495 /*
2496  * Listen on socket
2497  */
2498 
2499 int
2500 ng_btsocket_l2cap_listen(struct socket *so, int backlog, struct thread *td)
2501 {
2502 	ng_btsocket_l2cap_pcb_p	pcb = so2l2cap_pcb(so);
2503 	int error;
2504 
2505 	SOCK_LOCK(so);
2506 	error = solisten_proto_check(so);
2507 	if (error != 0)
2508 		goto out;
2509 	if (pcb == NULL) {
2510 		error = EINVAL;
2511 		goto out;
2512 	}
2513 	if (ng_btsocket_l2cap_node == NULL) {
2514 		error = EINVAL;
2515 		goto out;
2516 	}
2517 	if (pcb->psm == 0) {
2518 		error = EADDRNOTAVAIL;
2519 		goto out;
2520 	}
2521 	solisten_proto(so, backlog);
2522 out:
2523 	SOCK_UNLOCK(so);
2524 	return (error);
2525 } /* ng_btsocket_listen */
2526 
2527 /*
2528  * Get peer address
2529  */
2530 
2531 int
2532 ng_btsocket_l2cap_peeraddr(struct socket *so, struct sockaddr **nam)
2533 {
2534 	ng_btsocket_l2cap_pcb_p	pcb = so2l2cap_pcb(so);
2535 	struct sockaddr_l2cap	sa;
2536 
2537 	if (pcb == NULL)
2538 		return (EINVAL);
2539 	if (ng_btsocket_l2cap_node == NULL)
2540 		return (EINVAL);
2541 
2542 	bcopy(&pcb->dst, &sa.l2cap_bdaddr, sizeof(sa.l2cap_bdaddr));
2543 	sa.l2cap_psm = htole16(pcb->psm);
2544 	sa.l2cap_len = sizeof(sa);
2545 	sa.l2cap_family = AF_BLUETOOTH;
2546 	switch(pcb->idtype){
2547 	case NG_L2CAP_L2CA_IDTYPE_ATT:
2548 		sa.l2cap_cid = NG_L2CAP_ATT_CID;
2549 		break;
2550 	case NG_L2CAP_L2CA_IDTYPE_SMP:
2551 		sa.l2cap_cid = NG_L2CAP_SMP_CID;
2552 		break;
2553 	default:
2554 		sa.l2cap_cid = 0;
2555 		break;
2556 	}
2557 	sa.l2cap_bdaddr_type = pcb->dsttype;
2558 	*nam = sodupsockaddr((struct sockaddr *) &sa, M_NOWAIT);
2559 
2560 	return ((*nam == NULL)? ENOMEM : 0);
2561 } /* ng_btsocket_l2cap_peeraddr */
2562 
2563 /*
2564  * Send data to socket
2565  */
2566 
2567 int
2568 ng_btsocket_l2cap_send(struct socket *so, int flags, struct mbuf *m,
2569 		struct sockaddr *nam, struct mbuf *control, struct thread *td)
2570 {
2571 	ng_btsocket_l2cap_pcb_t	*pcb = so2l2cap_pcb(so);
2572 	int			 error = 0;
2573 
2574 	if (ng_btsocket_l2cap_node == NULL) {
2575 		error = ENETDOWN;
2576 		goto drop;
2577 	}
2578 
2579 	/* Check socket and input */
2580 	if (pcb == NULL || m == NULL || control != NULL) {
2581 		error = EINVAL;
2582 		goto drop;
2583 	}
2584 
2585 	mtx_lock(&pcb->pcb_mtx);
2586 
2587 	/* Make sure socket is connected */
2588 	if (pcb->state != NG_BTSOCKET_L2CAP_OPEN) {
2589 		mtx_unlock(&pcb->pcb_mtx);
2590 		error = ENOTCONN;
2591 		goto drop;
2592 	}
2593 
2594 	/* Check route */
2595 	if (pcb->rt == NULL ||
2596 	    pcb->rt->hook == NULL || NG_HOOK_NOT_VALID(pcb->rt->hook)) {
2597 		mtx_unlock(&pcb->pcb_mtx);
2598 		error = ENETDOWN;
2599 		goto drop;
2600 	}
2601 
2602 	/* Check packet size agains outgoing (peer's incoming) MTU) */
2603 	if (m->m_pkthdr.len > pcb->omtu) {
2604 		NG_BTSOCKET_L2CAP_ERR(
2605 "%s: Packet too big, len=%d, omtu=%d\n", __func__, m->m_pkthdr.len, pcb->omtu);
2606 
2607 		mtx_unlock(&pcb->pcb_mtx);
2608 		error = EMSGSIZE;
2609 		goto drop;
2610 	}
2611 
2612 	/*
2613 	 * First put packet on socket send queue. Then check if we have
2614 	 * pending timeout. If we do not have timeout then we must send
2615 	 * packet and schedule timeout. Otherwise do nothing and wait for
2616 	 * L2CA_WRITE_RSP.
2617 	 */
2618 
2619 	sbappendrecord(&pcb->so->so_snd, m);
2620 	m = NULL;
2621 
2622 	if (!(pcb->flags & NG_BTSOCKET_L2CAP_TIMO)) {
2623 		error = ng_btsocket_l2cap_send2(pcb);
2624 		if (error == 0)
2625 			ng_btsocket_l2cap_timeout(pcb);
2626 		else
2627 			sbdroprecord(&pcb->so->so_snd); /* XXX */
2628 	}
2629 
2630 	mtx_unlock(&pcb->pcb_mtx);
2631 drop:
2632 	NG_FREE_M(m); /* checks for != NULL */
2633 	NG_FREE_M(control);
2634 
2635 	return (error);
2636 } /* ng_btsocket_l2cap_send */
2637 
2638 /*
2639  * Send first packet in the socket queue to the L2CAP layer
2640  */
2641 
2642 static int
2643 ng_btsocket_l2cap_send2(ng_btsocket_l2cap_pcb_p pcb)
2644 {
2645 	struct	mbuf		*m = NULL;
2646 	ng_l2cap_l2ca_hdr_t	*hdr = NULL;
2647 	int			 error = 0;
2648 
2649 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
2650 
2651 	if (sbavail(&pcb->so->so_snd) == 0)
2652 		return (EINVAL); /* XXX */
2653 
2654 	m = m_dup(pcb->so->so_snd.sb_mb, M_NOWAIT);
2655 	if (m == NULL)
2656 		return (ENOBUFS);
2657 
2658 	/* Create L2CA packet header */
2659 	M_PREPEND(m, sizeof(*hdr), M_NOWAIT);
2660 	if (m != NULL)
2661 		if (m->m_len < sizeof(*hdr))
2662 			m = m_pullup(m, sizeof(*hdr));
2663 
2664 	if (m == NULL) {
2665 		NG_BTSOCKET_L2CAP_ERR(
2666 "%s: Failed to create L2CA packet header\n", __func__);
2667 
2668 		return (ENOBUFS);
2669 	}
2670 
2671 	hdr = mtod(m, ng_l2cap_l2ca_hdr_t *);
2672 	hdr->token = pcb->token;
2673 	hdr->length = m->m_pkthdr.len - sizeof(*hdr);
2674 	hdr->lcid = pcb->cid;
2675 	hdr->idtype = pcb->idtype;
2676 	NG_BTSOCKET_L2CAP_INFO(
2677 "%s: Sending packet: len=%d, length=%d, lcid=%d, token=%d, state=%d\n",
2678 		__func__, m->m_pkthdr.len, hdr->length, hdr->lcid,
2679 		hdr->token, pcb->state);
2680 
2681 	/*
2682 	 * If we got here than we have successfuly creates new L2CAP
2683 	 * data packet and now we can send it to the L2CAP layer
2684 	 */
2685 
2686 	NG_SEND_DATA_ONLY(error, pcb->rt->hook, m);
2687 
2688 	return (error);
2689 } /* ng_btsocket_l2cap_send2 */
2690 
2691 /*
2692  * Get socket address
2693  */
2694 
2695 int
2696 ng_btsocket_l2cap_sockaddr(struct socket *so, struct sockaddr **nam)
2697 {
2698 	ng_btsocket_l2cap_pcb_p	pcb = so2l2cap_pcb(so);
2699 	struct sockaddr_l2cap	sa;
2700 
2701 	if (pcb == NULL)
2702 		return (EINVAL);
2703 	if (ng_btsocket_l2cap_node == NULL)
2704 		return (EINVAL);
2705 
2706 	bcopy(&pcb->src, &sa.l2cap_bdaddr, sizeof(sa.l2cap_bdaddr));
2707 	sa.l2cap_psm = htole16(pcb->psm);
2708 	sa.l2cap_len = sizeof(sa);
2709 	sa.l2cap_family = AF_BLUETOOTH;
2710 	sa.l2cap_cid = 0;
2711 	sa.l2cap_bdaddr_type = pcb->srctype;
2712 
2713 	*nam = sodupsockaddr((struct sockaddr *) &sa, M_NOWAIT);
2714 
2715 	return ((*nam == NULL)? ENOMEM : 0);
2716 } /* ng_btsocket_l2cap_sockaddr */
2717 
2718 /*****************************************************************************
2719  *****************************************************************************
2720  **                              Misc. functions
2721  *****************************************************************************
2722  *****************************************************************************/
2723 
2724 /*
2725  * Look for the socket that listens on given PSM and bdaddr. Returns exact or
2726  * close match (if any). Caller must hold ng_btsocket_l2cap_sockets_mtx.
2727  */
2728 
2729 static ng_btsocket_l2cap_pcb_p
2730 ng_btsocket_l2cap_pcb_by_addr(bdaddr_p bdaddr, int psm)
2731 {
2732 	ng_btsocket_l2cap_pcb_p	p = NULL, p1 = NULL;
2733 
2734 	mtx_assert(&ng_btsocket_l2cap_sockets_mtx, MA_OWNED);
2735 
2736 	LIST_FOREACH(p, &ng_btsocket_l2cap_sockets, next) {
2737 		if (p->so == NULL || !(p->so->so_options & SO_ACCEPTCONN) ||
2738 		    p->psm != psm)
2739 			continue;
2740 
2741 		if (bcmp(&p->src, bdaddr, sizeof(p->src)) == 0)
2742 			break;
2743 
2744 		if (bcmp(&p->src, NG_HCI_BDADDR_ANY, sizeof(p->src)) == 0)
2745 			p1 = p;
2746 	}
2747 
2748 	return ((p != NULL)? p : p1);
2749 } /* ng_btsocket_l2cap_pcb_by_addr */
2750 
2751 /*
2752  * Look for the socket that has given token.
2753  * Caller must hold ng_btsocket_l2cap_sockets_mtx.
2754  */
2755 
2756 static ng_btsocket_l2cap_pcb_p
2757 ng_btsocket_l2cap_pcb_by_token(u_int32_t token)
2758 {
2759 	ng_btsocket_l2cap_pcb_p	p = NULL;
2760 
2761 	if (token == 0)
2762 		return (NULL);
2763 
2764 	mtx_assert(&ng_btsocket_l2cap_sockets_mtx, MA_OWNED);
2765 
2766 	LIST_FOREACH(p, &ng_btsocket_l2cap_sockets, next)
2767 		if (p->token == token)
2768 			break;
2769 
2770 	return (p);
2771 } /* ng_btsocket_l2cap_pcb_by_token */
2772 
2773 /*
2774  * Look for the socket that assigned to given source address and channel ID.
2775  * Caller must hold ng_btsocket_l2cap_sockets_mtx
2776  */
2777 
2778 static ng_btsocket_l2cap_pcb_p
2779 ng_btsocket_l2cap_pcb_by_cid(bdaddr_p src, int cid, int idtype)
2780 {
2781 	ng_btsocket_l2cap_pcb_p	p = NULL;
2782 
2783 	mtx_assert(&ng_btsocket_l2cap_sockets_mtx, MA_OWNED);
2784 
2785 	LIST_FOREACH(p, &ng_btsocket_l2cap_sockets, next){
2786 		if (p->cid == cid &&
2787 		    bcmp(src, &p->src, sizeof(p->src)) == 0&&
2788 		    p->idtype == idtype)
2789 			break;
2790 
2791 	}
2792 	return (p);
2793 } /* ng_btsocket_l2cap_pcb_by_cid */
2794 
2795 /*
2796  * Set timeout on socket
2797  */
2798 
2799 static void
2800 ng_btsocket_l2cap_timeout(ng_btsocket_l2cap_pcb_p pcb)
2801 {
2802 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
2803 
2804 	if (!(pcb->flags & NG_BTSOCKET_L2CAP_TIMO)) {
2805 		pcb->flags |= NG_BTSOCKET_L2CAP_TIMO;
2806 		callout_reset(&pcb->timo, bluetooth_l2cap_ertx_timeout(),
2807 		    ng_btsocket_l2cap_process_timeout, pcb);
2808 	} else
2809 		KASSERT(0,
2810 ("%s: Duplicated socket timeout?!\n", __func__));
2811 } /* ng_btsocket_l2cap_timeout */
2812 
2813 /*
2814  * Unset timeout on socket
2815  */
2816 
2817 static void
2818 ng_btsocket_l2cap_untimeout(ng_btsocket_l2cap_pcb_p pcb)
2819 {
2820 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
2821 
2822 	if (pcb->flags & NG_BTSOCKET_L2CAP_TIMO) {
2823 		callout_stop(&pcb->timo);
2824 		pcb->flags &= ~NG_BTSOCKET_L2CAP_TIMO;
2825 	} else
2826 		KASSERT(0,
2827 ("%s: No socket timeout?!\n", __func__));
2828 } /* ng_btsocket_l2cap_untimeout */
2829 
2830 /*
2831  * Process timeout on socket
2832  */
2833 
2834 static void
2835 ng_btsocket_l2cap_process_timeout(void *xpcb)
2836 {
2837 	ng_btsocket_l2cap_pcb_p	pcb = (ng_btsocket_l2cap_pcb_p) xpcb;
2838 
2839 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
2840 
2841 	pcb->flags &= ~NG_BTSOCKET_L2CAP_TIMO;
2842 	pcb->so->so_error = ETIMEDOUT;
2843 
2844 	switch (pcb->state) {
2845 	case NG_BTSOCKET_L2CAP_CONNECTING:
2846 	case NG_BTSOCKET_L2CAP_CONFIGURING:
2847 		/* Send disconnect request with "zero" token */
2848 		if (pcb->cid != 0)
2849 			ng_btsocket_l2cap_send_l2ca_discon_req(0, pcb);
2850 
2851 		/* ... and close the socket */
2852 		pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
2853 		soisdisconnected(pcb->so);
2854 		break;
2855 
2856 	case NG_BTSOCKET_L2CAP_OPEN:
2857 		/* Send timeout - drop packet and wakeup sender */
2858 		sbdroprecord(&pcb->so->so_snd);
2859 		sowwakeup(pcb->so);
2860 		break;
2861 
2862 	case NG_BTSOCKET_L2CAP_DISCONNECTING:
2863 		/* Disconnect timeout - disconnect the socket anyway */
2864 		pcb->state = NG_BTSOCKET_L2CAP_CLOSED;
2865 		soisdisconnected(pcb->so);
2866 		break;
2867 
2868 	default:
2869 		NG_BTSOCKET_L2CAP_ERR(
2870 "%s: Invalid socket state=%d\n", __func__, pcb->state);
2871 		break;
2872 	}
2873 } /* ng_btsocket_l2cap_process_timeout */
2874 
2875 /*
2876  * Translate HCI/L2CAP error code into "errno" code
2877  * XXX Note: Some L2CAP and HCI error codes have the same value, but
2878  *     different meaning
2879  */
2880 
2881 static int
2882 ng_btsocket_l2cap_result2errno(int result)
2883 {
2884 	switch (result) {
2885 	case 0x00: /* No error */
2886 		return (0);
2887 
2888 	case 0x01: /* Unknown HCI command */
2889 		return (ENODEV);
2890 
2891 	case 0x02: /* No connection */
2892 		return (ENOTCONN);
2893 
2894 	case 0x03: /* Hardware failure */
2895 		return (EIO);
2896 
2897 	case 0x04: /* Page timeout */
2898 		return (EHOSTDOWN);
2899 
2900 	case 0x05: /* Authentication failure */
2901 	case 0x06: /* Key missing */
2902 	case 0x18: /* Pairing not allowed */
2903 	case 0x21: /* Role change not allowed */
2904 	case 0x24: /* LMP PSU not allowed */
2905 	case 0x25: /* Encryption mode not acceptable */
2906 	case 0x26: /* Unit key used */
2907 		return (EACCES);
2908 
2909 	case 0x07: /* Memory full */
2910 		return (ENOMEM);
2911 
2912 	case 0x08:   /* Connection timeout */
2913 	case 0x10:   /* Host timeout */
2914 	case 0x22:   /* LMP response timeout */
2915 	case 0xee:   /* HCI timeout */
2916 	case 0xeeee: /* L2CAP timeout */
2917 		return (ETIMEDOUT);
2918 
2919 	case 0x09: /* Max number of connections */
2920 	case 0x0a: /* Max number of SCO connections to a unit */
2921 		return (EMLINK);
2922 
2923 	case 0x0b: /* ACL connection already exists */
2924 		return (EEXIST);
2925 
2926 	case 0x0c: /* Command disallowed */
2927 		return (EBUSY);
2928 
2929 	case 0x0d: /* Host rejected due to limited resources */
2930 	case 0x0e: /* Host rejected due to securiity reasons */
2931 	case 0x0f: /* Host rejected due to remote unit is a personal unit */
2932 	case 0x1b: /* SCO offset rejected */
2933 	case 0x1c: /* SCO interval rejected */
2934 	case 0x1d: /* SCO air mode rejected */
2935 		return (ECONNREFUSED);
2936 
2937 	case 0x11: /* Unsupported feature or parameter value */
2938 	case 0x19: /* Unknown LMP PDU */
2939 	case 0x1a: /* Unsupported remote feature */
2940 	case 0x20: /* Unsupported LMP parameter value */
2941 	case 0x27: /* QoS is not supported */
2942 	case 0x29: /* Paring with unit key not supported */
2943 		return (EOPNOTSUPP);
2944 
2945 	case 0x12: /* Invalid HCI command parameter */
2946 	case 0x1e: /* Invalid LMP parameters */
2947 		return (EINVAL);
2948 
2949 	case 0x13: /* Other end terminated connection: User ended connection */
2950 	case 0x14: /* Other end terminated connection: Low resources */
2951 	case 0x15: /* Other end terminated connection: About to power off */
2952 		return (ECONNRESET);
2953 
2954 	case 0x16: /* Connection terminated by local host */
2955 		return (ECONNABORTED);
2956 
2957 #if 0 /* XXX not yet */
2958 	case 0x17: /* Repeated attempts */
2959 	case 0x1f: /* Unspecified error */
2960 	case 0x23: /* LMP error transaction collision */
2961 	case 0x28: /* Instant passed */
2962 #endif
2963 	}
2964 
2965 	return (ENOSYS);
2966 } /* ng_btsocket_l2cap_result2errno */
2967 
2968