xref: /linux/drivers/hid/usbhid/hid-pidff.c (revision 70eda68668d1476b459b64e69b8f36659fa9dfa8)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Force feedback driver for USB HID PID compliant devices
4  *
5  *  Copyright (c) 2005, 2006 Anssi Hannula <anssi.hannula@gmail.com>
6  *  Upgraded 2025 by Oleg Makarenko and Tomasz Pakuła
7  */
8 
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10 
11 #include "hid-pidff.h"
12 #include <linux/hid.h>
13 #include <linux/input.h>
14 #include <linux/math64.h>
15 #include <linux/minmax.h>
16 #include <linux/slab.h>
17 #include <linux/stringify.h>
18 #include <linux/usb.h>
19 
20 #define	PID_EFFECTS_MAX		64
21 #define	PID_INFINITE		U16_MAX
22 
23 /* Linux Force Feedback API uses miliseconds as time unit */
24 #define FF_TIME_EXPONENT	-3
25 #define FF_INFINITE		0
26 
27 /* Report usage table used to put reports into an array */
28 #define PID_SET_EFFECT		0
29 #define PID_EFFECT_OPERATION	1
30 #define PID_DEVICE_GAIN		2
31 #define PID_POOL		3
32 #define PID_BLOCK_LOAD		4
33 #define PID_BLOCK_FREE		5
34 #define PID_DEVICE_CONTROL	6
35 #define PID_CREATE_NEW_EFFECT	7
36 
37 #define PID_REQUIRED_REPORTS	8
38 
39 #define PID_SET_ENVELOPE	8
40 #define PID_SET_CONDITION	9
41 #define PID_SET_PERIODIC	10
42 #define PID_SET_CONSTANT	11
43 #define PID_SET_RAMP		12
44 static const u8 pidff_reports[] = {
45 	0x21, 0x77, 0x7d, 0x7f, 0x89, 0x90, 0x96, 0xab,
46 	0x5a, 0x5f, 0x6e, 0x73, 0x74
47 };
48 /*
49  * device_control is really 0x95, but 0x96 specified
50  * as it is the usage of the only field in that report.
51  */
52 
53 /* PID special fields */
54 #define PID_EFFECT_TYPE			0x25
55 #define PID_AXES_ENABLE			0x55
56 #define PID_DIRECTION			0x57
57 #define PID_EFFECT_OPERATION_ARRAY	0x78
58 #define PID_BLOCK_LOAD_STATUS		0x8b
59 #define PID_DEVICE_CONTROL_ARRAY	0x96
60 
61 /* Value usage tables used to put fields and values into arrays */
62 #define PID_EFFECT_BLOCK_INDEX	0
63 
64 #define PID_DURATION		1
65 #define PID_GAIN		2
66 #define PID_TRIGGER_BUTTON	3
67 #define PID_TRIGGER_REPEAT_INT	4
68 #define PID_DIRECTION_ENABLE	5
69 #define PID_START_DELAY		6
70 static const u8 pidff_set_effect[] = {
71 	0x22, 0x50, 0x52, 0x53, 0x54, 0x56, 0xa7
72 };
73 
74 #define PID_ATTACK_LEVEL	1
75 #define PID_ATTACK_TIME		2
76 #define PID_FADE_LEVEL		3
77 #define PID_FADE_TIME		4
78 static const u8 pidff_set_envelope[] = { 0x22, 0x5b, 0x5c, 0x5d, 0x5e };
79 
80 #define PID_PARAM_BLOCK_OFFSET	1
81 #define PID_CP_OFFSET		2
82 #define PID_POS_COEFFICIENT	3
83 #define PID_NEG_COEFFICIENT	4
84 #define PID_POS_SATURATION	5
85 #define PID_NEG_SATURATION	6
86 #define PID_DEADBAND		7
87 static const u8 pidff_set_condition[] = {
88 	0x22, 0x23, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65
89 };
90 
91 #define PID_MAGNITUDE		1
92 #define PID_OFFSET		2
93 #define PID_PHASE		3
94 #define PID_PERIOD		4
95 static const u8 pidff_set_periodic[] = { 0x22, 0x70, 0x6f, 0x71, 0x72 };
96 static const u8 pidff_set_constant[] = { 0x22, 0x70 };
97 
98 #define PID_RAMP_START		1
99 #define PID_RAMP_END		2
100 static const u8 pidff_set_ramp[] = { 0x22, 0x75, 0x76 };
101 
102 #define PID_RAM_POOL_AVAILABLE	1
103 static const u8 pidff_block_load[] = { 0x22, 0xac };
104 
105 #define PID_LOOP_COUNT		1
106 static const u8 pidff_effect_operation[] = { 0x22, 0x7c };
107 
108 static const u8 pidff_block_free[] = { 0x22 };
109 
110 #define PID_DEVICE_GAIN_FIELD	0
111 static const u8 pidff_device_gain[] = { 0x7e };
112 
113 #define PID_RAM_POOL_SIZE	0
114 #define PID_SIMULTANEOUS_MAX	1
115 #define PID_DEVICE_MANAGED_POOL	2
116 static const u8 pidff_pool[] = { 0x80, 0x83, 0xa9 };
117 
118 /* Special field key tables used to put special field keys into arrays */
119 #define PID_ENABLE_ACTUATORS	0
120 #define PID_DISABLE_ACTUATORS	1
121 #define PID_STOP_ALL_EFFECTS	2
122 #define PID_RESET		3
123 #define PID_PAUSE		4
124 #define PID_CONTINUE		5
125 static const u8 pidff_device_control[] = { 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c };
126 
127 #define PID_CONSTANT	0
128 #define PID_RAMP	1
129 #define PID_SQUARE	2
130 #define PID_SINE	3
131 #define PID_TRIANGLE	4
132 #define PID_SAW_UP	5
133 #define PID_SAW_DOWN	6
134 #define PID_SPRING	7
135 #define PID_DAMPER	8
136 #define PID_INERTIA	9
137 #define PID_FRICTION	10
138 static const u8 pidff_effect_types[] = {
139 	0x26, 0x27, 0x30, 0x31, 0x32, 0x33, 0x34,
140 	0x40, 0x41, 0x42, 0x43
141 };
142 
143 #define PID_BLOCK_LOAD_SUCCESS	0
144 #define PID_BLOCK_LOAD_FULL	1
145 #define PID_BLOCK_LOAD_ERROR	2
146 static const u8 pidff_block_load_status[] = { 0x8c, 0x8d, 0x8e };
147 
148 #define PID_EFFECT_START	0
149 #define PID_EFFECT_STOP		1
150 static const u8 pidff_effect_operation_status[] = { 0x79, 0x7b };
151 
152 #define PID_DIRECTION_NORTH	0x0000
153 #define PID_DIRECTION_EAST	0x4000
154 #define PID_DIRECTION_SOUTH	0x8000
155 #define PID_DIRECTION_WEST	0xc000
156 
157 #define PIDFF_FIXED_WHEEL_DIRECTION	PID_DIRECTION_EAST
158 
159 /* AXES_ENABLE and DIRECTION axes */
160 enum pid_axes {
161 	PID_AXIS_X,
162 	PID_AXIS_Y,
163 	PID_AXIS_Z,
164 	PID_AXIS_RX,
165 	PID_AXIS_RY,
166 	PID_AXIS_RZ,
167 	PID_AXIS_SLIDER,
168 	PID_AXIS_DIAL,
169 	PID_AXIS_WHEEL,
170 	PID_AXES_COUNT,
171 };
172 static const u8 pidff_direction_axis[] = {
173 	HID_USAGE & HID_GD_X,
174 	HID_USAGE & HID_GD_Y,
175 	HID_USAGE & HID_GD_Z,
176 	HID_USAGE & HID_GD_RX,
177 	HID_USAGE & HID_GD_RY,
178 	HID_USAGE & HID_GD_RZ,
179 	HID_USAGE & HID_GD_SLIDER,
180 	HID_USAGE & HID_GD_DIAL,
181 	HID_USAGE & HID_GD_WHEEL,
182 };
183 
184 struct pidff_usage {
185 	struct hid_field *field;
186 	s32 *value;
187 };
188 
189 struct pidff_effect {
190 	int pid_id;
191 	int is_infinite;
192 	unsigned int loop_count;
193 };
194 
195 struct pidff_device {
196 	struct hid_device *hid;
197 
198 	struct hid_report *reports[ARRAY_SIZE(pidff_reports)];
199 
200 	struct pidff_usage set_effect[ARRAY_SIZE(pidff_set_effect)];
201 	struct pidff_usage set_envelope[ARRAY_SIZE(pidff_set_envelope)];
202 	struct pidff_usage set_condition[ARRAY_SIZE(pidff_set_condition)];
203 	struct pidff_usage set_periodic[ARRAY_SIZE(pidff_set_periodic)];
204 	struct pidff_usage set_constant[ARRAY_SIZE(pidff_set_constant)];
205 	struct pidff_usage set_ramp[ARRAY_SIZE(pidff_set_ramp)];
206 
207 	struct pidff_usage device_gain[ARRAY_SIZE(pidff_device_gain)];
208 	struct pidff_usage block_load[ARRAY_SIZE(pidff_block_load)];
209 	struct pidff_usage pool[ARRAY_SIZE(pidff_pool)];
210 	struct pidff_usage effect_operation[ARRAY_SIZE(pidff_effect_operation)];
211 	struct pidff_usage block_free[ARRAY_SIZE(pidff_block_free)];
212 
213 	struct pidff_effect effect[PID_EFFECTS_MAX];
214 
215 	/*
216 	 * Special field is a field that is not composed of
217 	 * usage<->value pairs that pidff_usage values are
218 	 */
219 
220 	/* Special field in create_new_effect */
221 	struct hid_field *create_new_effect_type;
222 
223 	/* Special fields in set_effect */
224 	struct hid_field *set_effect_type;
225 	struct hid_field *effect_direction;
226 	struct hid_field *axes_enable;
227 
228 	/* Special field in device_control */
229 	struct hid_field *device_control;
230 
231 	/* Special field in block_load */
232 	struct hid_field *block_load_status;
233 
234 	/* Special field in effect_operation */
235 	struct hid_field *effect_operation_status;
236 
237 	int control_id[ARRAY_SIZE(pidff_device_control)];
238 	int type_id[ARRAY_SIZE(pidff_effect_types)];
239 	int status_id[ARRAY_SIZE(pidff_block_load_status)];
240 	int operation_id[ARRAY_SIZE(pidff_effect_operation_status)];
241 	int direction_axis_id[ARRAY_SIZE(pidff_direction_axis)];
242 
243 	u32 quirks;
244 	u8 effect_count;
245 	u8 axis_count;
246 };
247 
pidff_is_effect_conditional(struct ff_effect * effect)248 static int pidff_is_effect_conditional(struct ff_effect *effect)
249 {
250 	return effect->type == FF_SPRING  ||
251 	       effect->type == FF_DAMPER  ||
252 	       effect->type == FF_INERTIA ||
253 	       effect->type == FF_FRICTION;
254 }
255 
pidff_is_duration_infinite(u16 duration)256 static int pidff_is_duration_infinite(u16 duration)
257 {
258 	return duration == FF_INFINITE || duration == PID_INFINITE;
259 }
260 
261 /*
262  * Get PID effect index from FF effect type.
263  * Return 0 if invalid.
264  */
pidff_effect_ff_to_pid(struct ff_effect * effect)265 static int pidff_effect_ff_to_pid(struct ff_effect *effect)
266 {
267 	switch (effect->type) {
268 	case FF_CONSTANT:
269 		return PID_CONSTANT;
270 	case FF_RAMP:
271 		return PID_RAMP;
272 	case FF_SPRING:
273 		return PID_SPRING;
274 	case FF_DAMPER:
275 		return PID_DAMPER;
276 	case FF_INERTIA:
277 		return PID_INERTIA;
278 	case FF_FRICTION:
279 		return PID_FRICTION;
280 	case FF_PERIODIC:
281 		switch (effect->u.periodic.waveform) {
282 		case FF_SQUARE:
283 			return PID_SQUARE;
284 		case FF_TRIANGLE:
285 			return PID_TRIANGLE;
286 		case FF_SINE:
287 			return PID_SINE;
288 		case FF_SAW_UP:
289 			return PID_SAW_UP;
290 		case FF_SAW_DOWN:
291 			return PID_SAW_DOWN;
292 		}
293 	}
294 	pr_err("invalid effect type\n");
295 	return -EINVAL;
296 }
297 
298 /*
299  * Get effect id in the device descriptor.
300  * Return 0 if invalid.
301  */
pidff_get_effect_type_id(struct pidff_device * pidff,struct ff_effect * effect)302 static int pidff_get_effect_type_id(struct pidff_device *pidff,
303 				    struct ff_effect *effect)
304 {
305 	int id = pidff_effect_ff_to_pid(effect);
306 
307 	if (id < 0)
308 		return 0;
309 
310 	if (effect->type == FF_PERIODIC &&
311 	    pidff->quirks & HID_PIDFF_QUIRK_PERIODIC_SINE_ONLY)
312 		id = PID_SINE;
313 
314 	return pidff->type_id[id];
315 }
316 
317 /*
318  * Clamp value for a given field
319  */
pidff_clamp(s32 i,struct hid_field * field)320 static s32 pidff_clamp(s32 i, struct hid_field *field)
321 {
322 	return (s32)clamp(i, field->logical_minimum, field->logical_maximum);
323 }
324 
325 /*
326  * Scale an unsigned value with range 0..max for the given field
327  */
pidff_rescale(int i,int max,struct hid_field * field)328 static int pidff_rescale(int i, int max, struct hid_field *field)
329 {
330 	/* 64 bits needed for big values during rescale */
331 	s64 result = field->logical_maximum - field->logical_minimum;
332 
333 	return div_s64(result * i, max) + field->logical_minimum;
334 }
335 
336 /*
337  * Scale a signed value in range S16_MIN..S16_MAX for the given field
338  */
pidff_rescale_signed(int i,struct hid_field * field)339 static int pidff_rescale_signed(int i, struct hid_field *field)
340 {
341 	if (i > 0)
342 		return i * field->logical_maximum / S16_MAX;
343 	if (i < 0)
344 		return i * field->logical_minimum / S16_MIN;
345 	return 0;
346 }
347 
348 /*
349  * Scale time value from Linux default (ms) to field units
350  */
pidff_rescale_time(u16 time,struct hid_field * field)351 static u32 pidff_rescale_time(u16 time, struct hid_field *field)
352 {
353 	u32 scaled_time = time;
354 	int exponent = field->unit_exponent;
355 
356 	pr_debug("time field exponent: %d\n", exponent);
357 	for (; exponent < FF_TIME_EXPONENT; exponent++)
358 		scaled_time *= 10;
359 	for (; exponent > FF_TIME_EXPONENT; exponent--)
360 		scaled_time /= 10;
361 
362 	pr_debug("time calculated from %d to %d\n", time, scaled_time);
363 	return scaled_time;
364 }
365 
pidff_set(struct pidff_usage * usage,u16 value)366 static void pidff_set(struct pidff_usage *usage, u16 value)
367 {
368 	usage->value[0] = pidff_rescale(value, U16_MAX, usage->field);
369 	pr_debug("calculated from %d to %d\n", value, usage->value[0]);
370 }
371 
pidff_set_signed(struct pidff_usage * usage,s16 value)372 static void pidff_set_signed(struct pidff_usage *usage, s16 value)
373 {
374 	if (usage->field->logical_minimum < 0)
375 		usage->value[0] = pidff_rescale_signed(value, usage->field);
376 	else {
377 		if (value < 0)
378 			usage->value[0] =
379 				pidff_rescale(-value, -S16_MIN, usage->field);
380 		else
381 			usage->value[0] =
382 				pidff_rescale(value, S16_MAX, usage->field);
383 	}
384 	pr_debug("calculated from %d to %d\n", value, usage->value[0]);
385 }
386 
pidff_set_time(struct pidff_usage * usage,u16 time)387 static void pidff_set_time(struct pidff_usage *usage, u16 time)
388 {
389 	usage->value[0] = pidff_clamp(pidff_rescale_time(time, usage->field),
390 				      usage->field);
391 }
392 
pidff_set_duration(struct pidff_usage * usage,u16 duration)393 static void pidff_set_duration(struct pidff_usage *usage, u16 duration)
394 {
395 	/* PID defines INFINITE as the max possible value for duration field */
396 	if (pidff_is_duration_infinite(duration)) {
397 		usage->value[0] = (1U << usage->field->report_size) - 1;
398 		return;
399 	}
400 
401 	pidff_set_time(usage, duration);
402 }
403 
pidff_set_effect_direction(struct pidff_device * pidff,struct ff_effect * effect)404 static void pidff_set_effect_direction(struct pidff_device *pidff,
405 				       struct ff_effect *effect)
406 {
407 	u16 direction = effect->direction;
408 	int direction_enable = 1;
409 
410 	/* Use fixed direction if needed */
411 	if (pidff->quirks & HID_PIDFF_QUIRK_FIX_CONDITIONAL_DIRECTION &&
412 	    pidff_is_effect_conditional(effect))
413 		direction = PIDFF_FIXED_WHEEL_DIRECTION;
414 
415 	pidff->set_effect[PID_DIRECTION_ENABLE].value[0] = direction_enable;
416 	pidff->effect_direction->value[0] =
417 		pidff_rescale(direction, U16_MAX, pidff->effect_direction);
418 
419 	if (direction_enable)
420 		return;
421 
422 	/*
423 	 * For use with improved FFB API
424 	 * We want to read the selected axes and their direction from the effect
425 	 * struct and only enable those. For now, enable all axes.
426 	 *
427 	 */
428 	for (int i = 0; i < PID_AXES_COUNT; i++) {
429 		/* HID index starts with 1 */
430 		int index = pidff->direction_axis_id[i] - 1;
431 
432 		if (index < 0)
433 			continue;
434 
435 		pidff->axes_enable->value[index] = 1;
436 		pidff->effect_direction->value[index] = pidff_rescale(
437 			direction, U16_MAX, pidff->effect_direction);
438 	}
439 }
440 
441 /*
442  * Send envelope report to the device
443  */
pidff_set_envelope_report(struct pidff_device * pidff,struct ff_envelope * envelope)444 static void pidff_set_envelope_report(struct pidff_device *pidff,
445 				      struct ff_envelope *envelope)
446 {
447 	pidff->set_envelope[PID_EFFECT_BLOCK_INDEX].value[0] =
448 		pidff->block_load[PID_EFFECT_BLOCK_INDEX].value[0];
449 
450 	pidff->set_envelope[PID_ATTACK_LEVEL].value[0] =
451 		pidff_rescale(envelope->attack_level >
452 			S16_MAX ? S16_MAX : envelope->attack_level, S16_MAX,
453 			pidff->set_envelope[PID_ATTACK_LEVEL].field);
454 	pidff->set_envelope[PID_FADE_LEVEL].value[0] =
455 		pidff_rescale(envelope->fade_level >
456 			S16_MAX ? S16_MAX : envelope->fade_level, S16_MAX,
457 			pidff->set_envelope[PID_FADE_LEVEL].field);
458 
459 	pidff_set_time(&pidff->set_envelope[PID_ATTACK_TIME],
460 		       envelope->attack_length);
461 	pidff_set_time(&pidff->set_envelope[PID_FADE_TIME],
462 		       envelope->fade_length);
463 
464 	hid_hw_request(pidff->hid, pidff->reports[PID_SET_ENVELOPE],
465 		       HID_REQ_SET_REPORT);
466 }
467 
468 /*
469  * Test if the new envelope differs from old one
470  */
pidff_needs_set_envelope(struct ff_envelope * envelope,struct ff_envelope * old)471 static int pidff_needs_set_envelope(struct ff_envelope *envelope,
472 				    struct ff_envelope *old)
473 {
474 	int needs_new_envelope;
475 
476 	needs_new_envelope = envelope->attack_level  != 0 ||
477 			     envelope->fade_level    != 0 ||
478 			     envelope->attack_length != 0 ||
479 			     envelope->fade_length   != 0;
480 
481 	if (!needs_new_envelope)
482 		return 0;
483 	if (!old)
484 		return needs_new_envelope;
485 
486 	return envelope->attack_level  != old->attack_level  ||
487 	       envelope->fade_level    != old->fade_level    ||
488 	       envelope->attack_length != old->attack_length ||
489 	       envelope->fade_length   != old->fade_length;
490 }
491 
492 /*
493  * Send constant force report to the device
494  */
pidff_set_constant_report(struct pidff_device * pidff,struct ff_effect * effect)495 static void pidff_set_constant_report(struct pidff_device *pidff,
496 				      struct ff_effect *effect)
497 {
498 	pidff->set_constant[PID_EFFECT_BLOCK_INDEX].value[0] =
499 		pidff->block_load[PID_EFFECT_BLOCK_INDEX].value[0];
500 	pidff_set_signed(&pidff->set_constant[PID_MAGNITUDE],
501 			 effect->u.constant.level);
502 
503 	hid_hw_request(pidff->hid, pidff->reports[PID_SET_CONSTANT],
504 		       HID_REQ_SET_REPORT);
505 }
506 
507 /*
508  * Test if the constant parameters have changed between effects
509  */
pidff_needs_set_constant(struct ff_effect * effect,struct ff_effect * old)510 static int pidff_needs_set_constant(struct ff_effect *effect,
511 				    struct ff_effect *old)
512 {
513 	return effect->u.constant.level != old->u.constant.level;
514 }
515 
516 /*
517  * Send set effect report to the device
518  */
pidff_set_effect_report(struct pidff_device * pidff,struct ff_effect * effect)519 static void pidff_set_effect_report(struct pidff_device *pidff,
520 				    struct ff_effect *effect)
521 {
522 	pidff->set_effect[PID_EFFECT_BLOCK_INDEX].value[0] =
523 		pidff->block_load[PID_EFFECT_BLOCK_INDEX].value[0];
524 	pidff->set_effect_type->value[0] =
525 		pidff->create_new_effect_type->value[0];
526 
527 	pidff_set_duration(&pidff->set_effect[PID_DURATION],
528 			   effect->replay.length);
529 
530 	/* Some games set this to random values that can be out of range */
531 	s32 trigger_button_max =
532 		pidff->set_effect[PID_TRIGGER_BUTTON].field->logical_maximum;
533 	if (effect->trigger.button <= trigger_button_max) {
534 		pidff->set_effect[PID_TRIGGER_BUTTON].value[0] =
535 			effect->trigger.button;
536 		pidff_set_time(&pidff->set_effect[PID_TRIGGER_REPEAT_INT],
537 			       effect->trigger.interval);
538 	} else {
539 		pidff->set_effect[PID_TRIGGER_BUTTON].value[0] = 0;
540 		pidff->set_effect[PID_TRIGGER_REPEAT_INT].value[0] = 0;
541 	}
542 
543 	pidff->set_effect[PID_GAIN].value[0] =
544 		pidff->set_effect[PID_GAIN].field->logical_maximum;
545 
546 	pidff_set_effect_direction(pidff, effect);
547 
548 	/* Omit setting delay field if it's missing */
549 	if (!(pidff->quirks & HID_PIDFF_QUIRK_MISSING_DELAY))
550 		pidff_set_time(&pidff->set_effect[PID_START_DELAY],
551 			       effect->replay.delay);
552 
553 	hid_hw_request(pidff->hid, pidff->reports[PID_SET_EFFECT],
554 		       HID_REQ_SET_REPORT);
555 }
556 
557 /*
558  * Test if the values used in set_effect have changed
559  */
pidff_needs_set_effect(struct ff_effect * effect,struct ff_effect * old)560 static int pidff_needs_set_effect(struct ff_effect *effect,
561 				  struct ff_effect *old)
562 {
563 	return effect->replay.length != old->replay.length ||
564 	       effect->trigger.interval != old->trigger.interval ||
565 	       effect->trigger.button != old->trigger.button ||
566 	       effect->direction != old->direction ||
567 	       effect->replay.delay != old->replay.delay;
568 }
569 
570 /*
571  * Send periodic effect report to the device
572  */
pidff_set_periodic_report(struct pidff_device * pidff,struct ff_effect * effect)573 static void pidff_set_periodic_report(struct pidff_device *pidff,
574 				      struct ff_effect *effect)
575 {
576 	pidff->set_periodic[PID_EFFECT_BLOCK_INDEX].value[0] =
577 		pidff->block_load[PID_EFFECT_BLOCK_INDEX].value[0];
578 	pidff_set_signed(&pidff->set_periodic[PID_MAGNITUDE],
579 			 effect->u.periodic.magnitude);
580 	pidff_set_signed(&pidff->set_periodic[PID_OFFSET],
581 			 effect->u.periodic.offset);
582 	pidff_set(&pidff->set_periodic[PID_PHASE], effect->u.periodic.phase);
583 	pidff_set_time(&pidff->set_periodic[PID_PERIOD],
584 		       effect->u.periodic.period);
585 
586 	hid_hw_request(pidff->hid, pidff->reports[PID_SET_PERIODIC],
587 		       HID_REQ_SET_REPORT);
588 }
589 
590 /*
591  * Test if periodic effect parameters have changed
592  */
pidff_needs_set_periodic(struct ff_effect * effect,struct ff_effect * old)593 static int pidff_needs_set_periodic(struct ff_effect *effect,
594 				    struct ff_effect *old)
595 {
596 	return effect->u.periodic.magnitude != old->u.periodic.magnitude ||
597 	       effect->u.periodic.offset != old->u.periodic.offset ||
598 	       effect->u.periodic.phase != old->u.periodic.phase ||
599 	       effect->u.periodic.period != old->u.periodic.period;
600 }
601 
602 /*
603  * Send condition effect reports to the device
604  */
pidff_set_condition_report(struct pidff_device * pidff,struct ff_effect * effect)605 static void pidff_set_condition_report(struct pidff_device *pidff,
606 				       struct ff_effect *effect)
607 {
608 	int i, max_axis;
609 
610 	/* Devices missing Parameter Block Offset can only have one axis */
611 	max_axis = pidff->quirks & HID_PIDFF_QUIRK_MISSING_PBO ? 1 : 2;
612 
613 	pidff->set_condition[PID_EFFECT_BLOCK_INDEX].value[0] =
614 		pidff->block_load[PID_EFFECT_BLOCK_INDEX].value[0];
615 
616 	for (i = 0; i < max_axis; i++) {
617 		/* Omit Parameter Block Offset if missing */
618 		if (!(pidff->quirks & HID_PIDFF_QUIRK_MISSING_PBO))
619 			pidff->set_condition[PID_PARAM_BLOCK_OFFSET].value[0] = i;
620 
621 		pidff_set_signed(&pidff->set_condition[PID_CP_OFFSET],
622 				 effect->u.condition[i].center);
623 		pidff_set_signed(&pidff->set_condition[PID_POS_COEFFICIENT],
624 				 effect->u.condition[i].right_coeff);
625 		pidff_set(&pidff->set_condition[PID_POS_SATURATION],
626 			  effect->u.condition[i].right_saturation);
627 
628 		/* Omit Negative Coefficient if missing */
629 		if (!(pidff->quirks & HID_PIDFF_QUIRK_MISSING_NEG_COEFFICIENT))
630 			pidff_set_signed(&pidff->set_condition[PID_NEG_COEFFICIENT],
631 					effect->u.condition[i].left_coeff);
632 
633 		/* Omit Negative Saturation if missing */
634 		if (!(pidff->quirks & HID_PIDFF_QUIRK_MISSING_NEG_SATURATION))
635 			pidff_set_signed(&pidff->set_condition[PID_NEG_SATURATION],
636 					effect->u.condition[i].left_saturation);
637 
638 		/* Omit Deadband field if missing */
639 		if (!(pidff->quirks & HID_PIDFF_QUIRK_MISSING_DEADBAND))
640 			pidff_set(&pidff->set_condition[PID_DEADBAND],
641 				effect->u.condition[i].deadband);
642 
643 		hid_hw_request(pidff->hid, pidff->reports[PID_SET_CONDITION],
644 			       HID_REQ_SET_REPORT);
645 	}
646 }
647 
648 /*
649  * Test if condition effect parameters have changed
650  */
pidff_needs_set_condition(struct ff_effect * effect,struct ff_effect * old)651 static int pidff_needs_set_condition(struct ff_effect *effect,
652 				     struct ff_effect *old)
653 {
654 	int i;
655 	int ret = 0;
656 
657 	for (i = 0; i < 2; i++) {
658 		struct ff_condition_effect *cond = &effect->u.condition[i];
659 		struct ff_condition_effect *old_cond = &old->u.condition[i];
660 
661 		ret |= cond->center != old_cond->center ||
662 		       cond->right_coeff != old_cond->right_coeff ||
663 		       cond->left_coeff != old_cond->left_coeff ||
664 		       cond->right_saturation != old_cond->right_saturation ||
665 		       cond->left_saturation != old_cond->left_saturation ||
666 		       cond->deadband != old_cond->deadband;
667 	}
668 
669 	return ret;
670 }
671 
672 /*
673  * Send ramp force report to the device
674  */
pidff_set_ramp_report(struct pidff_device * pidff,struct ff_effect * effect)675 static void pidff_set_ramp_report(struct pidff_device *pidff,
676 				  struct ff_effect *effect)
677 {
678 	pidff->set_ramp[PID_EFFECT_BLOCK_INDEX].value[0] =
679 		pidff->block_load[PID_EFFECT_BLOCK_INDEX].value[0];
680 	pidff_set_signed(&pidff->set_ramp[PID_RAMP_START],
681 			 effect->u.ramp.start_level);
682 	pidff_set_signed(&pidff->set_ramp[PID_RAMP_END],
683 			 effect->u.ramp.end_level);
684 	hid_hw_request(pidff->hid, pidff->reports[PID_SET_RAMP],
685 		       HID_REQ_SET_REPORT);
686 }
687 
688 /*
689  * Test if ramp force parameters have changed
690  */
pidff_needs_set_ramp(struct ff_effect * effect,struct ff_effect * old)691 static int pidff_needs_set_ramp(struct ff_effect *effect, struct ff_effect *old)
692 {
693 	return effect->u.ramp.start_level != old->u.ramp.start_level ||
694 	       effect->u.ramp.end_level != old->u.ramp.end_level;
695 }
696 
697 /*
698  * Set device gain
699  */
pidff_set_gain_report(struct pidff_device * pidff,u16 gain)700 static void pidff_set_gain_report(struct pidff_device *pidff, u16 gain)
701 {
702 	if (!pidff->device_gain[PID_DEVICE_GAIN_FIELD].field)
703 		return;
704 
705 	pidff_set(&pidff->device_gain[PID_DEVICE_GAIN_FIELD], gain);
706 	hid_hw_request(pidff->hid, pidff->reports[PID_DEVICE_GAIN],
707 		       HID_REQ_SET_REPORT);
708 }
709 
710 /*
711  * Send device control report to the device
712  */
pidff_set_device_control(struct pidff_device * pidff,int field)713 static void pidff_set_device_control(struct pidff_device *pidff, int field)
714 {
715 	const int field_index = pidff->control_id[field];
716 
717 	if (field_index < 1)
718 		return;
719 
720 	/* Detect if the field is a bitmask variable or an array */
721 	if (pidff->device_control->flags & HID_MAIN_ITEM_VARIABLE) {
722 		hid_dbg(pidff->hid, "DEVICE_CONTROL is a bitmask\n");
723 
724 		/* Clear current bitmask */
725 		for (int i = 0; i < ARRAY_SIZE(pidff_device_control); i++) {
726 			int index = pidff->control_id[i];
727 
728 			if (index < 1)
729 				continue;
730 
731 			pidff->device_control->value[index - 1] = 0;
732 		}
733 
734 		pidff->device_control->value[field_index - 1] = 1;
735 	} else {
736 		hid_dbg(pidff->hid, "DEVICE_CONTROL is an array\n");
737 		pidff->device_control->value[0] = field_index;
738 	}
739 
740 	hid_hw_request(pidff->hid, pidff->reports[PID_DEVICE_CONTROL], HID_REQ_SET_REPORT);
741 	hid_hw_wait(pidff->hid);
742 	hid_dbg(pidff->hid, "Device control command 0x%02x sent",
743 		pidff_device_control[field]);
744 }
745 
746 /*
747  * Reset the device, stop all effects, enable actuators
748  */
pidff_reset(struct pidff_device * pidff)749 static void pidff_reset(struct pidff_device *pidff)
750 {
751 	/* We reset twice as sometimes hid_wait_io isn't waiting long enough */
752 	pidff_set_device_control(pidff, PID_RESET);
753 	pidff_set_device_control(pidff, PID_RESET);
754 	pidff->effect_count = 0;
755 
756 	pidff_set_device_control(pidff, PID_STOP_ALL_EFFECTS);
757 	pidff_set_device_control(pidff, PID_ENABLE_ACTUATORS);
758 }
759 
760 /*
761  * Fetch pool report
762  */
pidff_fetch_pool(struct pidff_device * pidff)763 static void pidff_fetch_pool(struct pidff_device *pidff)
764 {
765 	int i;
766 	struct hid_device *hid = pidff->hid;
767 
768 	/* Repeat if PID_SIMULTANEOUS_MAX < 2 to make sure it's correct */
769 	for (i = 0; i < 20; i++) {
770 		hid_hw_request(hid, pidff->reports[PID_POOL], HID_REQ_GET_REPORT);
771 		hid_hw_wait(hid);
772 
773 		if (!pidff->pool[PID_SIMULTANEOUS_MAX].value)
774 			return;
775 		if (pidff->pool[PID_SIMULTANEOUS_MAX].value[0] >= 2)
776 			return;
777 	}
778 	hid_warn(hid, "device reports %d simultaneous effects\n",
779 		 pidff->pool[PID_SIMULTANEOUS_MAX].value[0]);
780 }
781 
782 /*
783  * Send a request for effect upload to the device
784  *
785  * Reset and enable actuators if no effects were present on the device
786  *
787  * Returns 0 if device reported success, -ENOSPC if the device reported memory
788  * is full. Upon unknown response the function will retry for 60 times, if
789  * still unsuccessful -EIO is returned.
790  */
pidff_request_effect_upload(struct pidff_device * pidff,int efnum)791 static int pidff_request_effect_upload(struct pidff_device *pidff, int efnum)
792 {
793 	pidff->create_new_effect_type->value[0] = efnum;
794 	hid_hw_request(pidff->hid, pidff->reports[PID_CREATE_NEW_EFFECT],
795 		       HID_REQ_SET_REPORT);
796 	hid_dbg(pidff->hid, "create_new_effect sent, type: %d\n", efnum);
797 
798 	pidff->block_load[PID_EFFECT_BLOCK_INDEX].value[0] = 0;
799 	pidff->block_load_status->value[0] = 0;
800 	hid_hw_wait(pidff->hid);
801 
802 	for (int i = 0; i < 60; i++) {
803 		hid_dbg(pidff->hid, "pid_block_load requested\n");
804 		hid_hw_request(pidff->hid, pidff->reports[PID_BLOCK_LOAD],
805 			       HID_REQ_GET_REPORT);
806 		hid_hw_wait(pidff->hid);
807 		if (pidff->block_load_status->value[0] ==
808 		    pidff->status_id[PID_BLOCK_LOAD_SUCCESS]) {
809 			hid_dbg(pidff->hid, "device reported free memory: %d bytes\n",
810 				 pidff->block_load[PID_RAM_POOL_AVAILABLE].value ?
811 				 pidff->block_load[PID_RAM_POOL_AVAILABLE].value[0] : -1);
812 			return 0;
813 		}
814 		if (pidff->block_load_status->value[0] ==
815 		    pidff->status_id[PID_BLOCK_LOAD_FULL]) {
816 			hid_dbg(pidff->hid, "not enough memory free: %d bytes\n",
817 				pidff->block_load[PID_RAM_POOL_AVAILABLE].value ?
818 				pidff->block_load[PID_RAM_POOL_AVAILABLE].value[0] : -1);
819 			return -ENOSPC;
820 		}
821 		if (pidff->block_load_status->value[0] ==
822 		    pidff->status_id[PID_BLOCK_LOAD_ERROR]) {
823 			hid_dbg(pidff->hid, "device error during effect creation\n");
824 			return -EREMOTEIO;
825 		}
826 	}
827 	hid_err(pidff->hid, "pid_block_load failed 60 times\n");
828 	return -EIO;
829 }
830 
pidff_needs_playback(struct pidff_device * pidff,int effect_id,int n)831 static int pidff_needs_playback(struct pidff_device *pidff, int effect_id, int n)
832 {
833 	return !pidff->effect[effect_id].is_infinite ||
834 		pidff->effect[effect_id].loop_count != n;
835 }
836 
837 /*
838  * Play the effect with PID id n times
839  */
pidff_playback_pid(struct pidff_device * pidff,int pid_id,int n)840 static void pidff_playback_pid(struct pidff_device *pidff, int pid_id, int n)
841 {
842 	pidff->effect_operation[PID_EFFECT_BLOCK_INDEX].value[0] = pid_id;
843 
844 	hid_dbg(pidff->hid, "%s PID effect %d", n == 0 ? "stopping" : "playing",
845 		pid_id);
846 
847 	if (n == 0) {
848 		pidff->effect_operation_status->value[0] =
849 			pidff->operation_id[PID_EFFECT_STOP];
850 	} else {
851 		pidff->effect_operation_status->value[0] =
852 			pidff->operation_id[PID_EFFECT_START];
853 		pidff->effect_operation[PID_LOOP_COUNT].value[0] =
854 			pidff_clamp(n, pidff->effect_operation[PID_LOOP_COUNT].field);
855 	}
856 
857 	hid_hw_request(pidff->hid, pidff->reports[PID_EFFECT_OPERATION],
858 		       HID_REQ_SET_REPORT);
859 }
860 
861 /*
862  * Play the effect with effect id @effect_id for @value times
863  */
pidff_playback(struct input_dev * dev,int effect_id,int value)864 static int pidff_playback(struct input_dev *dev, int effect_id, int value)
865 {
866 	struct pidff_device *pidff = dev->ff->private;
867 
868 	if (!pidff_needs_playback(pidff, effect_id, value))
869 		return 0;
870 
871 	hid_dbg(pidff->hid, "requesting %s on FF effect %d",
872 		value == 0 ? "stop" : "playback", effect_id);
873 
874 	pidff->effect[effect_id].loop_count = value;
875 	pidff_playback_pid(pidff, pidff->effect[effect_id].pid_id, value);
876 	return 0;
877 }
878 
879 /*
880  * Erase effect with PID id
881  * Decrease the device effect counter
882  */
pidff_erase_pid(struct pidff_device * pidff,int pid_id)883 static void pidff_erase_pid(struct pidff_device *pidff, int pid_id)
884 {
885 	pidff->block_free[PID_EFFECT_BLOCK_INDEX].value[0] = pid_id;
886 	hid_hw_request(pidff->hid, pidff->reports[PID_BLOCK_FREE],
887 		       HID_REQ_SET_REPORT);
888 }
889 
890 /*
891  * Stop and erase effect with effect_id
892  */
pidff_erase_effect(struct input_dev * dev,int effect_id)893 static int pidff_erase_effect(struct input_dev *dev, int effect_id)
894 {
895 	struct pidff_device *pidff = dev->ff->private;
896 	int pid_id = pidff->effect[effect_id].pid_id;
897 
898 	hid_dbg(pidff->hid, "starting to erase %d/%d\n", effect_id, pid_id);
899 
900 	/*
901 	 * Wait for the queue to clear. We do not want
902 	 * a full fifo to prevent the effect removal.
903 	 */
904 	hid_hw_wait(pidff->hid);
905 	pidff_playback_pid(pidff, pid_id, 0);
906 	pidff_erase_pid(pidff, pid_id);
907 
908 	if (pidff->effect_count > 0)
909 		pidff->effect_count--;
910 
911 	hid_dbg(pidff->hid, "current effect count: %d", pidff->effect_count);
912 	return 0;
913 }
914 
915 #define PIDFF_SET_REPORT_IF_NEEDED(type, effect, old) \
916 	({ if (!old || pidff_needs_set_## type(effect, old)) \
917 		pidff_set_ ##type## _report(pidff, effect); })
918 
919 #define PIDFF_SET_ENVELOPE_IF_NEEDED(type, effect, old) \
920 	({ if (pidff_needs_set_envelope(&effect->u.type.envelope, \
921 	       old ? &old->u.type.envelope : NULL)) \
922 		pidff_set_envelope_report(pidff, &effect->u.type.envelope); })
923 
924 /*
925  * Effect upload handler
926  */
pidff_upload_effect(struct input_dev * dev,struct ff_effect * new,struct ff_effect * old)927 static int pidff_upload_effect(struct input_dev *dev, struct ff_effect *new,
928 			       struct ff_effect *old)
929 {
930 	struct pidff_device *pidff = dev->ff->private;
931 	const int type_id = pidff_get_effect_type_id(pidff, new);
932 
933 	if (!type_id) {
934 		hid_err(pidff->hid, "effect type not supported\n");
935 		return -EINVAL;
936 	}
937 
938 	if (!pidff->effect_count)
939 		pidff_reset(pidff);
940 
941 	if (!old) {
942 		int error = pidff_request_effect_upload(pidff, type_id);
943 
944 		if (error)
945 			return error;
946 
947 		pidff->effect_count++;
948 		hid_dbg(pidff->hid, "current effect count: %d", pidff->effect_count);
949 		pidff->effect[new->id].loop_count = 0;
950 		pidff->effect[new->id].pid_id =
951 			pidff->block_load[PID_EFFECT_BLOCK_INDEX].value[0];
952 	}
953 
954 	pidff->effect[new->id].is_infinite =
955 		pidff_is_duration_infinite(new->replay.length);
956 
957 	pidff->block_load[PID_EFFECT_BLOCK_INDEX].value[0] =
958 		pidff->effect[new->id].pid_id;
959 
960 	PIDFF_SET_REPORT_IF_NEEDED(effect, new, old);
961 	switch (new->type) {
962 	case FF_CONSTANT:
963 		PIDFF_SET_REPORT_IF_NEEDED(constant, new, old);
964 		PIDFF_SET_ENVELOPE_IF_NEEDED(constant, new, old);
965 		break;
966 
967 	case FF_PERIODIC:
968 		PIDFF_SET_REPORT_IF_NEEDED(periodic, new, old);
969 		PIDFF_SET_ENVELOPE_IF_NEEDED(periodic, new, old);
970 		break;
971 
972 	case FF_RAMP:
973 		PIDFF_SET_REPORT_IF_NEEDED(ramp, new, old);
974 		PIDFF_SET_ENVELOPE_IF_NEEDED(ramp, new, old);
975 		break;
976 
977 	case FF_SPRING:
978 	case FF_DAMPER:
979 	case FF_INERTIA:
980 	case FF_FRICTION:
981 		PIDFF_SET_REPORT_IF_NEEDED(condition, new, old);
982 		break;
983 	}
984 	hid_dbg(pidff->hid, "uploaded\n");
985 	return 0;
986 }
987 
988 /*
989  * set_gain() handler
990  */
pidff_set_gain(struct input_dev * dev,u16 gain)991 static void pidff_set_gain(struct input_dev *dev, u16 gain)
992 {
993 	pidff_set_gain_report(dev->ff->private, gain);
994 }
995 
pidff_autocenter(struct pidff_device * pidff,u16 magnitude)996 static void pidff_autocenter(struct pidff_device *pidff, u16 magnitude)
997 {
998 	struct hid_field *field =
999 		pidff->block_load[PID_EFFECT_BLOCK_INDEX].field;
1000 
1001 	if (!magnitude) {
1002 		pidff_playback_pid(pidff, field->logical_minimum, 0);
1003 		return;
1004 	}
1005 
1006 	pidff_playback_pid(pidff, field->logical_minimum, 1);
1007 
1008 	pidff->set_effect[PID_EFFECT_BLOCK_INDEX].value[0] =
1009 		pidff->block_load[PID_EFFECT_BLOCK_INDEX].field->logical_minimum;
1010 	pidff->set_effect_type->value[0] = pidff->type_id[PID_SPRING];
1011 	pidff->set_effect[PID_DURATION].value[0] = 0;
1012 	pidff->set_effect[PID_TRIGGER_BUTTON].value[0] = 0;
1013 	pidff->set_effect[PID_TRIGGER_REPEAT_INT].value[0] = 0;
1014 	pidff_set(&pidff->set_effect[PID_GAIN], magnitude);
1015 	pidff->set_effect[PID_DIRECTION_ENABLE].value[0] = 1;
1016 
1017 	/* Omit setting delay field if it's missing */
1018 	if (!(pidff->quirks & HID_PIDFF_QUIRK_MISSING_DELAY))
1019 		pidff->set_effect[PID_START_DELAY].value[0] = 0;
1020 
1021 	hid_hw_request(pidff->hid, pidff->reports[PID_SET_EFFECT],
1022 		       HID_REQ_SET_REPORT);
1023 }
1024 
1025 /*
1026  * pidff_set_autocenter() handler
1027  */
pidff_set_autocenter(struct input_dev * dev,u16 magnitude)1028 static void pidff_set_autocenter(struct input_dev *dev, u16 magnitude)
1029 {
1030 	pidff_autocenter(dev->ff->private, magnitude);
1031 }
1032 
1033 /*
1034  * Find specific usage in a given hid_field
1035  */
pidff_find_usage(struct hid_field * fld,unsigned int usage_code)1036 static int pidff_find_usage(struct hid_field *fld, unsigned int usage_code)
1037 {
1038 	for (int i = 0; i < fld->maxusage; i++) {
1039 		if (fld->usage[i].hid == usage_code)
1040 			return i;
1041 	}
1042 	return -1;
1043 }
1044 
1045 /*
1046  * Find hid_field with a specific usage. Return the usage index as well
1047  */
pidff_find_field_with_usage(int * usage_index,struct hid_report * report,unsigned int usage_code)1048 static int pidff_find_field_with_usage(int *usage_index,
1049 				       struct hid_report *report,
1050 				       unsigned int usage_code)
1051 {
1052 	for (int i = 0; i < report->maxfield; i++) {
1053 		struct hid_field *fld = report->field[i];
1054 
1055 		if (fld->maxusage != fld->report_count) {
1056 			pr_debug("maxusage and report_count do not match, skipping\n");
1057 			continue;
1058 		}
1059 
1060 		int index = pidff_find_usage(fld, usage_code);
1061 
1062 		if (index >= 0) {
1063 			*usage_index = index;
1064 			return i;
1065 		}
1066 	}
1067 	return -1;
1068 }
1069 
1070 #define PIDFF_MISSING_FIELD(name, quirks) \
1071 	({ pr_debug("%s field not found, but that's OK\n", __stringify(name)); \
1072 	   pr_debug("Setting MISSING_%s quirk\n", __stringify(name)); \
1073 	   *quirks |= HID_PIDFF_QUIRK_MISSING_ ## name; })
1074 
1075 /*
1076  * Find fields from a report and fill a pidff_usage
1077  */
pidff_find_fields(struct pidff_usage * usage,const u8 * table,struct hid_report * report,int count,int strict,u32 * quirks)1078 static int pidff_find_fields(struct pidff_usage *usage, const u8 *table,
1079 			     struct hid_report *report, int count, int strict,
1080 			     u32 *quirks)
1081 {
1082 	if (!report) {
1083 		pr_debug("%s, null report\n", __func__);
1084 		return -1;
1085 	}
1086 
1087 	for (int i = 0; i < count; i++) {
1088 		int index;
1089 		int found = pidff_find_field_with_usage(&index, report,
1090 							HID_UP_PID | table[i]);
1091 
1092 		if (found >= 0) {
1093 			pr_debug("found %d at %d->%d\n", i, found, index);
1094 			usage[i].field = report->field[found];
1095 			usage[i].value = &report->field[found]->value[index];
1096 			continue;
1097 		}
1098 
1099 		/* Field quirks auto-detection */
1100 		if (table[i] == pidff_set_effect[PID_START_DELAY])
1101 			PIDFF_MISSING_FIELD(DELAY, quirks);
1102 
1103 		else if (table[i] == pidff_set_condition[PID_PARAM_BLOCK_OFFSET])
1104 			PIDFF_MISSING_FIELD(PBO, quirks);
1105 
1106 		else if (table[i] == pidff_set_condition[PID_NEG_COEFFICIENT])
1107 			PIDFF_MISSING_FIELD(NEG_COEFFICIENT, quirks);
1108 
1109 		else if (table[i] == pidff_set_condition[PID_NEG_SATURATION])
1110 			PIDFF_MISSING_FIELD(NEG_SATURATION, quirks);
1111 
1112 		else if (table[i] == pidff_set_condition[PID_DEADBAND])
1113 			PIDFF_MISSING_FIELD(DEADBAND, quirks);
1114 
1115 		else if (strict) {
1116 			pr_debug("failed to locate %d\n", i);
1117 			return -1;
1118 		}
1119 	}
1120 	return 0;
1121 }
1122 
1123 /*
1124  * Return index into pidff_reports for the given usage
1125  */
pidff_check_usage(int usage)1126 static int pidff_check_usage(int usage)
1127 {
1128 	int i;
1129 
1130 	for (i = 0; i < ARRAY_SIZE(pidff_reports); i++)
1131 		if (usage == (HID_UP_PID | pidff_reports[i]))
1132 			return i;
1133 
1134 	return -1;
1135 }
1136 
1137 /*
1138  * Find the reports and fill pidff->reports[]
1139  * report_type specifies either OUTPUT or FEATURE reports
1140  */
pidff_find_reports(struct hid_device * hid,int report_type,struct pidff_device * pidff)1141 static void pidff_find_reports(struct hid_device *hid, int report_type,
1142 			       struct pidff_device *pidff)
1143 {
1144 	struct hid_report *report;
1145 	int i, ret;
1146 
1147 	list_for_each_entry(report,
1148 			    &hid->report_enum[report_type].report_list, list) {
1149 		if (report->maxfield < 1)
1150 			continue;
1151 		ret = pidff_check_usage(report->field[0]->logical);
1152 		if (ret != -1) {
1153 			hid_dbg(hid, "found usage 0x%02x from field->logical\n",
1154 				pidff_reports[ret]);
1155 			pidff->reports[ret] = report;
1156 			continue;
1157 		}
1158 
1159 		/*
1160 		 * Sometimes logical collections are stacked to indicate
1161 		 * different usages for the report and the field, in which
1162 		 * case we want the usage of the parent. However, Linux HID
1163 		 * implementation hides this fact, so we have to dig it up
1164 		 * ourselves
1165 		 */
1166 		i = report->field[0]->usage[0].collection_index;
1167 		if (i <= 0 ||
1168 		    hid->collection[i - 1].type != HID_COLLECTION_LOGICAL)
1169 			continue;
1170 		ret = pidff_check_usage(hid->collection[i - 1].usage);
1171 		if (ret != -1 && !pidff->reports[ret]) {
1172 			hid_dbg(hid,
1173 				"found usage 0x%02x from collection array\n",
1174 				pidff_reports[ret]);
1175 			pidff->reports[ret] = report;
1176 		}
1177 	}
1178 }
1179 
1180 /*
1181  * Test if the required reports have been found
1182  */
pidff_reports_ok(struct pidff_device * pidff)1183 static int pidff_reports_ok(struct pidff_device *pidff)
1184 {
1185 	for (int i = 0; i < PID_REQUIRED_REPORTS; i++) {
1186 		if (!pidff->reports[i]) {
1187 			hid_dbg(pidff->hid, "%d missing\n", i);
1188 			return 0;
1189 		}
1190 	}
1191 
1192 	return 1;
1193 }
1194 
1195 /*
1196  * Find a field with a specific usage within a report
1197  */
pidff_find_special_field(struct hid_report * report,int usage,int enforce_min)1198 static struct hid_field *pidff_find_special_field(struct hid_report *report,
1199 						  int usage, int enforce_min)
1200 {
1201 	if (!report) {
1202 		pr_debug("%s, null report\n", __func__);
1203 		return NULL;
1204 	}
1205 
1206 	for (int i = 0; i < report->maxfield; i++) {
1207 		if (report->field[i]->logical == (HID_UP_PID | usage) &&
1208 		    report->field[i]->report_count > 0) {
1209 			if (!enforce_min ||
1210 			    report->field[i]->logical_minimum == 1)
1211 				return report->field[i];
1212 
1213 			pr_err("logical_minimum is not 1 as it should be\n");
1214 			return NULL;
1215 		}
1216 	}
1217 	return NULL;
1218 }
1219 
1220 /*
1221  * Fill a pidff->*_id struct table
1222  */
pidff_find_special_keys(int * keys,struct hid_field * fld,const u8 * usagetable,int count,unsigned int usage_page)1223 static int pidff_find_special_keys(int *keys, struct hid_field *fld,
1224 				   const u8 *usagetable, int count,
1225 				   unsigned int usage_page)
1226 {
1227 	int found = 0;
1228 
1229 	if (!fld)
1230 		return 0;
1231 
1232 	for (int i = 0; i < count; i++) {
1233 		keys[i] = pidff_find_usage(fld, usage_page | usagetable[i]) + 1;
1234 		if (keys[i])
1235 			found++;
1236 	}
1237 	return found;
1238 }
1239 
1240 #define PIDFF_FIND_SPECIAL_KEYS(keys, field, name) \
1241 	pidff_find_special_keys(pidff->keys, pidff->field, pidff_ ## name, \
1242 		ARRAY_SIZE(pidff_ ## name), HID_UP_PID)
1243 
1244 #define PIDFF_FIND_GENERAL_DESKTOP(keys, field, name) \
1245 	pidff_find_special_keys(pidff->keys, pidff->field, pidff_ ## name, \
1246 		ARRAY_SIZE(pidff_ ## name), HID_UP_GENDESK)
1247 
1248 /*
1249  * Find and check the special fields
1250  */
pidff_find_special_fields(struct pidff_device * pidff)1251 static int pidff_find_special_fields(struct pidff_device *pidff)
1252 {
1253 	hid_dbg(pidff->hid, "finding special fields\n");
1254 
1255 	pidff->create_new_effect_type =
1256 		pidff_find_special_field(pidff->reports[PID_CREATE_NEW_EFFECT],
1257 					 PID_EFFECT_TYPE, 1);
1258 	pidff->set_effect_type =
1259 		pidff_find_special_field(pidff->reports[PID_SET_EFFECT],
1260 					 PID_EFFECT_TYPE, 1);
1261 	pidff->axes_enable =
1262 		pidff_find_special_field(pidff->reports[PID_SET_EFFECT],
1263 					 PID_AXES_ENABLE, 0);
1264 	pidff->effect_direction =
1265 		pidff_find_special_field(pidff->reports[PID_SET_EFFECT],
1266 					 PID_DIRECTION, 0);
1267 	pidff->device_control =
1268 		pidff_find_special_field(pidff->reports[PID_DEVICE_CONTROL],
1269 			PID_DEVICE_CONTROL_ARRAY, 1);
1270 
1271 	/* Detect and set permissive control quirk */
1272 	if (!pidff->device_control) {
1273 		pr_debug("Setting PERMISSIVE_CONTROL quirk\n");
1274 		pidff->quirks |= HID_PIDFF_QUIRK_PERMISSIVE_CONTROL;
1275 		pidff->device_control = pidff_find_special_field(
1276 			pidff->reports[PID_DEVICE_CONTROL],
1277 			PID_DEVICE_CONTROL_ARRAY, 0);
1278 	}
1279 
1280 	pidff->block_load_status =
1281 		pidff_find_special_field(pidff->reports[PID_BLOCK_LOAD],
1282 					 PID_BLOCK_LOAD_STATUS, 1);
1283 	pidff->effect_operation_status =
1284 		pidff_find_special_field(pidff->reports[PID_EFFECT_OPERATION],
1285 					 PID_EFFECT_OPERATION_ARRAY, 1);
1286 
1287 	hid_dbg(pidff->hid, "search done\n");
1288 
1289 	if (!pidff->create_new_effect_type || !pidff->set_effect_type) {
1290 		hid_err(pidff->hid, "effect lists not found\n");
1291 		return -1;
1292 	}
1293 
1294 	if (!pidff->effect_direction) {
1295 		hid_err(pidff->hid, "direction field not found\n");
1296 		return -1;
1297 	}
1298 
1299 	if (!pidff->device_control) {
1300 		hid_err(pidff->hid, "device control field not found\n");
1301 		return -1;
1302 	}
1303 
1304 	if (!pidff->block_load_status) {
1305 		hid_err(pidff->hid, "block load status field not found\n");
1306 		return -1;
1307 	}
1308 
1309 	if (!pidff->effect_operation_status) {
1310 		hid_err(pidff->hid, "effect operation field not found\n");
1311 		return -1;
1312 	}
1313 
1314 	PIDFF_FIND_SPECIAL_KEYS(control_id, device_control, device_control);
1315 
1316 	if (!PIDFF_FIND_SPECIAL_KEYS(type_id, create_new_effect_type,
1317 				     effect_types)) {
1318 		hid_err(pidff->hid, "no effect types found\n");
1319 		return -1;
1320 	}
1321 
1322 	if (PIDFF_FIND_SPECIAL_KEYS(status_id, block_load_status,
1323 				    block_load_status) !=
1324 	    ARRAY_SIZE(pidff_block_load_status)) {
1325 		hid_err(pidff->hid,
1326 			"block load status identifiers not found\n");
1327 		return -1;
1328 	}
1329 
1330 	if (PIDFF_FIND_SPECIAL_KEYS(operation_id, effect_operation_status,
1331 				    effect_operation_status) !=
1332 	    ARRAY_SIZE(pidff_effect_operation_status)) {
1333 		hid_err(pidff->hid, "effect operation identifiers not found\n");
1334 		return -1;
1335 	}
1336 
1337 	if (!pidff->axes_enable) {
1338 		hid_info(pidff->hid, "axes enable field not found!\n");
1339 		return 0;
1340 	}
1341 
1342 	hid_dbg(pidff->hid, "axes enable report count: %u\n",
1343 		pidff->axes_enable->report_count);
1344 
1345 	uint found = PIDFF_FIND_GENERAL_DESKTOP(direction_axis_id, axes_enable,
1346 						direction_axis);
1347 
1348 	pidff->axis_count = found;
1349 	hid_dbg(pidff->hid, "found direction axes: %u", found);
1350 
1351 	for (int i = 0; i < ARRAY_SIZE(pidff_direction_axis); i++) {
1352 		if (!pidff->direction_axis_id[i])
1353 			continue;
1354 
1355 		hid_dbg(pidff->hid, "axis %d, usage: 0x%04x, index: %d", i + 1,
1356 			pidff_direction_axis[i], pidff->direction_axis_id[i]);
1357 	}
1358 
1359 	if (pidff->axes_enable && found != pidff->axes_enable->report_count)
1360 		hid_warn(pidff->hid, "axes_enable: %u != direction axes: %u",
1361 			 pidff->axes_enable->report_count, found);
1362 
1363 	return 0;
1364 }
1365 
1366 /*
1367  * Find the implemented effect types
1368  */
pidff_find_effects(struct pidff_device * pidff,struct input_dev * dev)1369 static int pidff_find_effects(struct pidff_device *pidff,
1370 			      struct input_dev *dev)
1371 {
1372 	int i;
1373 
1374 	for (i = 0; i < ARRAY_SIZE(pidff_effect_types); i++) {
1375 		int pidff_type = pidff->type_id[i];
1376 
1377 		if (pidff->set_effect_type->usage[pidff_type].hid !=
1378 		    pidff->create_new_effect_type->usage[pidff_type].hid) {
1379 			hid_err(pidff->hid,
1380 				"effect type number %d is invalid\n", i);
1381 			return -1;
1382 		}
1383 	}
1384 
1385 	if (pidff->type_id[PID_CONSTANT])
1386 		set_bit(FF_CONSTANT, dev->ffbit);
1387 	if (pidff->type_id[PID_RAMP])
1388 		set_bit(FF_RAMP, dev->ffbit);
1389 	if (pidff->type_id[PID_SQUARE]) {
1390 		set_bit(FF_SQUARE, dev->ffbit);
1391 		set_bit(FF_PERIODIC, dev->ffbit);
1392 	}
1393 	if (pidff->type_id[PID_SINE]) {
1394 		set_bit(FF_SINE, dev->ffbit);
1395 		set_bit(FF_PERIODIC, dev->ffbit);
1396 	}
1397 	if (pidff->type_id[PID_TRIANGLE]) {
1398 		set_bit(FF_TRIANGLE, dev->ffbit);
1399 		set_bit(FF_PERIODIC, dev->ffbit);
1400 	}
1401 	if (pidff->type_id[PID_SAW_UP]) {
1402 		set_bit(FF_SAW_UP, dev->ffbit);
1403 		set_bit(FF_PERIODIC, dev->ffbit);
1404 	}
1405 	if (pidff->type_id[PID_SAW_DOWN]) {
1406 		set_bit(FF_SAW_DOWN, dev->ffbit);
1407 		set_bit(FF_PERIODIC, dev->ffbit);
1408 	}
1409 	if (pidff->type_id[PID_SPRING])
1410 		set_bit(FF_SPRING, dev->ffbit);
1411 	if (pidff->type_id[PID_DAMPER])
1412 		set_bit(FF_DAMPER, dev->ffbit);
1413 	if (pidff->type_id[PID_INERTIA])
1414 		set_bit(FF_INERTIA, dev->ffbit);
1415 	if (pidff->type_id[PID_FRICTION])
1416 		set_bit(FF_FRICTION, dev->ffbit);
1417 
1418 	return 0;
1419 }
1420 
1421 #define PIDFF_FIND_FIELDS(name, report, strict) \
1422 	pidff_find_fields(pidff->name, pidff_ ## name, \
1423 		pidff->reports[report], \
1424 		ARRAY_SIZE(pidff_ ## name), strict, &pidff->quirks)
1425 
1426 /*
1427  * Fill and check the pidff_usages
1428  */
pidff_init_fields(struct pidff_device * pidff,struct input_dev * dev)1429 static int pidff_init_fields(struct pidff_device *pidff, struct input_dev *dev)
1430 {
1431 	if (PIDFF_FIND_FIELDS(set_effect, PID_SET_EFFECT, 1)) {
1432 		hid_err(pidff->hid, "unknown set_effect report layout\n");
1433 		return -ENODEV;
1434 	}
1435 
1436 	PIDFF_FIND_FIELDS(block_load, PID_BLOCK_LOAD, 0);
1437 	if (!pidff->block_load[PID_EFFECT_BLOCK_INDEX].value) {
1438 		hid_err(pidff->hid, "unknown pid_block_load report layout\n");
1439 		return -ENODEV;
1440 	}
1441 
1442 	if (PIDFF_FIND_FIELDS(effect_operation, PID_EFFECT_OPERATION, 1)) {
1443 		hid_err(pidff->hid, "unknown effect_operation report layout\n");
1444 		return -ENODEV;
1445 	}
1446 
1447 	if (PIDFF_FIND_FIELDS(block_free, PID_BLOCK_FREE, 1)) {
1448 		hid_err(pidff->hid, "unknown pid_block_free report layout\n");
1449 		return -ENODEV;
1450 	}
1451 
1452 	if (pidff_find_special_fields(pidff) || pidff_find_effects(pidff, dev))
1453 		return -ENODEV;
1454 
1455 	if (PIDFF_FIND_FIELDS(set_envelope, PID_SET_ENVELOPE, 1)) {
1456 		if (test_and_clear_bit(FF_CONSTANT, dev->ffbit))
1457 			hid_warn(pidff->hid,
1458 				 "has constant effect but no envelope\n");
1459 		if (test_and_clear_bit(FF_RAMP, dev->ffbit))
1460 			hid_warn(pidff->hid,
1461 				 "has ramp effect but no envelope\n");
1462 
1463 		if (test_and_clear_bit(FF_PERIODIC, dev->ffbit))
1464 			hid_warn(pidff->hid,
1465 				 "has periodic effect but no envelope\n");
1466 	}
1467 
1468 	if (PIDFF_FIND_FIELDS(set_constant, PID_SET_CONSTANT, 1) &&
1469 	    test_and_clear_bit(FF_CONSTANT, dev->ffbit))
1470 		hid_warn(pidff->hid, "unknown constant effect layout\n");
1471 
1472 	if (PIDFF_FIND_FIELDS(set_ramp, PID_SET_RAMP, 1) &&
1473 	    test_and_clear_bit(FF_RAMP, dev->ffbit))
1474 		hid_warn(pidff->hid, "unknown ramp effect layout\n");
1475 
1476 	if (PIDFF_FIND_FIELDS(set_condition, PID_SET_CONDITION, 1)) {
1477 		bool test = false;
1478 
1479 		test |= test_and_clear_bit(FF_SPRING, dev->ffbit);
1480 		test |= test_and_clear_bit(FF_DAMPER, dev->ffbit);
1481 		test |= test_and_clear_bit(FF_FRICTION, dev->ffbit);
1482 		test |= test_and_clear_bit(FF_INERTIA, dev->ffbit);
1483 		if (test)
1484 			hid_warn(pidff->hid, "unknown condition effect layout\n");
1485 	}
1486 
1487 	if (PIDFF_FIND_FIELDS(set_periodic, PID_SET_PERIODIC, 1) &&
1488 	    test_and_clear_bit(FF_PERIODIC, dev->ffbit))
1489 		hid_warn(pidff->hid, "unknown periodic effect layout\n");
1490 
1491 	PIDFF_FIND_FIELDS(pool, PID_POOL, 0);
1492 
1493 	if (!PIDFF_FIND_FIELDS(device_gain, PID_DEVICE_GAIN, 1))
1494 		set_bit(FF_GAIN, dev->ffbit);
1495 
1496 	return 0;
1497 }
1498 
1499 /*
1500  * Test if autocenter modification is using the supported method
1501  */
pidff_check_autocenter(struct pidff_device * pidff,struct input_dev * dev)1502 static int pidff_check_autocenter(struct pidff_device *pidff,
1503 				  struct input_dev *dev)
1504 {
1505 	int error;
1506 
1507 	/*
1508 	 * Let's find out if autocenter modification is supported
1509 	 * Specification doesn't specify anything, so we request an
1510 	 * effect upload and cancel it immediately. If the approved
1511 	 * effect id was one above the minimum, then we assume the first
1512 	 * effect id is a built-in spring type effect used for autocenter
1513 	 */
1514 
1515 	error = pidff_request_effect_upload(pidff, 1);
1516 	if (error) {
1517 		hid_err(pidff->hid, "upload request failed\n");
1518 		return error;
1519 	}
1520 
1521 	if (pidff->block_load[PID_EFFECT_BLOCK_INDEX].value[0] ==
1522 	    pidff->block_load[PID_EFFECT_BLOCK_INDEX].field->logical_minimum + 1) {
1523 		pidff_autocenter(pidff, U16_MAX);
1524 		set_bit(FF_AUTOCENTER, dev->ffbit);
1525 	} else {
1526 		hid_notice(pidff->hid,
1527 			   "device has unknown autocenter control method\n");
1528 	}
1529 	pidff_erase_pid(pidff,
1530 			pidff->block_load[PID_EFFECT_BLOCK_INDEX].value[0]);
1531 
1532 	return 0;
1533 }
1534 
1535 /*
1536  * Check if the device is PID and initialize it
1537  * Set initial quirks
1538  */
hid_pidff_init_with_quirks(struct hid_device * hid,u32 initial_quirks)1539 int hid_pidff_init_with_quirks(struct hid_device *hid, u32 initial_quirks)
1540 {
1541 	struct pidff_device *pidff;
1542 	struct hid_input *hidinput =
1543 		list_entry(hid->inputs.next, struct hid_input, list);
1544 	struct input_dev *dev = hidinput->input;
1545 	struct ff_device *ff;
1546 	int max_effects;
1547 	int error;
1548 
1549 	hid_dbg(hid, "starting pid init\n");
1550 
1551 	if (list_empty(&hid->report_enum[HID_OUTPUT_REPORT].report_list)) {
1552 		hid_dbg(hid, "not a PID device, no output report\n");
1553 		return -ENODEV;
1554 	}
1555 
1556 	pidff = kzalloc_obj(*pidff);
1557 	if (!pidff)
1558 		return -ENOMEM;
1559 
1560 	pidff->hid = hid;
1561 	pidff->quirks = initial_quirks;
1562 	pidff->effect_count = 0;
1563 
1564 	hid_device_io_start(hid);
1565 
1566 	pidff_find_reports(hid, HID_OUTPUT_REPORT, pidff);
1567 	pidff_find_reports(hid, HID_FEATURE_REPORT, pidff);
1568 
1569 	if (!pidff_reports_ok(pidff)) {
1570 		hid_dbg(hid, "reports not ok, aborting\n");
1571 		error = -ENODEV;
1572 		goto fail;
1573 	}
1574 
1575 	error = pidff_init_fields(pidff, dev);
1576 	if (error)
1577 		goto fail;
1578 
1579 	/* pool report is sometimes messed up, refetch it */
1580 	pidff_fetch_pool(pidff);
1581 	pidff_set_gain_report(pidff, U16_MAX);
1582 	error = pidff_check_autocenter(pidff, dev);
1583 	if (error)
1584 		goto fail;
1585 
1586 	max_effects =
1587 	    pidff->block_load[PID_EFFECT_BLOCK_INDEX].field->logical_maximum -
1588 	    pidff->block_load[PID_EFFECT_BLOCK_INDEX].field->logical_minimum +
1589 	    1;
1590 	hid_dbg(hid, "max effects is %d\n", max_effects);
1591 
1592 	if (max_effects > PID_EFFECTS_MAX)
1593 		max_effects = PID_EFFECTS_MAX;
1594 
1595 	if (pidff->pool[PID_SIMULTANEOUS_MAX].value)
1596 		hid_dbg(hid, "max simultaneous effects is %d\n",
1597 			pidff->pool[PID_SIMULTANEOUS_MAX].value[0]);
1598 
1599 	if (pidff->pool[PID_RAM_POOL_SIZE].value)
1600 		hid_dbg(hid, "device memory size is %d bytes\n",
1601 			pidff->pool[PID_RAM_POOL_SIZE].value[0]);
1602 
1603 	if (pidff->pool[PID_DEVICE_MANAGED_POOL].value &&
1604 	    pidff->pool[PID_DEVICE_MANAGED_POOL].value[0] == 0) {
1605 		error = -EPERM;
1606 		hid_notice(hid,
1607 			   "device does not support device managed pool\n");
1608 		goto fail;
1609 	}
1610 
1611 	error = input_ff_create(dev, max_effects);
1612 	if (error)
1613 		goto fail;
1614 
1615 	ff = dev->ff;
1616 	ff->private = pidff;
1617 	ff->upload = pidff_upload_effect;
1618 	ff->erase = pidff_erase_effect;
1619 	ff->set_gain = pidff_set_gain;
1620 	ff->set_autocenter = pidff_set_autocenter;
1621 	ff->playback = pidff_playback;
1622 
1623 	hid_info(dev, "Force feedback for USB HID PID devices by Anssi Hannula\n");
1624 	hid_dbg(dev, "Active quirks mask: 0x%08x\n", pidff->quirks);
1625 
1626 	hid_device_io_stop(hid);
1627 
1628 	return 0;
1629 
1630 fail:
1631 	hid_device_io_stop(hid);
1632 
1633 	kfree(pidff);
1634 	return error;
1635 }
1636 EXPORT_SYMBOL_GPL(hid_pidff_init_with_quirks);
1637 
1638 /*
1639  * Check if the device is PID and initialize it
1640  * Wrapper made to keep the compatibility with old
1641  * init function
1642  */
hid_pidff_init(struct hid_device * hid)1643 int hid_pidff_init(struct hid_device *hid)
1644 {
1645 	return hid_pidff_init_with_quirks(hid, 0);
1646 }
1647