File Index
Files and directories
Sign in
FILE

hid-core.c

File preview with syntax highlighting.

linux-6.19.14/drivers/hid/hid-core.c C
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/*
   3 *  HID support for Linux
   4 *
   5 *  Copyright (c) 1999 Andreas Gal
   6 *  Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
   7 *  Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
   8 *  Copyright (c) 2006-2012 Jiri Kosina
   9 */
  10
  11/*
  12 */
  13
  14#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  15
  16#include <linux/module.h>
  17#include <linux/slab.h>
  18#include <linux/init.h>
  19#include <linux/kernel.h>
  20#include <linux/list.h>
  21#include <linux/mm.h>
  22#include <linux/spinlock.h>
  23#include <linux/unaligned.h>
  24#include <asm/byteorder.h>
  25#include <linux/input.h>
  26#include <linux/wait.h>
  27#include <linux/vmalloc.h>
  28#include <linux/sched.h>
  29#include <linux/semaphore.h>
  30
  31#include <linux/hid.h>
  32#include <linux/hiddev.h>
  33#include <linux/hid-debug.h>
  34#include <linux/hidraw.h>
  35
  36#include "hid-ids.h"
  37
  38/*
  39 * Version Information
  40 */
  41
  42#define DRIVER_DESC "HID core driver"
  43
  44static int hid_ignore_special_drivers = 0;
  45module_param_named(ignore_special_drivers, hid_ignore_special_drivers, int, 0600);
  46MODULE_PARM_DESC(ignore_special_drivers, "Ignore any special drivers and handle all devices by generic driver");
  47
  48/*
  49 * Convert a signed n-bit integer to signed 32-bit integer.
  50 */
  51
  52static s32 snto32(__u32 value, unsigned int n)
  53{
  54	if (!value || !n)
  55		return 0;
  56
  57	if (n > 32)
  58		n = 32;
  59
  60	return sign_extend32(value, n - 1);
  61}
  62
  63/*
  64 * Convert a signed 32-bit integer to a signed n-bit integer.
  65 */
  66
  67static u32 s32ton(__s32 value, unsigned int n)
  68{
  69	s32 a;
  70
  71	if (!value || !n)
  72		return 0;
  73
  74	if (n > 32)
  75		n = 32;
  76
  77	a = value >> (n - 1);
  78	if (a && a != -1)
  79		return value < 0 ? 1 << (n - 1) : (1 << (n - 1)) - 1;
  80	return value & ((1 << n) - 1);
  81}
  82
  83/*
  84 * Register a new report for a device.
  85 */
  86
  87struct hid_report *hid_register_report(struct hid_device *device,
  88				       enum hid_report_type type, unsigned int id,
  89				       unsigned int application)
  90{
  91	struct hid_report_enum *report_enum = device->report_enum + type;
  92	struct hid_report *report;
  93
  94	if (id >= HID_MAX_IDS)
  95		return NULL;
  96	if (report_enum->report_id_hash[id])
  97		return report_enum->report_id_hash[id];
  98
  99	report = kzalloc(sizeof(struct hid_report), GFP_KERNEL);
 100	if (!report)
 101		return NULL;
 102
 103	if (id != 0)
 104		report_enum->numbered = 1;
 105
 106	report->id = id;
 107	report->type = type;
 108	report->size = 0;
 109	report->device = device;
 110	report->application = application;
 111	report_enum->report_id_hash[id] = report;
 112
 113	list_add_tail(&report->list, &report_enum->report_list);
 114	INIT_LIST_HEAD(&report->field_entry_list);
 115
 116	return report;
 117}
 118EXPORT_SYMBOL_GPL(hid_register_report);
 119
 120/*
 121 * Register a new field for this report.
 122 */
 123
 124static struct hid_field *hid_register_field(struct hid_report *report, unsigned usages)
 125{
 126	struct hid_field *field;
 127
 128	if (report->maxfield == HID_MAX_FIELDS) {
 129		hid_err(report->device, "too many fields in report\n");
 130		return NULL;
 131	}
 132
 133	field = kvzalloc((sizeof(struct hid_field) +
 134			  usages * sizeof(struct hid_usage) +
 135			  3 * usages * sizeof(unsigned int)), GFP_KERNEL);
 136	if (!field)
 137		return NULL;
 138
 139	field->index = report->maxfield++;
 140	report->field[field->index] = field;
 141	field->usage = (struct hid_usage *)(field + 1);
 142	field->value = (s32 *)(field->usage + usages);
 143	field->new_value = (s32 *)(field->value + usages);
 144	field->usages_priorities = (s32 *)(field->new_value + usages);
 145	field->report = report;
 146
 147	return field;
 148}
 149
 150/*
 151 * Open a collection. The type/usage is pushed on the stack.
 152 */
 153
 154static int open_collection(struct hid_parser *parser, unsigned type)
 155{
 156	struct hid_collection *collection;
 157	unsigned usage;
 158	int collection_index;
 159
 160	usage = parser->local.usage[0];
 161
 162	if (parser->collection_stack_ptr == parser->collection_stack_size) {
 163		unsigned int *collection_stack;
 164		unsigned int new_size = parser->collection_stack_size +
 165					HID_COLLECTION_STACK_SIZE;
 166
 167		collection_stack = krealloc(parser->collection_stack,
 168					    new_size * sizeof(unsigned int),
 169					    GFP_KERNEL);
 170		if (!collection_stack)
 171			return -ENOMEM;
 172
 173		parser->collection_stack = collection_stack;
 174		parser->collection_stack_size = new_size;
 175	}
 176
 177	if (parser->device->maxcollection == parser->device->collection_size) {
 178		collection = kmalloc(
 179				array3_size(sizeof(struct hid_collection),
 180					    parser->device->collection_size,
 181					    2),
 182				GFP_KERNEL);
 183		if (collection == NULL) {
 184			hid_err(parser->device, "failed to reallocate collection array\n");
 185			return -ENOMEM;
 186		}
 187		memcpy(collection, parser->device->collection,
 188			sizeof(struct hid_collection) *
 189			parser->device->collection_size);
 190		memset(collection + parser->device->collection_size, 0,
 191			sizeof(struct hid_collection) *
 192			parser->device->collection_size);
 193		kfree(parser->device->collection);
 194		parser->device->collection = collection;
 195		parser->device->collection_size *= 2;
 196	}
 197
 198	parser->collection_stack[parser->collection_stack_ptr++] =
 199		parser->device->maxcollection;
 200
 201	collection_index = parser->device->maxcollection++;
 202	collection = parser->device->collection + collection_index;
 203	collection->type = type;
 204	collection->usage = usage;
 205	collection->level = parser->collection_stack_ptr - 1;
 206	collection->parent_idx = (collection->level == 0) ? -1 :
 207		parser->collection_stack[collection->level - 1];
 208
 209	if (type == HID_COLLECTION_APPLICATION)
 210		parser->device->maxapplication++;
 211
 212	return 0;
 213}
 214
 215/*
 216 * Close a collection.
 217 */
 218
 219static int close_collection(struct hid_parser *parser)
 220{
 221	if (!parser->collection_stack_ptr) {
 222		hid_err(parser->device, "collection stack underflow\n");
 223		return -EINVAL;
 224	}
 225	parser->collection_stack_ptr--;
 226	return 0;
 227}
 228
 229/*
 230 * Climb up the stack, search for the specified collection type
 231 * and return the usage.
 232 */
 233
 234static unsigned hid_lookup_collection(struct hid_parser *parser, unsigned type)
 235{
 236	struct hid_collection *collection = parser->device->collection;
 237	int n;
 238
 239	for (n = parser->collection_stack_ptr - 1; n >= 0; n--) {
 240		unsigned index = parser->collection_stack[n];
 241		if (collection[index].type == type)
 242			return collection[index].usage;
 243	}
 244	return 0; /* we know nothing about this usage type */
 245}
 246
 247/*
 248 * Concatenate usage which defines 16 bits or less with the
 249 * currently defined usage page to form a 32 bit usage
 250 */
 251
 252static void complete_usage(struct hid_parser *parser, unsigned int index)
 253{
 254	parser->local.usage[index] &= 0xFFFF;
 255	parser->local.usage[index] |=
 256		(parser->global.usage_page & 0xFFFF) << 16;
 257}
 258
 259/*
 260 * Add a usage to the temporary parser table.
 261 */
 262
 263static int hid_add_usage(struct hid_parser *parser, unsigned usage, u8 size)
 264{
 265	if (parser->local.usage_index >= HID_MAX_USAGES) {
 266		hid_err(parser->device, "usage index exceeded\n");
 267		return -1;
 268	}
 269	parser->local.usage[parser->local.usage_index] = usage;
 270
 271	/*
 272	 * If Usage item only includes usage id, concatenate it with
 273	 * currently defined usage page
 274	 */
 275	if (size <= 2)
 276		complete_usage(parser, parser->local.usage_index);
 277
 278	parser->local.usage_size[parser->local.usage_index] = size;
 279	parser->local.collection_index[parser->local.usage_index] =
 280		parser->collection_stack_ptr ?
 281		parser->collection_stack[parser->collection_stack_ptr - 1] : 0;
 282	parser->local.usage_index++;
 283	return 0;
 284}
 285
 286/*
 287 * Register a new field for this report.
 288 */
 289
 290static int hid_add_field(struct hid_parser *parser, unsigned report_type, unsigned flags)
 291{
 292	struct hid_report *report;
 293	struct hid_field *field;
 294	unsigned int max_buffer_size = HID_MAX_BUFFER_SIZE;
 295	unsigned int usages;
 296	unsigned int offset;
 297	unsigned int i;
 298	unsigned int application;
 299
 300	application = hid_lookup_collection(parser, HID_COLLECTION_APPLICATION);
 301
 302	report = hid_register_report(parser->device, report_type,
 303				     parser->global.report_id, application);
 304	if (!report) {
 305		hid_err(parser->device, "hid_register_report failed\n");
 306		return -1;
 307	}
 308
 309	/* Handle both signed and unsigned cases properly */
 310	if ((parser->global.logical_minimum < 0 &&
 311		parser->global.logical_maximum <
 312		parser->global.logical_minimum) ||
 313		(parser->global.logical_minimum >= 0 &&
 314		(__u32)parser->global.logical_maximum <
 315		(__u32)parser->global.logical_minimum)) {
 316		dbg_hid("logical range invalid 0x%x 0x%x\n",
 317			parser->global.logical_minimum,
 318			parser->global.logical_maximum);
 319		return -1;
 320	}
 321
 322	offset = report->size;
 323	report->size += parser->global.report_size * parser->global.report_count;
 324
 325	if (parser->device->ll_driver->max_buffer_size)
 326		max_buffer_size = parser->device->ll_driver->max_buffer_size;
 327
 328	/* Total size check: Allow for possible report index byte */
 329	if (report->size > (max_buffer_size - 1) << 3) {
 330		hid_err(parser->device, "report is too long\n");
 331		return -1;
 332	}
 333
 334	if (!parser->local.usage_index) /* Ignore padding fields */
 335		return 0;
 336
 337	usages = max_t(unsigned, parser->local.usage_index,
 338				 parser->global.report_count);
 339
 340	field = hid_register_field(report, usages);
 341	if (!field)
 342		return 0;
 343
 344	field->physical = hid_lookup_collection(parser, HID_COLLECTION_PHYSICAL);
 345	field->logical = hid_lookup_collection(parser, HID_COLLECTION_LOGICAL);
 346	field->application = application;
 347
 348	for (i = 0; i < usages; i++) {
 349		unsigned j = i;
 350		/* Duplicate the last usage we parsed if we have excess values */
 351		if (i >= parser->local.usage_index)
 352			j = parser->local.usage_index - 1;
 353		field->usage[i].hid = parser->local.usage[j];
 354		field->usage[i].collection_index =
 355			parser->local.collection_index[j];
 356		field->usage[i].usage_index = i;
 357		field->usage[i].resolution_multiplier = 1;
 358	}
 359
 360	field->maxusage = usages;
 361	field->flags = flags;
 362	field->report_offset = offset;
 363	field->report_type = report_type;
 364	field->report_size = parser->global.report_size;
 365	field->report_count = parser->global.report_count;
 366	field->logical_minimum = parser->global.logical_minimum;
 367	field->logical_maximum = parser->global.logical_maximum;
 368	field->physical_minimum = parser->global.physical_minimum;
 369	field->physical_maximum = parser->global.physical_maximum;
 370	field->unit_exponent = parser->global.unit_exponent;
 371	field->unit = parser->global.unit;
 372
 373	return 0;
 374}
 375
 376/*
 377 * Read data value from item.
 378 */
 379
 380static u32 item_udata(struct hid_item *item)
 381{
 382	switch (item->size) {
 383	case 1: return item->data.u8;
 384	case 2: return item->data.u16;
 385	case 4: return item->data.u32;
 386	}
 387	return 0;
 388}
 389
 390static s32 item_sdata(struct hid_item *item)
 391{
 392	switch (item->size) {
 393	case 1: return item->data.s8;
 394	case 2: return item->data.s16;
 395	case 4: return item->data.s32;
 396	}
 397	return 0;
 398}
 399
 400/*
 401 * Process a global item.
 402 */
 403
 404static int hid_parser_global(struct hid_parser *parser, struct hid_item *item)
 405{
 406	__s32 raw_value;
 407	switch (item->tag) {
 408	case HID_GLOBAL_ITEM_TAG_PUSH:
 409
 410		if (parser->global_stack_ptr == HID_GLOBAL_STACK_SIZE) {
 411			hid_err(parser->device, "global environment stack overflow\n");
 412			return -1;
 413		}
 414
 415		memcpy(parser->global_stack + parser->global_stack_ptr++,
 416			&parser->global, sizeof(struct hid_global));
 417		return 0;
 418
 419	case HID_GLOBAL_ITEM_TAG_POP:
 420
 421		if (!parser->global_stack_ptr) {
 422			hid_err(parser->device, "global environment stack underflow\n");
 423			return -1;
 424		}
 425
 426		memcpy(&parser->global, parser->global_stack +
 427			--parser->global_stack_ptr, sizeof(struct hid_global));
 428		return 0;
 429
 430	case HID_GLOBAL_ITEM_TAG_USAGE_PAGE:
 431		parser->global.usage_page = item_udata(item);
 432		return 0;
 433
 434	case HID_GLOBAL_ITEM_TAG_LOGICAL_MINIMUM:
 435		parser->global.logical_minimum = item_sdata(item);
 436		return 0;
 437
 438	case HID_GLOBAL_ITEM_TAG_LOGICAL_MAXIMUM:
 439		if (parser->global.logical_minimum < 0)
 440			parser->global.logical_maximum = item_sdata(item);
 441		else
 442			parser->global.logical_maximum = item_udata(item);
 443		return 0;
 444
 445	case HID_GLOBAL_ITEM_TAG_PHYSICAL_MINIMUM:
 446		parser->global.physical_minimum = item_sdata(item);
 447		return 0;
 448
 449	case HID_GLOBAL_ITEM_TAG_PHYSICAL_MAXIMUM:
 450		if (parser->global.physical_minimum < 0)
 451			parser->global.physical_maximum = item_sdata(item);
 452		else
 453			parser->global.physical_maximum = item_udata(item);
 454		return 0;
 455
 456	case HID_GLOBAL_ITEM_TAG_UNIT_EXPONENT:
 457		/* Many devices provide unit exponent as a two's complement
 458		 * nibble due to the common misunderstanding of HID
 459		 * specification 1.11, 6.2.2.7 Global Items. Attempt to handle
 460		 * both this and the standard encoding. */
 461		raw_value = item_sdata(item);
 462		if (!(raw_value & 0xfffffff0))
 463			parser->global.unit_exponent = snto32(raw_value, 4);
 464		else
 465			parser->global.unit_exponent = raw_value;
 466		return 0;
 467
 468	case HID_GLOBAL_ITEM_TAG_UNIT:
 469		parser->global.unit = item_udata(item);
 470		return 0;
 471
 472	case HID_GLOBAL_ITEM_TAG_REPORT_SIZE:
 473		parser->global.report_size = item_udata(item);
 474		if (parser->global.report_size > 256) {
 475			hid_err(parser->device, "invalid report_size %d\n",
 476					parser->global.report_size);
 477			return -1;
 478		}
 479		return 0;
 480
 481	case HID_GLOBAL_ITEM_TAG_REPORT_COUNT:
 482		parser->global.report_count = item_udata(item);
 483		if (parser->global.report_count > HID_MAX_USAGES) {
 484			hid_err(parser->device, "invalid report_count %d\n",
 485					parser->global.report_count);
 486			return -1;
 487		}
 488		return 0;
 489
 490	case HID_GLOBAL_ITEM_TAG_REPORT_ID:
 491		parser->global.report_id = item_udata(item);
 492		if (parser->global.report_id == 0 ||
 493		    parser->global.report_id >= HID_MAX_IDS) {
 494			hid_err(parser->device, "report_id %u is invalid\n",
 495				parser->global.report_id);
 496			return -1;
 497		}
 498		return 0;
 499
 500	default:
 501		hid_err(parser->device, "unknown global tag 0x%x\n", item->tag);
 502		return -1;
 503	}
 504}
 505
 506/*
 507 * Process a local item.
 508 */
 509
 510static int hid_parser_local(struct hid_parser *parser, struct hid_item *item)
 511{
 512	__u32 data;
 513	unsigned n;
 514	__u32 count;
 515
 516	data = item_udata(item);
 517
 518	switch (item->tag) {
 519	case HID_LOCAL_ITEM_TAG_DELIMITER:
 520
 521		if (data) {
 522			/*
 523			 * We treat items before the first delimiter
 524			 * as global to all usage sets (branch 0).
 525			 * In the moment we process only these global
 526			 * items and the first delimiter set.
 527			 */
 528			if (parser->local.delimiter_depth != 0) {
 529				hid_err(parser->device, "nested delimiters\n");
 530				return -1;
 531			}
 532			parser->local.delimiter_depth++;
 533			parser->local.delimiter_branch++;
 534		} else {
 535			if (parser->local.delimiter_depth < 1) {
 536				hid_err(parser->device, "bogus close delimiter\n");
 537				return -1;
 538			}
 539			parser->local.delimiter_depth--;
 540		}
 541		return 0;
 542
 543	case HID_LOCAL_ITEM_TAG_USAGE:
 544
 545		if (parser->local.delimiter_branch > 1) {
 546			dbg_hid("alternative usage ignored\n");
 547			return 0;
 548		}
 549
 550		return hid_add_usage(parser, data, item->size);
 551
 552	case HID_LOCAL_ITEM_TAG_USAGE_MINIMUM:
 553
 554		if (parser->local.delimiter_branch > 1) {
 555			dbg_hid("alternative usage ignored\n");
 556			return 0;
 557		}
 558
 559		parser->local.usage_minimum = data;
 560		return 0;
 561
 562	case HID_LOCAL_ITEM_TAG_USAGE_MAXIMUM:
 563
 564		if (parser->local.delimiter_branch > 1) {
 565			dbg_hid("alternative usage ignored\n");
 566			return 0;
 567		}
 568
 569		count = data - parser->local.usage_minimum;
 570		if (count + parser->local.usage_index >= HID_MAX_USAGES) {
 571			/*
 572			 * We do not warn if the name is not set, we are
 573			 * actually pre-scanning the device.
 574			 */
 575			if (dev_name(&parser->device->dev))
 576				hid_warn(parser->device,
 577					 "ignoring exceeding usage max\n");
 578			data = HID_MAX_USAGES - parser->local.usage_index +
 579				parser->local.usage_minimum - 1;
 580			if (data <= 0) {
 581				hid_err(parser->device,
 582					"no more usage index available\n");
 583				return -1;
 584			}
 585		}
 586
 587		for (n = parser->local.usage_minimum; n <= data; n++)
 588			if (hid_add_usage(parser, n, item->size)) {
 589				dbg_hid("hid_add_usage failed\n");
 590				return -1;
 591			}
 592		return 0;
 593
 594	default:
 595
 596		dbg_hid("unknown local item tag 0x%x\n", item->tag);
 597		return 0;
 598	}
 599	return 0;
 600}
 601
 602/*
 603 * Concatenate Usage Pages into Usages where relevant:
 604 * As per specification, 6.2.2.8: "When the parser encounters a main item it
 605 * concatenates the last declared Usage Page with a Usage to form a complete
 606 * usage value."
 607 */
 608
 609static void hid_concatenate_last_usage_page(struct hid_parser *parser)
 610{
 611	int i;
 612	unsigned int usage_page;
 613	unsigned int current_page;
 614
 615	if (!parser->local.usage_index)
 616		return;
 617
 618	usage_page = parser->global.usage_page;
 619
 620	/*
 621	 * Concatenate usage page again only if last declared Usage Page
 622	 * has not been already used in previous usages concatenation
 623	 */
 624	for (i = parser->local.usage_index - 1; i >= 0; i--) {
 625		if (parser->local.usage_size[i] > 2)
 626			/* Ignore extended usages */
 627			continue;
 628
 629		current_page = parser->local.usage[i] >> 16;
 630		if (current_page == usage_page)
 631			break;
 632
 633		complete_usage(parser, i);
 634	}
 635}
 636
 637/*
 638 * Process a main item.
 639 */
 640
 641static int hid_parser_main(struct hid_parser *parser, struct hid_item *item)
 642{
 643	__u32 data;
 644	int ret;
 645
 646	hid_concatenate_last_usage_page(parser);
 647
 648	data = item_udata(item);
 649
 650	switch (item->tag) {
 651	case HID_MAIN_ITEM_TAG_BEGIN_COLLECTION:
 652		ret = open_collection(parser, data & 0xff);
 653		break;
 654	case HID_MAIN_ITEM_TAG_END_COLLECTION:
 655		ret = close_collection(parser);
 656		break;
 657	case HID_MAIN_ITEM_TAG_INPUT:
 658		ret = hid_add_field(parser, HID_INPUT_REPORT, data);
 659		break;
 660	case HID_MAIN_ITEM_TAG_OUTPUT:
 661		ret = hid_add_field(parser, HID_OUTPUT_REPORT, data);
 662		break;
 663	case HID_MAIN_ITEM_TAG_FEATURE:
 664		ret = hid_add_field(parser, HID_FEATURE_REPORT, data);
 665		break;
 666	default:
 667		if (item->tag >= HID_MAIN_ITEM_TAG_RESERVED_MIN &&
 668			item->tag <= HID_MAIN_ITEM_TAG_RESERVED_MAX)
 669			hid_warn_ratelimited(parser->device, "reserved main item tag 0x%x\n", item->tag);
 670		else
 671			hid_warn_ratelimited(parser->device, "unknown main item tag 0x%x\n", item->tag);
 672		ret = 0;
 673	}
 674
 675	memset(&parser->local, 0, sizeof(parser->local));	/* Reset the local parser environment */
 676
 677	return ret;
 678}
 679
 680/*
 681 * Process a reserved item.
 682 */
 683
 684static int hid_parser_reserved(struct hid_parser *parser, struct hid_item *item)
 685{
 686	dbg_hid("reserved item type, tag 0x%x\n", item->tag);
 687	return 0;
 688}
 689
 690/*
 691 * Free a report and all registered fields. The field->usage and
 692 * field->value table's are allocated behind the field, so we need
 693 * only to free(field) itself.
 694 */
 695
 696static void hid_free_report(struct hid_report *report)
 697{
 698	unsigned n;
 699
 700	kfree(report->field_entries);
 701
 702	for (n = 0; n < report->maxfield; n++)
 703		kvfree(report->field[n]);
 704	kfree(report);
 705}
 706
 707/*
 708 * Close report. This function returns the device
 709 * state to the point prior to hid_open_report().
 710 */
 711static void hid_close_report(struct hid_device *device)
 712{
 713	unsigned i, j;
 714
 715	for (i = 0; i < HID_REPORT_TYPES; i++) {
 716		struct hid_report_enum *report_enum = device->report_enum + i;
 717
 718		for (j = 0; j < HID_MAX_IDS; j++) {
 719			struct hid_report *report = report_enum->report_id_hash[j];
 720			if (report)
 721				hid_free_report(report);
 722		}
 723		memset(report_enum, 0, sizeof(*report_enum));
 724		INIT_LIST_HEAD(&report_enum->report_list);
 725	}
 726
 727	/*
 728	 * If the HID driver had a rdesc_fixup() callback, dev->rdesc
 729	 * will be allocated by hid-core and needs to be freed.
 730	 * Otherwise, it is either equal to dev_rdesc or bpf_rdesc, in
 731	 * which cases it'll be freed later on device removal or destroy.
 732	 */
 733	if (device->rdesc != device->dev_rdesc && device->rdesc != device->bpf_rdesc)
 734		kfree(device->rdesc);
 735	device->rdesc = NULL;
 736	device->rsize = 0;
 737
 738	kfree(device->collection);
 739	device->collection = NULL;
 740	device->collection_size = 0;
 741	device->maxcollection = 0;
 742	device->maxapplication = 0;
 743
 744	device->status &= ~HID_STAT_PARSED;
 745}
 746
 747static inline void hid_free_bpf_rdesc(struct hid_device *hdev)
 748{
 749	/* bpf_rdesc is either equal to dev_rdesc or allocated by call_hid_bpf_rdesc_fixup() */
 750	if (hdev->bpf_rdesc != hdev->dev_rdesc)
 751		kfree(hdev->bpf_rdesc);
 752	hdev->bpf_rdesc = NULL;
 753}
 754
 755/*
 756 * Free a device structure, all reports, and all fields.
 757 */
 758
 759void hiddev_free(struct kref *ref)
 760{
 761	struct hid_device *hid = container_of(ref, struct hid_device, ref);
 762
 763	hid_close_report(hid);
 764	hid_free_bpf_rdesc(hid);
 765	kfree(hid->dev_rdesc);
 766	kfree(hid);
 767}
 768
 769static void hid_device_release(struct device *dev)
 770{
 771	struct hid_device *hid = to_hid_device(dev);
 772
 773	kref_put(&hid->ref, hiddev_free);
 774}
 775
 776/*
 777 * Fetch a report description item from the data stream. We support long
 778 * items, though they are not used yet.
 779 */
 780
 781static const u8 *fetch_item(const __u8 *start, const __u8 *end, struct hid_item *item)
 782{
 783	u8 b;
 784
 785	if ((end - start) <= 0)
 786		return NULL;
 787
 788	b = *start++;
 789
 790	item->type = (b >> 2) & 3;
 791	item->tag  = (b >> 4) & 15;
 792
 793	if (item->tag == HID_ITEM_TAG_LONG) {
 794
 795		item->format = HID_ITEM_FORMAT_LONG;
 796
 797		if ((end - start) < 2)
 798			return NULL;
 799
 800		item->size = *start++;
 801		item->tag  = *start++;
 802
 803		if ((end - start) < item->size)
 804			return NULL;
 805
 806		item->data.longdata = start;
 807		start += item->size;
 808		return start;
 809	}
 810
 811	item->format = HID_ITEM_FORMAT_SHORT;
 812	item->size = BIT(b & 3) >> 1; /* 0, 1, 2, 3 -> 0, 1, 2, 4 */
 813
 814	if (end - start < item->size)
 815		return NULL;
 816
 817	switch (item->size) {
 818	case 0:
 819		break;
 820
 821	case 1:
 822		item->data.u8 = *start;
 823		break;
 824
 825	case 2:
 826		item->data.u16 = get_unaligned_le16(start);
 827		break;
 828
 829	case 4:
 830		item->data.u32 = get_unaligned_le32(start);
 831		break;
 832	}
 833
 834	return start + item->size;
 835}
 836
 837static void hid_scan_input_usage(struct hid_parser *parser, u32 usage)
 838{
 839	struct hid_device *hid = parser->device;
 840
 841	if (usage == HID_DG_CONTACTID)
 842		hid->group = HID_GROUP_MULTITOUCH;
 843}
 844
 845static void hid_scan_feature_usage(struct hid_parser *parser, u32 usage)
 846{
 847	if (usage == 0xff0000c5 && parser->global.report_count == 256 &&
 848	    parser->global.report_size == 8)
 849		parser->scan_flags |= HID_SCAN_FLAG_MT_WIN_8;
 850
 851	if (usage == 0xff0000c6 && parser->global.report_count == 1 &&
 852	    parser->global.report_size == 8)
 853		parser->scan_flags |= HID_SCAN_FLAG_MT_WIN_8;
 854}
 855
 856static void hid_scan_collection(struct hid_parser *parser, unsigned type)
 857{
 858	struct hid_device *hid = parser->device;
 859	int i;
 860
 861	if (((parser->global.usage_page << 16) == HID_UP_SENSOR) &&
 862	    (type == HID_COLLECTION_PHYSICAL ||
 863	     type == HID_COLLECTION_APPLICATION))
 864		hid->group = HID_GROUP_SENSOR_HUB;
 865
 866	if (hid->vendor == USB_VENDOR_ID_MICROSOFT &&
 867	    hid->product == USB_DEVICE_ID_MS_POWER_COVER &&
 868	    hid->group == HID_GROUP_MULTITOUCH)
 869		hid->group = HID_GROUP_GENERIC;
 870
 871	if ((parser->global.usage_page << 16) == HID_UP_GENDESK)
 872		for (i = 0; i < parser->local.usage_index; i++)
 873			if (parser->local.usage[i] == HID_GD_POINTER)
 874				parser->scan_flags |= HID_SCAN_FLAG_GD_POINTER;
 875
 876	if ((parser->global.usage_page << 16) >= HID_UP_MSVENDOR)
 877		parser->scan_flags |= HID_SCAN_FLAG_VENDOR_SPECIFIC;
 878
 879	if ((parser->global.usage_page << 16) == HID_UP_GOOGLEVENDOR)
 880		for (i = 0; i < parser->local.usage_index; i++)
 881			if (parser->local.usage[i] ==
 882					(HID_UP_GOOGLEVENDOR | 0x0001))
 883				parser->device->group =
 884					HID_GROUP_VIVALDI;
 885}
 886
 887static int hid_scan_main(struct hid_parser *parser, struct hid_item *item)
 888{
 889	__u32 data;
 890	int i;
 891
 892	hid_concatenate_last_usage_page(parser);
 893
 894	data = item_udata(item);
 895
 896	switch (item->tag) {
 897	case HID_MAIN_ITEM_TAG_BEGIN_COLLECTION:
 898		hid_scan_collection(parser, data & 0xff);
 899		break;
 900	case HID_MAIN_ITEM_TAG_END_COLLECTION:
 901		break;
 902	case HID_MAIN_ITEM_TAG_INPUT:
 903		/* ignore constant inputs, they will be ignored by hid-input */
 904		if (data & HID_MAIN_ITEM_CONSTANT)
 905			break;
 906		for (i = 0; i < parser->local.usage_index; i++)
 907			hid_scan_input_usage(parser, parser->local.usage[i]);
 908		break;
 909	case HID_MAIN_ITEM_TAG_OUTPUT:
 910		break;
 911	case HID_MAIN_ITEM_TAG_FEATURE:
 912		for (i = 0; i < parser->local.usage_index; i++)
 913			hid_scan_feature_usage(parser, parser->local.usage[i]);
 914		break;
 915	}
 916
 917	/* Reset the local parser environment */
 918	memset(&parser->local, 0, sizeof(parser->local));
 919
 920	return 0;
 921}
 922
 923/*
 924 * Scan a report descriptor before the device is added to the bus.
 925 * Sets device groups and other properties that determine what driver
 926 * to load.
 927 */
 928static int hid_scan_report(struct hid_device *hid)
 929{
 930	struct hid_parser *parser;
 931	struct hid_item item;
 932	const __u8 *start = hid->dev_rdesc;
 933	const __u8 *end = start + hid->dev_rsize;
 934	static int (*dispatch_type[])(struct hid_parser *parser,
 935				      struct hid_item *item) = {
 936		hid_scan_main,
 937		hid_parser_global,
 938		hid_parser_local,
 939		hid_parser_reserved
 940	};
 941
 942	parser = vzalloc(sizeof(struct hid_parser));
 943	if (!parser)
 944		return -ENOMEM;
 945
 946	parser->device = hid;
 947	hid->group = HID_GROUP_GENERIC;
 948
 949	/*
 950	 * In case we are re-scanning after a BPF has been loaded,
 951	 * we need to use the bpf report descriptor, not the original one.
 952	 */
 953	if (hid->bpf_rdesc && hid->bpf_rsize) {
 954		start = hid->bpf_rdesc;
 955		end = start + hid->bpf_rsize;
 956	}
 957
 958	/*
 959	 * The parsing is simpler than the one in hid_open_report() as we should
 960	 * be robust against hid errors. Those errors will be raised by
 961	 * hid_open_report() anyway.
 962	 */
 963	while ((start = fetch_item(start, end, &item)) != NULL)
 964		dispatch_type[item.type](parser, &item);
 965
 966	/*
 967	 * Handle special flags set during scanning.
 968	 */
 969	if ((parser->scan_flags & HID_SCAN_FLAG_MT_WIN_8) &&
 970	    (hid->group == HID_GROUP_MULTITOUCH))
 971		hid->group = HID_GROUP_MULTITOUCH_WIN_8;
 972
 973	/*
 974	 * Vendor specific handlings
 975	 */
 976	switch (hid->vendor) {
 977	case USB_VENDOR_ID_WACOM:
 978		hid->group = HID_GROUP_WACOM;
 979		break;
 980	case USB_VENDOR_ID_SYNAPTICS:
 981		if (hid->group == HID_GROUP_GENERIC)
 982			if ((parser->scan_flags & HID_SCAN_FLAG_VENDOR_SPECIFIC)
 983			    && (parser->scan_flags & HID_SCAN_FLAG_GD_POINTER))
 984				/*
 985				 * hid-rmi should take care of them,
 986				 * not hid-generic
 987				 */
 988				hid->group = HID_GROUP_RMI;
 989		break;
 990	}
 991
 992	kfree(parser->collection_stack);
 993	vfree(parser);
 994	return 0;
 995}
 996
 997/**
 998 * hid_parse_report - parse device report
 999 *
1000 * @hid: hid device
1001 * @start: report start
1002 * @size: report size
1003 *
1004 * Allocate the device report as read by the bus driver. This function should
1005 * only be called from parse() in ll drivers.
1006 */
1007int hid_parse_report(struct hid_device *hid, const __u8 *start, unsigned size)
1008{
1009	hid->dev_rdesc = kmemdup(start, size, GFP_KERNEL);
1010	if (!hid->dev_rdesc)
1011		return -ENOMEM;
1012	hid->dev_rsize = size;
1013	return 0;
1014}
1015EXPORT_SYMBOL_GPL(hid_parse_report);
1016
1017static const char * const hid_report_names[] = {
1018	"HID_INPUT_REPORT",
1019	"HID_OUTPUT_REPORT",
1020	"HID_FEATURE_REPORT",
1021};
1022/**
1023 * hid_validate_values - validate existing device report's value indexes
1024 *
1025 * @hid: hid device
1026 * @type: which report type to examine
1027 * @id: which report ID to examine (0 for first)
1028 * @field_index: which report field to examine
1029 * @report_counts: expected number of values
1030 *
1031 * Validate the number of values in a given field of a given report, after
1032 * parsing.
1033 */
1034struct hid_report *hid_validate_values(struct hid_device *hid,
1035				       enum hid_report_type type, unsigned int id,
1036				       unsigned int field_index,
1037				       unsigned int report_counts)
1038{
1039	struct hid_report *report;
1040
1041	if (type > HID_FEATURE_REPORT) {
1042		hid_err(hid, "invalid HID report type %u\n", type);
1043		return NULL;
1044	}
1045
1046	if (id >= HID_MAX_IDS) {
1047		hid_err(hid, "invalid HID report id %u\n", id);
1048		return NULL;
1049	}
1050
1051	/*
1052	 * Explicitly not using hid_get_report() here since it depends on
1053	 * ->numbered being checked, which may not always be the case when
1054	 * drivers go to access report values.
1055	 */
1056	if (id == 0) {
1057		/*
1058		 * Validating on id 0 means we should examine the first
1059		 * report in the list.
1060		 */
1061		report = list_first_entry_or_null(
1062				&hid->report_enum[type].report_list,
1063				struct hid_report, list);
1064	} else {
1065		report = hid->report_enum[type].report_id_hash[id];
1066	}
1067	if (!report) {
1068		hid_err(hid, "missing %s %u\n", hid_report_names[type], id);
1069		return NULL;
1070	}
1071	if (report->maxfield <= field_index) {
1072		hid_err(hid, "not enough fields in %s %u\n",
1073			hid_report_names[type], id);
1074		return NULL;
1075	}
1076	if (report->field[field_index]->report_count < report_counts) {
1077		hid_err(hid, "not enough values in %s %u field %u\n",
1078			hid_report_names[type], id, field_index);
1079		return NULL;
1080	}
1081	return report;
1082}
1083EXPORT_SYMBOL_GPL(hid_validate_values);
1084
1085static int hid_calculate_multiplier(struct hid_device *hid,
1086				     struct hid_field *multiplier)
1087{
1088	int m;
1089	__s32 v = *multiplier->value;
1090	__s32 lmin = multiplier->logical_minimum;
1091	__s32 lmax = multiplier->logical_maximum;
1092	__s32 pmin = multiplier->physical_minimum;
1093	__s32 pmax = multiplier->physical_maximum;
1094
1095	/*
1096	 * "Because OS implementations will generally divide the control's
1097	 * reported count by the Effective Resolution Multiplier, designers
1098	 * should take care not to establish a potential Effective
1099	 * Resolution Multiplier of zero."
1100	 * HID Usage Table, v1.12, Section 4.3.1, p31
1101	 */
1102	if (lmax - lmin == 0)
1103		return 1;
1104	/*
1105	 * Handling the unit exponent is left as an exercise to whoever
1106	 * finds a device where that exponent is not 0.
1107	 */
1108	m = ((v - lmin)/(lmax - lmin) * (pmax - pmin) + pmin);
1109	if (unlikely(multiplier->unit_exponent != 0)) {
1110		hid_warn(hid,
1111			 "unsupported Resolution Multiplier unit exponent %d\n",
1112			 multiplier->unit_exponent);
1113	}
1114
1115	/* There are no devices with an effective multiplier > 255 */
1116	if (unlikely(m == 0 || m > 255 || m < -255)) {
1117		hid_warn(hid, "unsupported Resolution Multiplier %d\n", m);
1118		m = 1;
1119	}
1120
1121	return m;
1122}
1123
1124static void hid_apply_multiplier_to_field(struct hid_device *hid,
1125					  struct hid_field *field,
1126					  struct hid_collection *multiplier_collection,
1127					  int effective_multiplier)
1128{
1129	struct hid_collection *collection;
1130	struct hid_usage *usage;
1131	int i;
1132
1133	/*
1134	 * If multiplier_collection is NULL, the multiplier applies
1135	 * to all fields in the report.
1136	 * Otherwise, it is the Logical Collection the multiplier applies to
1137	 * but our field may be in a subcollection of that collection.
1138	 */
1139	for (i = 0; i < field->maxusage; i++) {
1140		usage = &field->usage[i];
1141
1142		collection = &hid->collection[usage->collection_index];
1143		while (collection->parent_idx != -1 &&
1144		       collection != multiplier_collection)
1145			collection = &hid->collection[collection->parent_idx];
1146
1147		if (collection->parent_idx != -1 ||
1148		    multiplier_collection == NULL)
1149			usage->resolution_multiplier = effective_multiplier;
1150
1151	}
1152}
1153
1154static void hid_apply_multiplier(struct hid_device *hid,
1155				 struct hid_field *multiplier)
1156{
1157	struct hid_report_enum *rep_enum;
1158	struct hid_report *rep;
1159	struct hid_field *field;
1160	struct hid_collection *multiplier_collection;
1161	int effective_multiplier;
1162	int i;
1163
1164	/*
1165	 * "The Resolution Multiplier control must be contained in the same
1166	 * Logical Collection as the control(s) to which it is to be applied.
1167	 * If no Resolution Multiplier is defined, then the Resolution
1168	 * Multiplier defaults to 1.  If more than one control exists in a
1169	 * Logical Collection, the Resolution Multiplier is associated with
1170	 * all controls in the collection. If no Logical Collection is
1171	 * defined, the Resolution Multiplier is associated with all
1172	 * controls in the report."
1173	 * HID Usage Table, v1.12, Section 4.3.1, p30
1174	 *
1175	 * Thus, search from the current collection upwards until we find a
1176	 * logical collection. Then search all fields for that same parent
1177	 * collection. Those are the fields the multiplier applies to.
1178	 *
1179	 * If we have more than one multiplier, it will overwrite the
1180	 * applicable fields later.
1181	 */
1182	multiplier_collection = &hid->collection[multiplier->usage->collection_index];
1183	while (multiplier_collection->parent_idx != -1 &&
1184	       multiplier_collection->type != HID_COLLECTION_LOGICAL)
1185		multiplier_collection = &hid->collection[multiplier_collection->parent_idx];
1186	if (multiplier_collection->type != HID_COLLECTION_LOGICAL)
1187		multiplier_collection = NULL;
1188
1189	effective_multiplier = hid_calculate_multiplier(hid, multiplier);
1190
1191	rep_enum = &hid->report_enum[HID_INPUT_REPORT];
1192	list_for_each_entry(rep, &rep_enum->report_list, list) {
1193		for (i = 0; i < rep->maxfield; i++) {
1194			field = rep->field[i];
1195			hid_apply_multiplier_to_field(hid, field,
1196						      multiplier_collection,
1197						      effective_multiplier);
1198		}
1199	}
1200}
1201
1202/*
1203 * hid_setup_resolution_multiplier - set up all resolution multipliers
1204 *
1205 * @device: hid device
1206 *
1207 * Search for all Resolution Multiplier Feature Reports and apply their
1208 * value to all matching Input items. This only updates the internal struct
1209 * fields.
1210 *
1211 * The Resolution Multiplier is applied by the hardware. If the multiplier
1212 * is anything other than 1, the hardware will send pre-multiplied events
1213 * so that the same physical interaction generates an accumulated
1214 *	accumulated_value = value * * multiplier
1215 * This may be achieved by sending
1216 * - "value * multiplier" for each event, or
1217 * - "value" but "multiplier" times as frequently, or
1218 * - a combination of the above
1219 * The only guarantee is that the same physical interaction always generates
1220 * an accumulated 'value * multiplier'.
1221 *
1222 * This function must be called before any event processing and after
1223 * any SetRequest to the Resolution Multiplier.
1224 */
1225void hid_setup_resolution_multiplier(struct hid_device *hid)
1226{
1227	struct hid_report_enum *rep_enum;
1228	struct hid_report *rep;
1229	struct hid_usage *usage;
1230	int i, j;
1231
1232	rep_enum = &hid->report_enum[HID_FEATURE_REPORT];
1233	list_for_each_entry(rep, &rep_enum->report_list, list) {
1234		for (i = 0; i < rep->maxfield; i++) {
1235			/* Ignore if report count is out of bounds. */
1236			if (rep->field[i]->report_count < 1)
1237				continue;
1238
1239			for (j = 0; j < rep->field[i]->maxusage; j++) {
1240				usage = &rep->field[i]->usage[j];
1241				if (usage->hid == HID_GD_RESOLUTION_MULTIPLIER)
1242					hid_apply_multiplier(hid,
1243							     rep->field[i]);
1244			}
1245		}
1246	}
1247}
1248EXPORT_SYMBOL_GPL(hid_setup_resolution_multiplier);
1249
1250/**
1251 * hid_open_report - open a driver-specific device report
1252 *
1253 * @device: hid device
1254 *
1255 * Parse a report description into a hid_device structure. Reports are
1256 * enumerated, fields are attached to these reports.
1257 * 0 returned on success, otherwise nonzero error value.
1258 *
1259 * This function (or the equivalent hid_parse() macro) should only be
1260 * called from probe() in drivers, before starting the device.
1261 */
1262int hid_open_report(struct hid_device *device)
1263{
1264	struct hid_parser *parser;
1265	struct hid_item item;
1266	unsigned int size;
1267	const __u8 *start;
1268	const __u8 *end;
1269	const __u8 *next;
1270	int ret;
1271	int i;
1272	static int (*dispatch_type[])(struct hid_parser *parser,
1273				      struct hid_item *item) = {
1274		hid_parser_main,
1275		hid_parser_global,
1276		hid_parser_local,
1277		hid_parser_reserved
1278	};
1279
1280	if (WARN_ON(device->status & HID_STAT_PARSED))
1281		return -EBUSY;
1282
1283	start = device->bpf_rdesc;
1284	if (WARN_ON(!start))
1285		return -ENODEV;
1286	size = device->bpf_rsize;
1287
1288	if (device->driver->report_fixup) {
1289		/*
1290		 * device->driver->report_fixup() needs to work
1291		 * on a copy of our report descriptor so it can
1292		 * change it.
1293		 */
1294		__u8 *buf = kmemdup(start, size, GFP_KERNEL);
1295
1296		if (buf == NULL)
1297			return -ENOMEM;
1298
1299		start = device->driver->report_fixup(device, buf, &size);
1300
1301		/*
1302		 * The second kmemdup is required in case report_fixup() returns
1303		 * a static read-only memory, but we have no idea if that memory
1304		 * needs to be cleaned up or not at the end.
1305		 */
1306		start = kmemdup(start, size, GFP_KERNEL);
1307		kfree(buf);
1308		if (start == NULL)
1309			return -ENOMEM;
1310	}
1311
1312	device->rdesc = start;
1313	device->rsize = size;
1314
1315	parser = vzalloc(sizeof(struct hid_parser));
1316	if (!parser) {
1317		ret = -ENOMEM;
1318		goto alloc_err;
1319	}
1320
1321	parser->device = device;
1322
1323	end = start + size;
1324
1325	device->collection = kcalloc(HID_DEFAULT_NUM_COLLECTIONS,
1326				     sizeof(struct hid_collection), GFP_KERNEL);
1327	if (!device->collection) {
1328		ret = -ENOMEM;
1329		goto err;
1330	}
1331	device->collection_size = HID_DEFAULT_NUM_COLLECTIONS;
1332	for (i = 0; i < HID_DEFAULT_NUM_COLLECTIONS; i++)
1333		device->collection[i].parent_idx = -1;
1334
1335	ret = -EINVAL;
1336	while ((next = fetch_item(start, end, &item)) != NULL) {
1337		start = next;
1338
1339		if (item.format != HID_ITEM_FORMAT_SHORT) {
1340			hid_err(device, "unexpected long global item\n");
1341			goto err;
1342		}
1343
1344		if (dispatch_type[item.type](parser, &item)) {
1345			hid_err(device, "item %u %u %u %u parsing failed\n",
1346				item.format, (unsigned)item.size,
1347				(unsigned)item.type, (unsigned)item.tag);
1348			goto err;
1349		}
1350
1351		if (start == end) {
1352			if (parser->collection_stack_ptr) {
1353				hid_err(device, "unbalanced collection at end of report description\n");
1354				goto err;
1355			}
1356			if (parser->local.delimiter_depth) {
1357				hid_err(device, "unbalanced delimiter at end of report description\n");
1358				goto err;
1359			}
1360
1361			/*
1362			 * fetch initial values in case the device's
1363			 * default multiplier isn't the recommended 1
1364			 */
1365			hid_setup_resolution_multiplier(device);
1366
1367			kfree(parser->collection_stack);
1368			vfree(parser);
1369			device->status |= HID_STAT_PARSED;
1370
1371			return 0;
1372		}
1373	}
1374
1375	hid_err(device, "item fetching failed at offset %u/%u\n",
1376		size - (unsigned int)(end - start), size);
1377err:
1378	kfree(parser->collection_stack);
1379alloc_err:
1380	vfree(parser);
1381	hid_close_report(device);
1382	return ret;
1383}
1384EXPORT_SYMBOL_GPL(hid_open_report);
1385
1386/*
1387 * Extract/implement a data field from/to a little endian report (bit array).
1388 *
1389 * Code sort-of follows HID spec:
1390 *     http://www.usb.org/developers/hidpage/HID1_11.pdf
1391 *
1392 * While the USB HID spec allows unlimited length bit fields in "report
1393 * descriptors", most devices never use more than 16 bits.
1394 * One model of UPS is claimed to report "LINEV" as a 32-bit field.
1395 * Search linux-kernel and linux-usb-devel archives for "hid-core extract".
1396 */
1397
1398static u32 __extract(u8 *report, unsigned offset, int n)
1399{
1400	unsigned int idx = offset / 8;
1401	unsigned int bit_nr = 0;
1402	unsigned int bit_shift = offset % 8;
1403	int bits_to_copy = 8 - bit_shift;
1404	u32 value = 0;
1405	u32 mask = n < 32 ? (1U << n) - 1 : ~0U;
1406
1407	while (n > 0) {
1408		value |= ((u32)report[idx] >> bit_shift) << bit_nr;
1409		n -= bits_to_copy;
1410		bit_nr += bits_to_copy;
1411		bits_to_copy = 8;
1412		bit_shift = 0;
1413		idx++;
1414	}
1415
1416	return value & mask;
1417}
1418
1419u32 hid_field_extract(const struct hid_device *hid, u8 *report,
1420			unsigned offset, unsigned n)
1421{
1422	if (n > 32) {
1423		hid_warn_once(hid, "%s() called with n (%d) > 32! (%s)\n",
1424			      __func__, n, current->comm);
1425		n = 32;
1426	}
1427
1428	return __extract(report, offset, n);
1429}
1430EXPORT_SYMBOL_GPL(hid_field_extract);
1431
1432/*
1433 * "implement" : set bits in a little endian bit stream.
1434 * Same concepts as "extract" (see comments above).
1435 * The data mangled in the bit stream remains in little endian
1436 * order the whole time. It make more sense to talk about
1437 * endianness of register values by considering a register
1438 * a "cached" copy of the little endian bit stream.
1439 */
1440
1441static void __implement(u8 *report, unsigned offset, int n, u32 value)
1442{
1443	unsigned int idx = offset / 8;
1444	unsigned int bit_shift = offset % 8;
1445	int bits_to_set = 8 - bit_shift;
1446
1447	while (n - bits_to_set >= 0) {
1448		report[idx] &= ~(0xff << bit_shift);
1449		report[idx] |= value << bit_shift;
1450		value >>= bits_to_set;
1451		n -= bits_to_set;
1452		bits_to_set = 8;
1453		bit_shift = 0;
1454		idx++;
1455	}
1456
1457	/* last nibble */
1458	if (n) {
1459		u8 bit_mask = ((1U << n) - 1);
1460		report[idx] &= ~(bit_mask << bit_shift);
1461		report[idx] |= value << bit_shift;
1462	}
1463}
1464
1465static void implement(const struct hid_device *hid, u8 *report,
1466		      unsigned offset, unsigned n, u32 value)
1467{
1468	if (unlikely(n > 32)) {
1469		hid_warn(hid, "%s() called with n (%d) > 32! (%s)\n",
1470			 __func__, n, current->comm);
1471		n = 32;
1472	} else if (n < 32) {
1473		u32 m = (1U << n) - 1;
1474
1475		if (unlikely(value > m)) {
1476			hid_warn(hid,
1477				 "%s() called with too large value %d (n: %d)! (%s)\n",
1478				 __func__, value, n, current->comm);
1479			value &= m;
1480		}
1481	}
1482
1483	__implement(report, offset, n, value);
1484}
1485
1486/*
1487 * Search an array for a value.
1488 */
1489
1490static int search(__s32 *array, __s32 value, unsigned n)
1491{
1492	while (n--) {
1493		if (*array++ == value)
1494			return 0;
1495	}
1496	return -1;
1497}
1498
1499/**
1500 * hid_match_report - check if driver's raw_event should be called
1501 *
1502 * @hid: hid device
1503 * @report: hid report to match against
1504 *
1505 * compare hid->driver->report_table->report_type to report->type
1506 */
1507static int hid_match_report(struct hid_device *hid, struct hid_report *report)
1508{
1509	const struct hid_report_id *id = hid->driver->report_table;
1510
1511	if (!id) /* NULL means all */
1512		return 1;
1513
1514	for (; id->report_type != HID_TERMINATOR; id++)
1515		if (id->report_type == HID_ANY_ID ||
1516				id->report_type == report->type)
1517			return 1;
1518	return 0;
1519}
1520
1521/**
1522 * hid_match_usage - check if driver's event should be called
1523 *
1524 * @hid: hid device
1525 * @usage: usage to match against
1526 *
1527 * compare hid->driver->usage_table->usage_{type,code} to
1528 * usage->usage_{type,code}
1529 */
1530static int hid_match_usage(struct hid_device *hid, struct hid_usage *usage)
1531{
1532	const struct hid_usage_id *id = hid->driver->usage_table;
1533
1534	if (!id) /* NULL means all */
1535		return 1;
1536
1537	for (; id->usage_type != HID_ANY_ID - 1; id++)
1538		if ((id->usage_hid == HID_ANY_ID ||
1539				id->usage_hid == usage->hid) &&
1540				(id->usage_type == HID_ANY_ID ||
1541				id->usage_type == usage->type) &&
1542				(id->usage_code == HID_ANY_ID ||
1543				 id->usage_code == usage->code))
1544			return 1;
1545	return 0;
1546}
1547
1548static void hid_process_event(struct hid_device *hid, struct hid_field *field,
1549		struct hid_usage *usage, __s32 value, int interrupt)
1550{
1551	struct hid_driver *hdrv = hid->driver;
1552	int ret;
1553
1554	if (!list_empty(&hid->debug_list))
1555		hid_dump_input(hid, usage, value);
1556
1557	if (hdrv && hdrv->event && hid_match_usage(hid, usage)) {
1558		ret = hdrv->event(hid, field, usage, value);
1559		if (ret != 0) {
1560			if (ret < 0)
1561				hid_err(hid, "%s's event failed with %d\n",
1562						hdrv->name, ret);
1563			return;
1564		}
1565	}
1566
1567	if (hid->claimed & HID_CLAIMED_INPUT)
1568		hidinput_hid_event(hid, field, usage, value);
1569	if (hid->claimed & HID_CLAIMED_HIDDEV && interrupt && hid->hiddev_hid_event)
1570		hid->hiddev_hid_event(hid, field, usage, value);
1571}
1572
1573/*
1574 * Checks if the given value is valid within this field
1575 */
1576static inline int hid_array_value_is_valid(struct hid_field *field,
1577					   __s32 value)
1578{
1579	__s32 min = field->logical_minimum;
1580
1581	/*
1582	 * Value needs to be between logical min and max, and
1583	 * (value - min) is used as an index in the usage array.
1584	 * This array is of size field->maxusage
1585	 */
1586	return value >= min &&
1587	       value <= field->logical_maximum &&
1588	       value - min < field->maxusage;
1589}
1590
1591/*
1592 * Fetch the field from the data. The field content is stored for next
1593 * report processing (we do differential reporting to the layer).
1594 */
1595static void hid_input_fetch_field(struct hid_device *hid,
1596				  struct hid_field *field,
1597				  __u8 *data)
1598{
1599	unsigned n;
1600	unsigned count = field->report_count;
1601	unsigned offset = field->report_offset;
1602	unsigned size = field->report_size;
1603	__s32 min = field->logical_minimum;
1604	__s32 *value;
1605
1606	value = field->new_value;
1607	memset(value, 0, count * sizeof(__s32));
1608	field->ignored = false;
1609
1610	for (n = 0; n < count; n++) {
1611
1612		value[n] = min < 0 ?
1613			snto32(hid_field_extract(hid, data, offset + n * size,
1614			       size), size) :
1615			hid_field_extract(hid, data, offset + n * size, size);
1616
1617		/* Ignore report if ErrorRollOver */
1618		if (!(field->flags & HID_MAIN_ITEM_VARIABLE) &&
1619		    hid_array_value_is_valid(field, value[n]) &&
1620		    field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1) {
1621			field->ignored = true;
1622			return;
1623		}
1624	}
1625}
1626
1627/*
1628 * Process a received variable field.
1629 */
1630
1631static void hid_input_var_field(struct hid_device *hid,
1632				struct hid_field *field,
1633				int interrupt)
1634{
1635	unsigned int count = field->report_count;
1636	__s32 *value = field->new_value;
1637	unsigned int n;
1638
1639	for (n = 0; n < count; n++)
1640		hid_process_event(hid,
1641				  field,
1642				  &field->usage[n],
1643				  value[n],
1644				  interrupt);
1645
1646	memcpy(field->value, value, count * sizeof(__s32));
1647}
1648
1649/*
1650 * Process a received array field. The field content is stored for
1651 * next report processing (we do differential reporting to the layer).
1652 */
1653
1654static void hid_input_array_field(struct hid_device *hid,
1655				  struct hid_field *field,
1656				  int interrupt)
1657{
1658	unsigned int n;
1659	unsigned int count = field->report_count;
1660	__s32 min = field->logical_minimum;
1661	__s32 *value;
1662
1663	value = field->new_value;
1664
1665	/* ErrorRollOver */
1666	if (field->ignored)
1667		return;
1668
1669	for (n = 0; n < count; n++) {
1670		if (hid_array_value_is_valid(field, field->value[n]) &&
1671		    search(value, field->value[n], count))
1672			hid_process_event(hid,
1673					  field,
1674					  &field->usage[field->value[n] - min],
1675					  0,
1676					  interrupt);
1677
1678		if (hid_array_value_is_valid(field, value[n]) &&
1679		    search(field->value, value[n], count))
1680			hid_process_event(hid,
1681					  field,
1682					  &field->usage[value[n] - min],
1683					  1,
1684					  interrupt);
1685	}
1686
1687	memcpy(field->value, value, count * sizeof(__s32));
1688}
1689
1690/*
1691 * Analyse a received report, and fetch the data from it. The field
1692 * content is stored for next report processing (we do differential
1693 * reporting to the layer).
1694 */
1695static void hid_process_report(struct hid_device *hid,
1696			       struct hid_report *report,
1697			       __u8 *data,
1698			       int interrupt)
1699{
1700	unsigned int a;
1701	struct hid_field_entry *entry;
1702	struct hid_field *field;
1703
1704	/* first retrieve all incoming values in data */
1705	for (a = 0; a < report->maxfield; a++)
1706		hid_input_fetch_field(hid, report->field[a], data);
1707
1708	if (!list_empty(&report->field_entry_list)) {
1709		/* INPUT_REPORT, we have a priority list of fields */
1710		list_for_each_entry(entry,
1711				    &report->field_entry_list,
1712				    list) {
1713			field = entry->field;
1714
1715			if (field->flags & HID_MAIN_ITEM_VARIABLE)
1716				hid_process_event(hid,
1717						  field,
1718						  &field->usage[entry->index],
1719						  field->new_value[entry->index],
1720						  interrupt);
1721			else
1722				hid_input_array_field(hid, field, interrupt);
1723		}
1724
1725		/* we need to do the memcpy at the end for var items */
1726		for (a = 0; a < report->maxfield; a++) {
1727			field = report->field[a];
1728
1729			if (field->flags & HID_MAIN_ITEM_VARIABLE)
1730				memcpy(field->value, field->new_value,
1731				       field->report_count * sizeof(__s32));
1732		}
1733	} else {
1734		/* FEATURE_REPORT, regular processing */
1735		for (a = 0; a < report->maxfield; a++) {
1736			field = report->field[a];
1737
1738			if (field->flags & HID_MAIN_ITEM_VARIABLE)
1739				hid_input_var_field(hid, field, interrupt);
1740			else
1741				hid_input_array_field(hid, field, interrupt);
1742		}
1743	}
1744}
1745
1746/*
1747 * Insert a given usage_index in a field in the list
1748 * of processed usages in the report.
1749 *
1750 * The elements of lower priority score are processed
1751 * first.
1752 */
1753static void __hid_insert_field_entry(struct hid_device *hid,
1754				     struct hid_report *report,
1755				     struct hid_field_entry *entry,
1756				     struct hid_field *field,
1757				     unsigned int usage_index)
1758{
1759	struct hid_field_entry *next;
1760
1761	entry->field = field;
1762	entry->index = usage_index;
1763	entry->priority = field->usages_priorities[usage_index];
1764
1765	/* insert the element at the correct position */
1766	list_for_each_entry(next,
1767			    &report->field_entry_list,
1768			    list) {
1769		/*
1770		 * the priority of our element is strictly higher
1771		 * than the next one, insert it before
1772		 */
1773		if (entry->priority > next->priority) {
1774			list_add_tail(&entry->list, &next->list);
1775			return;
1776		}
1777	}
1778
1779	/* lowest priority score: insert at the end */
1780	list_add_tail(&entry->list, &report->field_entry_list);
1781}
1782
1783static void hid_report_process_ordering(struct hid_device *hid,
1784					struct hid_report *report)
1785{
1786	struct hid_field *field;
1787	struct hid_field_entry *entries;
1788	unsigned int a, u, usages;
1789	unsigned int count = 0;
1790
1791	/* count the number of individual fields in the report */
1792	for (a = 0; a < report->maxfield; a++) {
1793		field = report->field[a];
1794
1795		if (field->flags & HID_MAIN_ITEM_VARIABLE)
1796			count += field->report_count;
1797		else
1798			count++;
1799	}
1800
1801	/* allocate the memory to process the fields */
1802	entries = kcalloc(count, sizeof(*entries), GFP_KERNEL);
1803	if (!entries)
1804		return;
1805
1806	report->field_entries = entries;
1807
1808	/*
1809	 * walk through all fields in the report and
1810	 * store them by priority order in report->field_entry_list
1811	 *
1812	 * - Var elements are individualized (field + usage_index)
1813	 * - Arrays are taken as one, we can not chose an order for them
1814	 */
1815	usages = 0;
1816	for (a = 0; a < report->maxfield; a++) {
1817		field = report->field[a];
1818
1819		if (field->flags & HID_MAIN_ITEM_VARIABLE) {
1820			for (u = 0; u < field->report_count; u++) {
1821				__hid_insert_field_entry(hid, report,
1822							 &entries[usages],
1823							 field, u);
1824				usages++;
1825			}
1826		} else {
1827			__hid_insert_field_entry(hid, report, &entries[usages],
1828						 field, 0);
1829			usages++;
1830		}
1831	}
1832}
1833
1834static void hid_process_ordering(struct hid_device *hid)
1835{
1836	struct hid_report *report;
1837	struct hid_report_enum *report_enum = &hid->report_enum[HID_INPUT_REPORT];
1838
1839	list_for_each_entry(report, &report_enum->report_list, list)
1840		hid_report_process_ordering(hid, report);
1841}
1842
1843/*
1844 * Output the field into the report.
1845 */
1846
1847static void hid_output_field(const struct hid_device *hid,
1848			     struct hid_field *field, __u8 *data)
1849{
1850	unsigned count = field->report_count;
1851	unsigned offset = field->report_offset;
1852	unsigned size = field->report_size;
1853	unsigned n;
1854
1855	for (n = 0; n < count; n++) {
1856		if (field->logical_minimum < 0)	/* signed values */
1857			implement(hid, data, offset + n * size, size,
1858				  s32ton(field->value[n], size));
1859		else				/* unsigned values */
1860			implement(hid, data, offset + n * size, size,
1861				  field->value[n]);
1862	}
1863}
1864
1865/*
1866 * Compute the size of a report.
1867 */
1868static size_t hid_compute_report_size(struct hid_report *report)
1869{
1870	if (report->size)
1871		return ((report->size - 1) >> 3) + 1;
1872
1873	return 0;
1874}
1875
1876/*
1877 * Create a report. 'data' has to be allocated using
1878 * hid_alloc_report_buf() so that it has proper size.
1879 */
1880
1881void hid_output_report(struct hid_report *report, __u8 *data)
1882{
1883	unsigned n;
1884
1885	if (report->id > 0)
1886		*data++ = report->id;
1887
1888	memset(data, 0, hid_compute_report_size(report));
1889	for (n = 0; n < report->maxfield; n++)
1890		hid_output_field(report->device, report->field[n], data);
1891}
1892EXPORT_SYMBOL_GPL(hid_output_report);
1893
1894/*
1895 * Allocator for buffer that is going to be passed to hid_output_report()
1896 */
1897u8 *hid_alloc_report_buf(struct hid_report *report, gfp_t flags)
1898{
1899	/*
1900	 * 7 extra bytes are necessary to achieve proper functionality
1901	 * of implement() working on 8 byte chunks
1902	 * 1 extra byte for the report ID if it is null (not used) so
1903	 * we can reserve that extra byte in the first position of the buffer
1904	 * when sending it to .raw_request()
1905	 */
1906
1907	u32 len = hid_report_len(report) + 7 + (report->id == 0);
1908
1909	return kzalloc(len, flags);
1910}
1911EXPORT_SYMBOL_GPL(hid_alloc_report_buf);
1912
1913/*
1914 * Set a field value. The report this field belongs to has to be
1915 * created and transferred to the device, to set this value in the
1916 * device.
1917 */
1918
1919int hid_set_field(struct hid_field *field, unsigned offset, __s32 value)
1920{
1921	unsigned size;
1922
1923	if (!field)
1924		return -1;
1925
1926	size = field->report_size;
1927
1928	hid_dump_input(field->report->device, field->usage + offset, value);
1929
1930	if (offset >= field->report_count) {
1931		hid_err(field->report->device, "offset (%d) exceeds report_count (%d)\n",
1932				offset, field->report_count);
1933		return -1;
1934	}
1935	if (field->logical_minimum < 0) {
1936		if (value != snto32(s32ton(value, size), size)) {
1937			hid_err(field->report->device, "value %d is out of range\n", value);
1938			return -1;
1939		}
1940	}
1941	field->value[offset] = value;
1942	return 0;
1943}
1944EXPORT_SYMBOL_GPL(hid_set_field);
1945
1946struct hid_field *hid_find_field(struct hid_device *hdev, unsigned int report_type,
1947				 unsigned int application, unsigned int usage)
1948{
1949	struct list_head *report_list = &hdev->report_enum[report_type].report_list;
1950	struct hid_report *report;
1951	int i, j;
1952
1953	list_for_each_entry(report, report_list, list) {
1954		if (report->application != application)
1955			continue;
1956
1957		for (i = 0; i < report->maxfield; i++) {
1958			struct hid_field *field = report->field[i];
1959
1960			for (j = 0; j < field->maxusage; j++) {
1961				if (field->usage[j].hid == usage)
1962					return field;
1963			}
1964		}
1965	}
1966
1967	return NULL;
1968}
1969EXPORT_SYMBOL_GPL(hid_find_field);
1970
1971static struct hid_report *hid_get_report(struct hid_report_enum *report_enum,
1972		const u8 *data)
1973{
1974	struct hid_report *report;
1975	unsigned int n = 0;	/* Normally report number is 0 */
1976
1977	/* Device uses numbered reports, data[0] is report number */
1978	if (report_enum->numbered)
1979		n = *data;
1980
1981	report = report_enum->report_id_hash[n];
1982	if (report == NULL)
1983		dbg_hid("undefined report_id %u received\n", n);
1984
1985	return report;
1986}
1987
1988/*
1989 * Implement a generic .request() callback, using .raw_request()
1990 * DO NOT USE in hid drivers directly, but through hid_hw_request instead.
1991 */
1992int __hid_request(struct hid_device *hid, struct hid_report *report,
1993		enum hid_class_request reqtype)
1994{
1995	char *buf, *data_buf;
1996	int ret;
1997	u32 len;
1998
1999	buf = hid_alloc_report_buf(report, GFP_KERNEL);
2000	if (!buf)
2001		return -ENOMEM;
2002
2003	data_buf = buf;
2004	len = hid_report_len(report);
2005
2006	if (report->id == 0) {
2007		/* reserve the first byte for the report ID */
2008		data_buf++;
2009		len++;
2010	}
2011
2012	if (reqtype == HID_REQ_SET_REPORT)
2013		hid_output_report(report, data_buf);
2014
2015	ret = hid_hw_raw_request(hid, report->id, buf, len, report->type, reqtype);
2016	if (ret < 0) {
2017		dbg_hid("unable to complete request: %d\n", ret);
2018		goto out;
2019	}
2020
2021	if (reqtype == HID_REQ_GET_REPORT)
2022		hid_input_report(hid, report->type, buf, ret, 0);
2023
2024	ret = 0;
2025
2026out:
2027	kfree(buf);
2028	return ret;
2029}
2030EXPORT_SYMBOL_GPL(__hid_request);
2031
2032int hid_report_raw_event(struct hid_device *hid, enum hid_report_type type, u8 *data, u32 size,
2033			 int interrupt)
2034{
2035	struct hid_report_enum *report_enum = hid->report_enum + type;
2036	struct hid_report *report;
2037	struct hid_driver *hdrv;
2038	int max_buffer_size = HID_MAX_BUFFER_SIZE;
2039	u32 rsize, csize = size;
2040	u8 *cdata = data;
2041	int ret = 0;
2042
2043	report = hid_get_report(report_enum, data);
2044	if (!report)
2045		goto out;
2046
2047	if (report_enum->numbered) {
2048		cdata++;
2049		csize--;
2050	}
2051
2052	rsize = hid_compute_report_size(report);
2053
2054	if (hid->ll_driver->max_buffer_size)
2055		max_buffer_size = hid->ll_driver->max_buffer_size;
2056
2057	if (report_enum->numbered && rsize >= max_buffer_size)
2058		rsize = max_buffer_size - 1;
2059	else if (rsize > max_buffer_size)
2060		rsize = max_buffer_size;
2061
2062	if (csize < rsize) {
2063		hid_warn_ratelimited(hid, "Event data for report %d was too short (%d vs %d)\n",
2064				     report->id, rsize, csize);
2065		ret = -EINVAL;
2066		goto out;
2067	}
2068
2069	if ((hid->claimed & HID_CLAIMED_HIDDEV) && hid->hiddev_report_event)
2070		hid->hiddev_report_event(hid, report);
2071	if (hid->claimed & HID_CLAIMED_HIDRAW) {
2072		ret = hidraw_report_event(hid, data, size);
2073		if (ret)
2074			goto out;
2075	}
2076
2077	if (hid->claimed != HID_CLAIMED_HIDRAW && report->maxfield) {
2078		hid_process_report(hid, report, cdata, interrupt);
2079		hdrv = hid->driver;
2080		if (hdrv && hdrv->report)
2081			hdrv->report(hid, report);
2082	}
2083
2084	if (hid->claimed & HID_CLAIMED_INPUT)
2085		hidinput_report_event(hid, report);
2086out:
2087	return ret;
2088}
2089EXPORT_SYMBOL_GPL(hid_report_raw_event);
2090
2091
2092static int __hid_input_report(struct hid_device *hid, enum hid_report_type type,
2093			      u8 *data, u32 size, int interrupt, u64 source, bool from_bpf,
2094			      bool lock_already_taken)
2095{
2096	struct hid_report_enum *report_enum;
2097	struct hid_driver *hdrv;
2098	struct hid_report *report;
2099	int ret = 0;
2100
2101	if (!hid)
2102		return -ENODEV;
2103
2104	ret = down_trylock(&hid->driver_input_lock);
2105	if (lock_already_taken && !ret) {
2106		up(&hid->driver_input_lock);
2107		return -EINVAL;
2108	} else if (!lock_already_taken && ret) {
2109		return -EBUSY;
2110	}
2111
2112	if (!hid->driver) {
2113		ret = -ENODEV;
2114		goto unlock;
2115	}
2116	report_enum = hid->report_enum + type;
2117	hdrv = hid->driver;
2118
2119	data = dispatch_hid_bpf_device_event(hid, type, data, &size, interrupt, source, from_bpf);
2120	if (IS_ERR(data)) {
2121		ret = PTR_ERR(data);
2122		goto unlock;
2123	}
2124
2125	if (!size) {
2126		dbg_hid("empty report\n");
2127		ret = -1;
2128		goto unlock;
2129	}
2130
2131	/* Avoid unnecessary overhead if debugfs is disabled */
2132	if (!list_empty(&hid->debug_list))
2133		hid_dump_report(hid, type, data, size);
2134
2135	report = hid_get_report(report_enum, data);
2136
2137	if (!report) {
2138		ret = -1;
2139		goto unlock;
2140	}
2141
2142	if (hdrv && hdrv->raw_event && hid_match_report(hid, report)) {
2143		ret = hdrv->raw_event(hid, report, data, size);
2144		if (ret < 0)
2145			goto unlock;
2146	}
2147
2148	ret = hid_report_raw_event(hid, type, data, size, interrupt);
2149
2150unlock:
2151	if (!lock_already_taken)
2152		up(&hid->driver_input_lock);
2153	return ret;
2154}
2155
2156/**
2157 * hid_input_report - report data from lower layer (usb, bt...)
2158 *
2159 * @hid: hid device
2160 * @type: HID report type (HID_*_REPORT)
2161 * @data: report contents
2162 * @size: size of data parameter
2163 * @interrupt: distinguish between interrupt and control transfers
2164 *
2165 * This is data entry for lower layers.
2166 */
2167int hid_input_report(struct hid_device *hid, enum hid_report_type type, u8 *data, u32 size,
2168		     int interrupt)
2169{
2170	return __hid_input_report(hid, type, data, size, interrupt, 0,
2171				  false, /* from_bpf */
2172				  false /* lock_already_taken */);
2173}
2174EXPORT_SYMBOL_GPL(hid_input_report);
2175
2176bool hid_match_one_id(const struct hid_device *hdev,
2177		      const struct hid_device_id *id)
2178{
2179	return (id->bus == HID_BUS_ANY || id->bus == hdev->bus) &&
2180		(id->group == HID_GROUP_ANY || id->group == hdev->group) &&
2181		(id->vendor == HID_ANY_ID || id->vendor == hdev->vendor) &&
2182		(id->product == HID_ANY_ID || id->product == hdev->product);
2183}
2184
2185const struct hid_device_id *hid_match_id(const struct hid_device *hdev,
2186		const struct hid_device_id *id)
2187{
2188	for (; id->bus; id++)
2189		if (hid_match_one_id(hdev, id))
2190			return id;
2191
2192	return NULL;
2193}
2194EXPORT_SYMBOL_GPL(hid_match_id);
2195
2196static const struct hid_device_id hid_hiddev_list[] = {
2197	{ HID_USB_DEVICE(USB_VENDOR_ID_MGE, USB_DEVICE_ID_MGE_UPS) },
2198	{ HID_USB_DEVICE(USB_VENDOR_ID_MGE, USB_DEVICE_ID_MGE_UPS1) },
2199	{ }
2200};
2201
2202static bool hid_hiddev(struct hid_device *hdev)
2203{
2204	return !!hid_match_id(hdev, hid_hiddev_list);
2205}
2206
2207
2208static ssize_t
2209report_descriptor_read(struct file *filp, struct kobject *kobj,
2210		       const struct bin_attribute *attr,
2211		       char *buf, loff_t off, size_t count)
2212{
2213	struct device *dev = kobj_to_dev(kobj);
2214	struct hid_device *hdev = to_hid_device(dev);
2215
2216	if (off >= hdev->rsize)
2217		return 0;
2218
2219	if (off + count > hdev->rsize)
2220		count = hdev->rsize - off;
2221
2222	memcpy(buf, hdev->rdesc + off, count);
2223
2224	return count;
2225}
2226
2227static ssize_t
2228country_show(struct device *dev, struct device_attribute *attr,
2229	     char *buf)
2230{
2231	struct hid_device *hdev = to_hid_device(dev);
2232
2233	return sprintf(buf, "%02x\n", hdev->country & 0xff);
2234}
2235
2236static const BIN_ATTR_RO(report_descriptor, HID_MAX_DESCRIPTOR_SIZE);
2237
2238static const DEVICE_ATTR_RO(country);
2239
2240int hid_connect(struct hid_device *hdev, unsigned int connect_mask)
2241{
2242	static const char *types[] = { "Device", "Pointer", "Mouse", "Device",
2243		"Joystick", "Gamepad", "Keyboard", "Keypad",
2244		"Multi-Axis Controller"
2245	};
2246	const char *type, *bus;
2247	char buf[64] = "";
2248	unsigned int i;
2249	int len;
2250	int ret;
2251
2252	ret = hid_bpf_connect_device(hdev);
2253	if (ret)
2254		return ret;
2255
2256	if (hdev->quirks & HID_QUIRK_HIDDEV_FORCE)
2257		connect_mask |= (HID_CONNECT_HIDDEV_FORCE | HID_CONNECT_HIDDEV);
2258	if (hdev->quirks & HID_QUIRK_HIDINPUT_FORCE)
2259		connect_mask |= HID_CONNECT_HIDINPUT_FORCE;
2260	if (hdev->bus != BUS_USB)
2261		connect_mask &= ~HID_CONNECT_HIDDEV;
2262	if (hid_hiddev(hdev))
2263		connect_mask |= HID_CONNECT_HIDDEV_FORCE;
2264
2265	if ((connect_mask & HID_CONNECT_HIDINPUT) && !hidinput_connect(hdev,
2266				connect_mask & HID_CONNECT_HIDINPUT_FORCE))
2267		hdev->claimed |= HID_CLAIMED_INPUT;
2268
2269	if ((connect_mask & HID_CONNECT_HIDDEV) && hdev->hiddev_connect &&
2270			!hdev->hiddev_connect(hdev,
2271				connect_mask & HID_CONNECT_HIDDEV_FORCE))
2272		hdev->claimed |= HID_CLAIMED_HIDDEV;
2273	if ((connect_mask & HID_CONNECT_HIDRAW) && !hidraw_connect(hdev))
2274		hdev->claimed |= HID_CLAIMED_HIDRAW;
2275
2276	if (connect_mask & HID_CONNECT_DRIVER)
2277		hdev->claimed |= HID_CLAIMED_DRIVER;
2278
2279	/* Drivers with the ->raw_event callback set are not required to connect
2280	 * to any other listener. */
2281	if (!hdev->claimed && !hdev->driver->raw_event) {
2282		hid_err(hdev, "device has no listeners, quitting\n");
2283		return -ENODEV;
2284	}
2285
2286	hid_process_ordering(hdev);
2287
2288	if ((hdev->claimed & HID_CLAIMED_INPUT) &&
2289			(connect_mask & HID_CONNECT_FF) && hdev->ff_init)
2290		hdev->ff_init(hdev);
2291
2292	len = 0;
2293	if (hdev->claimed & HID_CLAIMED_INPUT)
2294		len += sprintf(buf + len, "input");
2295	if (hdev->claimed & HID_CLAIMED_HIDDEV)
2296		len += sprintf(buf + len, "%shiddev%d", len ? "," : "",
2297				((struct hiddev *)hdev->hiddev)->minor);
2298	if (hdev->claimed & HID_CLAIMED_HIDRAW)
2299		len += sprintf(buf + len, "%shidraw%d", len ? "," : "",
2300				((struct hidraw *)hdev->hidraw)->minor);
2301
2302	type = "Device";
2303	for (i = 0; i < hdev->maxcollection; i++) {
2304		struct hid_collection *col = &hdev->collection[i];
2305		if (col->type == HID_COLLECTION_APPLICATION &&
2306		   (col->usage & HID_USAGE_PAGE) == HID_UP_GENDESK &&
2307		   (col->usage & 0xffff) < ARRAY_SIZE(types)) {
2308			type = types[col->usage & 0xffff];
2309			break;
2310		}
2311	}
2312
2313	switch (hdev->bus) {
2314	case BUS_USB:
2315		bus = "USB";
2316		break;
2317	case BUS_BLUETOOTH:
2318		bus = "BLUETOOTH";
2319		break;
2320	case BUS_I2C:
2321		bus = "I2C";
2322		break;
2323	case BUS_SDW:
2324		bus = "SOUNDWIRE";
2325		break;
2326	case BUS_VIRTUAL:
2327		bus = "VIRTUAL";
2328		break;
2329	case BUS_INTEL_ISHTP:
2330	case BUS_AMD_SFH:
2331		bus = "SENSOR HUB";
2332		break;
2333	default:
2334		bus = "<UNKNOWN>";
2335	}
2336
2337	ret = device_create_file(&hdev->dev, &dev_attr_country);
2338	if (ret)
2339		hid_warn(hdev,
2340			 "can't create sysfs country code attribute err: %d\n", ret);
2341
2342	hid_info(hdev, "%s: %s HID v%x.%02x %s [%s] on %s\n",
2343		 buf, bus, hdev->version >> 8, hdev->version & 0xff,
2344		 type, hdev->name, hdev->phys);
2345
2346	return 0;
2347}
2348EXPORT_SYMBOL_GPL(hid_connect);
2349
2350void hid_disconnect(struct hid_device *hdev)
2351{
2352	device_remove_file(&hdev->dev, &dev_attr_country);
2353	if (hdev->claimed & HID_CLAIMED_INPUT)
2354		hidinput_disconnect(hdev);
2355	if (hdev->claimed & HID_CLAIMED_HIDDEV)
2356		hdev->hiddev_disconnect(hdev);
2357	if (hdev->claimed & HID_CLAIMED_HIDRAW)
2358		hidraw_disconnect(hdev);
2359	hdev->claimed = 0;
2360
2361	hid_bpf_disconnect_device(hdev);
2362}
2363EXPORT_SYMBOL_GPL(hid_disconnect);
2364
2365/**
2366 * hid_hw_start - start underlying HW
2367 * @hdev: hid device
2368 * @connect_mask: which outputs to connect, see HID_CONNECT_*
2369 *
2370 * Call this in probe function *after* hid_parse. This will setup HW
2371 * buffers and start the device (if not defeirred to device open).
2372 * hid_hw_stop must be called if this was successful.
2373 */
2374int hid_hw_start(struct hid_device *hdev, unsigned int connect_mask)
2375{
2376	int error;
2377
2378	error = hdev->ll_driver->start(hdev);
2379	if (error)
2380		return error;
2381
2382	if (connect_mask) {
2383		error = hid_connect(hdev, connect_mask);
2384		if (error) {
2385			hdev->ll_driver->stop(hdev);
2386			return error;
2387		}
2388	}
2389
2390	return 0;
2391}
2392EXPORT_SYMBOL_GPL(hid_hw_start);
2393
2394/**
2395 * hid_hw_stop - stop underlying HW
2396 * @hdev: hid device
2397 *
2398 * This is usually called from remove function or from probe when something
2399 * failed and hid_hw_start was called already.
2400 */
2401void hid_hw_stop(struct hid_device *hdev)
2402{
2403	hid_disconnect(hdev);
2404	hdev->ll_driver->stop(hdev);
2405}
2406EXPORT_SYMBOL_GPL(hid_hw_stop);
2407
2408/**
2409 * hid_hw_open - signal underlying HW to start delivering events
2410 * @hdev: hid device
2411 *
2412 * Tell underlying HW to start delivering events from the device.
2413 * This function should be called sometime after successful call
2414 * to hid_hw_start().
2415 */
2416int hid_hw_open(struct hid_device *hdev)
2417{
2418	int ret;
2419
2420	ret = mutex_lock_killable(&hdev->ll_open_lock);
2421	if (ret)
2422		return ret;
2423
2424	if (!hdev->ll_open_count++) {
2425		ret = hdev->ll_driver->open(hdev);
2426		if (ret)
2427			hdev->ll_open_count--;
2428
2429		if (hdev->driver->on_hid_hw_open)
2430			hdev->driver->on_hid_hw_open(hdev);
2431	}
2432
2433	mutex_unlock(&hdev->ll_open_lock);
2434	return ret;
2435}
2436EXPORT_SYMBOL_GPL(hid_hw_open);
2437
2438/**
2439 * hid_hw_close - signal underlaying HW to stop delivering events
2440 *
2441 * @hdev: hid device
2442 *
2443 * This function indicates that we are not interested in the events
2444 * from this device anymore. Delivery of events may or may not stop,
2445 * depending on the number of users still outstanding.
2446 */
2447void hid_hw_close(struct hid_device *hdev)
2448{
2449	mutex_lock(&hdev->ll_open_lock);
2450	if (!--hdev->ll_open_count) {
2451		hdev->ll_driver->close(hdev);
2452
2453		if (hdev->driver->on_hid_hw_close)
2454			hdev->driver->on_hid_hw_close(hdev);
2455	}
2456	mutex_unlock(&hdev->ll_open_lock);
2457}
2458EXPORT_SYMBOL_GPL(hid_hw_close);
2459
2460/**
2461 * hid_hw_request - send report request to device
2462 *
2463 * @hdev: hid device
2464 * @report: report to send
2465 * @reqtype: hid request type
2466 */
2467void hid_hw_request(struct hid_device *hdev,
2468		    struct hid_report *report, enum hid_class_request reqtype)
2469{
2470	if (hdev->ll_driver->request)
2471		return hdev->ll_driver->request(hdev, report, reqtype);
2472
2473	__hid_request(hdev, report, reqtype);
2474}
2475EXPORT_SYMBOL_GPL(hid_hw_request);
2476
2477int __hid_hw_raw_request(struct hid_device *hdev,
2478			 unsigned char reportnum, __u8 *buf,
2479			 size_t len, enum hid_report_type rtype,
2480			 enum hid_class_request reqtype,
2481			 u64 source, bool from_bpf)
2482{
2483	unsigned int max_buffer_size = HID_MAX_BUFFER_SIZE;
2484	int ret;
2485
2486	if (hdev->ll_driver->max_buffer_size)
2487		max_buffer_size = hdev->ll_driver->max_buffer_size;
2488
2489	if (len < 1 || len > max_buffer_size || !buf)
2490		return -EINVAL;
2491
2492	ret = dispatch_hid_bpf_raw_requests(hdev, reportnum, buf, len, rtype,
2493					    reqtype, source, from_bpf);
2494	if (ret)
2495		return ret;
2496
2497	return hdev->ll_driver->raw_request(hdev, reportnum, buf, len,
2498					    rtype, reqtype);
2499}
2500
2501/**
2502 * hid_hw_raw_request - send report request to device
2503 *
2504 * @hdev: hid device
2505 * @reportnum: report ID
2506 * @buf: in/out data to transfer
2507 * @len: length of buf
2508 * @rtype: HID report type
2509 * @reqtype: HID_REQ_GET_REPORT or HID_REQ_SET_REPORT
2510 *
2511 * Return: count of data transferred, negative if error
2512 *
2513 * Same behavior as hid_hw_request, but with raw buffers instead.
2514 */
2515int hid_hw_raw_request(struct hid_device *hdev,
2516		       unsigned char reportnum, __u8 *buf,
2517		       size_t len, enum hid_report_type rtype, enum hid_class_request reqtype)
2518{
2519	return __hid_hw_raw_request(hdev, reportnum, buf, len, rtype, reqtype, 0, false);
2520}
2521EXPORT_SYMBOL_GPL(hid_hw_raw_request);
2522
2523int __hid_hw_output_report(struct hid_device *hdev, __u8 *buf, size_t len, u64 source,
2524			   bool from_bpf)
2525{
2526	unsigned int max_buffer_size = HID_MAX_BUFFER_SIZE;
2527	int ret;
2528
2529	if (hdev->ll_driver->max_buffer_size)
2530		max_buffer_size = hdev->ll_driver->max_buffer_size;
2531
2532	if (len < 1 || len > max_buffer_size || !buf)
2533		return -EINVAL;
2534
2535	ret = dispatch_hid_bpf_output_report(hdev, buf, len, source, from_bpf);
2536	if (ret)
2537		return ret;
2538
2539	if (hdev->ll_driver->output_report)
2540		return hdev->ll_driver->output_report(hdev, buf, len);
2541
2542	return -ENOSYS;
2543}
2544
2545/**
2546 * hid_hw_output_report - send output report to device
2547 *
2548 * @hdev: hid device
2549 * @buf: raw data to transfer
2550 * @len: length of buf
2551 *
2552 * Return: count of data transferred, negative if error
2553 */
2554int hid_hw_output_report(struct hid_device *hdev, __u8 *buf, size_t len)
2555{
2556	return __hid_hw_output_report(hdev, buf, len, 0, false);
2557}
2558EXPORT_SYMBOL_GPL(hid_hw_output_report);
2559
2560#ifdef CONFIG_PM
2561int hid_driver_suspend(struct hid_device *hdev, pm_message_t state)
2562{
2563	if (hdev->driver && hdev->driver->suspend)
2564		return hdev->driver->suspend(hdev, state);
2565
2566	return 0;
2567}
2568EXPORT_SYMBOL_GPL(hid_driver_suspend);
2569
2570int hid_driver_reset_resume(struct hid_device *hdev)
2571{
2572	if (hdev->driver && hdev->driver->reset_resume)
2573		return hdev->driver->reset_resume(hdev);
2574
2575	return 0;
2576}
2577EXPORT_SYMBOL_GPL(hid_driver_reset_resume);
2578
2579int hid_driver_resume(struct hid_device *hdev)
2580{
2581	if (hdev->driver && hdev->driver->resume)
2582		return hdev->driver->resume(hdev);
2583
2584	return 0;
2585}
2586EXPORT_SYMBOL_GPL(hid_driver_resume);
2587#endif /* CONFIG_PM */
2588
2589struct hid_dynid {
2590	struct list_head list;
2591	struct hid_device_id id;
2592};
2593
2594/**
2595 * new_id_store - add a new HID device ID to this driver and re-probe devices
2596 * @drv: target device driver
2597 * @buf: buffer for scanning device ID data
2598 * @count: input size
2599 *
2600 * Adds a new dynamic hid device ID to this driver,
2601 * and causes the driver to probe for all devices again.
2602 */
2603static ssize_t new_id_store(struct device_driver *drv, const char *buf,
2604		size_t count)
2605{
2606	struct hid_driver *hdrv = to_hid_driver(drv);
2607	struct hid_dynid *dynid;
2608	__u32 bus, vendor, product;
2609	unsigned long driver_data = 0;
2610	int ret;
2611
2612	ret = sscanf(buf, "%x %x %x %lx",
2613			&bus, &vendor, &product, &driver_data);
2614	if (ret < 3)
2615		return -EINVAL;
2616
2617	dynid = kzalloc(sizeof(*dynid), GFP_KERNEL);
2618	if (!dynid)
2619		return -ENOMEM;
2620
2621	dynid->id.bus = bus;
2622	dynid->id.group = HID_GROUP_ANY;
2623	dynid->id.vendor = vendor;
2624	dynid->id.product = product;
2625	dynid->id.driver_data = driver_data;
2626
2627	spin_lock(&hdrv->dyn_lock);
2628	list_add_tail(&dynid->list, &hdrv->dyn_list);
2629	spin_unlock(&hdrv->dyn_lock);
2630
2631	ret = driver_attach(&hdrv->driver);
2632
2633	return ret ? : count;
2634}
2635static DRIVER_ATTR_WO(new_id);
2636
2637static struct attribute *hid_drv_attrs[] = {
2638	&driver_attr_new_id.attr,
2639	NULL,
2640};
2641ATTRIBUTE_GROUPS(hid_drv);
2642
2643static void hid_free_dynids(struct hid_driver *hdrv)
2644{
2645	struct hid_dynid *dynid, *n;
2646
2647	spin_lock(&hdrv->dyn_lock);
2648	list_for_each_entry_safe(dynid, n, &hdrv->dyn_list, list) {
2649		list_del(&dynid->list);
2650		kfree(dynid);
2651	}
2652	spin_unlock(&hdrv->dyn_lock);
2653}
2654
2655const struct hid_device_id *hid_match_device(struct hid_device *hdev,
2656					     struct hid_driver *hdrv)
2657{
2658	struct hid_dynid *dynid;
2659
2660	spin_lock(&hdrv->dyn_lock);
2661	list_for_each_entry(dynid, &hdrv->dyn_list, list) {
2662		if (hid_match_one_id(hdev, &dynid->id)) {
2663			spin_unlock(&hdrv->dyn_lock);
2664			return &dynid->id;
2665		}
2666	}
2667	spin_unlock(&hdrv->dyn_lock);
2668
2669	return hid_match_id(hdev, hdrv->id_table);
2670}
2671EXPORT_SYMBOL_GPL(hid_match_device);
2672
2673static int hid_bus_match(struct device *dev, const struct device_driver *drv)
2674{
2675	struct hid_driver *hdrv = to_hid_driver(drv);
2676	struct hid_device *hdev = to_hid_device(dev);
2677
2678	return hid_match_device(hdev, hdrv) != NULL;
2679}
2680
2681/**
2682 * hid_compare_device_paths - check if both devices share the same path
2683 * @hdev_a: hid device
2684 * @hdev_b: hid device
2685 * @separator: char to use as separator
2686 *
2687 * Check if two devices share the same path up to the last occurrence of
2688 * the separator char. Both paths must exist (i.e., zero-length paths
2689 * don't match).
2690 */
2691bool hid_compare_device_paths(struct hid_device *hdev_a,
2692			      struct hid_device *hdev_b, char separator)
2693{
2694	int n1 = strrchr(hdev_a->phys, separator) - hdev_a->phys;
2695	int n2 = strrchr(hdev_b->phys, separator) - hdev_b->phys;
2696
2697	if (n1 != n2 || n1 <= 0 || n2 <= 0)
2698		return false;
2699
2700	return !strncmp(hdev_a->phys, hdev_b->phys, n1);
2701}
2702EXPORT_SYMBOL_GPL(hid_compare_device_paths);
2703
2704static bool hid_check_device_match(struct hid_device *hdev,
2705				   struct hid_driver *hdrv,
2706				   const struct hid_device_id **id)
2707{
2708	*id = hid_match_device(hdev, hdrv);
2709	if (!*id)
2710		return false;
2711
2712	if (hdrv->match)
2713		return hdrv->match(hdev, hid_ignore_special_drivers);
2714
2715	/*
2716	 * hid-generic implements .match(), so we must be dealing with a
2717	 * different HID driver here, and can simply check if
2718	 * hid_ignore_special_drivers or HID_QUIRK_IGNORE_SPECIAL_DRIVER
2719	 * are set or not.
2720	 */
2721	return !hid_ignore_special_drivers && !(hdev->quirks & HID_QUIRK_IGNORE_SPECIAL_DRIVER);
2722}
2723
2724static void hid_set_group(struct hid_device *hdev)
2725{
2726	int ret;
2727
2728	if (hid_ignore_special_drivers) {
2729		hdev->group = HID_GROUP_GENERIC;
2730	} else if (!hdev->group &&
2731		   !(hdev->quirks & HID_QUIRK_HAVE_SPECIAL_DRIVER)) {
2732		ret = hid_scan_report(hdev);
2733		if (ret)
2734			hid_warn(hdev, "bad device descriptor (%d)\n", ret);
2735	}
2736}
2737
2738static int __hid_device_probe(struct hid_device *hdev, struct hid_driver *hdrv)
2739{
2740	const struct hid_device_id *id;
2741	int ret;
2742
2743	if (!hdev->bpf_rsize) {
2744		/* we keep a reference to the currently scanned report descriptor */
2745		const __u8  *original_rdesc = hdev->bpf_rdesc;
2746
2747		if (!original_rdesc)
2748			original_rdesc = hdev->dev_rdesc;
2749
2750		/* in case a bpf program gets detached, we need to free the old one */
2751		hid_free_bpf_rdesc(hdev);
2752
2753		/* keep this around so we know we called it once */
2754		hdev->bpf_rsize = hdev->dev_rsize;
2755
2756		/* call_hid_bpf_rdesc_fixup will always return a valid pointer */
2757		hdev->bpf_rdesc = call_hid_bpf_rdesc_fixup(hdev, hdev->dev_rdesc,
2758							   &hdev->bpf_rsize);
2759
2760		/* the report descriptor changed, we need to re-scan it */
2761		if (original_rdesc != hdev->bpf_rdesc) {
2762			hdev->group = 0;
2763			hid_set_group(hdev);
2764		}
2765	}
2766
2767	if (!hid_check_device_match(hdev, hdrv, &id))
2768		return -ENODEV;
2769
2770	hdev->devres_group_id = devres_open_group(&hdev->dev, NULL, GFP_KERNEL);
2771	if (!hdev->devres_group_id)
2772		return -ENOMEM;
2773
2774	/* reset the quirks that has been previously set */
2775	hdev->quirks = hid_lookup_quirk(hdev);
2776	hdev->driver = hdrv;
2777
2778	if (hdrv->probe) {
2779		ret = hdrv->probe(hdev, id);
2780	} else { /* default probe */
2781		ret = hid_open_report(hdev);
2782		if (!ret)
2783			ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);
2784	}
2785
2786	/*
2787	 * Note that we are not closing the devres group opened above so
2788	 * even resources that were attached to the device after probe is
2789	 * run are released when hid_device_remove() is executed. This is
2790	 * needed as some drivers would allocate additional resources,
2791	 * for example when updating firmware.
2792	 */
2793
2794	if (ret) {
2795		devres_release_group(&hdev->dev, hdev->devres_group_id);
2796		hid_close_report(hdev);
2797		hdev->driver = NULL;
2798	}
2799
2800	return ret;
2801}
2802
2803static int hid_device_probe(struct device *dev)
2804{
2805	struct hid_device *hdev = to_hid_device(dev);
2806	struct hid_driver *hdrv = to_hid_driver(dev->driver);
2807	int ret = 0;
2808
2809	if (down_interruptible(&hdev->driver_input_lock))
2810		return -EINTR;
2811
2812	hdev->io_started = false;
2813	clear_bit(ffs(HID_STAT_REPROBED), &hdev->status);
2814
2815	if (!hdev->driver)
2816		ret = __hid_device_probe(hdev, hdrv);
2817
2818	if (!hdev->io_started)
2819		up(&hdev->driver_input_lock);
2820
2821	return ret;
2822}
2823
2824static void hid_device_remove(struct device *dev)
2825{
2826	struct hid_device *hdev = to_hid_device(dev);
2827	struct hid_driver *hdrv;
2828
2829	down(&hdev->driver_input_lock);
2830	hdev->io_started = false;
2831
2832	hdrv = hdev->driver;
2833	if (hdrv) {
2834		if (hdrv->remove)
2835			hdrv->remove(hdev);
2836		else /* default remove */
2837			hid_hw_stop(hdev);
2838
2839		/* Release all devres resources allocated by the driver */
2840		devres_release_group(&hdev->dev, hdev->devres_group_id);
2841
2842		hid_close_report(hdev);
2843		hdev->driver = NULL;
2844	}
2845
2846	if (!hdev->io_started)
2847		up(&hdev->driver_input_lock);
2848}
2849
2850static ssize_t modalias_show(struct device *dev, struct device_attribute *a,
2851			     char *buf)
2852{
2853	struct hid_device *hdev = container_of(dev, struct hid_device, dev);
2854
2855	return sysfs_emit(buf, "hid:b%04Xg%04Xv%08Xp%08X\n",
2856			 hdev->bus, hdev->group, hdev->vendor, hdev->product);
2857}
2858static DEVICE_ATTR_RO(modalias);
2859
2860static struct attribute *hid_dev_attrs[] = {
2861	&dev_attr_modalias.attr,
2862	NULL,
2863};
2864static const struct bin_attribute *hid_dev_bin_attrs[] = {
2865	&bin_attr_report_descriptor,
2866	NULL
2867};
2868static const struct attribute_group hid_dev_group = {
2869	.attrs = hid_dev_attrs,
2870	.bin_attrs = hid_dev_bin_attrs,
2871};
2872__ATTRIBUTE_GROUPS(hid_dev);
2873
2874static int hid_uevent(const struct device *dev, struct kobj_uevent_env *env)
2875{
2876	const struct hid_device *hdev = to_hid_device(dev);
2877
2878	if (add_uevent_var(env, "HID_ID=%04X:%08X:%08X",
2879			hdev->bus, hdev->vendor, hdev->product))
2880		return -ENOMEM;
2881
2882	if (add_uevent_var(env, "HID_NAME=%s", hdev->name))
2883		return -ENOMEM;
2884
2885	if (add_uevent_var(env, "HID_PHYS=%s", hdev->phys))
2886		return -ENOMEM;
2887
2888	if (add_uevent_var(env, "HID_UNIQ=%s", hdev->uniq))
2889		return -ENOMEM;
2890
2891	if (add_uevent_var(env, "MODALIAS=hid:b%04Xg%04Xv%08Xp%08X",
2892			   hdev->bus, hdev->group, hdev->vendor, hdev->product))
2893		return -ENOMEM;
2894
2895	return 0;
2896}
2897
2898const struct bus_type hid_bus_type = {
2899	.name		= "hid",
2900	.dev_groups	= hid_dev_groups,
2901	.drv_groups	= hid_drv_groups,
2902	.match		= hid_bus_match,
2903	.probe		= hid_device_probe,
2904	.remove		= hid_device_remove,
2905	.uevent		= hid_uevent,
2906};
2907EXPORT_SYMBOL(hid_bus_type);
2908
2909int hid_add_device(struct hid_device *hdev)
2910{
2911	static atomic_t id = ATOMIC_INIT(0);
2912	int ret;
2913
2914	if (WARN_ON(hdev->status & HID_STAT_ADDED))
2915		return -EBUSY;
2916
2917	hdev->quirks = hid_lookup_quirk(hdev);
2918
2919	/* we need to kill them here, otherwise they will stay allocated to
2920	 * wait for coming driver */
2921	if (hid_ignore(hdev))
2922		return -ENODEV;
2923
2924	/*
2925	 * Check for the mandatory transport channel.
2926	 */
2927	 if (!hdev->ll_driver->raw_request) {
2928		hid_err(hdev, "transport driver missing .raw_request()\n");
2929		return -EINVAL;
2930	 }
2931
2932	/*
2933	 * Read the device report descriptor once and use as template
2934	 * for the driver-specific modifications.
2935	 */
2936	ret = hdev->ll_driver->parse(hdev);
2937	if (ret)
2938		return ret;
2939	if (!hdev->dev_rdesc)
2940		return -ENODEV;
2941
2942	/*
2943	 * Scan generic devices for group information
2944	 */
2945	hid_set_group(hdev);
2946
2947	hdev->id = atomic_inc_return(&id);
2948
2949	/* XXX hack, any other cleaner solution after the driver core
2950	 * is converted to allow more than 20 bytes as the device name? */
2951	dev_set_name(&hdev->dev, "%04X:%04X:%04X.%04X", hdev->bus,
2952		     hdev->vendor, hdev->product, hdev->id);
2953
2954	hid_debug_register(hdev, dev_name(&hdev->dev));
2955	ret = device_add(&hdev->dev);
2956	if (!ret)
2957		hdev->status |= HID_STAT_ADDED;
2958	else
2959		hid_debug_unregister(hdev);
2960
2961	return ret;
2962}
2963EXPORT_SYMBOL_GPL(hid_add_device);
2964
2965/**
2966 * hid_allocate_device - allocate new hid device descriptor
2967 *
2968 * Allocate and initialize hid device, so that hid_destroy_device might be
2969 * used to free it.
2970 *
2971 * New hid_device pointer is returned on success, otherwise ERR_PTR encoded
2972 * error value.
2973 */
2974struct hid_device *hid_allocate_device(void)
2975{
2976	struct hid_device *hdev;
2977	int ret = -ENOMEM;
2978
2979	hdev = kzalloc(sizeof(*hdev), GFP_KERNEL);
2980	if (hdev == NULL)
2981		return ERR_PTR(ret);
2982
2983	device_initialize(&hdev->dev);
2984	hdev->dev.release = hid_device_release;
2985	hdev->dev.bus = &hid_bus_type;
2986	device_enable_async_suspend(&hdev->dev);
2987
2988	hid_close_report(hdev);
2989
2990	init_waitqueue_head(&hdev->debug_wait);
2991	INIT_LIST_HEAD(&hdev->debug_list);
2992	spin_lock_init(&hdev->debug_list_lock);
2993	sema_init(&hdev->driver_input_lock, 1);
2994	mutex_init(&hdev->ll_open_lock);
2995	kref_init(&hdev->ref);
2996
2997	ret = hid_bpf_device_init(hdev);
2998	if (ret)
2999		goto out_err;
3000
3001	return hdev;
3002
3003out_err:
3004	hid_destroy_device(hdev);
3005	return ERR_PTR(ret);
3006}
3007EXPORT_SYMBOL_GPL(hid_allocate_device);
3008
3009static void hid_remove_device(struct hid_device *hdev)
3010{
3011	if (hdev->status & HID_STAT_ADDED) {
3012		device_del(&hdev->dev);
3013		hid_debug_unregister(hdev);
3014		hdev->status &= ~HID_STAT_ADDED;
3015	}
3016	hid_free_bpf_rdesc(hdev);
3017	kfree(hdev->dev_rdesc);
3018	hdev->dev_rdesc = NULL;
3019	hdev->dev_rsize = 0;
3020	hdev->bpf_rsize = 0;
3021}
3022
3023/**
3024 * hid_destroy_device - free previously allocated device
3025 *
3026 * @hdev: hid device
3027 *
3028 * If you allocate hid_device through hid_allocate_device, you should ever
3029 * free by this function.
3030 */
3031void hid_destroy_device(struct hid_device *hdev)
3032{
3033	hid_bpf_destroy_device(hdev);
3034	hid_remove_device(hdev);
3035	put_device(&hdev->dev);
3036}
3037EXPORT_SYMBOL_GPL(hid_destroy_device);
3038
3039
3040static int __hid_bus_reprobe_drivers(struct device *dev, void *data)
3041{
3042	struct hid_driver *hdrv = data;
3043	struct hid_device *hdev = to_hid_device(dev);
3044
3045	if (hdev->driver == hdrv &&
3046	    !hdrv->match(hdev, hid_ignore_special_drivers) &&
3047	    !test_and_set_bit(ffs(HID_STAT_REPROBED), &hdev->status))
3048		return device_reprobe(dev);
3049
3050	return 0;
3051}
3052
3053static int __hid_bus_driver_added(struct device_driver *drv, void *data)
3054{
3055	struct hid_driver *hdrv = to_hid_driver(drv);
3056
3057	if (hdrv->match) {
3058		bus_for_each_dev(&hid_bus_type, NULL, hdrv,
3059				 __hid_bus_reprobe_drivers);
3060	}
3061
3062	return 0;
3063}
3064
3065static int __bus_removed_driver(struct device_driver *drv, void *data)
3066{
3067	return bus_rescan_devices(&hid_bus_type);
3068}
3069
3070int __hid_register_driver(struct hid_driver *hdrv, struct module *owner,
3071		const char *mod_name)
3072{
3073	int ret;
3074
3075	hdrv->driver.name = hdrv->name;
3076	hdrv->driver.bus = &hid_bus_type;
3077	hdrv->driver.owner = owner;
3078	hdrv->driver.mod_name = mod_name;
3079
3080	INIT_LIST_HEAD(&hdrv->dyn_list);
3081	spin_lock_init(&hdrv->dyn_lock);
3082
3083	ret = driver_register(&hdrv->driver);
3084
3085	if (ret == 0)
3086		bus_for_each_drv(&hid_bus_type, NULL, NULL,
3087				 __hid_bus_driver_added);
3088
3089	return ret;
3090}
3091EXPORT_SYMBOL_GPL(__hid_register_driver);
3092
3093void hid_unregister_driver(struct hid_driver *hdrv)
3094{
3095	driver_unregister(&hdrv->driver);
3096	hid_free_dynids(hdrv);
3097
3098	bus_for_each_drv(&hid_bus_type, NULL, hdrv, __bus_removed_driver);
3099}
3100EXPORT_SYMBOL_GPL(hid_unregister_driver);
3101
3102int hid_check_keys_pressed(struct hid_device *hid)
3103{
3104	struct hid_input *hidinput;
3105	int i;
3106
3107	if (!(hid->claimed & HID_CLAIMED_INPUT))
3108		return 0;
3109
3110	list_for_each_entry(hidinput, &hid->inputs, list) {
3111		for (i = 0; i < BITS_TO_LONGS(KEY_MAX); i++)
3112			if (hidinput->input->key[i])
3113				return 1;
3114	}
3115
3116	return 0;
3117}
3118EXPORT_SYMBOL_GPL(hid_check_keys_pressed);
3119
3120#ifdef CONFIG_HID_BPF
3121static const struct hid_ops __hid_ops = {
3122	.hid_get_report = hid_get_report,
3123	.hid_hw_raw_request = __hid_hw_raw_request,
3124	.hid_hw_output_report = __hid_hw_output_report,
3125	.hid_input_report = __hid_input_report,
3126	.owner = THIS_MODULE,
3127	.bus_type = &hid_bus_type,
3128};
3129#endif
3130
3131static int __init hid_init(void)
3132{
3133	int ret;
3134
3135	ret = bus_register(&hid_bus_type);
3136	if (ret) {
3137		pr_err("can't register hid bus\n");
3138		goto err;
3139	}
3140
3141#ifdef CONFIG_HID_BPF
3142	hid_ops = &__hid_ops;
3143#endif
3144
3145	ret = hidraw_init();
3146	if (ret)
3147		goto err_bus;
3148
3149	hid_debug_init();
3150
3151	return 0;
3152err_bus:
3153	bus_unregister(&hid_bus_type);
3154err:
3155	return ret;
3156}
3157
3158static void __exit hid_exit(void)
3159{
3160#ifdef CONFIG_HID_BPF
3161	hid_ops = NULL;
3162#endif
3163	hid_debug_exit();
3164	hidraw_exit();
3165	bus_unregister(&hid_bus_type);
3166	hid_quirks_exit(HID_BUS_ANY);
3167}
3168
3169module_init(hid_init);
3170module_exit(hid_exit);
3171
3172MODULE_AUTHOR("Andreas Gal");
3173MODULE_AUTHOR("Vojtech Pavlik");
3174MODULE_AUTHOR("Jiri Kosina");
3175MODULE_DESCRIPTION("HID support for Linux");
3176MODULE_LICENSE("GPL");
~/ Read-only file preview.