1 /*
2  * ng_btsocket_hci_raw.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_hci_raw.c,v 1.14 2003/09/14 23:29:06 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/priv.h>
50 #include <sys/protosw.h>
51 #include <sys/queue.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sysctl.h>
55 #include <sys/taskqueue.h>
56 
57 #include <net/vnet.h>
58 
59 #include <netgraph/ng_message.h>
60 #include <netgraph/netgraph.h>
61 #include <netgraph/bluetooth/include/ng_bluetooth.h>
62 #include <netgraph/bluetooth/include/ng_hci.h>
63 #include <netgraph/bluetooth/include/ng_l2cap.h>
64 #include <netgraph/bluetooth/include/ng_btsocket.h>
65 #include <netgraph/bluetooth/include/ng_btsocket_hci_raw.h>
66 
67 /* MALLOC define */
68 #ifdef NG_SEPARATE_MALLOC
69 static MALLOC_DEFINE(M_NETGRAPH_BTSOCKET_HCI_RAW, "netgraph_btsocks_hci_raw",
70 	"Netgraph Bluetooth raw HCI sockets");
71 #else
72 #define M_NETGRAPH_BTSOCKET_HCI_RAW M_NETGRAPH
73 #endif /* NG_SEPARATE_MALLOC */
74 
75 /* Netgraph node methods */
76 static ng_constructor_t	ng_btsocket_hci_raw_node_constructor;
77 static ng_rcvmsg_t	ng_btsocket_hci_raw_node_rcvmsg;
78 static ng_shutdown_t	ng_btsocket_hci_raw_node_shutdown;
79 static ng_newhook_t	ng_btsocket_hci_raw_node_newhook;
80 static ng_connect_t	ng_btsocket_hci_raw_node_connect;
81 static ng_rcvdata_t	ng_btsocket_hci_raw_node_rcvdata;
82 static ng_disconnect_t	ng_btsocket_hci_raw_node_disconnect;
83 
84 static void 		ng_btsocket_hci_raw_input (void *, int);
85 static void 		ng_btsocket_hci_raw_output(node_p, hook_p, void *, int);
86 static void		ng_btsocket_hci_raw_savctl(ng_btsocket_hci_raw_pcb_p,
87 						   struct mbuf **,
88 						   struct mbuf *);
89 static int		ng_btsocket_hci_raw_filter(ng_btsocket_hci_raw_pcb_p,
90 						   struct mbuf *, int);
91 
92 #define ng_btsocket_hci_raw_wakeup_input_task() \
93 	taskqueue_enqueue(taskqueue_swi, &ng_btsocket_hci_raw_task)
94 
95 /* Security filter */
96 struct ng_btsocket_hci_raw_sec_filter {
97 	bitstr_t	bit_decl(events, 0xff);
98 	bitstr_t	bit_decl(commands[0x3f], 0x3ff);
99 };
100 
101 /* Netgraph type descriptor */
102 static struct ng_type typestruct = {
103 	.version =	NG_ABI_VERSION,
104 	.name =		NG_BTSOCKET_HCI_RAW_NODE_TYPE,
105 	.constructor =	ng_btsocket_hci_raw_node_constructor,
106 	.rcvmsg =	ng_btsocket_hci_raw_node_rcvmsg,
107 	.shutdown =	ng_btsocket_hci_raw_node_shutdown,
108 	.newhook =	ng_btsocket_hci_raw_node_newhook,
109 	.connect =	ng_btsocket_hci_raw_node_connect,
110 	.rcvdata =	ng_btsocket_hci_raw_node_rcvdata,
111 	.disconnect =	ng_btsocket_hci_raw_node_disconnect,
112 };
113 
114 /* Globals */
115 static u_int32_t				ng_btsocket_hci_raw_debug_level;
116 static u_int32_t				ng_btsocket_hci_raw_ioctl_timeout;
117 static node_p					ng_btsocket_hci_raw_node;
118 static struct ng_bt_itemq			ng_btsocket_hci_raw_queue;
119 static struct mtx				ng_btsocket_hci_raw_queue_mtx;
120 static struct task				ng_btsocket_hci_raw_task;
121 static LIST_HEAD(, ng_btsocket_hci_raw_pcb)	ng_btsocket_hci_raw_sockets;
122 static struct mtx				ng_btsocket_hci_raw_sockets_mtx;
123 static u_int32_t				ng_btsocket_hci_raw_token;
124 static struct mtx				ng_btsocket_hci_raw_token_mtx;
125 static struct ng_btsocket_hci_raw_sec_filter	*ng_btsocket_hci_raw_sec_filter;
126 static struct timeval				ng_btsocket_hci_raw_lasttime;
127 static int					ng_btsocket_hci_raw_curpps;
128 
129 /* Sysctl tree */
130 SYSCTL_DECL(_net_bluetooth_hci_sockets);
131 static SYSCTL_NODE(_net_bluetooth_hci_sockets, OID_AUTO, raw,
132     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
133     "Bluetooth raw HCI sockets family");
134 SYSCTL_UINT(_net_bluetooth_hci_sockets_raw, OID_AUTO, debug_level, CTLFLAG_RW,
135         &ng_btsocket_hci_raw_debug_level, NG_BTSOCKET_WARN_LEVEL,
136 	"Bluetooth raw HCI sockets debug level");
137 SYSCTL_UINT(_net_bluetooth_hci_sockets_raw, OID_AUTO, ioctl_timeout, CTLFLAG_RW,
138         &ng_btsocket_hci_raw_ioctl_timeout, 5,
139 	"Bluetooth raw HCI sockets ioctl timeout");
140 SYSCTL_UINT(_net_bluetooth_hci_sockets_raw, OID_AUTO, queue_len, CTLFLAG_RD,
141         &ng_btsocket_hci_raw_queue.len, 0,
142         "Bluetooth raw HCI sockets input queue length");
143 SYSCTL_UINT(_net_bluetooth_hci_sockets_raw, OID_AUTO, queue_maxlen, CTLFLAG_RD,
144         &ng_btsocket_hci_raw_queue.maxlen, 0,
145         "Bluetooth raw HCI sockets input queue max. length");
146 SYSCTL_UINT(_net_bluetooth_hci_sockets_raw, OID_AUTO, queue_drops, CTLFLAG_RD,
147         &ng_btsocket_hci_raw_queue.drops, 0,
148         "Bluetooth raw HCI sockets input queue drops");
149 
150 /* Debug */
151 #define NG_BTSOCKET_HCI_RAW_INFO \
152 	if (ng_btsocket_hci_raw_debug_level >= NG_BTSOCKET_INFO_LEVEL && \
153 	    ppsratecheck(&ng_btsocket_hci_raw_lasttime, &ng_btsocket_hci_raw_curpps, 1)) \
154 		printf
155 
156 #define NG_BTSOCKET_HCI_RAW_WARN \
157 	if (ng_btsocket_hci_raw_debug_level >= NG_BTSOCKET_WARN_LEVEL && \
158 	    ppsratecheck(&ng_btsocket_hci_raw_lasttime, &ng_btsocket_hci_raw_curpps, 1)) \
159 		printf
160 
161 #define NG_BTSOCKET_HCI_RAW_ERR \
162 	if (ng_btsocket_hci_raw_debug_level >= NG_BTSOCKET_ERR_LEVEL && \
163 	    ppsratecheck(&ng_btsocket_hci_raw_lasttime, &ng_btsocket_hci_raw_curpps, 1)) \
164 		printf
165 
166 #define NG_BTSOCKET_HCI_RAW_ALERT \
167 	if (ng_btsocket_hci_raw_debug_level >= NG_BTSOCKET_ALERT_LEVEL && \
168 	    ppsratecheck(&ng_btsocket_hci_raw_lasttime, &ng_btsocket_hci_raw_curpps, 1)) \
169 		printf
170 
171 /****************************************************************************
172  ****************************************************************************
173  **                          Netgraph specific
174  ****************************************************************************
175  ****************************************************************************/
176 
177 /*
178  * Netgraph node constructor. Do not allow to create node of this type.
179  */
180 
181 static int
182 ng_btsocket_hci_raw_node_constructor(node_p node)
183 {
184 	return (EINVAL);
185 } /* ng_btsocket_hci_raw_node_constructor */
186 
187 /*
188  * Netgraph node destructor. Just let old node go and create new fresh one.
189  */
190 
191 static int
192 ng_btsocket_hci_raw_node_shutdown(node_p node)
193 {
194 	int	error = 0;
195 
196 	NG_NODE_UNREF(node);
197 
198 	error = ng_make_node_common(&typestruct, &ng_btsocket_hci_raw_node);
199 	if (error  != 0) {
200 		NG_BTSOCKET_HCI_RAW_ALERT(
201 "%s: Could not create Netgraph node, error=%d\n", __func__, error);
202 
203 		ng_btsocket_hci_raw_node = NULL;
204 
205 		return (ENOMEM);
206         }
207 
208 	error = ng_name_node(ng_btsocket_hci_raw_node,
209 				NG_BTSOCKET_HCI_RAW_NODE_TYPE);
210 	if (error != 0) {
211 		NG_BTSOCKET_HCI_RAW_ALERT(
212 "%s: Could not name Netgraph node, error=%d\n", __func__, error);
213 
214 		NG_NODE_UNREF(ng_btsocket_hci_raw_node);
215 		ng_btsocket_hci_raw_node = NULL;
216 
217 		return (EINVAL);
218 	}
219 
220 	return (0);
221 } /* ng_btsocket_hci_raw_node_shutdown */
222 
223 /*
224  * Create new hook. Just say "yes"
225  */
226 
227 static int
228 ng_btsocket_hci_raw_node_newhook(node_p node, hook_p hook, char const *name)
229 {
230 	return (0);
231 } /* ng_btsocket_hci_raw_node_newhook */
232 
233 /*
234  * Connect hook. Just say "yes"
235  */
236 
237 static int
238 ng_btsocket_hci_raw_node_connect(hook_p hook)
239 {
240 	return (0);
241 } /* ng_btsocket_hci_raw_node_connect */
242 
243 /*
244  * Disconnect hook
245  */
246 
247 static int
248 ng_btsocket_hci_raw_node_disconnect(hook_p hook)
249 {
250 	return (0);
251 } /* ng_btsocket_hci_raw_node_disconnect */
252 
253 /*
254  * Receive control message.
255  * Make sure it is a message from HCI node and it is a response.
256  * Enqueue item and schedule input task.
257  */
258 
259 static int
260 ng_btsocket_hci_raw_node_rcvmsg(node_p node, item_p item, hook_p lasthook)
261 {
262 	struct ng_mesg	*msg = NGI_MSG(item); /* item still has message */
263 	int		 error = 0;
264 
265 	/*
266 	 * Check for empty sockets list creates LOR when both sender and
267 	 * receiver device are connected to the same host, so remove it
268 	 * for now
269 	 */
270 
271 	if (msg != NULL &&
272 	    (msg->header.typecookie == NGM_HCI_COOKIE ||
273 	     msg->header.typecookie == NGM_GENERIC_COOKIE) &&
274 	    msg->header.flags & NGF_RESP) {
275 		if (msg->header.token == 0) {
276 			NG_FREE_ITEM(item);
277 			return (0);
278 		}
279 
280 		mtx_lock(&ng_btsocket_hci_raw_queue_mtx);
281 		if (NG_BT_ITEMQ_FULL(&ng_btsocket_hci_raw_queue)) {
282 			NG_BTSOCKET_HCI_RAW_ERR(
283 "%s: Input queue is full\n", __func__);
284 
285 			NG_BT_ITEMQ_DROP(&ng_btsocket_hci_raw_queue);
286 			NG_FREE_ITEM(item);
287 			error = ENOBUFS;
288 		} else {
289 			NG_BT_ITEMQ_ENQUEUE(&ng_btsocket_hci_raw_queue, item);
290 			error = ng_btsocket_hci_raw_wakeup_input_task();
291 		}
292 		mtx_unlock(&ng_btsocket_hci_raw_queue_mtx);
293 	} else {
294 		NG_FREE_ITEM(item);
295 		error = EINVAL;
296 	}
297 
298 	return (error);
299 } /* ng_btsocket_hci_raw_node_rcvmsg */
300 
301 /*
302  * Receive packet from the one of our hook.
303  * Prepend every packet with sockaddr_hci and record sender's node name.
304  * Enqueue item and schedule input task.
305  */
306 
307 static int
308 ng_btsocket_hci_raw_node_rcvdata(hook_p hook, item_p item)
309 {
310 	struct mbuf	*nam = NULL;
311 	int		 error;
312 
313 	/*
314 	 * Check for empty sockets list creates LOR when both sender and
315 	 * receiver device are connected to the same host, so remove it
316 	 * for now
317 	 */
318 
319 	MGET(nam, M_NOWAIT, MT_SONAME);
320 	if (nam != NULL) {
321 		struct sockaddr_hci	*sa = mtod(nam, struct sockaddr_hci *);
322 
323 		nam->m_len = sizeof(struct sockaddr_hci);
324 
325 		sa->hci_len = sizeof(*sa);
326 		sa->hci_family = AF_BLUETOOTH;
327 		strlcpy(sa->hci_node, NG_PEER_NODE_NAME(hook),
328 			sizeof(sa->hci_node));
329 
330 		NGI_GET_M(item, nam->m_next);
331 		NGI_M(item) = nam;
332 
333 		mtx_lock(&ng_btsocket_hci_raw_queue_mtx);
334 		if (NG_BT_ITEMQ_FULL(&ng_btsocket_hci_raw_queue)) {
335 			NG_BTSOCKET_HCI_RAW_ERR(
336 "%s: Input queue is full\n", __func__);
337 
338 			NG_BT_ITEMQ_DROP(&ng_btsocket_hci_raw_queue);
339 			NG_FREE_ITEM(item);
340 			error = ENOBUFS;
341 		} else {
342 			NG_BT_ITEMQ_ENQUEUE(&ng_btsocket_hci_raw_queue, item);
343 			error = ng_btsocket_hci_raw_wakeup_input_task();
344 		}
345 		mtx_unlock(&ng_btsocket_hci_raw_queue_mtx);
346 	} else {
347 		NG_BTSOCKET_HCI_RAW_ERR(
348 "%s: Failed to allocate address mbuf\n", __func__);
349 
350 		NG_FREE_ITEM(item);
351 		error = ENOBUFS;
352 	}
353 
354 	return (error);
355 } /* ng_btsocket_hci_raw_node_rcvdata */
356 
357 /****************************************************************************
358  ****************************************************************************
359  **                              Sockets specific
360  ****************************************************************************
361  ****************************************************************************/
362 
363 /*
364  * Get next token. We need token to avoid theoretical race where process
365  * submits ioctl() message then interrupts ioctl() and re-submits another
366  * ioctl() on the same socket *before* first ioctl() complete.
367  */
368 
369 static void
370 ng_btsocket_hci_raw_get_token(u_int32_t *token)
371 {
372 	mtx_lock(&ng_btsocket_hci_raw_token_mtx);
373 
374 	if (++ ng_btsocket_hci_raw_token == 0)
375 		ng_btsocket_hci_raw_token = 1;
376 
377 	*token = ng_btsocket_hci_raw_token;
378 
379 	mtx_unlock(&ng_btsocket_hci_raw_token_mtx);
380 } /* ng_btsocket_hci_raw_get_token */
381 
382 /*
383  * Send Netgraph message to the node - do not expect reply
384  */
385 
386 static int
387 ng_btsocket_hci_raw_send_ngmsg(char *path, int cmd, void *arg, int arglen)
388 {
389 	struct ng_mesg	*msg = NULL;
390 	int		 error = 0;
391 
392 	NG_MKMESSAGE(msg, NGM_HCI_COOKIE, cmd, arglen, M_NOWAIT);
393 	if (msg == NULL)
394 		return (ENOMEM);
395 
396 	if (arg != NULL && arglen > 0)
397 		bcopy(arg, msg->data, arglen);
398 
399 	NG_SEND_MSG_PATH(error, ng_btsocket_hci_raw_node, msg, path, 0);
400 
401 	return (error);
402 } /* ng_btsocket_hci_raw_send_ngmsg */
403 
404 /*
405  * Send Netgraph message to the node (no data) and wait for reply
406  */
407 
408 static int
409 ng_btsocket_hci_raw_send_sync_ngmsg(ng_btsocket_hci_raw_pcb_p pcb, char *path,
410 		int cmd, void *rsp, int rsplen)
411 {
412 	struct ng_mesg	*msg = NULL;
413 	int		 error = 0;
414 
415 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
416 
417 	NG_MKMESSAGE(msg, NGM_HCI_COOKIE, cmd, 0, M_NOWAIT);
418 	if (msg == NULL)
419 		return (ENOMEM);
420 
421 	ng_btsocket_hci_raw_get_token(&msg->header.token);
422 	pcb->token = msg->header.token;
423 	pcb->msg = NULL;
424 
425 	NG_SEND_MSG_PATH(error, ng_btsocket_hci_raw_node, msg, path, 0);
426 	if (error != 0) {
427 		pcb->token = 0;
428 		return (error);
429 	}
430 
431 	error = msleep(&pcb->msg, &pcb->pcb_mtx, PZERO|PCATCH, "hcictl",
432 			ng_btsocket_hci_raw_ioctl_timeout * hz);
433 	pcb->token = 0;
434 
435 	if (error != 0)
436 		return (error);
437 
438 	if (pcb->msg != NULL && pcb->msg->header.cmd == cmd)
439 		bcopy(pcb->msg->data, rsp, rsplen);
440 	else
441 		error = EINVAL;
442 
443 	NG_FREE_MSG(pcb->msg); /* checks for != NULL */
444 
445 	return (0);
446 } /* ng_btsocket_hci_raw_send_sync_ngmsg */
447 
448 /*
449  * Create control information for the packet
450  */
451 
452 static void
453 ng_btsocket_hci_raw_savctl(ng_btsocket_hci_raw_pcb_p pcb, struct mbuf **ctl,
454 		struct mbuf *m)
455 {
456 	int		dir;
457 	struct timeval	tv;
458 
459 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
460 
461 	if (pcb->flags & NG_BTSOCKET_HCI_RAW_DIRECTION) {
462 		dir = (m->m_flags & M_PROTO1)? 1 : 0;
463 		*ctl = sbcreatecontrol((caddr_t) &dir, sizeof(dir),
464 					SCM_HCI_RAW_DIRECTION, SOL_HCI_RAW);
465 		if (*ctl != NULL)
466 			ctl = &((*ctl)->m_next);
467 	}
468 
469 	if (pcb->so->so_options & SO_TIMESTAMP) {
470 		microtime(&tv);
471 		*ctl = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
472 					SCM_TIMESTAMP, SOL_SOCKET);
473 		if (*ctl != NULL)
474 			ctl = &((*ctl)->m_next);
475 	}
476 } /* ng_btsocket_hci_raw_savctl */
477 
478 /*
479  * Raw HCI sockets data input routine
480  */
481 
482 static void
483 ng_btsocket_hci_raw_data_input(struct mbuf *nam)
484 {
485 	ng_btsocket_hci_raw_pcb_p	 pcb = NULL;
486 	struct mbuf			*m0 = NULL, *m = NULL;
487 	struct sockaddr_hci		*sa = NULL;
488 
489 	m0 = nam->m_next;
490 	nam->m_next = NULL;
491 
492 	KASSERT((nam->m_type == MT_SONAME),
493 		("%s: m_type=%d\n", __func__, nam->m_type));
494 	KASSERT((m0->m_flags & M_PKTHDR),
495 		("%s: m_flags=%#x\n", __func__, m0->m_flags));
496 
497 	sa = mtod(nam, struct sockaddr_hci *);
498 
499 	mtx_lock(&ng_btsocket_hci_raw_sockets_mtx);
500 
501 	LIST_FOREACH(pcb, &ng_btsocket_hci_raw_sockets, next) {
502 
503 		mtx_lock(&pcb->pcb_mtx);
504 
505 		/*
506 		 * If socket was bound then check address and
507 		 *  make sure it matches.
508 		 */
509 
510 		if (pcb->addr.hci_node[0] != 0 &&
511 		    strcmp(sa->hci_node, pcb->addr.hci_node) != 0)
512 			goto next;
513 
514 		/*
515 		 * Check packet against filters
516 		 * XXX do we have to call m_pullup() here?
517 		 */
518 
519 		if (ng_btsocket_hci_raw_filter(pcb, m0, 1) != 0)
520 			goto next;
521 
522 		/*
523 		 * Make a copy of the packet, append to the socket's
524 		 * receive queue and wakeup socket. sbappendaddr()
525 		 * will check if socket has enough buffer space.
526 		 */
527 
528 		m = m_dup(m0, M_NOWAIT);
529 		if (m != NULL) {
530 			struct mbuf	*ctl = NULL;
531 
532 			ng_btsocket_hci_raw_savctl(pcb, &ctl, m);
533 
534 			if (sbappendaddr(&pcb->so->so_rcv,
535 					(struct sockaddr *) sa, m, ctl))
536 				sorwakeup(pcb->so);
537 			else {
538 				NG_BTSOCKET_HCI_RAW_INFO(
539 "%s: sbappendaddr() failed\n", __func__);
540 
541 				NG_FREE_M(m);
542 				NG_FREE_M(ctl);
543 			}
544 		}
545 next:
546 		mtx_unlock(&pcb->pcb_mtx);
547 	}
548 
549 	mtx_unlock(&ng_btsocket_hci_raw_sockets_mtx);
550 
551 	NG_FREE_M(nam);
552 	NG_FREE_M(m0);
553 } /* ng_btsocket_hci_raw_data_input */
554 
555 /*
556  * Raw HCI sockets message input routine
557  */
558 
559 static void
560 ng_btsocket_hci_raw_msg_input(struct ng_mesg *msg)
561 {
562 	ng_btsocket_hci_raw_pcb_p	pcb = NULL;
563 
564 	mtx_lock(&ng_btsocket_hci_raw_sockets_mtx);
565 
566 	LIST_FOREACH(pcb, &ng_btsocket_hci_raw_sockets, next) {
567 		mtx_lock(&pcb->pcb_mtx);
568 
569 		if (msg->header.token == pcb->token) {
570 			pcb->msg = msg;
571 			wakeup(&pcb->msg);
572 
573 			mtx_unlock(&pcb->pcb_mtx);
574 			mtx_unlock(&ng_btsocket_hci_raw_sockets_mtx);
575 
576 			return;
577 		}
578 
579 		mtx_unlock(&pcb->pcb_mtx);
580 	}
581 
582 	mtx_unlock(&ng_btsocket_hci_raw_sockets_mtx);
583 
584 	NG_FREE_MSG(msg); /* checks for != NULL */
585 } /* ng_btsocket_hci_raw_msg_input */
586 
587 /*
588  * Raw HCI sockets input routines
589  */
590 
591 static void
592 ng_btsocket_hci_raw_input(void *context, int pending)
593 {
594 	item_p	item = NULL;
595 
596 	for (;;) {
597 		mtx_lock(&ng_btsocket_hci_raw_queue_mtx);
598 		NG_BT_ITEMQ_DEQUEUE(&ng_btsocket_hci_raw_queue, item);
599 		mtx_unlock(&ng_btsocket_hci_raw_queue_mtx);
600 
601 		if (item == NULL)
602 			break;
603 
604 		switch(item->el_flags & NGQF_TYPE) {
605 		case NGQF_DATA: {
606 			struct mbuf	*m = NULL;
607 
608 			NGI_GET_M(item, m);
609 			ng_btsocket_hci_raw_data_input(m);
610 			} break;
611 
612 		case NGQF_MESG: {
613 			struct ng_mesg	*msg = NULL;
614 
615 			NGI_GET_MSG(item, msg);
616 			ng_btsocket_hci_raw_msg_input(msg);
617 			} break;
618 
619 		default:
620 			KASSERT(0,
621 ("%s: invalid item type=%ld\n", __func__, (item->el_flags & NGQF_TYPE)));
622 			break;
623 		}
624 
625 		NG_FREE_ITEM(item);
626 	}
627 } /* ng_btsocket_hci_raw_input */
628 
629 /*
630  * Raw HCI sockets output routine
631  */
632 
633 static void
634 ng_btsocket_hci_raw_output(node_p node, hook_p hook, void *arg1, int arg2)
635 {
636 	struct mbuf		*nam = (struct mbuf *) arg1, *m = NULL;
637 	struct sockaddr_hci	*sa = NULL;
638 	int			 error;
639 
640 	m = nam->m_next;
641 	nam->m_next = NULL;
642 
643 	KASSERT((nam->m_type == MT_SONAME),
644 		("%s: m_type=%d\n", __func__, nam->m_type));
645 	KASSERT((m->m_flags & M_PKTHDR),
646 		("%s: m_flags=%#x\n", __func__, m->m_flags));
647 
648 	sa = mtod(nam, struct sockaddr_hci *);
649 
650 	/*
651 	 * Find downstream hook
652 	 * XXX For now access node hook list directly. Should be safe because
653 	 * we used ng_send_fn() and we should have exclusive lock on the node.
654 	 */
655 
656 	LIST_FOREACH(hook, &node->nd_hooks, hk_hooks) {
657 		if (hook == NULL || NG_HOOK_NOT_VALID(hook) ||
658 		    NG_NODE_NOT_VALID(NG_PEER_NODE(hook)))
659 			continue;
660 
661 		if (strcmp(sa->hci_node, NG_PEER_NODE_NAME(hook)) == 0) {
662 			NG_SEND_DATA_ONLY(error, hook, m); /* sets m to NULL */
663 			break;
664 		}
665 	}
666 
667 	NG_FREE_M(nam); /* check for != NULL */
668 	NG_FREE_M(m);
669 } /* ng_btsocket_hci_raw_output */
670 
671 /*
672  * Check frame against security and socket filters.
673  * d (direction bit) == 1 means incoming frame.
674  */
675 
676 static int
677 ng_btsocket_hci_raw_filter(ng_btsocket_hci_raw_pcb_p pcb, struct mbuf *m, int d)
678 {
679 	int	type, event, opcode;
680 
681 	mtx_assert(&pcb->pcb_mtx, MA_OWNED);
682 
683 	switch ((type = *mtod(m, u_int8_t *))) {
684 	case NG_HCI_CMD_PKT:
685 		if (!(pcb->flags & NG_BTSOCKET_HCI_RAW_PRIVILEGED)) {
686 			opcode = le16toh(mtod(m, ng_hci_cmd_pkt_t *)->opcode);
687 
688 			if (!bit_test(
689 ng_btsocket_hci_raw_sec_filter->commands[NG_HCI_OGF(opcode) - 1],
690 NG_HCI_OCF(opcode) - 1))
691 				return (EPERM);
692 		}
693 
694 		if (d && !bit_test(pcb->filter.packet_mask, NG_HCI_CMD_PKT - 1))
695 			return (EPERM);
696 		break;
697 
698 	case NG_HCI_ACL_DATA_PKT:
699 	case NG_HCI_SCO_DATA_PKT:
700 		if (!(pcb->flags & NG_BTSOCKET_HCI_RAW_PRIVILEGED) ||
701 		    !bit_test(pcb->filter.packet_mask, type - 1) ||
702 		    !d)
703 			return (EPERM);
704 		break;
705 
706 	case NG_HCI_EVENT_PKT:
707 		if (!d)
708 			return (EINVAL);
709 
710 		event = mtod(m, ng_hci_event_pkt_t *)->event - 1;
711 
712 		if (!(pcb->flags & NG_BTSOCKET_HCI_RAW_PRIVILEGED))
713 			if (!bit_test(ng_btsocket_hci_raw_sec_filter->events, event))
714 				return (EPERM);
715 
716 		if (!bit_test(pcb->filter.event_mask, event))
717 			return (EPERM);
718 		break;
719 
720 	default:
721 		return (EINVAL);
722 	}
723 
724 	return (0);
725 } /* ng_btsocket_hci_raw_filter */
726 
727 /*
728  * Initialize everything
729  */
730 
731 void
732 ng_btsocket_hci_raw_init(void)
733 {
734 	bitstr_t	*f = NULL;
735 	int		 error = 0;
736 
737 	/* Skip initialization of globals for non-default instances. */
738 	if (!IS_DEFAULT_VNET(curvnet))
739 		return;
740 
741 	ng_btsocket_hci_raw_node = NULL;
742 	ng_btsocket_hci_raw_debug_level = NG_BTSOCKET_WARN_LEVEL;
743 	ng_btsocket_hci_raw_ioctl_timeout = 5;
744 
745 	/* Register Netgraph node type */
746 	error = ng_newtype(&typestruct);
747 	if (error != 0) {
748 		NG_BTSOCKET_HCI_RAW_ALERT(
749 "%s: Could not register Netgraph node type, error=%d\n", __func__, error);
750 
751 		return;
752 	}
753 
754 	/* Create Netgrapg node */
755 	error = ng_make_node_common(&typestruct, &ng_btsocket_hci_raw_node);
756 	if (error != 0) {
757 		NG_BTSOCKET_HCI_RAW_ALERT(
758 "%s: Could not create Netgraph node, error=%d\n", __func__, error);
759 
760 		ng_btsocket_hci_raw_node = NULL;
761 
762 		return;
763         }
764 
765 	error = ng_name_node(ng_btsocket_hci_raw_node,
766 				NG_BTSOCKET_HCI_RAW_NODE_TYPE);
767 	if (error != 0) {
768 		NG_BTSOCKET_HCI_RAW_ALERT(
769 "%s: Could not name Netgraph node, error=%d\n", __func__, error);
770 
771 		NG_NODE_UNREF(ng_btsocket_hci_raw_node);
772 		ng_btsocket_hci_raw_node = NULL;
773 
774 		return;
775 	}
776 
777 	/* Create input queue */
778 	NG_BT_ITEMQ_INIT(&ng_btsocket_hci_raw_queue, 300);
779 	mtx_init(&ng_btsocket_hci_raw_queue_mtx,
780 		"btsocks_hci_raw_queue_mtx", NULL, MTX_DEF);
781 	TASK_INIT(&ng_btsocket_hci_raw_task, 0,
782 		ng_btsocket_hci_raw_input, NULL);
783 
784 	/* Create list of sockets */
785 	LIST_INIT(&ng_btsocket_hci_raw_sockets);
786 	mtx_init(&ng_btsocket_hci_raw_sockets_mtx,
787 		"btsocks_hci_raw_sockets_mtx", NULL, MTX_DEF);
788 
789 	/* Tokens */
790 	ng_btsocket_hci_raw_token = 0;
791 	mtx_init(&ng_btsocket_hci_raw_token_mtx,
792 		"btsocks_hci_raw_token_mtx", NULL, MTX_DEF);
793 
794 	/*
795 	 * Security filter
796 	 * XXX never free()ed
797 	 */
798 	ng_btsocket_hci_raw_sec_filter =
799 	    malloc(sizeof(struct ng_btsocket_hci_raw_sec_filter),
800 		M_NETGRAPH_BTSOCKET_HCI_RAW, M_NOWAIT|M_ZERO);
801 	if (ng_btsocket_hci_raw_sec_filter == NULL) {
802 		printf("%s: Could not allocate security filter!\n", __func__);
803 		return;
804 	}
805 
806 	/*
807 	 * XXX How paranoid can we get?
808 	 *
809 	 * Initialize security filter. If bit is set in the mask then
810 	 * unprivileged socket is allowed to send (receive) this command
811 	 * (event).
812 	 */
813 
814 	/* Enable all events */
815 	memset(&ng_btsocket_hci_raw_sec_filter->events, 0xff,
816 		sizeof(ng_btsocket_hci_raw_sec_filter->events)/
817 			sizeof(ng_btsocket_hci_raw_sec_filter->events[0]));
818 
819 	/* Disable some critical events */
820 	f = ng_btsocket_hci_raw_sec_filter->events;
821 	bit_clear(f, NG_HCI_EVENT_RETURN_LINK_KEYS - 1);
822 	bit_clear(f, NG_HCI_EVENT_LINK_KEY_NOTIFICATION - 1);
823 	bit_clear(f, NG_HCI_EVENT_VENDOR - 1);
824 
825 	/* Commands - Link control */
826 	f = ng_btsocket_hci_raw_sec_filter->commands[NG_HCI_OGF_LINK_CONTROL-1];
827 	bit_set(f, NG_HCI_OCF_INQUIRY - 1);
828 	bit_set(f, NG_HCI_OCF_INQUIRY_CANCEL - 1);
829 	bit_set(f, NG_HCI_OCF_PERIODIC_INQUIRY - 1);
830 	bit_set(f, NG_HCI_OCF_EXIT_PERIODIC_INQUIRY - 1);
831 	bit_set(f, NG_HCI_OCF_REMOTE_NAME_REQ - 1);
832 	bit_set(f, NG_HCI_OCF_READ_REMOTE_FEATURES - 1);
833 	bit_set(f, NG_HCI_OCF_READ_REMOTE_VER_INFO - 1);
834 	bit_set(f, NG_HCI_OCF_READ_CLOCK_OFFSET - 1);
835 
836 	/* Commands - Link policy */
837 	f = ng_btsocket_hci_raw_sec_filter->commands[NG_HCI_OGF_LINK_POLICY-1];
838 	bit_set(f, NG_HCI_OCF_ROLE_DISCOVERY - 1);
839 	bit_set(f, NG_HCI_OCF_READ_LINK_POLICY_SETTINGS - 1);
840 
841 	/* Commands - Host controller and baseband */
842 	f = ng_btsocket_hci_raw_sec_filter->commands[NG_HCI_OGF_HC_BASEBAND-1];
843 	bit_set(f, NG_HCI_OCF_READ_PIN_TYPE - 1);
844 	bit_set(f, NG_HCI_OCF_READ_LOCAL_NAME - 1);
845 	bit_set(f, NG_HCI_OCF_READ_CON_ACCEPT_TIMO - 1);
846 	bit_set(f, NG_HCI_OCF_READ_PAGE_TIMO - 1);
847 	bit_set(f, NG_HCI_OCF_READ_SCAN_ENABLE - 1);
848 	bit_set(f, NG_HCI_OCF_READ_PAGE_SCAN_ACTIVITY - 1);
849 	bit_set(f, NG_HCI_OCF_READ_INQUIRY_SCAN_ACTIVITY - 1);
850 	bit_set(f, NG_HCI_OCF_READ_AUTH_ENABLE - 1);
851 	bit_set(f, NG_HCI_OCF_READ_ENCRYPTION_MODE - 1);
852 	bit_set(f, NG_HCI_OCF_READ_UNIT_CLASS - 1);
853 	bit_set(f, NG_HCI_OCF_READ_VOICE_SETTINGS - 1);
854 	bit_set(f, NG_HCI_OCF_READ_AUTO_FLUSH_TIMO - 1);
855 	bit_set(f, NG_HCI_OCF_READ_NUM_BROADCAST_RETRANS - 1);
856 	bit_set(f, NG_HCI_OCF_READ_HOLD_MODE_ACTIVITY - 1);
857 	bit_set(f, NG_HCI_OCF_READ_XMIT_LEVEL - 1);
858 	bit_set(f, NG_HCI_OCF_READ_SCO_FLOW_CONTROL - 1);
859 	bit_set(f, NG_HCI_OCF_READ_LINK_SUPERVISION_TIMO - 1);
860 	bit_set(f, NG_HCI_OCF_READ_SUPPORTED_IAC_NUM - 1);
861 	bit_set(f, NG_HCI_OCF_READ_IAC_LAP - 1);
862 	bit_set(f, NG_HCI_OCF_READ_PAGE_SCAN_PERIOD - 1);
863 	bit_set(f, NG_HCI_OCF_READ_PAGE_SCAN - 1);
864 	bit_set(f, NG_HCI_OCF_READ_LE_HOST_SUPPORTED -1);
865 
866 	/* Commands - Informational */
867 	f = ng_btsocket_hci_raw_sec_filter->commands[NG_HCI_OGF_INFO - 1];
868 	bit_set(f, NG_HCI_OCF_READ_LOCAL_VER - 1);
869 	bit_set(f, NG_HCI_OCF_READ_LOCAL_FEATURES - 1);
870 	bit_set(f, NG_HCI_OCF_READ_BUFFER_SIZE - 1);
871 	bit_set(f, NG_HCI_OCF_READ_COUNTRY_CODE - 1);
872 	bit_set(f, NG_HCI_OCF_READ_BDADDR - 1);
873 
874 	/* Commands - Status */
875 	f = ng_btsocket_hci_raw_sec_filter->commands[NG_HCI_OGF_STATUS - 1];
876 	bit_set(f, NG_HCI_OCF_READ_FAILED_CONTACT_CNTR - 1);
877 	bit_set(f, NG_HCI_OCF_GET_LINK_QUALITY - 1);
878 	bit_set(f, NG_HCI_OCF_READ_RSSI - 1);
879 
880 	/* Commands - Testing */
881 	f = ng_btsocket_hci_raw_sec_filter->commands[NG_HCI_OGF_TESTING - 1];
882 	bit_set(f, NG_HCI_OCF_READ_LOOPBACK_MODE - 1);
883 	/*Commands - LE*/
884 	f = ng_btsocket_hci_raw_sec_filter->commands[NG_HCI_OGF_LE -1];
885 	bit_set(f, NG_HCI_OCF_LE_SET_SCAN_ENABLE - 1);
886 	bit_set(f, NG_HCI_OCF_LE_SET_SCAN_PARAMETERS - 1);
887 	bit_set(f, NG_HCI_OCF_LE_READ_LOCAL_SUPPORTED_FEATURES - 1);
888 	bit_set(f, NG_HCI_OCF_LE_READ_BUFFER_SIZE - 1);
889 	bit_set(f, NG_HCI_OCF_LE_READ_WHITE_LIST_SIZE - 1);
890 
891 } /* ng_btsocket_hci_raw_init */
892 
893 /*
894  * Abort connection on socket
895  */
896 
897 void
898 ng_btsocket_hci_raw_abort(struct socket *so)
899 {
900 } /* ng_btsocket_hci_raw_abort */
901 
902 void
903 ng_btsocket_hci_raw_close(struct socket *so)
904 {
905 } /* ng_btsocket_hci_raw_close */
906 
907 /*
908  * Create new raw HCI socket
909  */
910 
911 int
912 ng_btsocket_hci_raw_attach(struct socket *so, int proto, struct thread *td)
913 {
914 	ng_btsocket_hci_raw_pcb_p	pcb = so2hci_raw_pcb(so);
915 	int				error = 0;
916 
917 	if (pcb != NULL)
918 		return (EISCONN);
919 
920 	if (ng_btsocket_hci_raw_node == NULL)
921 		return (EPROTONOSUPPORT);
922 	if (proto != BLUETOOTH_PROTO_HCI)
923 		return (EPROTONOSUPPORT);
924 	if (so->so_type != SOCK_RAW)
925 		return (ESOCKTNOSUPPORT);
926 
927 	error = soreserve(so, NG_BTSOCKET_HCI_RAW_SENDSPACE,
928 				NG_BTSOCKET_HCI_RAW_RECVSPACE);
929 	if (error != 0)
930 		return (error);
931 
932 	pcb = malloc(sizeof(*pcb),
933 		M_NETGRAPH_BTSOCKET_HCI_RAW, M_NOWAIT|M_ZERO);
934 	if (pcb == NULL)
935 		return (ENOMEM);
936 
937 	so->so_pcb = (caddr_t) pcb;
938 	pcb->so = so;
939 
940 	if (priv_check(td, PRIV_NETBLUETOOTH_RAW) == 0)
941 		pcb->flags |= NG_BTSOCKET_HCI_RAW_PRIVILEGED;
942 
943 	/*
944 	 * Set default socket filter. By default socket only accepts HCI
945 	 * Command_Complete and Command_Status event packets.
946 	 */
947 
948 	bit_set(pcb->filter.event_mask, NG_HCI_EVENT_COMMAND_COMPL - 1);
949 	bit_set(pcb->filter.event_mask, NG_HCI_EVENT_COMMAND_STATUS - 1);
950 
951 	mtx_init(&pcb->pcb_mtx, "btsocks_hci_raw_pcb_mtx", NULL, MTX_DEF);
952 
953 	mtx_lock(&ng_btsocket_hci_raw_sockets_mtx);
954 	LIST_INSERT_HEAD(&ng_btsocket_hci_raw_sockets, pcb, next);
955 	mtx_unlock(&ng_btsocket_hci_raw_sockets_mtx);
956 
957 	return (0);
958 } /* ng_btsocket_hci_raw_attach */
959 
960 /*
961  * Bind raw HCI socket
962  */
963 
964 int
965 ng_btsocket_hci_raw_bind(struct socket *so, struct sockaddr *nam,
966 		struct thread *td)
967 {
968 	ng_btsocket_hci_raw_pcb_p	 pcb = so2hci_raw_pcb(so);
969 	struct sockaddr_hci		*sa = (struct sockaddr_hci *) nam;
970 
971 	if (pcb == NULL)
972 		return (EINVAL);
973 	if (ng_btsocket_hci_raw_node == NULL)
974 		return (EINVAL);
975 
976 	if (sa == NULL)
977 		return (EINVAL);
978 	if (sa->hci_family != AF_BLUETOOTH)
979 		return (EAFNOSUPPORT);
980 	if (sa->hci_len != sizeof(*sa))
981 		return (EINVAL);
982 	if (sa->hci_node[0] == 0)
983 		return (EINVAL);
984 
985 	mtx_lock(&pcb->pcb_mtx);
986 	bcopy(sa, &pcb->addr, sizeof(pcb->addr));
987 	mtx_unlock(&pcb->pcb_mtx);
988 
989 	return (0);
990 } /* ng_btsocket_hci_raw_bind */
991 
992 /*
993  * Connect raw HCI socket
994  */
995 
996 int
997 ng_btsocket_hci_raw_connect(struct socket *so, struct sockaddr *nam,
998 		struct thread *td)
999 {
1000 	ng_btsocket_hci_raw_pcb_p	 pcb = so2hci_raw_pcb(so);
1001 	struct sockaddr_hci		*sa = (struct sockaddr_hci *) nam;
1002 
1003 	if (pcb == NULL)
1004 		return (EINVAL);
1005 	if (ng_btsocket_hci_raw_node == NULL)
1006 		return (EINVAL);
1007 
1008 	if (sa == NULL)
1009 		return (EINVAL);
1010 	if (sa->hci_family != AF_BLUETOOTH)
1011 		return (EAFNOSUPPORT);
1012 	if (sa->hci_len != sizeof(*sa))
1013 		return (EINVAL);
1014 	if (sa->hci_node[0] == 0)
1015 		return (EDESTADDRREQ);
1016 
1017 	mtx_lock(&pcb->pcb_mtx);
1018 
1019 	if (bcmp(sa, &pcb->addr, sizeof(pcb->addr)) != 0) {
1020 		mtx_unlock(&pcb->pcb_mtx);
1021 		return (EADDRNOTAVAIL);
1022 	}
1023 
1024 	soisconnected(so);
1025 
1026 	mtx_unlock(&pcb->pcb_mtx);
1027 
1028 	return (0);
1029 } /* ng_btsocket_hci_raw_connect */
1030 
1031 /*
1032  * Process ioctl on socket
1033  */
1034 
1035 int
1036 ng_btsocket_hci_raw_control(struct socket *so, u_long cmd, caddr_t data,
1037 		struct ifnet *ifp, struct thread *td)
1038 {
1039 	ng_btsocket_hci_raw_pcb_p	 pcb = so2hci_raw_pcb(so);
1040 	char				 path[NG_NODESIZ + 1];
1041 	struct ng_mesg			*msg = NULL;
1042 	int				 error = 0;
1043 
1044 	if (pcb == NULL)
1045 		return (EINVAL);
1046 	if (ng_btsocket_hci_raw_node == NULL)
1047 		return (EINVAL);
1048 
1049 	mtx_lock(&pcb->pcb_mtx);
1050 
1051 	/* Check if we have device name */
1052 	if (pcb->addr.hci_node[0] == 0) {
1053 		mtx_unlock(&pcb->pcb_mtx);
1054 		return (EHOSTUNREACH);
1055 	}
1056 
1057 	/* Check if we have pending ioctl() */
1058 	if (pcb->token != 0) {
1059 		mtx_unlock(&pcb->pcb_mtx);
1060 		return (EBUSY);
1061 	}
1062 
1063 	snprintf(path, sizeof(path), "%s:", pcb->addr.hci_node);
1064 
1065 	switch (cmd) {
1066 	case SIOC_HCI_RAW_NODE_GET_STATE: {
1067 		struct ng_btsocket_hci_raw_node_state	*p =
1068 			(struct ng_btsocket_hci_raw_node_state *) data;
1069 
1070 		error = ng_btsocket_hci_raw_send_sync_ngmsg(pcb, path,
1071 				NGM_HCI_NODE_GET_STATE,
1072 				&p->state, sizeof(p->state));
1073 		} break;
1074 
1075 	case SIOC_HCI_RAW_NODE_INIT:
1076 		if (pcb->flags & NG_BTSOCKET_HCI_RAW_PRIVILEGED)
1077 			error = ng_btsocket_hci_raw_send_ngmsg(path,
1078 					NGM_HCI_NODE_INIT, NULL, 0);
1079 		else
1080 			error = EPERM;
1081 		break;
1082 
1083 	case SIOC_HCI_RAW_NODE_GET_DEBUG: {
1084 		struct ng_btsocket_hci_raw_node_debug	*p =
1085 			(struct ng_btsocket_hci_raw_node_debug *) data;
1086 
1087 		error = ng_btsocket_hci_raw_send_sync_ngmsg(pcb, path,
1088 				NGM_HCI_NODE_GET_DEBUG,
1089 				&p->debug, sizeof(p->debug));
1090 		} break;
1091 
1092 	case SIOC_HCI_RAW_NODE_SET_DEBUG: {
1093 		struct ng_btsocket_hci_raw_node_debug	*p =
1094 			(struct ng_btsocket_hci_raw_node_debug *) data;
1095 
1096 		if (pcb->flags & NG_BTSOCKET_HCI_RAW_PRIVILEGED)
1097 			error = ng_btsocket_hci_raw_send_ngmsg(path,
1098 					NGM_HCI_NODE_SET_DEBUG, &p->debug,
1099 					sizeof(p->debug));
1100 		else
1101 			error = EPERM;
1102 		} break;
1103 
1104 	case SIOC_HCI_RAW_NODE_GET_BUFFER: {
1105 		struct ng_btsocket_hci_raw_node_buffer	*p =
1106 			(struct ng_btsocket_hci_raw_node_buffer *) data;
1107 
1108 		error = ng_btsocket_hci_raw_send_sync_ngmsg(pcb, path,
1109 				NGM_HCI_NODE_GET_BUFFER,
1110 				&p->buffer, sizeof(p->buffer));
1111 		} break;
1112 
1113 	case SIOC_HCI_RAW_NODE_GET_BDADDR: {
1114 		struct ng_btsocket_hci_raw_node_bdaddr	*p =
1115 			(struct ng_btsocket_hci_raw_node_bdaddr *) data;
1116 
1117 		error = ng_btsocket_hci_raw_send_sync_ngmsg(pcb, path,
1118 				NGM_HCI_NODE_GET_BDADDR,
1119 				&p->bdaddr, sizeof(p->bdaddr));
1120 		} break;
1121 
1122 	case SIOC_HCI_RAW_NODE_GET_FEATURES: {
1123 		struct ng_btsocket_hci_raw_node_features	*p =
1124 			(struct ng_btsocket_hci_raw_node_features *) data;
1125 
1126 		error = ng_btsocket_hci_raw_send_sync_ngmsg(pcb, path,
1127 				NGM_HCI_NODE_GET_FEATURES,
1128 				&p->features, sizeof(p->features));
1129 		} break;
1130 
1131 	case SIOC_HCI_RAW_NODE_GET_STAT: {
1132 		struct ng_btsocket_hci_raw_node_stat	*p =
1133 			(struct ng_btsocket_hci_raw_node_stat *) data;
1134 
1135 		error = ng_btsocket_hci_raw_send_sync_ngmsg(pcb, path,
1136 				NGM_HCI_NODE_GET_STAT,
1137 				&p->stat, sizeof(p->stat));
1138 		} break;
1139 
1140 	case SIOC_HCI_RAW_NODE_RESET_STAT:
1141 		if (pcb->flags & NG_BTSOCKET_HCI_RAW_PRIVILEGED)
1142 			error = ng_btsocket_hci_raw_send_ngmsg(path,
1143 					NGM_HCI_NODE_RESET_STAT, NULL, 0);
1144 		else
1145 			error = EPERM;
1146 		break;
1147 
1148 	case SIOC_HCI_RAW_NODE_FLUSH_NEIGHBOR_CACHE:
1149 		if (pcb->flags & NG_BTSOCKET_HCI_RAW_PRIVILEGED)
1150 			error = ng_btsocket_hci_raw_send_ngmsg(path,
1151 					NGM_HCI_NODE_FLUSH_NEIGHBOR_CACHE,
1152 					NULL, 0);
1153 		else
1154 			error = EPERM;
1155 		break;
1156 
1157 	case SIOC_HCI_RAW_NODE_GET_NEIGHBOR_CACHE:  {
1158 		struct ng_btsocket_hci_raw_node_neighbor_cache	*p =
1159 			(struct ng_btsocket_hci_raw_node_neighbor_cache *) data;
1160 		ng_hci_node_get_neighbor_cache_ep		*p1 = NULL;
1161 		ng_hci_node_neighbor_cache_entry_ep		*p2 = NULL;
1162 
1163 		if (p->num_entries <= 0 ||
1164 		    p->num_entries > NG_HCI_MAX_NEIGHBOR_NUM ||
1165 		    p->entries == NULL) {
1166 			mtx_unlock(&pcb->pcb_mtx);
1167 			return (EINVAL);
1168 		}
1169 
1170 		NG_MKMESSAGE(msg, NGM_HCI_COOKIE,
1171 			NGM_HCI_NODE_GET_NEIGHBOR_CACHE, 0, M_NOWAIT);
1172 		if (msg == NULL) {
1173 			mtx_unlock(&pcb->pcb_mtx);
1174 			return (ENOMEM);
1175 		}
1176 		ng_btsocket_hci_raw_get_token(&msg->header.token);
1177 		pcb->token = msg->header.token;
1178 		pcb->msg = NULL;
1179 
1180 		NG_SEND_MSG_PATH(error, ng_btsocket_hci_raw_node, msg, path, 0);
1181 		if (error != 0) {
1182 			pcb->token = 0;
1183 			mtx_unlock(&pcb->pcb_mtx);
1184 			return (error);
1185 		}
1186 
1187 		error = msleep(&pcb->msg, &pcb->pcb_mtx,
1188 				PZERO|PCATCH, "hcictl",
1189 				ng_btsocket_hci_raw_ioctl_timeout * hz);
1190 		pcb->token = 0;
1191 
1192 		if (error != 0) {
1193 			mtx_unlock(&pcb->pcb_mtx);
1194 			return (error);
1195 		}
1196 
1197 		msg = pcb->msg;
1198 		pcb->msg = NULL;
1199 
1200 		mtx_unlock(&pcb->pcb_mtx);
1201 
1202 		if (msg != NULL &&
1203 		    msg->header.cmd == NGM_HCI_NODE_GET_NEIGHBOR_CACHE) {
1204 			/* Return data back to user space */
1205 			p1 = (ng_hci_node_get_neighbor_cache_ep *)(msg->data);
1206 			p2 = (ng_hci_node_neighbor_cache_entry_ep *)(p1 + 1);
1207 
1208 			p->num_entries = min(p->num_entries, p1->num_entries);
1209 			if (p->num_entries > 0)
1210 				error = copyout((caddr_t) p2,
1211 						(caddr_t) p->entries,
1212 						p->num_entries * sizeof(*p2));
1213 		} else
1214 			error = EINVAL;
1215 
1216 		NG_FREE_MSG(msg); /* checks for != NULL */
1217 		return (error);
1218 		} /* NOTREACHED */
1219 
1220 	case SIOC_HCI_RAW_NODE_GET_CON_LIST: {
1221 		struct ng_btsocket_hci_raw_con_list	*p =
1222 			(struct ng_btsocket_hci_raw_con_list *) data;
1223 		ng_hci_node_con_list_ep			*p1 = NULL;
1224 		ng_hci_node_con_ep			*p2 = NULL;
1225 
1226 		if (p->num_connections == 0 ||
1227 		    p->num_connections > NG_HCI_MAX_CON_NUM ||
1228 		    p->connections == NULL) {
1229 			mtx_unlock(&pcb->pcb_mtx);
1230 			return (EINVAL);
1231 		}
1232 
1233 		NG_MKMESSAGE(msg, NGM_HCI_COOKIE, NGM_HCI_NODE_GET_CON_LIST,
1234 			0, M_NOWAIT);
1235 		if (msg == NULL) {
1236 			mtx_unlock(&pcb->pcb_mtx);
1237 			return (ENOMEM);
1238 		}
1239 		ng_btsocket_hci_raw_get_token(&msg->header.token);
1240 		pcb->token = msg->header.token;
1241 		pcb->msg = NULL;
1242 
1243 		NG_SEND_MSG_PATH(error, ng_btsocket_hci_raw_node, msg, path, 0);
1244 		if (error != 0) {
1245 			pcb->token = 0;
1246 			mtx_unlock(&pcb->pcb_mtx);
1247 			return (error);
1248 		}
1249 
1250 		error = msleep(&pcb->msg, &pcb->pcb_mtx,
1251 				PZERO|PCATCH, "hcictl",
1252 				ng_btsocket_hci_raw_ioctl_timeout * hz);
1253 		pcb->token = 0;
1254 
1255 		if (error != 0) {
1256 			mtx_unlock(&pcb->pcb_mtx);
1257 			return (error);
1258 		}
1259 
1260 		msg = pcb->msg;
1261 		pcb->msg = NULL;
1262 
1263 		mtx_unlock(&pcb->pcb_mtx);
1264 
1265 		if (msg != NULL &&
1266 		    msg->header.cmd == NGM_HCI_NODE_GET_CON_LIST) {
1267 			/* Return data back to user space */
1268 			p1 = (ng_hci_node_con_list_ep *)(msg->data);
1269 			p2 = (ng_hci_node_con_ep *)(p1 + 1);
1270 
1271 			p->num_connections = min(p->num_connections,
1272 						p1->num_connections);
1273 			if (p->num_connections > 0)
1274 				error = copyout((caddr_t) p2,
1275 					(caddr_t) p->connections,
1276 					p->num_connections * sizeof(*p2));
1277 		} else
1278 			error = EINVAL;
1279 
1280 		NG_FREE_MSG(msg); /* checks for != NULL */
1281 		return (error);
1282 		} /* NOTREACHED */
1283 
1284 	case SIOC_HCI_RAW_NODE_GET_LINK_POLICY_MASK: {
1285 		struct ng_btsocket_hci_raw_node_link_policy_mask	*p =
1286 			(struct ng_btsocket_hci_raw_node_link_policy_mask *)
1287 				data;
1288 
1289 		error = ng_btsocket_hci_raw_send_sync_ngmsg(pcb, path,
1290 				NGM_HCI_NODE_GET_LINK_POLICY_SETTINGS_MASK,
1291 				&p->policy_mask, sizeof(p->policy_mask));
1292 		} break;
1293 
1294 	case SIOC_HCI_RAW_NODE_SET_LINK_POLICY_MASK: {
1295 		struct ng_btsocket_hci_raw_node_link_policy_mask	*p =
1296 			(struct ng_btsocket_hci_raw_node_link_policy_mask *)
1297 				data;
1298 
1299 		if (pcb->flags & NG_BTSOCKET_HCI_RAW_PRIVILEGED)
1300 			error = ng_btsocket_hci_raw_send_ngmsg(path,
1301 					NGM_HCI_NODE_SET_LINK_POLICY_SETTINGS_MASK,
1302 					&p->policy_mask,
1303 					sizeof(p->policy_mask));
1304 		else
1305 			error = EPERM;
1306 		} break;
1307 
1308 	case SIOC_HCI_RAW_NODE_GET_PACKET_MASK: {
1309 		struct ng_btsocket_hci_raw_node_packet_mask	*p =
1310 			(struct ng_btsocket_hci_raw_node_packet_mask *) data;
1311 
1312 		error = ng_btsocket_hci_raw_send_sync_ngmsg(pcb, path,
1313 				NGM_HCI_NODE_GET_PACKET_MASK,
1314 				&p->packet_mask, sizeof(p->packet_mask));
1315 		} break;
1316 
1317 	case SIOC_HCI_RAW_NODE_SET_PACKET_MASK: {
1318 		struct ng_btsocket_hci_raw_node_packet_mask	*p =
1319 			(struct ng_btsocket_hci_raw_node_packet_mask *) data;
1320 
1321 		if (pcb->flags & NG_BTSOCKET_HCI_RAW_PRIVILEGED)
1322 			error = ng_btsocket_hci_raw_send_ngmsg(path,
1323 					NGM_HCI_NODE_SET_PACKET_MASK,
1324 					&p->packet_mask,
1325 					sizeof(p->packet_mask));
1326 		else
1327 			error = EPERM;
1328 		} break;
1329 
1330 	case SIOC_HCI_RAW_NODE_GET_ROLE_SWITCH: {
1331 		struct ng_btsocket_hci_raw_node_role_switch	*p =
1332 			(struct ng_btsocket_hci_raw_node_role_switch *) data;
1333 
1334 		error = ng_btsocket_hci_raw_send_sync_ngmsg(pcb, path,
1335 				NGM_HCI_NODE_GET_ROLE_SWITCH,
1336 				&p->role_switch, sizeof(p->role_switch));
1337 		} break;
1338 
1339 	case SIOC_HCI_RAW_NODE_SET_ROLE_SWITCH: {
1340 		struct ng_btsocket_hci_raw_node_role_switch	*p =
1341 			(struct ng_btsocket_hci_raw_node_role_switch *) data;
1342 
1343 		if (pcb->flags & NG_BTSOCKET_HCI_RAW_PRIVILEGED)
1344 			error = ng_btsocket_hci_raw_send_ngmsg(path,
1345 					NGM_HCI_NODE_SET_ROLE_SWITCH,
1346 					&p->role_switch,
1347 					sizeof(p->role_switch));
1348 		else
1349 			error = EPERM;
1350 		} break;
1351 
1352 	case SIOC_HCI_RAW_NODE_LIST_NAMES: {
1353 		struct ng_btsocket_hci_raw_node_list_names	*nl =
1354 			(struct ng_btsocket_hci_raw_node_list_names *) data;
1355 		struct nodeinfo					*ni = nl->names;
1356 
1357 		if (nl->num_names == 0) {
1358 			mtx_unlock(&pcb->pcb_mtx);
1359 			return (EINVAL);
1360 		}
1361 
1362 		NG_MKMESSAGE(msg, NGM_GENERIC_COOKIE, NGM_LISTNAMES,
1363 			0, M_NOWAIT);
1364 		if (msg == NULL) {
1365 			mtx_unlock(&pcb->pcb_mtx);
1366 			return (ENOMEM);
1367 		}
1368 		ng_btsocket_hci_raw_get_token(&msg->header.token);
1369 		pcb->token = msg->header.token;
1370 		pcb->msg = NULL;
1371 
1372 		NG_SEND_MSG_PATH(error, ng_btsocket_hci_raw_node, msg, ".:", 0);
1373 		if (error != 0) {
1374 			pcb->token = 0;
1375 			mtx_unlock(&pcb->pcb_mtx);
1376 			return (error);
1377 		}
1378 
1379 		error = msleep(&pcb->msg, &pcb->pcb_mtx,
1380 				PZERO|PCATCH, "hcictl",
1381 				ng_btsocket_hci_raw_ioctl_timeout * hz);
1382 		pcb->token = 0;
1383 
1384 		if (error != 0) {
1385 			mtx_unlock(&pcb->pcb_mtx);
1386 			return (error);
1387 		}
1388 
1389 		msg = pcb->msg;
1390 		pcb->msg = NULL;
1391 
1392 		mtx_unlock(&pcb->pcb_mtx);
1393 
1394 		if (msg != NULL && msg->header.cmd == NGM_LISTNAMES) {
1395 			/* Return data back to user space */
1396 			struct namelist	*nl1 = (struct namelist *) msg->data;
1397 			struct nodeinfo	*ni1 = &nl1->nodeinfo[0];
1398 
1399 			while (nl->num_names > 0 && nl1->numnames > 0) {
1400 				if (strcmp(ni1->type, NG_HCI_NODE_TYPE) == 0) {
1401 					error = copyout((caddr_t) ni1,
1402 							(caddr_t) ni,
1403 							sizeof(*ni));
1404 					if (error != 0)
1405 						break;
1406 
1407 					nl->num_names --;
1408 					ni ++;
1409 				}
1410 
1411 				nl1->numnames --;
1412 				ni1 ++;
1413 			}
1414 
1415 			nl->num_names = ni - nl->names;
1416 		} else
1417 			error = EINVAL;
1418 
1419 		NG_FREE_MSG(msg); /* checks for != NULL */
1420 		return (error);
1421 		} /* NOTREACHED */
1422 
1423 	default:
1424 		error = EINVAL;
1425 		break;
1426 	}
1427 
1428 	mtx_unlock(&pcb->pcb_mtx);
1429 
1430 	return (error);
1431 } /* ng_btsocket_hci_raw_control */
1432 
1433 /*
1434  * Process getsockopt/setsockopt system calls
1435  */
1436 
1437 int
1438 ng_btsocket_hci_raw_ctloutput(struct socket *so, struct sockopt *sopt)
1439 {
1440 	ng_btsocket_hci_raw_pcb_p		pcb = so2hci_raw_pcb(so);
1441 	struct ng_btsocket_hci_raw_filter	filter;
1442 	int					error = 0, dir;
1443 
1444 	if (pcb == NULL)
1445 		return (EINVAL);
1446 	if (ng_btsocket_hci_raw_node == NULL)
1447 		return (EINVAL);
1448 
1449 	if (sopt->sopt_level != SOL_HCI_RAW)
1450 		return (0);
1451 
1452 	mtx_lock(&pcb->pcb_mtx);
1453 
1454 	switch (sopt->sopt_dir) {
1455 	case SOPT_GET:
1456 		switch (sopt->sopt_name) {
1457 		case SO_HCI_RAW_FILTER:
1458 			error = sooptcopyout(sopt, &pcb->filter,
1459 						sizeof(pcb->filter));
1460 			break;
1461 
1462 		case SO_HCI_RAW_DIRECTION:
1463 			dir = (pcb->flags & NG_BTSOCKET_HCI_RAW_DIRECTION)?1:0;
1464 			error = sooptcopyout(sopt, &dir, sizeof(dir));
1465 			break;
1466 
1467 		default:
1468 			error = EINVAL;
1469 			break;
1470 		}
1471 		break;
1472 
1473 	case SOPT_SET:
1474 		switch (sopt->sopt_name) {
1475 		case SO_HCI_RAW_FILTER:
1476 			error = sooptcopyin(sopt, &filter, sizeof(filter),
1477 						sizeof(filter));
1478 			if (error == 0)
1479 				bcopy(&filter, &pcb->filter,
1480 						sizeof(pcb->filter));
1481 			break;
1482 
1483 		case SO_HCI_RAW_DIRECTION:
1484 			error = sooptcopyin(sopt, &dir, sizeof(dir),
1485 						sizeof(dir));
1486 			if (error != 0)
1487 				break;
1488 
1489 			if (dir)
1490 				pcb->flags |= NG_BTSOCKET_HCI_RAW_DIRECTION;
1491 			else
1492 				pcb->flags &= ~NG_BTSOCKET_HCI_RAW_DIRECTION;
1493 			break;
1494 
1495 		default:
1496 			error = EINVAL;
1497 			break;
1498 		}
1499 		break;
1500 
1501 	default:
1502 		error = EINVAL;
1503 		break;
1504 	}
1505 
1506 	mtx_unlock(&pcb->pcb_mtx);
1507 
1508 	return (error);
1509 } /* ng_btsocket_hci_raw_ctloutput */
1510 
1511 /*
1512  * Detach raw HCI socket
1513  */
1514 
1515 void
1516 ng_btsocket_hci_raw_detach(struct socket *so)
1517 {
1518 	ng_btsocket_hci_raw_pcb_p	pcb = so2hci_raw_pcb(so);
1519 
1520 	KASSERT(pcb != NULL, ("ng_btsocket_hci_raw_detach: pcb == NULL"));
1521 
1522 	if (ng_btsocket_hci_raw_node == NULL)
1523 		return;
1524 
1525 	mtx_lock(&ng_btsocket_hci_raw_sockets_mtx);
1526 	mtx_lock(&pcb->pcb_mtx);
1527 
1528 	LIST_REMOVE(pcb, next);
1529 
1530 	mtx_unlock(&pcb->pcb_mtx);
1531 	mtx_unlock(&ng_btsocket_hci_raw_sockets_mtx);
1532 
1533 	mtx_destroy(&pcb->pcb_mtx);
1534 
1535 	bzero(pcb, sizeof(*pcb));
1536 	free(pcb, M_NETGRAPH_BTSOCKET_HCI_RAW);
1537 
1538 	so->so_pcb = NULL;
1539 } /* ng_btsocket_hci_raw_detach */
1540 
1541 /*
1542  * Disconnect raw HCI socket
1543  */
1544 
1545 int
1546 ng_btsocket_hci_raw_disconnect(struct socket *so)
1547 {
1548 	ng_btsocket_hci_raw_pcb_p	 pcb = so2hci_raw_pcb(so);
1549 
1550 	if (pcb == NULL)
1551 		return (EINVAL);
1552 	if (ng_btsocket_hci_raw_node == NULL)
1553 		return (EINVAL);
1554 
1555 	mtx_lock(&pcb->pcb_mtx);
1556 	soisdisconnected(so);
1557 	mtx_unlock(&pcb->pcb_mtx);
1558 
1559 	return (0);
1560 } /* ng_btsocket_hci_raw_disconnect */
1561 
1562 /*
1563  * Get socket peer's address
1564  */
1565 
1566 int
1567 ng_btsocket_hci_raw_peeraddr(struct socket *so, struct sockaddr **nam)
1568 {
1569 	return (ng_btsocket_hci_raw_sockaddr(so, nam));
1570 } /* ng_btsocket_hci_raw_peeraddr */
1571 
1572 /*
1573  * Send data
1574  */
1575 
1576 int
1577 ng_btsocket_hci_raw_send(struct socket *so, int flags, struct mbuf *m,
1578 		struct sockaddr *sa, struct mbuf *control, struct thread *td)
1579 {
1580 	ng_btsocket_hci_raw_pcb_p	 pcb = so2hci_raw_pcb(so);
1581 	struct mbuf			*nam = NULL;
1582 	int				 error = 0;
1583 
1584 	if (ng_btsocket_hci_raw_node == NULL) {
1585 		error = ENETDOWN;
1586 		goto drop;
1587 	}
1588 	if (pcb == NULL) {
1589 		error = EINVAL;
1590 		goto drop;
1591 	}
1592 	if (control != NULL) {
1593 		error = EINVAL;
1594 		goto drop;
1595 	}
1596 
1597 	if (m->m_pkthdr.len < sizeof(ng_hci_cmd_pkt_t) ||
1598 	    m->m_pkthdr.len > sizeof(ng_hci_cmd_pkt_t) + NG_HCI_CMD_PKT_SIZE) {
1599 		error = EMSGSIZE;
1600 		goto drop;
1601 	}
1602 
1603 	if (m->m_len < sizeof(ng_hci_cmd_pkt_t)) {
1604 		if ((m = m_pullup(m, sizeof(ng_hci_cmd_pkt_t))) == NULL) {
1605 			error = ENOBUFS;
1606 			goto drop;
1607 		}
1608 	}
1609 	if (*mtod(m, u_int8_t *) != NG_HCI_CMD_PKT) {
1610 		error = ENOTSUP;
1611 		goto drop;
1612 	}
1613 
1614 	mtx_lock(&pcb->pcb_mtx);
1615 
1616 	error = ng_btsocket_hci_raw_filter(pcb, m, 0);
1617 	if (error != 0) {
1618 		mtx_unlock(&pcb->pcb_mtx);
1619 		goto drop;
1620 	}
1621 
1622 	if (sa == NULL) {
1623 		if (pcb->addr.hci_node[0] == 0) {
1624 			mtx_unlock(&pcb->pcb_mtx);
1625 			error = EDESTADDRREQ;
1626 			goto drop;
1627 		}
1628 
1629 		sa = (struct sockaddr *) &pcb->addr;
1630 	}
1631 
1632 	MGET(nam, M_NOWAIT, MT_SONAME);
1633 	if (nam == NULL) {
1634 		mtx_unlock(&pcb->pcb_mtx);
1635 		error = ENOBUFS;
1636 		goto drop;
1637 	}
1638 
1639 	nam->m_len = sizeof(struct sockaddr_hci);
1640 	bcopy(sa,mtod(nam, struct sockaddr_hci *),sizeof(struct sockaddr_hci));
1641 
1642 	nam->m_next = m;
1643 	m = NULL;
1644 
1645 	mtx_unlock(&pcb->pcb_mtx);
1646 
1647 	return (ng_send_fn(ng_btsocket_hci_raw_node, NULL,
1648 				ng_btsocket_hci_raw_output, nam, 0));
1649 drop:
1650 	NG_FREE_M(control); /* NG_FREE_M checks for != NULL */
1651 	NG_FREE_M(nam);
1652 	NG_FREE_M(m);
1653 
1654 	return (error);
1655 } /* ng_btsocket_hci_raw_send */
1656 
1657 /*
1658  * Get socket address
1659  */
1660 
1661 int
1662 ng_btsocket_hci_raw_sockaddr(struct socket *so, struct sockaddr **nam)
1663 {
1664 	ng_btsocket_hci_raw_pcb_p	pcb = so2hci_raw_pcb(so);
1665 	struct sockaddr_hci		sa;
1666 
1667 	if (pcb == NULL)
1668 		return (EINVAL);
1669 	if (ng_btsocket_hci_raw_node == NULL)
1670 		return (EINVAL);
1671 
1672 	bzero(&sa, sizeof(sa));
1673 	sa.hci_len = sizeof(sa);
1674 	sa.hci_family = AF_BLUETOOTH;
1675 
1676 	mtx_lock(&pcb->pcb_mtx);
1677 	strlcpy(sa.hci_node, pcb->addr.hci_node, sizeof(sa.hci_node));
1678 	mtx_unlock(&pcb->pcb_mtx);
1679 
1680 	*nam = sodupsockaddr((struct sockaddr *) &sa, M_NOWAIT);
1681 
1682 	return ((*nam == NULL)? ENOMEM : 0);
1683 } /* ng_btsocket_hci_raw_sockaddr */
1684 
1685