Linux Audio

Check our new training course

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