xref: /linux/net/bluetooth/hidp/core.c (revision bea06c7c1b83bcd0519b91141999369eae6925bd)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3    HIDP implementation for Linux Bluetooth stack (BlueZ).
4    Copyright (C) 2003-2004 Marcel Holtmann <marcel@holtmann.org>
5    Copyright (C) 2013 David Herrmann <dh.herrmann@gmail.com>
6 
7    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
10    IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
11    CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
12    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 
16    ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
17    COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
18    SOFTWARE IS DISCLAIMED.
19 */
20 
21 #include <linux/kref.h>
22 #include <linux/module.h>
23 #include <linux/file.h>
24 #include <linux/kthread.h>
25 #include <linux/hidraw.h>
26 
27 #include <net/bluetooth/bluetooth.h>
28 #include <net/bluetooth/hci_core.h>
29 #include <net/bluetooth/l2cap.h>
30 
31 #include "hidp.h"
32 
33 #define VERSION "1.2"
34 
35 static DECLARE_RWSEM(hidp_session_sem);
36 static DECLARE_WAIT_QUEUE_HEAD(hidp_session_wq);
37 static LIST_HEAD(hidp_session_list);
38 
39 static unsigned char hidp_keycode[256] = {
40 	  0,   0,   0,   0,  30,  48,  46,  32,  18,  33,  34,  35,  23,  36,
41 	 37,  38,  50,  49,  24,  25,  16,  19,  31,  20,  22,  47,  17,  45,
42 	 21,  44,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  28,   1,
43 	 14,  15,  57,  12,  13,  26,  27,  43,  43,  39,  40,  41,  51,  52,
44 	 53,  58,  59,  60,  61,  62,  63,  64,  65,  66,  67,  68,  87,  88,
45 	 99,  70, 119, 110, 102, 104, 111, 107, 109, 106, 105, 108, 103,  69,
46 	 98,  55,  74,  78,  96,  79,  80,  81,  75,  76,  77,  71,  72,  73,
47 	 82,  83,  86, 127, 116, 117, 183, 184, 185, 186, 187, 188, 189, 190,
48 	191, 192, 193, 194, 134, 138, 130, 132, 128, 129, 131, 137, 133, 135,
49 	136, 113, 115, 114,   0,   0,   0, 121,   0,  89,  93, 124,  92,  94,
50 	 95,   0,   0,   0, 122, 123,  90,  91,  85,   0,   0,   0,   0,   0,
51 	  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
52 	  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
53 	  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
54 	  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
55 	  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
56 	 29,  42,  56, 125,  97,  54, 100, 126, 164, 166, 165, 163, 161, 115,
57 	114, 113, 150, 158, 159, 128, 136, 177, 178, 176, 142, 152, 173, 140
58 };
59 
60 static unsigned char hidp_mkeyspat[] = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };
61 
62 static int hidp_session_probe(struct l2cap_conn *conn,
63 			      struct l2cap_user *user);
64 static void hidp_session_remove(struct l2cap_conn *conn,
65 				struct l2cap_user *user);
66 static int hidp_session_thread(void *arg);
67 static void hidp_session_terminate(struct hidp_session *s);
68 
69 static void hidp_copy_session(struct hidp_session *session, struct hidp_conninfo *ci)
70 {
71 	u32 valid_flags = 0;
72 	memset(ci, 0, sizeof(*ci));
73 	bacpy(&ci->bdaddr, &session->bdaddr);
74 
75 	ci->flags = session->flags & valid_flags;
76 	ci->state = BT_CONNECTED;
77 
78 	if (session->input) {
79 		ci->vendor  = session->input->id.vendor;
80 		ci->product = session->input->id.product;
81 		ci->version = session->input->id.version;
82 		if (session->input->name)
83 			strscpy(ci->name, session->input->name, 128);
84 		else
85 			strscpy(ci->name, "HID Boot Device", 128);
86 	} else if (session->hid) {
87 		ci->vendor  = session->hid->vendor;
88 		ci->product = session->hid->product;
89 		ci->version = session->hid->version;
90 		strscpy(ci->name, session->hid->name, 128);
91 	}
92 }
93 
94 /* assemble skb, queue message on @transmit and wake up the session thread */
95 static int hidp_send_message(struct hidp_session *session, struct socket *sock,
96 			     struct sk_buff_head *transmit, unsigned char hdr,
97 			     const unsigned char *data, int size)
98 {
99 	struct sk_buff *skb;
100 	struct sock *sk = sock->sk;
101 	int ret;
102 
103 	BT_DBG("session %p data %p size %d", session, data, size);
104 
105 	if (atomic_read(&session->terminate))
106 		return -EIO;
107 
108 	skb = alloc_skb(size + 1, GFP_ATOMIC);
109 	if (!skb) {
110 		BT_ERR("Can't allocate memory for new frame");
111 		return -ENOMEM;
112 	}
113 
114 	skb_put_u8(skb, hdr);
115 	if (data && size > 0) {
116 		skb_put_data(skb, data, size);
117 		ret = size;
118 	} else {
119 		ret = 0;
120 	}
121 
122 	skb_queue_tail(transmit, skb);
123 	wake_up_interruptible(sk_sleep(sk));
124 
125 	return ret;
126 }
127 
128 static int hidp_send_ctrl_message(struct hidp_session *session,
129 				  unsigned char hdr, const unsigned char *data,
130 				  int size)
131 {
132 	return hidp_send_message(session, session->ctrl_sock,
133 				 &session->ctrl_transmit, hdr, data, size);
134 }
135 
136 static int hidp_send_intr_message(struct hidp_session *session,
137 				  unsigned char hdr, const unsigned char *data,
138 				  int size)
139 {
140 	return hidp_send_message(session, session->intr_sock,
141 				 &session->intr_transmit, hdr, data, size);
142 }
143 
144 static int hidp_input_event(struct input_dev *dev, unsigned int type,
145 			    unsigned int code, int value)
146 {
147 	struct hidp_session *session = input_get_drvdata(dev);
148 	unsigned char newleds;
149 	unsigned char hdr, data[2];
150 
151 	BT_DBG("session %p type %d code %d value %d",
152 	       session, type, code, value);
153 
154 	if (type != EV_LED)
155 		return -1;
156 
157 	newleds = (!!test_bit(LED_KANA,    dev->led) << 3) |
158 		  (!!test_bit(LED_COMPOSE, dev->led) << 3) |
159 		  (!!test_bit(LED_SCROLLL, dev->led) << 2) |
160 		  (!!test_bit(LED_CAPSL,   dev->led) << 1) |
161 		  (!!test_bit(LED_NUML,    dev->led) << 0);
162 
163 	if (session->leds == newleds)
164 		return 0;
165 
166 	session->leds = newleds;
167 
168 	hdr = HIDP_TRANS_DATA | HIDP_DATA_RTYPE_OUPUT;
169 	data[0] = 0x01;
170 	data[1] = newleds;
171 
172 	return hidp_send_intr_message(session, hdr, data, 2);
173 }
174 
175 static void hidp_input_report(struct hidp_session *session, struct sk_buff *skb)
176 {
177 	struct input_dev *dev = session->input;
178 	unsigned char *keys = session->keys;
179 	unsigned char *udata;
180 	signed char *sdata;
181 	u8 *hdr;
182 	int i;
183 
184 	hdr = skb_pull_data(skb, 1);
185 	if (!hdr)
186 		return;
187 
188 	switch (*hdr) {
189 	case 0x01:	/* Keyboard report */
190 		udata = skb_pull_data(skb, 8);
191 		if (!udata)
192 			break;
193 
194 		for (i = 0; i < 8; i++)
195 			input_report_key(dev, hidp_keycode[i + 224], (udata[0] >> i) & 1);
196 
197 		/* If all the key codes have been set to 0x01, it means
198 		 * too many keys were pressed at the same time. */
199 		if (!memcmp(udata + 2, hidp_mkeyspat, 6))
200 			break;
201 
202 		for (i = 2; i < 8; i++) {
203 			if (keys[i] > 3 && memscan(udata + 2, keys[i], 6) == udata + 8) {
204 				if (hidp_keycode[keys[i]])
205 					input_report_key(dev, hidp_keycode[keys[i]], 0);
206 				else
207 					BT_ERR("Unknown key (scancode %#x) released.", keys[i]);
208 			}
209 
210 			if (udata[i] > 3 && memscan(keys + 2, udata[i], 6) == keys + 8) {
211 				if (hidp_keycode[udata[i]])
212 					input_report_key(dev, hidp_keycode[udata[i]], 1);
213 				else
214 					BT_ERR("Unknown key (scancode %#x) pressed.", udata[i]);
215 			}
216 		}
217 
218 		memcpy(keys, udata, 8);
219 		break;
220 
221 	case 0x02:	/* Mouse report */
222 		sdata = skb_pull_data(skb, 3);
223 		if (!sdata)
224 			break;
225 
226 		input_report_key(dev, BTN_LEFT,   sdata[0] & 0x01);
227 		input_report_key(dev, BTN_RIGHT,  sdata[0] & 0x02);
228 		input_report_key(dev, BTN_MIDDLE, sdata[0] & 0x04);
229 		input_report_key(dev, BTN_SIDE,   sdata[0] & 0x08);
230 		input_report_key(dev, BTN_EXTRA,  sdata[0] & 0x10);
231 
232 		input_report_rel(dev, REL_X, sdata[1]);
233 		input_report_rel(dev, REL_Y, sdata[2]);
234 
235 		if (skb->len > 0)
236 			input_report_rel(dev, REL_WHEEL, sdata[3]);
237 		break;
238 	}
239 
240 	input_sync(dev);
241 }
242 
243 static int hidp_get_raw_report(struct hid_device *hid,
244 		unsigned char report_number,
245 		unsigned char *data, size_t count,
246 		unsigned char report_type)
247 {
248 	struct hidp_session *session = hid->driver_data;
249 	struct sk_buff *skb;
250 	size_t len;
251 	int numbered_reports = hid->report_enum[report_type].numbered;
252 	int ret;
253 
254 	if (atomic_read(&session->terminate))
255 		return -EIO;
256 
257 	switch (report_type) {
258 	case HID_FEATURE_REPORT:
259 		report_type = HIDP_TRANS_GET_REPORT | HIDP_DATA_RTYPE_FEATURE;
260 		break;
261 	case HID_INPUT_REPORT:
262 		report_type = HIDP_TRANS_GET_REPORT | HIDP_DATA_RTYPE_INPUT;
263 		break;
264 	case HID_OUTPUT_REPORT:
265 		report_type = HIDP_TRANS_GET_REPORT | HIDP_DATA_RTYPE_OUPUT;
266 		break;
267 	default:
268 		return -EINVAL;
269 	}
270 
271 	if (mutex_lock_interruptible(&session->report_mutex))
272 		return -ERESTARTSYS;
273 
274 	/* Set up our wait, and send the report request to the device. */
275 	session->waiting_report_type = report_type & HIDP_DATA_RTYPE_MASK;
276 	session->waiting_report_number = numbered_reports ? report_number : -1;
277 	set_bit(HIDP_WAITING_FOR_RETURN, &session->flags);
278 	data[0] = report_number;
279 	ret = hidp_send_ctrl_message(session, report_type, data, 1);
280 	if (ret < 0)
281 		goto err;
282 
283 	/* Wait for the return of the report. The returned report
284 	   gets put in session->report_return.  */
285 	while (test_bit(HIDP_WAITING_FOR_RETURN, &session->flags) &&
286 	       !atomic_read(&session->terminate)) {
287 		int res;
288 
289 		res = wait_event_interruptible_timeout(session->report_queue,
290 			!test_bit(HIDP_WAITING_FOR_RETURN, &session->flags)
291 				|| atomic_read(&session->terminate),
292 			5*HZ);
293 		if (res == 0) {
294 			/* timeout */
295 			ret = -EIO;
296 			goto err;
297 		}
298 		if (res < 0) {
299 			/* signal */
300 			ret = -ERESTARTSYS;
301 			goto err;
302 		}
303 	}
304 
305 	skb = session->report_return;
306 	if (skb) {
307 		len = skb->len < count ? skb->len : count;
308 		memcpy(data, skb->data, len);
309 
310 		kfree_skb(skb);
311 		session->report_return = NULL;
312 	} else {
313 		/* Device returned a HANDSHAKE, indicating  protocol error. */
314 		len = -EIO;
315 	}
316 
317 	clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags);
318 	mutex_unlock(&session->report_mutex);
319 
320 	return len;
321 
322 err:
323 	clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags);
324 	mutex_unlock(&session->report_mutex);
325 	return ret;
326 }
327 
328 static int hidp_set_raw_report(struct hid_device *hid, unsigned char reportnum,
329 			       unsigned char *data, size_t count,
330 			       unsigned char report_type)
331 {
332 	struct hidp_session *session = hid->driver_data;
333 	int ret;
334 
335 	switch (report_type) {
336 	case HID_FEATURE_REPORT:
337 		report_type = HIDP_TRANS_SET_REPORT | HIDP_DATA_RTYPE_FEATURE;
338 		break;
339 	case HID_INPUT_REPORT:
340 		report_type = HIDP_TRANS_SET_REPORT | HIDP_DATA_RTYPE_INPUT;
341 		break;
342 	case HID_OUTPUT_REPORT:
343 		report_type = HIDP_TRANS_SET_REPORT | HIDP_DATA_RTYPE_OUPUT;
344 		break;
345 	default:
346 		return -EINVAL;
347 	}
348 
349 	if (mutex_lock_interruptible(&session->report_mutex))
350 		return -ERESTARTSYS;
351 
352 	/* Set up our wait, and send the report request to the device. */
353 	data[0] = reportnum;
354 	set_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags);
355 	ret = hidp_send_ctrl_message(session, report_type, data, count);
356 	if (ret < 0)
357 		goto err;
358 
359 	/* Wait for the ACK from the device. */
360 	while (test_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags) &&
361 	       !atomic_read(&session->terminate)) {
362 		int res;
363 
364 		res = wait_event_interruptible_timeout(session->report_queue,
365 			!test_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags)
366 				|| atomic_read(&session->terminate),
367 			10*HZ);
368 		if (res == 0) {
369 			/* timeout */
370 			ret = -EIO;
371 			goto err;
372 		}
373 		if (res < 0) {
374 			/* signal */
375 			ret = -ERESTARTSYS;
376 			goto err;
377 		}
378 	}
379 
380 	if (!session->output_report_success) {
381 		ret = -EIO;
382 		goto err;
383 	}
384 
385 	ret = count;
386 
387 err:
388 	clear_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags);
389 	mutex_unlock(&session->report_mutex);
390 	return ret;
391 }
392 
393 static int hidp_output_report(struct hid_device *hid, __u8 *data, size_t count)
394 {
395 	struct hidp_session *session = hid->driver_data;
396 
397 	return hidp_send_intr_message(session,
398 				      HIDP_TRANS_DATA | HIDP_DATA_RTYPE_OUPUT,
399 				      data, count);
400 }
401 
402 static int hidp_raw_request(struct hid_device *hid, unsigned char reportnum,
403 			    __u8 *buf, size_t len, unsigned char rtype,
404 			    int reqtype)
405 {
406 	switch (reqtype) {
407 	case HID_REQ_GET_REPORT:
408 		return hidp_get_raw_report(hid, reportnum, buf, len, rtype);
409 	case HID_REQ_SET_REPORT:
410 		return hidp_set_raw_report(hid, reportnum, buf, len, rtype);
411 	default:
412 		return -EIO;
413 	}
414 }
415 
416 static void hidp_idle_timeout(struct timer_list *t)
417 {
418 	struct hidp_session *session = timer_container_of(session, t, timer);
419 
420 	/* The HIDP user-space API only contains calls to add and remove
421 	 * devices. There is no way to forward events of any kind. Therefore,
422 	 * we have to forcefully disconnect a device on idle-timeouts. This is
423 	 * unfortunate and weird API design, but it is spec-compliant and
424 	 * required for backwards-compatibility. Hence, on idle-timeout, we
425 	 * signal driver-detach events, so poll() will be woken up with an
426 	 * error-condition on both sockets.
427 	 */
428 
429 	session->intr_sock->sk->sk_err = EUNATCH;
430 	session->ctrl_sock->sk->sk_err = EUNATCH;
431 	wake_up_interruptible(sk_sleep(session->intr_sock->sk));
432 	wake_up_interruptible(sk_sleep(session->ctrl_sock->sk));
433 
434 	hidp_session_terminate(session);
435 }
436 
437 static void hidp_set_timer(struct hidp_session *session)
438 {
439 	if (session->idle_to > 0)
440 		mod_timer(&session->timer, jiffies + HZ * session->idle_to);
441 }
442 
443 static void hidp_del_timer(struct hidp_session *session)
444 {
445 	if (session->idle_to > 0)
446 		timer_delete_sync(&session->timer);
447 }
448 
449 static void hidp_process_report(struct hidp_session *session, int type,
450 				const u8 *data, unsigned int len, int intr)
451 {
452 	if (len > HID_MAX_BUFFER_SIZE)
453 		len = HID_MAX_BUFFER_SIZE;
454 
455 	memcpy(session->input_buf, data, len);
456 	hid_input_report(session->hid, type, session->input_buf, len, intr);
457 }
458 
459 static void hidp_process_handshake(struct hidp_session *session,
460 					unsigned char param)
461 {
462 	BT_DBG("session %p param 0x%02x", session, param);
463 	session->output_report_success = 0; /* default condition */
464 
465 	switch (param) {
466 	case HIDP_HSHK_SUCCESSFUL:
467 		/* FIXME: Call into SET_ GET_ handlers here */
468 		session->output_report_success = 1;
469 		break;
470 
471 	case HIDP_HSHK_NOT_READY:
472 	case HIDP_HSHK_ERR_INVALID_REPORT_ID:
473 	case HIDP_HSHK_ERR_UNSUPPORTED_REQUEST:
474 	case HIDP_HSHK_ERR_INVALID_PARAMETER:
475 		if (test_and_clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags))
476 			wake_up_interruptible(&session->report_queue);
477 
478 		/* FIXME: Call into SET_ GET_ handlers here */
479 		break;
480 
481 	case HIDP_HSHK_ERR_UNKNOWN:
482 		break;
483 
484 	case HIDP_HSHK_ERR_FATAL:
485 		/* Device requests a reboot, as this is the only way this error
486 		 * can be recovered. */
487 		hidp_send_ctrl_message(session,
488 			HIDP_TRANS_HID_CONTROL | HIDP_CTRL_SOFT_RESET, NULL, 0);
489 		break;
490 
491 	default:
492 		hidp_send_ctrl_message(session,
493 			HIDP_TRANS_HANDSHAKE | HIDP_HSHK_ERR_INVALID_PARAMETER, NULL, 0);
494 		break;
495 	}
496 
497 	/* Wake up the waiting thread. */
498 	if (test_and_clear_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags))
499 		wake_up_interruptible(&session->report_queue);
500 }
501 
502 static void hidp_process_hid_control(struct hidp_session *session,
503 					unsigned char param)
504 {
505 	BT_DBG("session %p param 0x%02x", session, param);
506 
507 	if (param == HIDP_CTRL_VIRTUAL_CABLE_UNPLUG) {
508 		/* Flush the transmit queues */
509 		skb_queue_purge(&session->ctrl_transmit);
510 		skb_queue_purge(&session->intr_transmit);
511 
512 		hidp_session_terminate(session);
513 	}
514 }
515 
516 /* Returns true if the passed-in skb should be freed by the caller. */
517 static int hidp_process_data(struct hidp_session *session, struct sk_buff *skb,
518 				unsigned char param)
519 {
520 	int done_with_skb = 1;
521 	BT_DBG("session %p skb %p len %u param 0x%02x", session, skb, skb->len, param);
522 
523 	switch (param) {
524 	case HIDP_DATA_RTYPE_INPUT:
525 		hidp_set_timer(session);
526 
527 		if (session->input)
528 			hidp_input_report(session, skb);
529 
530 		if (session->hid)
531 			hidp_process_report(session, HID_INPUT_REPORT,
532 					    skb->data, skb->len, 0);
533 		break;
534 
535 	case HIDP_DATA_RTYPE_OTHER:
536 	case HIDP_DATA_RTYPE_OUPUT:
537 	case HIDP_DATA_RTYPE_FEATURE:
538 		break;
539 
540 	default:
541 		hidp_send_ctrl_message(session,
542 			HIDP_TRANS_HANDSHAKE | HIDP_HSHK_ERR_INVALID_PARAMETER, NULL, 0);
543 	}
544 
545 	if (test_bit(HIDP_WAITING_FOR_RETURN, &session->flags) &&
546 				param == session->waiting_report_type) {
547 		if (session->waiting_report_number < 0 ||
548 		    session->waiting_report_number == skb->data[0]) {
549 			/* hidp_get_raw_report() is waiting on this report. */
550 			session->report_return = skb;
551 			done_with_skb = 0;
552 			clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags);
553 			wake_up_interruptible(&session->report_queue);
554 		}
555 	}
556 
557 	return done_with_skb;
558 }
559 
560 static void hidp_recv_ctrl_frame(struct hidp_session *session,
561 					struct sk_buff *skb)
562 {
563 	unsigned char hdr, type, param;
564 	int free_skb = 1;
565 
566 	BT_DBG("session %p skb %p len %u", session, skb, skb->len);
567 
568 	hdr = skb->data[0];
569 	skb_pull(skb, 1);
570 
571 	type = hdr & HIDP_HEADER_TRANS_MASK;
572 	param = hdr & HIDP_HEADER_PARAM_MASK;
573 
574 	switch (type) {
575 	case HIDP_TRANS_HANDSHAKE:
576 		hidp_process_handshake(session, param);
577 		break;
578 
579 	case HIDP_TRANS_HID_CONTROL:
580 		hidp_process_hid_control(session, param);
581 		break;
582 
583 	case HIDP_TRANS_DATA:
584 		free_skb = hidp_process_data(session, skb, param);
585 		break;
586 
587 	default:
588 		hidp_send_ctrl_message(session,
589 			HIDP_TRANS_HANDSHAKE | HIDP_HSHK_ERR_UNSUPPORTED_REQUEST, NULL, 0);
590 		break;
591 	}
592 
593 	if (free_skb)
594 		kfree_skb(skb);
595 }
596 
597 static void hidp_recv_intr_frame(struct hidp_session *session,
598 				struct sk_buff *skb)
599 {
600 	unsigned char hdr;
601 
602 	BT_DBG("session %p skb %p len %u", session, skb, skb->len);
603 
604 	hdr = skb->data[0];
605 	skb_pull(skb, 1);
606 
607 	if (hdr == (HIDP_TRANS_DATA | HIDP_DATA_RTYPE_INPUT)) {
608 		hidp_set_timer(session);
609 
610 		if (session->input)
611 			hidp_input_report(session, skb);
612 
613 		if (session->hid) {
614 			hidp_process_report(session, HID_INPUT_REPORT,
615 					    skb->data, skb->len, 1);
616 			BT_DBG("report len %d", skb->len);
617 		}
618 	} else {
619 		BT_DBG("Unsupported protocol header 0x%02x", hdr);
620 	}
621 
622 	kfree_skb(skb);
623 }
624 
625 static int hidp_send_frame(struct socket *sock, unsigned char *data, int len)
626 {
627 	struct kvec iv = { data, len };
628 	struct msghdr msg;
629 
630 	BT_DBG("sock %p data %p len %d", sock, data, len);
631 
632 	if (!len)
633 		return 0;
634 
635 	memset(&msg, 0, sizeof(msg));
636 
637 	return kernel_sendmsg(sock, &msg, &iv, 1, len);
638 }
639 
640 /* dequeue message from @transmit and send via @sock */
641 static void hidp_process_transmit(struct hidp_session *session,
642 				  struct sk_buff_head *transmit,
643 				  struct socket *sock)
644 {
645 	struct sk_buff *skb;
646 	int ret;
647 
648 	BT_DBG("session %p", session);
649 
650 	while ((skb = skb_dequeue(transmit))) {
651 		ret = hidp_send_frame(sock, skb->data, skb->len);
652 		if (ret == -EAGAIN) {
653 			skb_queue_head(transmit, skb);
654 			break;
655 		} else if (ret < 0) {
656 			hidp_session_terminate(session);
657 			kfree_skb(skb);
658 			break;
659 		}
660 
661 		hidp_set_timer(session);
662 		kfree_skb(skb);
663 	}
664 }
665 
666 static int hidp_setup_input(struct hidp_session *session,
667 				const struct hidp_connadd_req *req)
668 {
669 	struct input_dev *input;
670 	int i;
671 
672 	input = input_allocate_device();
673 	if (!input)
674 		return -ENOMEM;
675 
676 	session->input = input;
677 
678 	input_set_drvdata(input, session);
679 
680 	input->name = "Bluetooth HID Boot Protocol Device";
681 
682 	input->id.bustype = BUS_BLUETOOTH;
683 	input->id.vendor  = req->vendor;
684 	input->id.product = req->product;
685 	input->id.version = req->version;
686 
687 	if (req->subclass & 0x40) {
688 		set_bit(EV_KEY, input->evbit);
689 		set_bit(EV_LED, input->evbit);
690 		set_bit(EV_REP, input->evbit);
691 
692 		set_bit(LED_NUML,    input->ledbit);
693 		set_bit(LED_CAPSL,   input->ledbit);
694 		set_bit(LED_SCROLLL, input->ledbit);
695 		set_bit(LED_COMPOSE, input->ledbit);
696 		set_bit(LED_KANA,    input->ledbit);
697 
698 		for (i = 0; i < sizeof(hidp_keycode); i++)
699 			set_bit(hidp_keycode[i], input->keybit);
700 		clear_bit(0, input->keybit);
701 	}
702 
703 	if (req->subclass & 0x80) {
704 		input->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
705 		input->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |
706 			BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_MIDDLE);
707 		input->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y);
708 		input->keybit[BIT_WORD(BTN_MOUSE)] |= BIT_MASK(BTN_SIDE) |
709 			BIT_MASK(BTN_EXTRA);
710 		input->relbit[0] |= BIT_MASK(REL_WHEEL);
711 	}
712 
713 	input->dev.parent = &session->conn->hcon->dev;
714 
715 	input->event = hidp_input_event;
716 
717 	return 0;
718 }
719 
720 static int hidp_open(struct hid_device *hid)
721 {
722 	return 0;
723 }
724 
725 static void hidp_close(struct hid_device *hid)
726 {
727 }
728 
729 static int hidp_parse(struct hid_device *hid)
730 {
731 	struct hidp_session *session = hid->driver_data;
732 
733 	return hid_parse_report(session->hid, session->rd_data,
734 			session->rd_size);
735 }
736 
737 static int hidp_start(struct hid_device *hid)
738 {
739 	return 0;
740 }
741 
742 static void hidp_stop(struct hid_device *hid)
743 {
744 	struct hidp_session *session = hid->driver_data;
745 
746 	skb_queue_purge(&session->ctrl_transmit);
747 	skb_queue_purge(&session->intr_transmit);
748 
749 	hid->claimed = 0;
750 }
751 
752 static const struct hid_ll_driver hidp_hid_driver = {
753 	.parse = hidp_parse,
754 	.start = hidp_start,
755 	.stop = hidp_stop,
756 	.open  = hidp_open,
757 	.close = hidp_close,
758 	.raw_request = hidp_raw_request,
759 	.output_report = hidp_output_report,
760 };
761 
762 /* This function sets up the hid device. It does not add it
763    to the HID system. That is done in hidp_add_connection(). */
764 static int hidp_setup_hid(struct hidp_session *session,
765 				const struct hidp_connadd_req *req)
766 {
767 	struct hid_device *hid;
768 	int err;
769 
770 	session->rd_data = memdup_user(req->rd_data, req->rd_size);
771 	if (IS_ERR(session->rd_data))
772 		return PTR_ERR(session->rd_data);
773 
774 	session->rd_size = req->rd_size;
775 
776 	hid = hid_allocate_device();
777 	if (IS_ERR(hid)) {
778 		err = PTR_ERR(hid);
779 		goto fault;
780 	}
781 
782 	session->hid = hid;
783 
784 	hid->driver_data = session;
785 
786 	hid->bus     = BUS_BLUETOOTH;
787 	hid->vendor  = req->vendor;
788 	hid->product = req->product;
789 	hid->version = req->version;
790 	hid->country = req->country;
791 
792 	strscpy(hid->name, req->name, sizeof(hid->name));
793 
794 	snprintf(hid->phys, sizeof(hid->phys), "%pMR",
795 		 &l2cap_pi(session->ctrl_sock->sk)->chan->src);
796 
797 	/* NOTE: Some device modules depend on the dst address being stored in
798 	 * uniq. Please be aware of this before making changes to this behavior.
799 	 */
800 	snprintf(hid->uniq, sizeof(hid->uniq), "%pMR",
801 		 &l2cap_pi(session->ctrl_sock->sk)->chan->dst);
802 
803 	hid->dev.parent = &session->conn->hcon->dev;
804 	hid->ll_driver = &hidp_hid_driver;
805 
806 	/* True if device is blocked in drivers/hid/hid-quirks.c */
807 	if (hid_ignore(hid)) {
808 		hid_destroy_device(session->hid);
809 		session->hid = NULL;
810 		return -ENODEV;
811 	}
812 
813 	return 0;
814 
815 fault:
816 	kfree(session->rd_data);
817 	session->rd_data = NULL;
818 
819 	return err;
820 }
821 
822 /* initialize session devices */
823 static int hidp_session_dev_init(struct hidp_session *session,
824 				 const struct hidp_connadd_req *req)
825 {
826 	int ret;
827 
828 	if (req->rd_size > 0) {
829 		ret = hidp_setup_hid(session, req);
830 		if (ret && ret != -ENODEV)
831 			return ret;
832 	}
833 
834 	if (!session->hid) {
835 		ret = hidp_setup_input(session, req);
836 		if (ret < 0)
837 			return ret;
838 	}
839 
840 	return 0;
841 }
842 
843 /* destroy session devices */
844 static void hidp_session_dev_destroy(struct hidp_session *session)
845 {
846 	if (session->hid)
847 		put_device(&session->hid->dev);
848 	else if (session->input)
849 		input_put_device(session->input);
850 
851 	kfree(session->rd_data);
852 	session->rd_data = NULL;
853 }
854 
855 /* add HID/input devices to their underlying bus systems */
856 static int hidp_session_dev_add(struct hidp_session *session)
857 {
858 	int ret;
859 
860 	/* Both HID and input systems drop a ref-count when unregistering the
861 	 * device but they don't take a ref-count when registering them. Work
862 	 * around this by explicitly taking a refcount during registration
863 	 * which is dropped automatically by unregistering the devices. */
864 
865 	if (session->hid) {
866 		ret = hid_add_device(session->hid);
867 		if (ret)
868 			return ret;
869 		get_device(&session->hid->dev);
870 	} else if (session->input) {
871 		ret = input_register_device(session->input);
872 		if (ret)
873 			return ret;
874 		input_get_device(session->input);
875 	}
876 
877 	return 0;
878 }
879 
880 /* remove HID/input devices from their bus systems */
881 static void hidp_session_dev_del(struct hidp_session *session)
882 {
883 	if (session->hid)
884 		hid_destroy_device(session->hid);
885 	else if (session->input)
886 		input_unregister_device(session->input);
887 }
888 
889 /*
890  * Asynchronous device registration
891  * HID device drivers might want to perform I/O during initialization to
892  * detect device types. Therefore, call device registration in a separate
893  * worker so the HIDP thread can schedule I/O operations.
894  * Note that this must be called after the worker thread was initialized
895  * successfully. This will then add the devices and increase session state
896  * on success, otherwise it will terminate the session thread.
897  */
898 static void hidp_session_dev_work(struct work_struct *work)
899 {
900 	struct hidp_session *session = container_of(work,
901 						    struct hidp_session,
902 						    dev_init);
903 	int ret;
904 
905 	ret = hidp_session_dev_add(session);
906 	if (!ret)
907 		atomic_inc(&session->state);
908 	else
909 		hidp_session_terminate(session);
910 }
911 
912 /*
913  * Create new session object
914  * Allocate session object, initialize static fields, copy input data into the
915  * object and take a reference to all sub-objects.
916  * This returns 0 on success and puts a pointer to the new session object in
917  * \out. Otherwise, an error code is returned.
918  * The new session object has an initial ref-count of 1.
919  */
920 static int hidp_session_new(struct hidp_session **out, const bdaddr_t *bdaddr,
921 			    struct socket *ctrl_sock,
922 			    struct socket *intr_sock,
923 			    const struct hidp_connadd_req *req,
924 			    struct l2cap_conn *conn)
925 {
926 	struct hidp_session *session;
927 	int ret;
928 	struct bt_sock *ctrl, *intr;
929 
930 	ctrl = bt_sk(ctrl_sock->sk);
931 	intr = bt_sk(intr_sock->sk);
932 
933 	session = kzalloc_obj(*session);
934 	if (!session)
935 		return -ENOMEM;
936 
937 	/* object and runtime management */
938 	kref_init(&session->ref);
939 	atomic_set(&session->state, HIDP_SESSION_IDLING);
940 	init_waitqueue_head(&session->state_queue);
941 	session->flags = req->flags & BIT(HIDP_BLUETOOTH_VENDOR_ID);
942 
943 	/* connection management */
944 	bacpy(&session->bdaddr, bdaddr);
945 	session->conn = l2cap_conn_get(conn);
946 	session->user.probe = hidp_session_probe;
947 	session->user.remove = hidp_session_remove;
948 	INIT_LIST_HEAD(&session->user.list);
949 	session->ctrl_sock = ctrl_sock;
950 	session->intr_sock = intr_sock;
951 	skb_queue_head_init(&session->ctrl_transmit);
952 	skb_queue_head_init(&session->intr_transmit);
953 	session->ctrl_mtu = min_t(uint, l2cap_pi(ctrl)->chan->omtu,
954 					l2cap_pi(ctrl)->chan->imtu);
955 	session->intr_mtu = min_t(uint, l2cap_pi(intr)->chan->omtu,
956 					l2cap_pi(intr)->chan->imtu);
957 	session->idle_to = req->idle_to;
958 
959 	/* device management */
960 	INIT_WORK(&session->dev_init, hidp_session_dev_work);
961 	timer_setup(&session->timer, hidp_idle_timeout, 0);
962 
963 	/* session data */
964 	mutex_init(&session->report_mutex);
965 	init_waitqueue_head(&session->report_queue);
966 
967 	ret = hidp_session_dev_init(session, req);
968 	if (ret)
969 		goto err_free;
970 
971 	get_file(session->intr_sock->file);
972 	get_file(session->ctrl_sock->file);
973 	*out = session;
974 	return 0;
975 
976 err_free:
977 	l2cap_conn_put(session->conn);
978 	kfree(session);
979 	return ret;
980 }
981 
982 /* increase ref-count of the given session by one */
983 static void hidp_session_get(struct hidp_session *session)
984 {
985 	kref_get(&session->ref);
986 }
987 
988 /* release callback */
989 static void session_free(struct kref *ref)
990 {
991 	struct hidp_session *session = container_of(ref, struct hidp_session,
992 						    ref);
993 
994 	hidp_session_dev_destroy(session);
995 	skb_queue_purge(&session->ctrl_transmit);
996 	skb_queue_purge(&session->intr_transmit);
997 	fput(session->intr_sock->file);
998 	fput(session->ctrl_sock->file);
999 	if (session->conn)
1000 		l2cap_conn_put(session->conn);
1001 	kfree(session);
1002 }
1003 
1004 /* decrease ref-count of the given session by one */
1005 static void hidp_session_put(struct hidp_session *session)
1006 {
1007 	kref_put(&session->ref, session_free);
1008 }
1009 
1010 /*
1011  * Search the list of active sessions for a session with target address
1012  * \bdaddr. You must hold at least a read-lock on \hidp_session_sem. As long as
1013  * you do not release this lock, the session objects cannot vanish and you can
1014  * safely take a reference to the session yourself.
1015  */
1016 static struct hidp_session *__hidp_session_find(const bdaddr_t *bdaddr)
1017 {
1018 	struct hidp_session *session;
1019 
1020 	list_for_each_entry(session, &hidp_session_list, list) {
1021 		if (!bacmp(bdaddr, &session->bdaddr))
1022 			return session;
1023 	}
1024 
1025 	return NULL;
1026 }
1027 
1028 /*
1029  * Same as __hidp_session_find() but no locks must be held. This also takes a
1030  * reference of the returned session (if non-NULL) so you must drop this
1031  * reference if you no longer use the object.
1032  */
1033 static struct hidp_session *hidp_session_find(const bdaddr_t *bdaddr)
1034 {
1035 	struct hidp_session *session;
1036 
1037 	down_read(&hidp_session_sem);
1038 
1039 	session = __hidp_session_find(bdaddr);
1040 	if (session)
1041 		hidp_session_get(session);
1042 
1043 	up_read(&hidp_session_sem);
1044 
1045 	return session;
1046 }
1047 
1048 /*
1049  * Consume session->conn: clear the member under hidp_session_sem, then
1050  * l2cap_unregister_user() and l2cap_conn_put() the snapshot outside the
1051  * sem.  At most one caller wins; later callers see NULL and skip.  The
1052  * reference is the one hidp_session_new() took via l2cap_conn_get().
1053  */
1054 static void hidp_session_unregister_conn(struct hidp_session *session)
1055 {
1056 	struct l2cap_conn *conn;
1057 
1058 	down_write(&hidp_session_sem);
1059 	conn = session->conn;
1060 	if (conn)
1061 		session->conn = NULL;
1062 	up_write(&hidp_session_sem);
1063 
1064 	if (conn) {
1065 		l2cap_unregister_user(conn, &session->user);
1066 		l2cap_conn_put(conn);
1067 	}
1068 }
1069 
1070 /*
1071  * Start session synchronously
1072  * This starts a session thread and waits until initialization
1073  * is done or returns an error if it couldn't be started.
1074  * If this returns 0 the session thread is up and running. You must call
1075  * hipd_session_stop_sync() before deleting any runtime resources.
1076  */
1077 static int hidp_session_start_sync(struct hidp_session *session)
1078 {
1079 	unsigned int vendor, product;
1080 
1081 	if (session->hid) {
1082 		vendor  = session->hid->vendor;
1083 		product = session->hid->product;
1084 	} else if (session->input) {
1085 		vendor  = session->input->id.vendor;
1086 		product = session->input->id.product;
1087 	} else {
1088 		vendor = 0x0000;
1089 		product = 0x0000;
1090 	}
1091 
1092 	session->task = kthread_run(hidp_session_thread, session,
1093 				    "khidpd_%04x%04x", vendor, product);
1094 	if (IS_ERR(session->task))
1095 		return PTR_ERR(session->task);
1096 
1097 	while (atomic_read(&session->state) <= HIDP_SESSION_IDLING)
1098 		wait_event(session->state_queue,
1099 			   atomic_read(&session->state) > HIDP_SESSION_IDLING);
1100 
1101 	return 0;
1102 }
1103 
1104 /*
1105  * Terminate session thread
1106  * Wake up session thread and notify it to stop. This is asynchronous and
1107  * returns immediately. Call this whenever a runtime error occurs and you want
1108  * the session to stop.
1109  * Note: wake_up_interruptible() performs any necessary memory-barriers for us.
1110  */
1111 static void hidp_session_terminate(struct hidp_session *session)
1112 {
1113 	atomic_inc(&session->terminate);
1114 	/*
1115 	 * See the comment preceding the call to wait_woken()
1116 	 * in hidp_session_run().
1117 	 */
1118 	wake_up_interruptible(&hidp_session_wq);
1119 }
1120 
1121 /*
1122  * Probe HIDP session
1123  * This is called from the l2cap_conn core when our l2cap_user object is bound
1124  * to the hci-connection. We get the session via the \user object and can now
1125  * start the session thread, link it into the global session list and
1126  * schedule HID/input device registration.
1127  * The global session-list owns its own reference to the session object so you
1128  * can drop your own reference after registering the l2cap_user object.
1129  */
1130 static int hidp_session_probe(struct l2cap_conn *conn,
1131 			      struct l2cap_user *user)
1132 {
1133 	struct hidp_session *session = container_of(user,
1134 						    struct hidp_session,
1135 						    user);
1136 	struct hidp_session *s;
1137 	int ret;
1138 
1139 	down_write(&hidp_session_sem);
1140 
1141 	/* check that no other session for this device exists */
1142 	s = __hidp_session_find(&session->bdaddr);
1143 	if (s) {
1144 		ret = -EEXIST;
1145 		goto out_unlock;
1146 	}
1147 
1148 	if (session->input) {
1149 		ret = hidp_session_dev_add(session);
1150 		if (ret)
1151 			goto out_unlock;
1152 	}
1153 
1154 	ret = hidp_session_start_sync(session);
1155 	if (ret)
1156 		goto out_del;
1157 
1158 	/* HID device registration is async to allow I/O during probe */
1159 	if (session->input)
1160 		atomic_inc(&session->state);
1161 	else
1162 		schedule_work(&session->dev_init);
1163 
1164 	hidp_session_get(session);
1165 	list_add(&session->list, &hidp_session_list);
1166 	ret = 0;
1167 	goto out_unlock;
1168 
1169 out_del:
1170 	if (session->input)
1171 		hidp_session_dev_del(session);
1172 out_unlock:
1173 	up_write(&hidp_session_sem);
1174 	return ret;
1175 }
1176 
1177 /*
1178  * Remove HIDP session
1179  * Called from the l2cap_conn core when either we explicitly unregistered
1180  * the l2cap_user object or if the underlying connection is shut down.
1181  * We signal the hidp-session thread to shut down, unregister the HID/input
1182  * devices and unlink the session from the global list.
1183  * This drops the reference to the session that is owned by the global
1184  * session-list.
1185  * Note: We _must_ not synchronosly wait for the session-thread to shut down.
1186  * This is, because the session-thread might be waiting for an HCI lock that is
1187  * held while we are called. Therefore, we only unregister the devices and
1188  * notify the session-thread to terminate. The thread itself owns a reference
1189  * to the session object so it can safely shut down.
1190  */
1191 static void hidp_session_remove(struct l2cap_conn *conn,
1192 				struct l2cap_user *user)
1193 {
1194 	struct hidp_session *session = container_of(user,
1195 						    struct hidp_session,
1196 						    user);
1197 
1198 	down_write(&hidp_session_sem);
1199 
1200 	/* Drop L2CAP reference immediately to indicate that
1201 	 * l2cap_unregister_user() shall not be called as it is already
1202 	 * considered removed.
1203 	 */
1204 	if (session->conn) {
1205 		l2cap_conn_put(session->conn);
1206 		session->conn = NULL;
1207 	}
1208 
1209 	hidp_session_terminate(session);
1210 
1211 	cancel_work_sync(&session->dev_init);
1212 	if (session->input ||
1213 	    atomic_read(&session->state) > HIDP_SESSION_PREPARING)
1214 		hidp_session_dev_del(session);
1215 
1216 	list_del(&session->list);
1217 
1218 	up_write(&hidp_session_sem);
1219 
1220 	hidp_session_put(session);
1221 }
1222 
1223 /*
1224  * Session Worker
1225  * This performs the actual main-loop of the HIDP worker. We first check
1226  * whether the underlying connection is still alive, then parse all pending
1227  * messages and finally send all outstanding messages.
1228  */
1229 static void hidp_session_run(struct hidp_session *session)
1230 {
1231 	struct sock *ctrl_sk = session->ctrl_sock->sk;
1232 	struct sock *intr_sk = session->intr_sock->sk;
1233 	struct sk_buff *skb;
1234 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
1235 
1236 	add_wait_queue(&hidp_session_wq, &wait);
1237 	for (;;) {
1238 		/*
1239 		 * This thread can be woken up two ways:
1240 		 *  - You call hidp_session_terminate() which sets the
1241 		 *    session->terminate flag and wakes this thread up.
1242 		 *  - Via modifying the socket state of ctrl/intr_sock. This
1243 		 *    thread is woken up by ->sk_state_changed().
1244 		 */
1245 
1246 		if (atomic_read(&session->terminate))
1247 			break;
1248 
1249 		if (ctrl_sk->sk_state != BT_CONNECTED ||
1250 		    intr_sk->sk_state != BT_CONNECTED)
1251 			break;
1252 
1253 		/* parse incoming intr-skbs */
1254 		while ((skb = skb_dequeue(&intr_sk->sk_receive_queue))) {
1255 			skb_orphan(skb);
1256 			if (!skb_linearize(skb))
1257 				hidp_recv_intr_frame(session, skb);
1258 			else
1259 				kfree_skb(skb);
1260 		}
1261 
1262 		/* send pending intr-skbs */
1263 		hidp_process_transmit(session, &session->intr_transmit,
1264 				      session->intr_sock);
1265 
1266 		/* parse incoming ctrl-skbs */
1267 		while ((skb = skb_dequeue(&ctrl_sk->sk_receive_queue))) {
1268 			skb_orphan(skb);
1269 			if (!skb_linearize(skb))
1270 				hidp_recv_ctrl_frame(session, skb);
1271 			else
1272 				kfree_skb(skb);
1273 		}
1274 
1275 		/* send pending ctrl-skbs */
1276 		hidp_process_transmit(session, &session->ctrl_transmit,
1277 				      session->ctrl_sock);
1278 
1279 		/*
1280 		 * wait_woken() performs the necessary memory barriers
1281 		 * for us; see the header comment for this primitive.
1282 		 */
1283 		wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
1284 	}
1285 	remove_wait_queue(&hidp_session_wq, &wait);
1286 
1287 	atomic_inc(&session->terminate);
1288 }
1289 
1290 static int hidp_session_wake_function(wait_queue_entry_t *wait,
1291 				      unsigned int mode,
1292 				      int sync, void *key)
1293 {
1294 	wake_up_interruptible(&hidp_session_wq);
1295 	return false;
1296 }
1297 
1298 /*
1299  * HIDP session thread
1300  * This thread runs the I/O for a single HIDP session. Startup is synchronous
1301  * which allows us to take references to ourself here instead of doing that in
1302  * the caller.
1303  * When we are ready to run we notify the caller and call hidp_session_run().
1304  */
1305 static int hidp_session_thread(void *arg)
1306 {
1307 	struct hidp_session *session = arg;
1308 	DEFINE_WAIT_FUNC(ctrl_wait, hidp_session_wake_function);
1309 	DEFINE_WAIT_FUNC(intr_wait, hidp_session_wake_function);
1310 
1311 	BT_DBG("session %p", session);
1312 
1313 	/* initialize runtime environment */
1314 	hidp_session_get(session);
1315 	__module_get(THIS_MODULE);
1316 	set_user_nice(current, -15);
1317 	hidp_set_timer(session);
1318 
1319 	add_wait_queue(sk_sleep(session->ctrl_sock->sk), &ctrl_wait);
1320 	add_wait_queue(sk_sleep(session->intr_sock->sk), &intr_wait);
1321 	/* This memory barrier is paired with wq_has_sleeper(). See
1322 	 * sock_poll_wait() for more information why this is needed. */
1323 	smp_mb__before_atomic();
1324 
1325 	/* notify synchronous startup that we're ready */
1326 	atomic_inc(&session->state);
1327 	wake_up(&session->state_queue);
1328 
1329 	/* run session */
1330 	hidp_session_run(session);
1331 
1332 	/* cleanup runtime environment */
1333 	remove_wait_queue(sk_sleep(session->intr_sock->sk), &intr_wait);
1334 	remove_wait_queue(sk_sleep(session->ctrl_sock->sk), &ctrl_wait);
1335 	wake_up_interruptible(&session->report_queue);
1336 	hidp_del_timer(session);
1337 
1338 	/*
1339 	 * If we stopped ourself due to any internal signal, we should try to
1340 	 * unregister our own session here to avoid having it linger until the
1341 	 * parent l2cap_conn dies or user-space cleans it up.
1342 	 * This does not deadlock as we don't do any synchronous shutdown.
1343 	 * Instead, this call has the same semantics as if user-space tried to
1344 	 * delete the session.
1345 	 */
1346 	hidp_session_unregister_conn(session);
1347 
1348 	hidp_session_put(session);
1349 
1350 	module_put_and_kthread_exit(0);
1351 	return 0;
1352 }
1353 
1354 static int hidp_verify_sockets(struct socket *ctrl_sock,
1355 			       struct socket *intr_sock)
1356 {
1357 	struct l2cap_chan *ctrl_chan, *intr_chan;
1358 	struct bt_sock *ctrl, *intr;
1359 	struct hidp_session *session;
1360 
1361 	if (!l2cap_is_socket(ctrl_sock) || !l2cap_is_socket(intr_sock))
1362 		return -EINVAL;
1363 
1364 	ctrl_chan = l2cap_pi(ctrl_sock->sk)->chan;
1365 	intr_chan = l2cap_pi(intr_sock->sk)->chan;
1366 
1367 	if (bacmp(&ctrl_chan->src, &intr_chan->src) ||
1368 	    bacmp(&ctrl_chan->dst, &intr_chan->dst))
1369 		return -ENOTUNIQ;
1370 
1371 	ctrl = bt_sk(ctrl_sock->sk);
1372 	intr = bt_sk(intr_sock->sk);
1373 
1374 	if (ctrl->sk.sk_state != BT_CONNECTED ||
1375 	    intr->sk.sk_state != BT_CONNECTED)
1376 		return -EBADFD;
1377 
1378 	/* early session check, we check again during session registration */
1379 	session = hidp_session_find(&ctrl_chan->dst);
1380 	if (session) {
1381 		hidp_session_put(session);
1382 		return -EEXIST;
1383 	}
1384 
1385 	return 0;
1386 }
1387 
1388 int hidp_connection_add(const struct hidp_connadd_req *req,
1389 			struct socket *ctrl_sock,
1390 			struct socket *intr_sock)
1391 {
1392 	u32 valid_flags = BIT(HIDP_VIRTUAL_CABLE_UNPLUG) |
1393 			  BIT(HIDP_BOOT_PROTOCOL_MODE);
1394 	struct hidp_session *session;
1395 	struct l2cap_conn *conn;
1396 	struct l2cap_chan *chan;
1397 	int ret;
1398 
1399 	ret = hidp_verify_sockets(ctrl_sock, intr_sock);
1400 	if (ret)
1401 		return ret;
1402 
1403 	if (req->flags & ~valid_flags)
1404 		return -EINVAL;
1405 
1406 	chan = l2cap_pi(ctrl_sock->sk)->chan;
1407 	conn = NULL;
1408 	l2cap_chan_lock(chan);
1409 	if (chan->conn)
1410 		conn = l2cap_conn_get(chan->conn);
1411 	l2cap_chan_unlock(chan);
1412 
1413 	if (!conn)
1414 		return -EBADFD;
1415 
1416 	ret = hidp_session_new(&session, &chan->dst, ctrl_sock,
1417 			       intr_sock, req, conn);
1418 	if (ret)
1419 		goto out_conn;
1420 
1421 	ret = l2cap_register_user(conn, &session->user);
1422 	if (ret)
1423 		goto out_session;
1424 
1425 	ret = 0;
1426 
1427 out_session:
1428 	hidp_session_put(session);
1429 out_conn:
1430 	l2cap_conn_put(conn);
1431 	return ret;
1432 }
1433 
1434 int hidp_connection_del(struct hidp_conndel_req *req)
1435 {
1436 	u32 valid_flags = BIT(HIDP_VIRTUAL_CABLE_UNPLUG);
1437 	struct hidp_session *session;
1438 
1439 	if (req->flags & ~valid_flags)
1440 		return -EINVAL;
1441 
1442 	session = hidp_session_find(&req->bdaddr);
1443 	if (!session)
1444 		return -ENOENT;
1445 
1446 	if (req->flags & BIT(HIDP_VIRTUAL_CABLE_UNPLUG))
1447 		hidp_send_ctrl_message(session,
1448 				       HIDP_TRANS_HID_CONTROL |
1449 				         HIDP_CTRL_VIRTUAL_CABLE_UNPLUG,
1450 				       NULL, 0);
1451 	else
1452 		hidp_session_unregister_conn(session);
1453 
1454 	hidp_session_put(session);
1455 
1456 	return 0;
1457 }
1458 
1459 int hidp_get_connlist(struct hidp_connlist_req *req)
1460 {
1461 	struct hidp_session *session;
1462 	int err = 0, n = 0;
1463 
1464 	BT_DBG("");
1465 
1466 	down_read(&hidp_session_sem);
1467 
1468 	list_for_each_entry(session, &hidp_session_list, list) {
1469 		struct hidp_conninfo ci;
1470 
1471 		hidp_copy_session(session, &ci);
1472 
1473 		if (copy_to_user(req->ci, &ci, sizeof(ci))) {
1474 			err = -EFAULT;
1475 			break;
1476 		}
1477 
1478 		if (++n >= req->cnum)
1479 			break;
1480 
1481 		req->ci++;
1482 	}
1483 	req->cnum = n;
1484 
1485 	up_read(&hidp_session_sem);
1486 	return err;
1487 }
1488 
1489 int hidp_get_conninfo(struct hidp_conninfo *ci)
1490 {
1491 	struct hidp_session *session;
1492 
1493 	session = hidp_session_find(&ci->bdaddr);
1494 	if (session) {
1495 		hidp_copy_session(session, ci);
1496 		hidp_session_put(session);
1497 	}
1498 
1499 	return session ? 0 : -ENOENT;
1500 }
1501 
1502 static int __init hidp_init(void)
1503 {
1504 	BT_INFO("HIDP (Human Interface Emulation) ver %s", VERSION);
1505 
1506 	return hidp_init_sockets();
1507 }
1508 
1509 static void __exit hidp_exit(void)
1510 {
1511 	hidp_cleanup_sockets();
1512 }
1513 
1514 module_init(hidp_init);
1515 module_exit(hidp_exit);
1516 
1517 MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>");
1518 MODULE_AUTHOR("David Herrmann <dh.herrmann@gmail.com>");
1519 MODULE_DESCRIPTION("Bluetooth HIDP ver " VERSION);
1520 MODULE_VERSION(VERSION);
1521 MODULE_LICENSE("GPL");
1522 MODULE_ALIAS("bt-proto-6");
1523