xref: /linux-6.15/drivers/input/input-mt.c (revision 4e3929ce)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Input Multitouch Library
4  *
5  * Copyright (c) 2008-2010 Henrik Rydberg
6  */
7 
8 #include <linux/input/mt.h>
9 #include <linux/export.h>
10 #include <linux/slab.h>
11 #include "input-core-private.h"
12 
13 #define TRKID_SGN	((TRKID_MAX + 1) >> 1)
14 
15 static void copy_abs(struct input_dev *dev, unsigned int dst, unsigned int src)
16 {
17 	if (dev->absinfo && test_bit(src, dev->absbit)) {
18 		dev->absinfo[dst] = dev->absinfo[src];
19 		dev->absinfo[dst].fuzz = 0;
20 		__set_bit(dst, dev->absbit);
21 	}
22 }
23 
24 /**
25  * input_mt_init_slots() - initialize MT input slots
26  * @dev: input device supporting MT events and finger tracking
27  * @num_slots: number of slots used by the device
28  * @flags: mt tasks to handle in core
29  *
30  * This function allocates all necessary memory for MT slot handling
31  * in the input device, prepares the ABS_MT_SLOT and
32  * ABS_MT_TRACKING_ID events for use and sets up appropriate buffers.
33  * Depending on the flags set, it also performs pointer emulation and
34  * frame synchronization.
35  *
36  * May be called repeatedly. Returns -EINVAL if attempting to
37  * reinitialize with a different number of slots.
38  */
39 int input_mt_init_slots(struct input_dev *dev, unsigned int num_slots,
40 			unsigned int flags)
41 {
42 	struct input_mt *mt = dev->mt;
43 	int i;
44 
45 	if (!num_slots)
46 		return 0;
47 	if (mt)
48 		return mt->num_slots != num_slots ? -EINVAL : 0;
49 	/* Arbitrary limit for avoiding too large memory allocation. */
50 	if (num_slots > 1024)
51 		return -EINVAL;
52 
53 	mt = kzalloc(struct_size(mt, slots, num_slots), GFP_KERNEL);
54 	if (!mt)
55 		goto err_mem;
56 
57 	mt->num_slots = num_slots;
58 	mt->flags = flags;
59 	input_set_abs_params(dev, ABS_MT_SLOT, 0, num_slots - 1, 0, 0);
60 	input_set_abs_params(dev, ABS_MT_TRACKING_ID, 0, TRKID_MAX, 0, 0);
61 
62 	if (flags & (INPUT_MT_POINTER | INPUT_MT_DIRECT)) {
63 		__set_bit(EV_KEY, dev->evbit);
64 		__set_bit(BTN_TOUCH, dev->keybit);
65 
66 		copy_abs(dev, ABS_X, ABS_MT_POSITION_X);
67 		copy_abs(dev, ABS_Y, ABS_MT_POSITION_Y);
68 		copy_abs(dev, ABS_PRESSURE, ABS_MT_PRESSURE);
69 	}
70 	if (flags & INPUT_MT_POINTER) {
71 		__set_bit(BTN_TOOL_FINGER, dev->keybit);
72 		__set_bit(BTN_TOOL_DOUBLETAP, dev->keybit);
73 		if (num_slots >= 3)
74 			__set_bit(BTN_TOOL_TRIPLETAP, dev->keybit);
75 		if (num_slots >= 4)
76 			__set_bit(BTN_TOOL_QUADTAP, dev->keybit);
77 		if (num_slots >= 5)
78 			__set_bit(BTN_TOOL_QUINTTAP, dev->keybit);
79 		__set_bit(INPUT_PROP_POINTER, dev->propbit);
80 	}
81 	if (flags & INPUT_MT_DIRECT)
82 		__set_bit(INPUT_PROP_DIRECT, dev->propbit);
83 	if (flags & INPUT_MT_SEMI_MT)
84 		__set_bit(INPUT_PROP_SEMI_MT, dev->propbit);
85 	if (flags & INPUT_MT_TRACK) {
86 		unsigned int n2 = num_slots * num_slots;
87 		mt->red = kcalloc(n2, sizeof(*mt->red), GFP_KERNEL);
88 		if (!mt->red)
89 			goto err_mem;
90 	}
91 
92 	/* Mark slots as 'inactive' */
93 	for (i = 0; i < num_slots; i++)
94 		input_mt_set_value(&mt->slots[i], ABS_MT_TRACKING_ID, -1);
95 
96 	/* Mark slots as 'unused' */
97 	mt->frame = 1;
98 
99 	dev->mt = mt;
100 	return 0;
101 err_mem:
102 	kfree(mt);
103 	return -ENOMEM;
104 }
105 EXPORT_SYMBOL(input_mt_init_slots);
106 
107 /**
108  * input_mt_destroy_slots() - frees the MT slots of the input device
109  * @dev: input device with allocated MT slots
110  *
111  * This function is only needed in error path as the input core will
112  * automatically free the MT slots when the device is destroyed.
113  */
114 void input_mt_destroy_slots(struct input_dev *dev)
115 {
116 	if (dev->mt) {
117 		kfree(dev->mt->red);
118 		kfree(dev->mt);
119 	}
120 	dev->mt = NULL;
121 }
122 EXPORT_SYMBOL(input_mt_destroy_slots);
123 
124 /**
125  * input_mt_report_slot_state() - report contact state
126  * @dev: input device with allocated MT slots
127  * @tool_type: the tool type to use in this slot
128  * @active: true if contact is active, false otherwise
129  *
130  * Reports a contact via ABS_MT_TRACKING_ID, and optionally
131  * ABS_MT_TOOL_TYPE. If active is true and the slot is currently
132  * inactive, or if the tool type is changed, a new tracking id is
133  * assigned to the slot. The tool type is only reported if the
134  * corresponding absbit field is set.
135  *
136  * Returns true if contact is active.
137  */
138 bool input_mt_report_slot_state(struct input_dev *dev,
139 				unsigned int tool_type, bool active)
140 {
141 	struct input_mt *mt = dev->mt;
142 	struct input_mt_slot *slot;
143 	int id;
144 
145 	if (!mt)
146 		return false;
147 
148 	slot = &mt->slots[mt->slot];
149 	slot->frame = mt->frame;
150 
151 	if (!active) {
152 		input_event(dev, EV_ABS, ABS_MT_TRACKING_ID, -1);
153 		return false;
154 	}
155 
156 	id = input_mt_get_value(slot, ABS_MT_TRACKING_ID);
157 	if (id < 0)
158 		id = input_mt_new_trkid(mt);
159 
160 	input_event(dev, EV_ABS, ABS_MT_TRACKING_ID, id);
161 	input_event(dev, EV_ABS, ABS_MT_TOOL_TYPE, tool_type);
162 
163 	return true;
164 }
165 EXPORT_SYMBOL(input_mt_report_slot_state);
166 
167 /**
168  * input_mt_report_finger_count() - report contact count
169  * @dev: input device with allocated MT slots
170  * @count: the number of contacts
171  *
172  * Reports the contact count via BTN_TOOL_FINGER, BTN_TOOL_DOUBLETAP,
173  * BTN_TOOL_TRIPLETAP and BTN_TOOL_QUADTAP.
174  *
175  * The input core ensures only the KEY events already setup for
176  * this device will produce output.
177  */
178 void input_mt_report_finger_count(struct input_dev *dev, int count)
179 {
180 	input_event(dev, EV_KEY, BTN_TOOL_FINGER, count == 1);
181 	input_event(dev, EV_KEY, BTN_TOOL_DOUBLETAP, count == 2);
182 	input_event(dev, EV_KEY, BTN_TOOL_TRIPLETAP, count == 3);
183 	input_event(dev, EV_KEY, BTN_TOOL_QUADTAP, count == 4);
184 	input_event(dev, EV_KEY, BTN_TOOL_QUINTTAP, count == 5);
185 }
186 EXPORT_SYMBOL(input_mt_report_finger_count);
187 
188 /**
189  * input_mt_report_pointer_emulation() - common pointer emulation
190  * @dev: input device with allocated MT slots
191  * @use_count: report number of active contacts as finger count
192  *
193  * Performs legacy pointer emulation via BTN_TOUCH, ABS_X, ABS_Y and
194  * ABS_PRESSURE. Touchpad finger count is emulated if use_count is true.
195  *
196  * The input core ensures only the KEY and ABS axes already setup for
197  * this device will produce output.
198  */
199 void input_mt_report_pointer_emulation(struct input_dev *dev, bool use_count)
200 {
201 	struct input_mt *mt = dev->mt;
202 	struct input_mt_slot *oldest;
203 	int oldid, count, i;
204 
205 	if (!mt)
206 		return;
207 
208 	oldest = NULL;
209 	oldid = mt->trkid;
210 	count = 0;
211 
212 	for (i = 0; i < mt->num_slots; ++i) {
213 		struct input_mt_slot *ps = &mt->slots[i];
214 		int id = input_mt_get_value(ps, ABS_MT_TRACKING_ID);
215 
216 		if (id < 0)
217 			continue;
218 		if ((id - oldid) & TRKID_SGN) {
219 			oldest = ps;
220 			oldid = id;
221 		}
222 		count++;
223 	}
224 
225 	input_event(dev, EV_KEY, BTN_TOUCH, count > 0);
226 
227 	if (use_count) {
228 		if (count == 0 &&
229 		    !test_bit(ABS_MT_DISTANCE, dev->absbit) &&
230 		    test_bit(ABS_DISTANCE, dev->absbit) &&
231 		    input_abs_get_val(dev, ABS_DISTANCE) != 0) {
232 			/*
233 			 * Force reporting BTN_TOOL_FINGER for devices that
234 			 * only report general hover (and not per-contact
235 			 * distance) when contact is in proximity but not
236 			 * on the surface.
237 			 */
238 			count = 1;
239 		}
240 
241 		input_mt_report_finger_count(dev, count);
242 	}
243 
244 	if (oldest) {
245 		int x = input_mt_get_value(oldest, ABS_MT_POSITION_X);
246 		int y = input_mt_get_value(oldest, ABS_MT_POSITION_Y);
247 
248 		input_event(dev, EV_ABS, ABS_X, x);
249 		input_event(dev, EV_ABS, ABS_Y, y);
250 
251 		if (test_bit(ABS_MT_PRESSURE, dev->absbit)) {
252 			int p = input_mt_get_value(oldest, ABS_MT_PRESSURE);
253 			input_event(dev, EV_ABS, ABS_PRESSURE, p);
254 		}
255 	} else {
256 		if (test_bit(ABS_MT_PRESSURE, dev->absbit))
257 			input_event(dev, EV_ABS, ABS_PRESSURE, 0);
258 	}
259 }
260 EXPORT_SYMBOL(input_mt_report_pointer_emulation);
261 
262 static void __input_mt_drop_unused(struct input_dev *dev, struct input_mt *mt)
263 {
264 	int i;
265 
266 	lockdep_assert_held(&dev->event_lock);
267 
268 	for (i = 0; i < mt->num_slots; i++) {
269 		if (input_mt_is_active(&mt->slots[i]) &&
270 		    !input_mt_is_used(mt, &mt->slots[i])) {
271 			input_handle_event(dev, EV_ABS, ABS_MT_SLOT, i);
272 			input_handle_event(dev, EV_ABS, ABS_MT_TRACKING_ID, -1);
273 		}
274 	}
275 }
276 
277 /**
278  * input_mt_drop_unused() - Inactivate slots not seen in this frame
279  * @dev: input device with allocated MT slots
280  *
281  * Lift all slots not seen since the last call to this function.
282  */
283 void input_mt_drop_unused(struct input_dev *dev)
284 {
285 	struct input_mt *mt = dev->mt;
286 
287 	if (mt) {
288 		guard(spinlock_irqsave)(&dev->event_lock);
289 
290 		__input_mt_drop_unused(dev, mt);
291 		mt->frame++;
292 	}
293 }
294 EXPORT_SYMBOL(input_mt_drop_unused);
295 
296 /**
297  * input_mt_release_slots() - Deactivate all slots
298  * @dev: input device with allocated MT slots
299  *
300  * Lift all active slots.
301  */
302 void input_mt_release_slots(struct input_dev *dev)
303 {
304 	struct input_mt *mt = dev->mt;
305 
306 	lockdep_assert_held(&dev->event_lock);
307 
308 	if (mt) {
309 		/* This will effectively mark all slots unused. */
310 		mt->frame++;
311 
312 		__input_mt_drop_unused(dev, mt);
313 
314 		if (test_bit(ABS_PRESSURE, dev->absbit))
315 			input_handle_event(dev, EV_ABS, ABS_PRESSURE, 0);
316 
317 		mt->frame++;
318 	}
319 }
320 
321 /**
322  * input_mt_sync_frame() - synchronize mt frame
323  * @dev: input device with allocated MT slots
324  *
325  * Close the frame and prepare the internal state for a new one.
326  * Depending on the flags, marks unused slots as inactive and performs
327  * pointer emulation.
328  */
329 void input_mt_sync_frame(struct input_dev *dev)
330 {
331 	struct input_mt *mt = dev->mt;
332 	bool use_count = false;
333 
334 	if (!mt)
335 		return;
336 
337 	if (mt->flags & INPUT_MT_DROP_UNUSED) {
338 		guard(spinlock_irqsave)(&dev->event_lock);
339 		__input_mt_drop_unused(dev, mt);
340 	}
341 
342 	if ((mt->flags & INPUT_MT_POINTER) && !(mt->flags & INPUT_MT_SEMI_MT))
343 		use_count = true;
344 
345 	input_mt_report_pointer_emulation(dev, use_count);
346 
347 	mt->frame++;
348 }
349 EXPORT_SYMBOL(input_mt_sync_frame);
350 
351 static int adjust_dual(int *begin, int step, int *end, int eq, int mu)
352 {
353 	int f, *p, s, c;
354 
355 	if (begin == end)
356 		return 0;
357 
358 	f = *begin;
359 	p = begin + step;
360 	s = p == end ? f + 1 : *p;
361 
362 	for (; p != end; p += step) {
363 		if (*p < f) {
364 			s = f;
365 			f = *p;
366 		} else if (*p < s) {
367 			s = *p;
368 		}
369 	}
370 
371 	c = (f + s + 1) / 2;
372 	if (c == 0 || (c > mu && (!eq || mu > 0)))
373 		return 0;
374 	/* Improve convergence for positive matrices by penalizing overcovers */
375 	if (s < 0 && mu <= 0)
376 		c *= 2;
377 
378 	for (p = begin; p != end; p += step)
379 		*p -= c;
380 
381 	return (c < s && s <= 0) || (f >= 0 && f < c);
382 }
383 
384 static void find_reduced_matrix(int *w, int nr, int nc, int nrc, int mu)
385 {
386 	int i, k, sum;
387 
388 	for (k = 0; k < nrc; k++) {
389 		for (i = 0; i < nr; i++)
390 			adjust_dual(w + i, nr, w + i + nrc, nr <= nc, mu);
391 		sum = 0;
392 		for (i = 0; i < nrc; i += nr)
393 			sum += adjust_dual(w + i, 1, w + i + nr, nc <= nr, mu);
394 		if (!sum)
395 			break;
396 	}
397 }
398 
399 static int input_mt_set_matrix(struct input_mt *mt,
400 			       const struct input_mt_pos *pos, int num_pos,
401 			       int mu)
402 {
403 	const struct input_mt_pos *p;
404 	struct input_mt_slot *s;
405 	int *w = mt->red;
406 	int x, y;
407 
408 	for (s = mt->slots; s != mt->slots + mt->num_slots; s++) {
409 		if (!input_mt_is_active(s))
410 			continue;
411 		x = input_mt_get_value(s, ABS_MT_POSITION_X);
412 		y = input_mt_get_value(s, ABS_MT_POSITION_Y);
413 		for (p = pos; p != pos + num_pos; p++) {
414 			int dx = x - p->x, dy = y - p->y;
415 			*w++ = dx * dx + dy * dy - mu;
416 		}
417 	}
418 
419 	return w - mt->red;
420 }
421 
422 static void input_mt_set_slots(struct input_mt *mt,
423 			       int *slots, int num_pos)
424 {
425 	struct input_mt_slot *s;
426 	int *w = mt->red, j;
427 
428 	for (j = 0; j != num_pos; j++)
429 		slots[j] = -1;
430 
431 	for (s = mt->slots; s != mt->slots + mt->num_slots; s++) {
432 		if (!input_mt_is_active(s))
433 			continue;
434 
435 		for (j = 0; j != num_pos; j++) {
436 			if (w[j] < 0) {
437 				slots[j] = s - mt->slots;
438 				break;
439 			}
440 		}
441 
442 		w += num_pos;
443 	}
444 
445 	for (s = mt->slots; s != mt->slots + mt->num_slots; s++) {
446 		if (input_mt_is_active(s))
447 			continue;
448 
449 		for (j = 0; j != num_pos; j++) {
450 			if (slots[j] < 0) {
451 				slots[j] = s - mt->slots;
452 				break;
453 			}
454 		}
455 	}
456 }
457 
458 /**
459  * input_mt_assign_slots() - perform a best-match assignment
460  * @dev: input device with allocated MT slots
461  * @slots: the slot assignment to be filled
462  * @pos: the position array to match
463  * @num_pos: number of positions
464  * @dmax: maximum ABS_MT_POSITION displacement (zero for infinite)
465  *
466  * Performs a best match against the current contacts and returns
467  * the slot assignment list. New contacts are assigned to unused
468  * slots.
469  *
470  * The assignments are balanced so that all coordinate displacements are
471  * below the euclidian distance dmax. If no such assignment can be found,
472  * some contacts are assigned to unused slots.
473  *
474  * Returns zero on success, or negative error in case of failure.
475  */
476 int input_mt_assign_slots(struct input_dev *dev, int *slots,
477 			  const struct input_mt_pos *pos, int num_pos,
478 			  int dmax)
479 {
480 	struct input_mt *mt = dev->mt;
481 	int mu = 2 * dmax * dmax;
482 	int nrc;
483 
484 	if (!mt || !mt->red)
485 		return -ENXIO;
486 	if (num_pos > mt->num_slots)
487 		return -EINVAL;
488 	if (num_pos < 1)
489 		return 0;
490 
491 	nrc = input_mt_set_matrix(mt, pos, num_pos, mu);
492 	find_reduced_matrix(mt->red, num_pos, nrc / num_pos, nrc, mu);
493 	input_mt_set_slots(mt, slots, num_pos);
494 
495 	return 0;
496 }
497 EXPORT_SYMBOL(input_mt_assign_slots);
498 
499 /**
500  * input_mt_get_slot_by_key() - return slot matching key
501  * @dev: input device with allocated MT slots
502  * @key: the key of the sought slot
503  *
504  * Returns the slot of the given key, if it exists, otherwise
505  * set the key on the first unused slot and return.
506  *
507  * If no available slot can be found, -1 is returned.
508  * Note that for this function to work properly, input_mt_sync_frame() has
509  * to be called at each frame.
510  */
511 int input_mt_get_slot_by_key(struct input_dev *dev, int key)
512 {
513 	struct input_mt *mt = dev->mt;
514 	struct input_mt_slot *s;
515 
516 	if (!mt)
517 		return -1;
518 
519 	for (s = mt->slots; s != mt->slots + mt->num_slots; s++)
520 		if (input_mt_is_active(s) && s->key == key)
521 			return s - mt->slots;
522 
523 	for (s = mt->slots; s != mt->slots + mt->num_slots; s++)
524 		if (!input_mt_is_active(s) && !input_mt_is_used(mt, s)) {
525 			s->key = key;
526 			return s - mt->slots;
527 		}
528 
529 	return -1;
530 }
531 EXPORT_SYMBOL(input_mt_get_slot_by_key);
532