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