xref: /linux/drivers/hid/hid-magicmouse.c (revision e814f3fd16acfb7f9966773953de8f740a1e3202)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Apple "Magic" Wireless Mouse driver
4  *
5  *   Copyright (c) 2010 Michael Poole <mdpoole@troilus.org>
6  *   Copyright (c) 2010 Chase Douglas <chase.douglas@canonical.com>
7  */
8 
9 /*
10  */
11 
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 
14 #include <linux/device.h>
15 #include <linux/hid.h>
16 #include <linux/input/mt.h>
17 #include <linux/module.h>
18 #include <linux/slab.h>
19 #include <linux/workqueue.h>
20 
21 #include "hid-ids.h"
22 
23 static bool emulate_3button = true;
24 module_param(emulate_3button, bool, 0644);
25 MODULE_PARM_DESC(emulate_3button, "Emulate a middle button");
26 
27 static int middle_button_start = -350;
28 static int middle_button_stop = +350;
29 
30 static bool emulate_scroll_wheel = true;
31 module_param(emulate_scroll_wheel, bool, 0644);
32 MODULE_PARM_DESC(emulate_scroll_wheel, "Emulate a scroll wheel");
33 
34 static unsigned int scroll_speed = 32;
35 static int param_set_scroll_speed(const char *val,
36 				  const struct kernel_param *kp) {
37 	unsigned long speed;
38 	if (!val || kstrtoul(val, 0, &speed) || speed > 63)
39 		return -EINVAL;
40 	scroll_speed = speed;
41 	return 0;
42 }
43 module_param_call(scroll_speed, param_set_scroll_speed, param_get_uint, &scroll_speed, 0644);
44 MODULE_PARM_DESC(scroll_speed, "Scroll speed, value from 0 (slow) to 63 (fast)");
45 
46 static bool scroll_acceleration = false;
47 module_param(scroll_acceleration, bool, 0644);
48 MODULE_PARM_DESC(scroll_acceleration, "Accelerate sequential scroll events");
49 
50 static bool report_undeciphered;
51 module_param(report_undeciphered, bool, 0644);
52 MODULE_PARM_DESC(report_undeciphered, "Report undeciphered multi-touch state field using a MSC_RAW event");
53 
54 #define TRACKPAD2_2021_BT_VERSION 0x110
55 #define TRACKPAD_2024_BT_VERSION 0x314
56 
57 #define TRACKPAD_REPORT_ID 0x28
58 #define TRACKPAD2_USB_REPORT_ID 0x02
59 #define TRACKPAD2_BT_REPORT_ID 0x31
60 #define MOUSE_REPORT_ID    0x29
61 #define MOUSE2_REPORT_ID   0x12
62 #define DOUBLE_REPORT_ID   0xf7
63 #define USB_BATTERY_TIMEOUT_MS 60000
64 
65 /* These definitions are not precise, but they're close enough.  (Bits
66  * 0x03 seem to indicate the aspect ratio of the touch, bits 0x70 seem
67  * to be some kind of bit mask -- 0x20 may be a near-field reading,
68  * and 0x40 is actual contact, and 0x10 may be a start/stop or change
69  * indication.)
70  */
71 #define TOUCH_STATE_MASK  0xf0
72 #define TOUCH_STATE_NONE  0x00
73 #define TOUCH_STATE_START 0x30
74 #define TOUCH_STATE_DRAG  0x40
75 
76 /* Number of high-resolution events for each low-resolution detent. */
77 #define SCROLL_HR_STEPS 10
78 #define SCROLL_HR_MULT (120 / SCROLL_HR_STEPS)
79 #define SCROLL_HR_THRESHOLD 90 /* units */
80 #define SCROLL_ACCEL_DEFAULT 7
81 
82 /* Touch surface information. Dimension is in hundredths of a mm, min and max
83  * are in units. */
84 #define MOUSE_DIMENSION_X (float)9056
85 #define MOUSE_MIN_X -1100
86 #define MOUSE_MAX_X 1258
87 #define MOUSE_RES_X ((MOUSE_MAX_X - MOUSE_MIN_X) / (MOUSE_DIMENSION_X / 100))
88 #define MOUSE_DIMENSION_Y (float)5152
89 #define MOUSE_MIN_Y -1589
90 #define MOUSE_MAX_Y 2047
91 #define MOUSE_RES_Y ((MOUSE_MAX_Y - MOUSE_MIN_Y) / (MOUSE_DIMENSION_Y / 100))
92 
93 #define TRACKPAD_DIMENSION_X (float)13000
94 #define TRACKPAD_MIN_X -2909
95 #define TRACKPAD_MAX_X 3167
96 #define TRACKPAD_RES_X \
97 	((TRACKPAD_MAX_X - TRACKPAD_MIN_X) / (TRACKPAD_DIMENSION_X / 100))
98 #define TRACKPAD_DIMENSION_Y (float)11000
99 #define TRACKPAD_MIN_Y -2456
100 #define TRACKPAD_MAX_Y 2565
101 #define TRACKPAD_RES_Y \
102 	((TRACKPAD_MAX_Y - TRACKPAD_MIN_Y) / (TRACKPAD_DIMENSION_Y / 100))
103 
104 #define TRACKPAD2_DIMENSION_X (float)16000
105 #define TRACKPAD2_MIN_X -3678
106 #define TRACKPAD2_MAX_X 3934
107 #define TRACKPAD2_RES_X \
108 	((TRACKPAD2_MAX_X - TRACKPAD2_MIN_X) / (TRACKPAD2_DIMENSION_X / 100))
109 #define TRACKPAD2_DIMENSION_Y (float)11490
110 #define TRACKPAD2_MIN_Y -2478
111 #define TRACKPAD2_MAX_Y 2587
112 #define TRACKPAD2_RES_Y \
113 	((TRACKPAD2_MAX_Y - TRACKPAD2_MIN_Y) / (TRACKPAD2_DIMENSION_Y / 100))
114 
115 /**
116  * struct magicmouse_sc - Tracks Magic Mouse-specific data.
117  * @input: Input device through which we report events.
118  * @quirks: Currently unused.
119  * @ntouches: Number of touches in most recent touch report.
120  * @scroll_accel: Number of consecutive scroll motions.
121  * @scroll_jiffies: Time of last scroll motion.
122  * @touches: Most recent data for a touch, indexed by tracking ID.
123  * @tracking_ids: Mapping of current touch input data to @touches.
124  * @hdev: Pointer to the underlying HID device.
125  * @work: Workqueue to handle initialization retry for quirky devices.
126  * @battery_timer: Timer for obtaining battery level information.
127  */
128 struct magicmouse_sc {
129 	struct input_dev *input;
130 	unsigned long quirks;
131 
132 	int ntouches;
133 	int scroll_accel;
134 	unsigned long scroll_jiffies;
135 
136 	struct {
137 		short x;
138 		short y;
139 		short scroll_x;
140 		short scroll_y;
141 		short scroll_x_hr;
142 		short scroll_y_hr;
143 		u8 size;
144 		bool scroll_x_active;
145 		bool scroll_y_active;
146 	} touches[16];
147 	int tracking_ids[16];
148 
149 	struct hid_device *hdev;
150 	struct delayed_work work;
151 	struct timer_list battery_timer;
152 };
153 
154 static int magicmouse_firm_touch(struct magicmouse_sc *msc)
155 {
156 	int touch = -1;
157 	int ii;
158 
159 	/* If there is only one "firm" touch, set touch to its
160 	 * tracking ID.
161 	 */
162 	for (ii = 0; ii < msc->ntouches; ii++) {
163 		int idx = msc->tracking_ids[ii];
164 		if (msc->touches[idx].size < 8) {
165 			/* Ignore this touch. */
166 		} else if (touch >= 0) {
167 			touch = -1;
168 			break;
169 		} else {
170 			touch = idx;
171 		}
172 	}
173 
174 	return touch;
175 }
176 
177 static void magicmouse_emit_buttons(struct magicmouse_sc *msc, int state)
178 {
179 	int last_state = test_bit(BTN_LEFT, msc->input->key) << 0 |
180 		test_bit(BTN_RIGHT, msc->input->key) << 1 |
181 		test_bit(BTN_MIDDLE, msc->input->key) << 2;
182 
183 	if (emulate_3button) {
184 		int id;
185 
186 		/* If some button was pressed before, keep it held
187 		 * down.  Otherwise, if there's exactly one firm
188 		 * touch, use that to override the mouse's guess.
189 		 */
190 		if (state == 0) {
191 			/* The button was released. */
192 		} else if (last_state != 0) {
193 			state = last_state;
194 		} else if ((id = magicmouse_firm_touch(msc)) >= 0) {
195 			int x = msc->touches[id].x;
196 			if (x < middle_button_start)
197 				state = 1;
198 			else if (x > middle_button_stop)
199 				state = 2;
200 			else
201 				state = 4;
202 		} /* else: we keep the mouse's guess */
203 
204 		input_report_key(msc->input, BTN_MIDDLE, state & 4);
205 	}
206 
207 	input_report_key(msc->input, BTN_LEFT, state & 1);
208 	input_report_key(msc->input, BTN_RIGHT, state & 2);
209 
210 	if (state != last_state)
211 		msc->scroll_accel = SCROLL_ACCEL_DEFAULT;
212 }
213 
214 static void magicmouse_emit_touch(struct magicmouse_sc *msc, int raw_id, u8 *tdata)
215 {
216 	struct input_dev *input = msc->input;
217 	int id, x, y, size, orientation, touch_major, touch_minor, state, down;
218 	int pressure = 0;
219 
220 	if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE ||
221 	    input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE2) {
222 		id = (tdata[6] << 2 | tdata[5] >> 6) & 0xf;
223 		x = (tdata[1] << 28 | tdata[0] << 20) >> 20;
224 		y = -((tdata[2] << 24 | tdata[1] << 16) >> 20);
225 		size = tdata[5] & 0x3f;
226 		orientation = (tdata[6] >> 2) - 32;
227 		touch_major = tdata[3];
228 		touch_minor = tdata[4];
229 		state = tdata[7] & TOUCH_STATE_MASK;
230 		down = state != TOUCH_STATE_NONE;
231 	} else if (input->id.product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 ||
232 		   input->id.product ==
233 			   USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC) {
234 		id = tdata[8] & 0xf;
235 		x = (tdata[1] << 27 | tdata[0] << 19) >> 19;
236 		y = -((tdata[3] << 30 | tdata[2] << 22 | tdata[1] << 14) >> 19);
237 		size = tdata[6];
238 		orientation = (tdata[8] >> 5) - 4;
239 		touch_major = tdata[4];
240 		touch_minor = tdata[5];
241 		pressure = tdata[7];
242 		state = tdata[3] & 0xC0;
243 		down = state == 0x80;
244 	} else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */
245 		id = (tdata[7] << 2 | tdata[6] >> 6) & 0xf;
246 		x = (tdata[1] << 27 | tdata[0] << 19) >> 19;
247 		y = -((tdata[3] << 30 | tdata[2] << 22 | tdata[1] << 14) >> 19);
248 		size = tdata[6] & 0x3f;
249 		orientation = (tdata[7] >> 2) - 32;
250 		touch_major = tdata[4];
251 		touch_minor = tdata[5];
252 		state = tdata[8] & TOUCH_STATE_MASK;
253 		down = state != TOUCH_STATE_NONE;
254 	}
255 
256 	/* Store tracking ID and other fields. */
257 	msc->tracking_ids[raw_id] = id;
258 	msc->touches[id].x = x;
259 	msc->touches[id].y = y;
260 	msc->touches[id].size = size;
261 
262 	/* If requested, emulate a scroll wheel by detecting small
263 	 * vertical touch motions.
264 	 */
265 	if (emulate_scroll_wheel &&
266 	    input->id.product != USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 &&
267 	    input->id.product != USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC) {
268 		unsigned long now = jiffies;
269 		int step_x = msc->touches[id].scroll_x - x;
270 		int step_y = msc->touches[id].scroll_y - y;
271 		int step_hr =
272 			max_t(int,
273 			      ((64 - (int)scroll_speed) * msc->scroll_accel) /
274 					SCROLL_HR_STEPS,
275 			      1);
276 		int step_x_hr = msc->touches[id].scroll_x_hr - x;
277 		int step_y_hr = msc->touches[id].scroll_y_hr - y;
278 
279 		/* Calculate and apply the scroll motion. */
280 		switch (state) {
281 		case TOUCH_STATE_START:
282 			msc->touches[id].scroll_x = x;
283 			msc->touches[id].scroll_y = y;
284 			msc->touches[id].scroll_x_hr = x;
285 			msc->touches[id].scroll_y_hr = y;
286 			msc->touches[id].scroll_x_active = false;
287 			msc->touches[id].scroll_y_active = false;
288 
289 			/* Reset acceleration after half a second. */
290 			if (scroll_acceleration && time_before(now,
291 						msc->scroll_jiffies + HZ / 2))
292 				msc->scroll_accel = max_t(int,
293 						msc->scroll_accel - 1, 1);
294 			else
295 				msc->scroll_accel = SCROLL_ACCEL_DEFAULT;
296 
297 			break;
298 		case TOUCH_STATE_DRAG:
299 			step_x /= (64 - (int)scroll_speed) * msc->scroll_accel;
300 			if (step_x != 0) {
301 				msc->touches[id].scroll_x -= step_x *
302 					(64 - scroll_speed) * msc->scroll_accel;
303 				msc->scroll_jiffies = now;
304 				input_report_rel(input, REL_HWHEEL, -step_x);
305 			}
306 
307 			step_y /= (64 - (int)scroll_speed) * msc->scroll_accel;
308 			if (step_y != 0) {
309 				msc->touches[id].scroll_y -= step_y *
310 					(64 - scroll_speed) * msc->scroll_accel;
311 				msc->scroll_jiffies = now;
312 				input_report_rel(input, REL_WHEEL, step_y);
313 			}
314 
315 			if (!msc->touches[id].scroll_x_active &&
316 			    abs(step_x_hr) > SCROLL_HR_THRESHOLD) {
317 				msc->touches[id].scroll_x_active = true;
318 				msc->touches[id].scroll_x_hr = x;
319 				step_x_hr = 0;
320 			}
321 
322 			step_x_hr /= step_hr;
323 			if (step_x_hr != 0 &&
324 			    msc->touches[id].scroll_x_active) {
325 				msc->touches[id].scroll_x_hr -= step_x_hr *
326 					step_hr;
327 				input_report_rel(input,
328 						 REL_HWHEEL_HI_RES,
329 						 -step_x_hr * SCROLL_HR_MULT);
330 			}
331 
332 			if (!msc->touches[id].scroll_y_active &&
333 			    abs(step_y_hr) > SCROLL_HR_THRESHOLD) {
334 				msc->touches[id].scroll_y_active = true;
335 				msc->touches[id].scroll_y_hr = y;
336 				step_y_hr = 0;
337 			}
338 
339 			step_y_hr /= step_hr;
340 			if (step_y_hr != 0 &&
341 			    msc->touches[id].scroll_y_active) {
342 				msc->touches[id].scroll_y_hr -= step_y_hr *
343 					step_hr;
344 				input_report_rel(input,
345 						 REL_WHEEL_HI_RES,
346 						 step_y_hr * SCROLL_HR_MULT);
347 			}
348 			break;
349 		}
350 	}
351 
352 	if (down)
353 		msc->ntouches++;
354 
355 	input_mt_slot(input, id);
356 	input_mt_report_slot_state(input, MT_TOOL_FINGER, down);
357 
358 	/* Generate the input events for this touch. */
359 	if (down) {
360 		input_report_abs(input, ABS_MT_TOUCH_MAJOR, touch_major << 2);
361 		input_report_abs(input, ABS_MT_TOUCH_MINOR, touch_minor << 2);
362 		input_report_abs(input, ABS_MT_ORIENTATION, -orientation);
363 		input_report_abs(input, ABS_MT_POSITION_X, x);
364 		input_report_abs(input, ABS_MT_POSITION_Y, y);
365 
366 		if (input->id.product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 ||
367 		    input->id.product ==
368 			    USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC)
369 			input_report_abs(input, ABS_MT_PRESSURE, pressure);
370 
371 		if (report_undeciphered) {
372 			if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE ||
373 			    input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE2)
374 				input_event(input, EV_MSC, MSC_RAW, tdata[7]);
375 			else if (input->id.product !=
376 					 USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 &&
377 				 input->id.product !=
378 					 USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC)
379 				input_event(input, EV_MSC, MSC_RAW, tdata[8]);
380 		}
381 	}
382 }
383 
384 static int magicmouse_raw_event(struct hid_device *hdev,
385 		struct hid_report *report, u8 *data, int size)
386 {
387 	struct magicmouse_sc *msc = hid_get_drvdata(hdev);
388 	struct input_dev *input = msc->input;
389 	int x = 0, y = 0, ii, clicks = 0, npoints;
390 
391 	switch (data[0]) {
392 	case TRACKPAD_REPORT_ID:
393 	case TRACKPAD2_BT_REPORT_ID:
394 		/* Expect four bytes of prefix, and N*9 bytes of touch data. */
395 		if (size < 4 || ((size - 4) % 9) != 0)
396 			return 0;
397 		npoints = (size - 4) / 9;
398 		if (npoints > 15) {
399 			hid_warn(hdev, "invalid size value (%d) for TRACKPAD_REPORT_ID\n",
400 					size);
401 			return 0;
402 		}
403 		msc->ntouches = 0;
404 		for (ii = 0; ii < npoints; ii++)
405 			magicmouse_emit_touch(msc, ii, data + ii * 9 + 4);
406 
407 		clicks = data[1];
408 
409 		/* The following bits provide a device specific timestamp. They
410 		 * are unused here.
411 		 *
412 		 * ts = data[1] >> 6 | data[2] << 2 | data[3] << 10;
413 		 */
414 		break;
415 	case TRACKPAD2_USB_REPORT_ID:
416 		/* Expect twelve bytes of prefix and N*9 bytes of touch data. */
417 		if (size < 12 || ((size - 12) % 9) != 0)
418 			return 0;
419 		npoints = (size - 12) / 9;
420 		if (npoints > 15) {
421 			hid_warn(hdev, "invalid size value (%d) for TRACKPAD2_USB_REPORT_ID\n",
422 					size);
423 			return 0;
424 		}
425 		msc->ntouches = 0;
426 		for (ii = 0; ii < npoints; ii++)
427 			magicmouse_emit_touch(msc, ii, data + ii * 9 + 12);
428 
429 		clicks = data[1];
430 		break;
431 	case MOUSE_REPORT_ID:
432 		/* Expect six bytes of prefix, and N*8 bytes of touch data. */
433 		if (size < 6 || ((size - 6) % 8) != 0)
434 			return 0;
435 		npoints = (size - 6) / 8;
436 		if (npoints > 15) {
437 			hid_warn(hdev, "invalid size value (%d) for MOUSE_REPORT_ID\n",
438 					size);
439 			return 0;
440 		}
441 		msc->ntouches = 0;
442 		for (ii = 0; ii < npoints; ii++)
443 			magicmouse_emit_touch(msc, ii, data + ii * 8 + 6);
444 
445 		/* When emulating three-button mode, it is important
446 		 * to have the current touch information before
447 		 * generating a click event.
448 		 */
449 		x = (int)(((data[3] & 0x0c) << 28) | (data[1] << 22)) >> 22;
450 		y = (int)(((data[3] & 0x30) << 26) | (data[2] << 22)) >> 22;
451 		clicks = data[3];
452 
453 		/* The following bits provide a device specific timestamp. They
454 		 * are unused here.
455 		 *
456 		 * ts = data[3] >> 6 | data[4] << 2 | data[5] << 10;
457 		 */
458 		break;
459 	case MOUSE2_REPORT_ID:
460 		/* Size is either 8 or (14 + 8 * N) */
461 		if (size != 8 && (size < 14 || (size - 14) % 8 != 0))
462 			return 0;
463 		npoints = (size - 14) / 8;
464 		if (npoints > 15) {
465 			hid_warn(hdev, "invalid size value (%d) for MOUSE2_REPORT_ID\n",
466 					size);
467 			return 0;
468 		}
469 		msc->ntouches = 0;
470 		for (ii = 0; ii < npoints; ii++)
471 			magicmouse_emit_touch(msc, ii, data + ii * 8 + 14);
472 
473 		/* When emulating three-button mode, it is important
474 		 * to have the current touch information before
475 		 * generating a click event.
476 		 */
477 		x = (int)((data[3] << 24) | (data[2] << 16)) >> 16;
478 		y = (int)((data[5] << 24) | (data[4] << 16)) >> 16;
479 		clicks = data[1];
480 
481 		/* The following bits provide a device specific timestamp. They
482 		 * are unused here.
483 		 *
484 		 * ts = data[11] >> 6 | data[12] << 2 | data[13] << 10;
485 		 */
486 		break;
487 	case DOUBLE_REPORT_ID:
488 		/* Sometimes the trackpad sends two touch reports in one
489 		 * packet.
490 		 */
491 		magicmouse_raw_event(hdev, report, data + 2, data[1]);
492 		magicmouse_raw_event(hdev, report, data + 2 + data[1],
493 			size - 2 - data[1]);
494 		return 0;
495 	default:
496 		return 0;
497 	}
498 
499 	if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE ||
500 	    input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE2) {
501 		magicmouse_emit_buttons(msc, clicks & 3);
502 		input_report_rel(input, REL_X, x);
503 		input_report_rel(input, REL_Y, y);
504 	} else if (input->id.product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 ||
505 		   input->id.product ==
506 			   USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC) {
507 		input_mt_sync_frame(input);
508 		input_report_key(input, BTN_MOUSE, clicks & 1);
509 	} else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */
510 		input_report_key(input, BTN_MOUSE, clicks & 1);
511 		input_mt_report_pointer_emulation(input, true);
512 	}
513 
514 	input_sync(input);
515 	return 1;
516 }
517 
518 static int magicmouse_event(struct hid_device *hdev, struct hid_field *field,
519 		struct hid_usage *usage, __s32 value)
520 {
521 	struct magicmouse_sc *msc = hid_get_drvdata(hdev);
522 	if (msc->input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE2 &&
523 	    field->report->id == MOUSE2_REPORT_ID) {
524 		/*
525 		 * magic_mouse_raw_event has done all the work. Skip hidinput.
526 		 *
527 		 * Specifically, hidinput may modify BTN_LEFT and BTN_RIGHT,
528 		 * breaking emulate_3button.
529 		 */
530 		return 1;
531 	}
532 	return 0;
533 }
534 
535 static int magicmouse_setup_input(struct input_dev *input, struct hid_device *hdev)
536 {
537 	int error;
538 	int mt_flags = 0;
539 
540 	__set_bit(EV_KEY, input->evbit);
541 
542 	if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE ||
543 	    input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE2) {
544 		__set_bit(BTN_LEFT, input->keybit);
545 		__set_bit(BTN_RIGHT, input->keybit);
546 		if (emulate_3button)
547 			__set_bit(BTN_MIDDLE, input->keybit);
548 
549 		__set_bit(EV_REL, input->evbit);
550 		__set_bit(REL_X, input->relbit);
551 		__set_bit(REL_Y, input->relbit);
552 		if (emulate_scroll_wheel) {
553 			__set_bit(REL_WHEEL, input->relbit);
554 			__set_bit(REL_HWHEEL, input->relbit);
555 			__set_bit(REL_WHEEL_HI_RES, input->relbit);
556 			__set_bit(REL_HWHEEL_HI_RES, input->relbit);
557 		}
558 	} else if (input->id.product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 ||
559 		   input->id.product ==
560 			   USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC) {
561 		/* If the trackpad has been connected to a Mac, the name is
562 		 * automatically personalized, e.g., "José Expósito's Trackpad".
563 		 * When connected through Bluetooth, the personalized name is
564 		 * reported, however, when connected through USB the generic
565 		 * name is reported.
566 		 * Set the device name to ensure the same driver settings get
567 		 * loaded, whether connected through bluetooth or USB.
568 		 */
569 		if (hdev->vendor == BT_VENDOR_ID_APPLE) {
570 			if (input->id.version == TRACKPAD2_2021_BT_VERSION)
571 				input->name = "Apple Inc. Magic Trackpad 2021";
572 			else if (input->id.version == TRACKPAD_2024_BT_VERSION) {
573 				input->name = "Apple Inc. Magic Trackpad USB-C";
574 			} else {
575 				input->name = "Apple Inc. Magic Trackpad";
576 			}
577 		} else { /* USB_VENDOR_ID_APPLE */
578 			input->name = hdev->name;
579 		}
580 
581 		__clear_bit(EV_MSC, input->evbit);
582 		__clear_bit(BTN_0, input->keybit);
583 		__clear_bit(BTN_RIGHT, input->keybit);
584 		__clear_bit(BTN_MIDDLE, input->keybit);
585 		__set_bit(BTN_MOUSE, input->keybit);
586 		__set_bit(INPUT_PROP_BUTTONPAD, input->propbit);
587 		__set_bit(BTN_TOOL_FINGER, input->keybit);
588 
589 		mt_flags = INPUT_MT_POINTER | INPUT_MT_DROP_UNUSED |
590 				INPUT_MT_TRACK;
591 	} else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */
592 		/* input->keybit is initialized with incorrect button info
593 		 * for Magic Trackpad. There really is only one physical
594 		 * button (BTN_LEFT == BTN_MOUSE). Make sure we don't
595 		 * advertise buttons that don't exist...
596 		 */
597 		__clear_bit(BTN_RIGHT, input->keybit);
598 		__clear_bit(BTN_MIDDLE, input->keybit);
599 		__set_bit(BTN_MOUSE, input->keybit);
600 		__set_bit(BTN_TOOL_FINGER, input->keybit);
601 		__set_bit(BTN_TOOL_DOUBLETAP, input->keybit);
602 		__set_bit(BTN_TOOL_TRIPLETAP, input->keybit);
603 		__set_bit(BTN_TOOL_QUADTAP, input->keybit);
604 		__set_bit(BTN_TOOL_QUINTTAP, input->keybit);
605 		__set_bit(BTN_TOUCH, input->keybit);
606 		__set_bit(INPUT_PROP_POINTER, input->propbit);
607 		__set_bit(INPUT_PROP_BUTTONPAD, input->propbit);
608 	}
609 
610 
611 	__set_bit(EV_ABS, input->evbit);
612 
613 	error = input_mt_init_slots(input, 16, mt_flags);
614 	if (error)
615 		return error;
616 	input_set_abs_params(input, ABS_MT_TOUCH_MAJOR, 0, 255 << 2,
617 			     4, 0);
618 	input_set_abs_params(input, ABS_MT_TOUCH_MINOR, 0, 255 << 2,
619 			     4, 0);
620 
621 	/* Note: Touch Y position from the device is inverted relative
622 	 * to how pointer motion is reported (and relative to how USB
623 	 * HID recommends the coordinates work).  This driver keeps
624 	 * the origin at the same position, and just uses the additive
625 	 * inverse of the reported Y.
626 	 */
627 	if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE ||
628 	    input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE2) {
629 		input_set_abs_params(input, ABS_MT_ORIENTATION, -31, 32, 1, 0);
630 		input_set_abs_params(input, ABS_MT_POSITION_X,
631 				     MOUSE_MIN_X, MOUSE_MAX_X, 4, 0);
632 		input_set_abs_params(input, ABS_MT_POSITION_Y,
633 				     MOUSE_MIN_Y, MOUSE_MAX_Y, 4, 0);
634 
635 		input_abs_set_res(input, ABS_MT_POSITION_X,
636 				  MOUSE_RES_X);
637 		input_abs_set_res(input, ABS_MT_POSITION_Y,
638 				  MOUSE_RES_Y);
639 	} else if (input->id.product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 ||
640 		   input->id.product ==
641 			   USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC) {
642 		input_set_abs_params(input, ABS_MT_PRESSURE, 0, 253, 0, 0);
643 		input_set_abs_params(input, ABS_PRESSURE, 0, 253, 0, 0);
644 		input_set_abs_params(input, ABS_MT_ORIENTATION, -3, 4, 0, 0);
645 		input_set_abs_params(input, ABS_X, TRACKPAD2_MIN_X,
646 				     TRACKPAD2_MAX_X, 0, 0);
647 		input_set_abs_params(input, ABS_Y, TRACKPAD2_MIN_Y,
648 				     TRACKPAD2_MAX_Y, 0, 0);
649 		input_set_abs_params(input, ABS_MT_POSITION_X,
650 				     TRACKPAD2_MIN_X, TRACKPAD2_MAX_X, 0, 0);
651 		input_set_abs_params(input, ABS_MT_POSITION_Y,
652 				     TRACKPAD2_MIN_Y, TRACKPAD2_MAX_Y, 0, 0);
653 
654 		input_abs_set_res(input, ABS_X, TRACKPAD2_RES_X);
655 		input_abs_set_res(input, ABS_Y, TRACKPAD2_RES_Y);
656 		input_abs_set_res(input, ABS_MT_POSITION_X, TRACKPAD2_RES_X);
657 		input_abs_set_res(input, ABS_MT_POSITION_Y, TRACKPAD2_RES_Y);
658 	} else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */
659 		input_set_abs_params(input, ABS_MT_ORIENTATION, -31, 32, 1, 0);
660 		input_set_abs_params(input, ABS_X, TRACKPAD_MIN_X,
661 				     TRACKPAD_MAX_X, 4, 0);
662 		input_set_abs_params(input, ABS_Y, TRACKPAD_MIN_Y,
663 				     TRACKPAD_MAX_Y, 4, 0);
664 		input_set_abs_params(input, ABS_MT_POSITION_X,
665 				     TRACKPAD_MIN_X, TRACKPAD_MAX_X, 4, 0);
666 		input_set_abs_params(input, ABS_MT_POSITION_Y,
667 				     TRACKPAD_MIN_Y, TRACKPAD_MAX_Y, 4, 0);
668 
669 		input_abs_set_res(input, ABS_X, TRACKPAD_RES_X);
670 		input_abs_set_res(input, ABS_Y, TRACKPAD_RES_Y);
671 		input_abs_set_res(input, ABS_MT_POSITION_X,
672 				  TRACKPAD_RES_X);
673 		input_abs_set_res(input, ABS_MT_POSITION_Y,
674 				  TRACKPAD_RES_Y);
675 	}
676 
677 	input_set_events_per_packet(input, 60);
678 
679 	if (report_undeciphered &&
680 	    input->id.product != USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 &&
681 	    input->id.product != USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC) {
682 		__set_bit(EV_MSC, input->evbit);
683 		__set_bit(MSC_RAW, input->mscbit);
684 	}
685 
686 	/*
687 	 * hid-input may mark device as using autorepeat, but neither
688 	 * the trackpad, nor the mouse actually want it.
689 	 */
690 	__clear_bit(EV_REP, input->evbit);
691 
692 	return 0;
693 }
694 
695 static int magicmouse_input_mapping(struct hid_device *hdev,
696 		struct hid_input *hi, struct hid_field *field,
697 		struct hid_usage *usage, unsigned long **bit, int *max)
698 {
699 	struct magicmouse_sc *msc = hid_get_drvdata(hdev);
700 
701 	if (!msc->input)
702 		msc->input = hi->input;
703 
704 	/* Magic Trackpad does not give relative data after switching to MT */
705 	if ((hi->input->id.product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD ||
706 	     hi->input->id.product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 ||
707 	     hi->input->id.product ==
708 		     USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC) &&
709 	    field->flags & HID_MAIN_ITEM_RELATIVE)
710 		return -1;
711 
712 	return 0;
713 }
714 
715 static int magicmouse_input_configured(struct hid_device *hdev,
716 		struct hid_input *hi)
717 
718 {
719 	struct magicmouse_sc *msc = hid_get_drvdata(hdev);
720 	int ret;
721 
722 	ret = magicmouse_setup_input(msc->input, hdev);
723 	if (ret) {
724 		hid_err(hdev, "magicmouse setup input failed (%d)\n", ret);
725 		/* clean msc->input to notify probe() of the failure */
726 		msc->input = NULL;
727 		return ret;
728 	}
729 
730 	return 0;
731 }
732 
733 static int magicmouse_enable_multitouch(struct hid_device *hdev)
734 {
735 	const u8 *feature;
736 	const u8 feature_mt[] = { 0xD7, 0x01 };
737 	const u8 feature_mt_mouse2[] = { 0xF1, 0x02, 0x01 };
738 	const u8 feature_mt_trackpad2_usb[] = { 0x02, 0x01 };
739 	const u8 feature_mt_trackpad2_bt[] = { 0xF1, 0x02, 0x01 };
740 	u8 *buf;
741 	int ret;
742 	int feature_size;
743 
744 	if (hdev->product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 ||
745 	    hdev->product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC) {
746 		if (hdev->vendor == BT_VENDOR_ID_APPLE) {
747 			feature_size = sizeof(feature_mt_trackpad2_bt);
748 			feature = feature_mt_trackpad2_bt;
749 		} else { /* USB_VENDOR_ID_APPLE */
750 			feature_size = sizeof(feature_mt_trackpad2_usb);
751 			feature = feature_mt_trackpad2_usb;
752 		}
753 	} else if (hdev->product == USB_DEVICE_ID_APPLE_MAGICMOUSE2) {
754 		feature_size = sizeof(feature_mt_mouse2);
755 		feature = feature_mt_mouse2;
756 	} else {
757 		feature_size = sizeof(feature_mt);
758 		feature = feature_mt;
759 	}
760 
761 	buf = kmemdup(feature, feature_size, GFP_KERNEL);
762 	if (!buf)
763 		return -ENOMEM;
764 
765 	ret = hid_hw_raw_request(hdev, buf[0], buf, feature_size,
766 				HID_FEATURE_REPORT, HID_REQ_SET_REPORT);
767 	kfree(buf);
768 	return ret;
769 }
770 
771 static void magicmouse_enable_mt_work(struct work_struct *work)
772 {
773 	struct magicmouse_sc *msc =
774 		container_of(work, struct magicmouse_sc, work.work);
775 	int ret;
776 
777 	ret = magicmouse_enable_multitouch(msc->hdev);
778 	if (ret < 0)
779 		hid_err(msc->hdev, "unable to request touch data (%d)\n", ret);
780 }
781 
782 static int magicmouse_fetch_battery(struct hid_device *hdev)
783 {
784 #ifdef CONFIG_HID_BATTERY_STRENGTH
785 	struct hid_report_enum *report_enum;
786 	struct hid_report *report;
787 
788 	if (!hdev->battery || hdev->vendor != USB_VENDOR_ID_APPLE ||
789 	    (hdev->product != USB_DEVICE_ID_APPLE_MAGICMOUSE2 &&
790 	     hdev->product != USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 &&
791 	     hdev->product != USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC))
792 		return -1;
793 
794 	report_enum = &hdev->report_enum[hdev->battery_report_type];
795 	report = report_enum->report_id_hash[hdev->battery_report_id];
796 
797 	if (!report || report->maxfield < 1)
798 		return -1;
799 
800 	if (hdev->battery_capacity == hdev->battery_max)
801 		return -1;
802 
803 	hid_hw_request(hdev, report, HID_REQ_GET_REPORT);
804 	return 0;
805 #else
806 	return -1;
807 #endif
808 }
809 
810 static void magicmouse_battery_timer_tick(struct timer_list *t)
811 {
812 	struct magicmouse_sc *msc = from_timer(msc, t, battery_timer);
813 	struct hid_device *hdev = msc->hdev;
814 
815 	if (magicmouse_fetch_battery(hdev) == 0) {
816 		mod_timer(&msc->battery_timer,
817 			  jiffies + msecs_to_jiffies(USB_BATTERY_TIMEOUT_MS));
818 	}
819 }
820 
821 static int magicmouse_probe(struct hid_device *hdev,
822 	const struct hid_device_id *id)
823 {
824 	struct magicmouse_sc *msc;
825 	struct hid_report *report;
826 	int ret;
827 
828 	msc = devm_kzalloc(&hdev->dev, sizeof(*msc), GFP_KERNEL);
829 	if (msc == NULL) {
830 		hid_err(hdev, "can't alloc magicmouse descriptor\n");
831 		return -ENOMEM;
832 	}
833 
834 	msc->scroll_accel = SCROLL_ACCEL_DEFAULT;
835 	msc->hdev = hdev;
836 	INIT_DEFERRABLE_WORK(&msc->work, magicmouse_enable_mt_work);
837 
838 	msc->quirks = id->driver_data;
839 	hid_set_drvdata(hdev, msc);
840 
841 	ret = hid_parse(hdev);
842 	if (ret) {
843 		hid_err(hdev, "magicmouse hid parse failed\n");
844 		return ret;
845 	}
846 
847 	ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);
848 	if (ret) {
849 		hid_err(hdev, "magicmouse hw start failed\n");
850 		return ret;
851 	}
852 
853 	timer_setup(&msc->battery_timer, magicmouse_battery_timer_tick, 0);
854 	mod_timer(&msc->battery_timer,
855 		  jiffies + msecs_to_jiffies(USB_BATTERY_TIMEOUT_MS));
856 	magicmouse_fetch_battery(hdev);
857 
858 	if (id->vendor == USB_VENDOR_ID_APPLE &&
859 	    (id->product == USB_DEVICE_ID_APPLE_MAGICMOUSE2 ||
860 	     ((id->product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 ||
861 	       id->product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC) &&
862 	      hdev->type != HID_TYPE_USBMOUSE)))
863 		return 0;
864 
865 	if (!msc->input) {
866 		hid_err(hdev, "magicmouse input not registered\n");
867 		ret = -ENOMEM;
868 		goto err_stop_hw;
869 	}
870 
871 	if (id->product == USB_DEVICE_ID_APPLE_MAGICMOUSE)
872 		report = hid_register_report(hdev, HID_INPUT_REPORT,
873 			MOUSE_REPORT_ID, 0);
874 	else if (id->product == USB_DEVICE_ID_APPLE_MAGICMOUSE2)
875 		report = hid_register_report(hdev, HID_INPUT_REPORT,
876 			MOUSE2_REPORT_ID, 0);
877 	else if (id->product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 ||
878 		 id->product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC) {
879 		if (id->vendor == BT_VENDOR_ID_APPLE)
880 			report = hid_register_report(hdev, HID_INPUT_REPORT,
881 				TRACKPAD2_BT_REPORT_ID, 0);
882 		else /* USB_VENDOR_ID_APPLE */
883 			report = hid_register_report(hdev, HID_INPUT_REPORT,
884 				TRACKPAD2_USB_REPORT_ID, 0);
885 	} else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */
886 		report = hid_register_report(hdev, HID_INPUT_REPORT,
887 			TRACKPAD_REPORT_ID, 0);
888 		report = hid_register_report(hdev, HID_INPUT_REPORT,
889 			DOUBLE_REPORT_ID, 0);
890 	}
891 
892 	if (!report) {
893 		hid_err(hdev, "unable to register touch report\n");
894 		ret = -ENOMEM;
895 		goto err_stop_hw;
896 	}
897 	report->size = 6;
898 
899 	/*
900 	 * Some devices repond with 'invalid report id' when feature
901 	 * report switching it into multitouch mode is sent to it.
902 	 *
903 	 * This results in -EIO from the _raw low-level transport callback,
904 	 * but there seems to be no other way of switching the mode.
905 	 * Thus the super-ugly hacky success check below.
906 	 */
907 	ret = magicmouse_enable_multitouch(hdev);
908 	if (ret != -EIO && ret < 0) {
909 		hid_err(hdev, "unable to request touch data (%d)\n", ret);
910 		goto err_stop_hw;
911 	}
912 	if (ret == -EIO && id->product == USB_DEVICE_ID_APPLE_MAGICMOUSE2) {
913 		schedule_delayed_work(&msc->work, msecs_to_jiffies(500));
914 	}
915 
916 	return 0;
917 err_stop_hw:
918 	del_timer_sync(&msc->battery_timer);
919 	hid_hw_stop(hdev);
920 	return ret;
921 }
922 
923 static void magicmouse_remove(struct hid_device *hdev)
924 {
925 	struct magicmouse_sc *msc = hid_get_drvdata(hdev);
926 
927 	if (msc) {
928 		cancel_delayed_work_sync(&msc->work);
929 		del_timer_sync(&msc->battery_timer);
930 	}
931 
932 	hid_hw_stop(hdev);
933 }
934 
935 static const __u8 *magicmouse_report_fixup(struct hid_device *hdev, __u8 *rdesc,
936 					   unsigned int *rsize)
937 {
938 	/*
939 	 * Change the usage from:
940 	 *   0x06, 0x00, 0xff, // Usage Page (Vendor Defined Page 1)  0
941 	 *   0x09, 0x0b,       // Usage (Vendor Usage 0x0b)           3
942 	 * To:
943 	 *   0x05, 0x01,       // Usage Page (Generic Desktop)        0
944 	 *   0x09, 0x02,       // Usage (Mouse)                       2
945 	 */
946 	if (hdev->vendor == USB_VENDOR_ID_APPLE &&
947 	    (hdev->product == USB_DEVICE_ID_APPLE_MAGICMOUSE2 ||
948 	     hdev->product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2 ||
949 	     hdev->product == USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC) &&
950 	    *rsize == 83 && rdesc[46] == 0x84 && rdesc[58] == 0x85) {
951 		hid_info(hdev,
952 			 "fixing up magicmouse battery report descriptor\n");
953 		*rsize = *rsize - 1;
954 		rdesc = kmemdup(rdesc + 1, *rsize, GFP_KERNEL);
955 		if (!rdesc)
956 			return NULL;
957 
958 		rdesc[0] = 0x05;
959 		rdesc[1] = 0x01;
960 		rdesc[2] = 0x09;
961 		rdesc[3] = 0x02;
962 	}
963 
964 	return rdesc;
965 }
966 
967 static const struct hid_device_id magic_mice[] = {
968 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE,
969 		USB_DEVICE_ID_APPLE_MAGICMOUSE), .driver_data = 0 },
970 	{ HID_BLUETOOTH_DEVICE(BT_VENDOR_ID_APPLE,
971 		USB_DEVICE_ID_APPLE_MAGICMOUSE2), .driver_data = 0 },
972 	{ HID_USB_DEVICE(USB_VENDOR_ID_APPLE,
973 		USB_DEVICE_ID_APPLE_MAGICMOUSE2), .driver_data = 0 },
974 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE,
975 		USB_DEVICE_ID_APPLE_MAGICTRACKPAD), .driver_data = 0 },
976 	{ HID_BLUETOOTH_DEVICE(BT_VENDOR_ID_APPLE,
977 		USB_DEVICE_ID_APPLE_MAGICTRACKPAD2), .driver_data = 0 },
978 	{ HID_USB_DEVICE(USB_VENDOR_ID_APPLE,
979 		USB_DEVICE_ID_APPLE_MAGICTRACKPAD2), .driver_data = 0 },
980 	{ HID_BLUETOOTH_DEVICE(BT_VENDOR_ID_APPLE,
981 		USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC), .driver_data = 0 },
982 	{ HID_USB_DEVICE(USB_VENDOR_ID_APPLE,
983 		USB_DEVICE_ID_APPLE_MAGICTRACKPAD2_USBC), .driver_data = 0 },
984 	{ }
985 };
986 MODULE_DEVICE_TABLE(hid, magic_mice);
987 
988 static struct hid_driver magicmouse_driver = {
989 	.name = "magicmouse",
990 	.id_table = magic_mice,
991 	.probe = magicmouse_probe,
992 	.remove = magicmouse_remove,
993 	.report_fixup = magicmouse_report_fixup,
994 	.raw_event = magicmouse_raw_event,
995 	.event = magicmouse_event,
996 	.input_mapping = magicmouse_input_mapping,
997 	.input_configured = magicmouse_input_configured,
998 };
999 module_hid_driver(magicmouse_driver);
1000 
1001 MODULE_DESCRIPTION("Apple \"Magic\" Wireless Mouse driver");
1002 MODULE_LICENSE("GPL");
1003