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